Skip to main content

proa_cli/
ui.rs

1// Copyright Proa Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::{
5    collections::{BTreeMap, BTreeSet},
6    env, fs,
7    io::Write,
8    path::{Component, Path, PathBuf},
9    time::{SystemTime, UNIX_EPOCH},
10};
11
12use anyhow::{bail, Context, Result};
13use reqwest::{
14    blocking::{Client, RequestBuilder},
15    StatusCode, Url,
16};
17use serde::{Deserialize, Serialize};
18use sha2::{Digest, Sha256};
19
20use crate::config::{
21    self, ComponentLockFile, InstalledCargoDependency, InstalledComponent, InstalledRustModules,
22    ProjectConfig, LOCK_FILE,
23};
24
25pub const COMPONENT_MANIFEST_SCHEMA: &str = "https://proa.so/schema/ui-component-manifest-v1.json";
26const COMPONENT_MANIFEST_VERSION: u32 = 1;
27const MAX_MANIFEST_BYTES: usize = 1024 * 1024;
28const MAX_COMPONENT_FILES: usize = 512;
29const MAX_FILE_BYTES: usize = 8 * 1024 * 1024;
30const MAX_TRANSACTION_BYTES: usize = 64 * 1024 * 1024;
31const PUBLIC_REGISTRY: &str = "@proa";
32const PRO_REGISTRY: &str = "@proa-pro";
33
34#[derive(Debug, Clone)]
35pub struct AddOptions {
36    pub root: PathBuf,
37    pub component: String,
38    pub registry: Option<String>,
39    pub dry_run: bool,
40    /// Overwrite components already recorded in the lock file.
41    pub force: bool,
42}
43
44#[derive(Debug, Clone, Serialize)]
45#[serde(rename_all = "camelCase")]
46pub struct AddReport {
47    pub root: PathBuf,
48    pub requested: String,
49    pub resolved: String,
50    pub registry: String,
51    pub version: String,
52    pub dry_run: bool,
53    pub components: Vec<InstalledComponentReport>,
54    pub files_written: Vec<PathBuf>,
55    pub files_unchanged: Vec<PathBuf>,
56    pub lock_path: PathBuf,
57}
58
59#[derive(Debug, Clone, Serialize)]
60#[serde(rename_all = "camelCase")]
61pub struct InstalledComponentReport {
62    pub name: String,
63    pub kind: RegistryItemKind,
64    pub registry: String,
65    pub version: String,
66    pub tier: ComponentTier,
67    pub dependency: bool,
68}
69
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
71#[serde(rename_all = "lowercase")]
72pub enum ComponentTier {
73    Free,
74    Pro,
75}
76
77#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
78#[serde(rename_all = "lowercase")]
79pub enum RegistryItemKind {
80    #[default]
81    Component,
82    Block,
83}
84
85#[derive(Debug, Clone, Deserialize)]
86#[serde(rename_all = "camelCase", deny_unknown_fields)]
87struct ComponentManifest {
88    #[serde(rename = "$schema")]
89    schema: String,
90    schema_version: u32,
91    name: String,
92    version: String,
93    registry: String,
94    #[serde(default)]
95    kind: RegistryItemKind,
96    tier: ComponentTier,
97    license: String,
98    #[serde(default)]
99    dependencies: Vec<String>,
100    #[serde(default)]
101    rust_modules: Vec<ComponentRustModules>,
102    #[serde(default)]
103    cargo_dependencies: Vec<ComponentCargoDependency>,
104    files: Vec<ComponentManifestFile>,
105}
106
107#[derive(Debug, Clone, Deserialize)]
108#[serde(rename_all = "camelCase", deny_unknown_fields)]
109struct ComponentManifestFile {
110    source: String,
111    target: String,
112    sha256: String,
113}
114
115#[derive(Debug, Clone, Deserialize)]
116#[serde(rename_all = "camelCase", deny_unknown_fields)]
117struct ComponentRustModules {
118    target: String,
119    modules: Vec<String>,
120}
121
122#[derive(Debug, Clone, Deserialize)]
123#[serde(rename_all = "camelCase", deny_unknown_fields)]
124struct ComponentCargoDependency {
125    name: String,
126    #[serde(default)]
127    path: Option<String>,
128    #[serde(default)]
129    version: Option<String>,
130    #[serde(default)]
131    git: Option<String>,
132    #[serde(default)]
133    registry: Option<String>,
134    #[serde(default)]
135    features: Vec<String>,
136    #[serde(default)]
137    default_features: Option<bool>,
138}
139
140#[derive(Debug, Clone)]
141enum ResourceLocation {
142    Http(Url),
143    File(PathBuf),
144}
145
146impl ResourceLocation {
147    fn display(&self) -> String {
148        match self {
149            Self::Http(url) => url.to_string(),
150            Self::File(path) => path.display().to_string(),
151        }
152    }
153
154    fn resolve_relative(&self, relative: &str) -> Result<Self> {
155        if relative.contains('\\')
156            || relative.contains('?')
157            || relative.contains('#')
158            || relative.starts_with("//")
159            || Url::parse(relative).is_ok()
160        {
161            bail!("artifact source `{relative}` must be a plain relative URL path");
162        }
163        validate_relative_path(Path::new(relative), "artifact source")?;
164        match self {
165            Self::Http(url) => {
166                let resolved = url
167                    .join(relative)
168                    .with_context(|| format!("resolve artifact `{relative}` relative to {url}"))?;
169                ensure_supported_http_url(&resolved)?;
170                if resolved.origin() != url.origin() {
171                    bail!(
172                        "artifact source `{relative}` resolves outside manifest origin {}",
173                        url.origin().ascii_serialization()
174                    );
175                }
176                Ok(Self::Http(resolved))
177            }
178            Self::File(path) => {
179                let parent = path.parent().ok_or_else(|| {
180                    anyhow::anyhow!(
181                        "manifest path {} has no parent for artifact `{relative}`",
182                        path.display()
183                    )
184                })?;
185                Ok(Self::File(parent.join(relative)))
186            }
187        }
188    }
189}
190
191#[derive(Debug, thiserror::Error)]
192enum FetchError {
193    #[error("{0}")]
194    NotFound(String),
195    #[error("{0}")]
196    Unauthorized(String),
197    #[error("{0}")]
198    Failed(String),
199}
200
201#[derive(Debug)]
202struct LoadedManifest {
203    location: ResourceLocation,
204    manifest: ComponentManifest,
205}
206
207#[derive(Debug, Clone)]
208struct PreparedFile {
209    target: PathBuf,
210    target_relative: PathBuf,
211    bytes: Vec<u8>,
212}
213
214#[derive(Debug)]
215struct PreparedComponent {
216    manifest: ComponentManifest,
217    files: Vec<PreparedFile>,
218    source_hash: String,
219    dependency_ids: Vec<String>,
220    rust_modules: Vec<PreparedRustModules>,
221    cargo_dependencies: Vec<PreparedCargoDependency>,
222}
223
224#[derive(Debug)]
225struct PreparedRustModules {
226    target_relative: PathBuf,
227    modules: Vec<String>,
228}
229
230#[derive(Debug)]
231struct PreparedCargoDependency {
232    name: String,
233    source: PreparedCargoDependencySource,
234    features: Vec<String>,
235    default_features: Option<bool>,
236}
237
238#[derive(Debug, Clone, PartialEq, Eq)]
239enum PreparedCargoDependencySource {
240    Path(PathBuf),
241    Version {
242        version: String,
243        registry: Option<String>,
244    },
245    Git(String),
246}
247
248struct Resolver<'a> {
249    root: &'a Path,
250    config: &'a ProjectConfig,
251    client: Client,
252    components: BTreeMap<String, PreparedComponent>,
253    order: Vec<String>,
254    stack: Vec<String>,
255    total_bytes: usize,
256}
257
258pub fn add(options: AddOptions) -> Result<AddReport> {
259    let root = canonical_project_root(&options.root)?;
260    let config = config::load_project_config(&root)?;
261    // Registry slugs are underscored because a component's slug is also its
262    // Cargo feature name. Hyphens are what people type, so accept them and
263    // resolve to the canonical spelling rather than 404ing on `alert-dialog`.
264    let requested = canonical_component_reference(&options.component);
265    let (qualified_registry, slug) = parse_component_reference(&requested)?;
266    let requested_registry = normalize_registry_option(options.registry.as_deref())?;
267
268    if let (Some(from_name), Some(from_flag)) = (qualified_registry, requested_registry) {
269        if from_name != from_flag {
270            bail!(
271                "component `{}` selects registry `{from_name}`, but --registry selected `{from_flag}`",
272                options.component
273            );
274        }
275    }
276
277    let explicit_registry = qualified_registry.or(requested_registry);
278    let client = Client::builder()
279        .user_agent(concat!("proa-cli/", env!("CARGO_PKG_VERSION")))
280        .redirect(reqwest::redirect::Policy::limited(5))
281        .build()
282        .context("build Proa UI registry client")?;
283    let mut resolver = Resolver {
284        root: &root,
285        config: &config,
286        client,
287        components: BTreeMap::new(),
288        order: Vec::new(),
289        stack: Vec::new(),
290        total_bytes: 0,
291    };
292
293    let (resolved_registry, loaded) = resolver.resolve_top_level(explicit_registry, slug)?;
294    let resolved_id = component_id(resolved_registry, slug);
295    resolver.resolve_loaded(resolved_registry, slug, loaded)?;
296
297    let existing_lock = config::load_component_lock(&root)?;
298    let mut next_lock = existing_lock.clone();
299    for id in &resolver.order {
300        let component = resolver
301            .components
302            .get(id)
303            .expect("resolver order only contains resolved components");
304        next_lock.components.insert(
305            id.clone(),
306            InstalledComponent {
307                version: component.manifest.version.clone(),
308                registry: component.manifest.registry.clone(),
309                mode: "source".to_string(),
310                source_hash: component.source_hash.clone(),
311                local_hash_at_install: component.source_hash.clone(),
312                installed_files: component
313                    .files
314                    .iter()
315                    .map(|file| file.target_relative.clone())
316                    .collect(),
317                dependencies: component.dependency_ids.clone(),
318                rust_modules: component
319                    .rust_modules
320                    .iter()
321                    .map(|modules| InstalledRustModules {
322                        target: modules.target_relative.clone(),
323                        modules: modules.modules.clone(),
324                    })
325                    .collect(),
326                cargo_dependencies: component
327                    .cargo_dependencies
328                    .iter()
329                    .map(|dependency| InstalledCargoDependency {
330                        name: dependency.name.clone(),
331                        path: match &dependency.source {
332                            PreparedCargoDependencySource::Path(path) => Some(path.clone()),
333                            _ => None,
334                        },
335                        version: match &dependency.source {
336                            PreparedCargoDependencySource::Version { version, .. } => {
337                                Some(version.clone())
338                            }
339                            _ => None,
340                        },
341                        git: match &dependency.source {
342                            PreparedCargoDependencySource::Git(url) => Some(url.clone()),
343                            _ => None,
344                        },
345                        registry: match &dependency.source {
346                            PreparedCargoDependencySource::Version { registry, .. } => {
347                                registry.clone()
348                            }
349                            _ => None,
350                        },
351                        features: dependency.features.clone(),
352                        default_features: dependency.default_features,
353                    })
354                    .collect(),
355            },
356        );
357    }
358
359    let transaction = prepare_transaction(
360        &root,
361        &existing_lock,
362        &next_lock,
363        &resolver.components,
364        &resolver.order,
365        options.force,
366    )?;
367
368    if !options.dry_run {
369        commit_transaction(&root, &transaction.mutations, &next_lock)?;
370    }
371
372    let top = resolver
373        .components
374        .get(&resolved_id)
375        .expect("top-level component was resolved");
376    let components = resolver
377        .order
378        .iter()
379        .map(|id| {
380            let component = resolver
381                .components
382                .get(id)
383                .expect("resolver order only contains resolved components");
384            InstalledComponentReport {
385                name: component.manifest.name.clone(),
386                kind: component.manifest.kind,
387                registry: component.manifest.registry.clone(),
388                version: component.manifest.version.clone(),
389                tier: component.manifest.tier,
390                dependency: id != &resolved_id,
391            }
392        })
393        .collect();
394
395    Ok(AddReport {
396        root: root.clone(),
397        requested: options.component,
398        resolved: resolved_id,
399        registry: resolved_registry.to_string(),
400        version: top.manifest.version.clone(),
401        dry_run: options.dry_run,
402        components,
403        files_written: transaction
404            .mutations
405            .iter()
406            .map(|mutation| mutation.target_relative.clone())
407            .collect(),
408        files_unchanged: transaction.files_unchanged,
409        lock_path: root.join(LOCK_FILE),
410    })
411}
412
413pub fn print_add_report(report: &AddReport, json: bool) -> Result<()> {
414    if json {
415        println!("{}", serde_json::to_string_pretty(report)?);
416        return Ok(());
417    }
418
419    let action = if report.dry_run {
420        "Would install"
421    } else {
422        "Installed"
423    };
424    println!(
425        "{action} {} {} from {}",
426        report.resolved, report.version, report.registry
427    );
428    for component in &report.components {
429        if component.dependency {
430            println!(
431                "  dependency {}/{} {}",
432                component.registry, component.name, component.version
433            );
434        }
435    }
436    let written = report.files_written.len();
437    let unchanged = report.files_unchanged.len();
438    println!(
439        "  {written} file(s) {}, {unchanged} already current",
440        if report.dry_run { "planned" } else { "written" }
441    );
442    if !report.dry_run {
443        println!("  lock {}", report.lock_path.display());
444    }
445    Ok(())
446}
447
448impl<'a> Resolver<'a> {
449    fn resolve_top_level(
450        &self,
451        explicit_registry: Option<&str>,
452        slug: &str,
453    ) -> Result<(&'static str, LoadedManifest)> {
454        if let Some(registry) = explicit_registry {
455            let registry = canonical_registry(registry)?;
456            return self
457                .fetch_manifest(registry, slug)
458                .map(|manifest| (registry, manifest))
459                .map_err(|error| fetch_error_to_anyhow(registry, slug, error));
460        }
461
462        let public_not_found = if self.config.registries.contains_key(PUBLIC_REGISTRY) {
463            match self.fetch_manifest(PUBLIC_REGISTRY, slug) {
464                Ok(manifest) => return Ok((PUBLIC_REGISTRY, manifest)),
465                Err(FetchError::NotFound(detail)) => Some(detail),
466                Err(error) => {
467                    return Err(fetch_error_to_anyhow(PUBLIC_REGISTRY, slug, error));
468                }
469            }
470        } else {
471            None
472        };
473
474        if self.config.registries.contains_key(PRO_REGISTRY) {
475            match self.fetch_manifest(PRO_REGISTRY, slug) {
476                Ok(manifest) => return Ok((PRO_REGISTRY, manifest)),
477                Err(error) => {
478                    if let Some(public_detail) = public_not_found {
479                        return Err(bare_registry_fallback_error(slug, &public_detail, error));
480                    }
481                    return Err(fetch_error_to_anyhow(PRO_REGISTRY, slug, error));
482                }
483            }
484        }
485
486        if let Some(public_detail) = public_not_found {
487            bail!(
488                "component `{slug}` was not found in the public Free registry \
489                 `{PUBLIC_REGISTRY}` ({public_detail}), and `{PRO_REGISTRY}` is not configured. \
490                 Free registry access does not require a bearer token. No project files were changed."
491            );
492        }
493
494        bail!(
495            "component `{slug}` was not found in {PUBLIC_REGISTRY} or {PRO_REGISTRY}; \
496             check the slug with `proa registry list`, or select a registry explicitly"
497        )
498    }
499
500    fn resolve(&mut self, registry: &'static str, slug: &str) -> Result<()> {
501        let id = component_id(registry, slug);
502        if self.components.contains_key(&id) {
503            return Ok(());
504        }
505        let loaded = self
506            .fetch_manifest(registry, slug)
507            .map_err(|error| fetch_error_to_anyhow(registry, slug, error))?;
508        self.resolve_loaded(registry, slug, loaded)
509    }
510
511    fn resolve_loaded(
512        &mut self,
513        registry: &'static str,
514        slug: &str,
515        loaded: LoadedManifest,
516    ) -> Result<()> {
517        let id = component_id(registry, slug);
518        if self.components.contains_key(&id) {
519            return Ok(());
520        }
521        if let Some(position) = self.stack.iter().position(|item| item == &id) {
522            let mut cycle = self.stack[position..].to_vec();
523            cycle.push(id);
524            bail!("component dependency cycle: {}", cycle.join(" -> "));
525        }
526
527        validate_manifest(registry, slug, &loaded.manifest)?;
528        self.stack.push(id.clone());
529
530        let mut dependency_ids = Vec::with_capacity(loaded.manifest.dependencies.len());
531        let mut seen_dependencies = BTreeSet::new();
532        for dependency in &loaded.manifest.dependencies {
533            let (dependency_registry, dependency_slug) =
534                parse_dependency_reference(registry, dependency)?;
535            let dependency_id = component_id(dependency_registry, dependency_slug);
536            if !seen_dependencies.insert(dependency_id.clone()) {
537                bail!("manifest `{id}` lists dependency `{dependency_id}` more than once");
538            }
539            self.resolve(dependency_registry, dependency_slug)?;
540            let child = self
541                .components
542                .get(&dependency_id)
543                .expect("resolved dependency exists");
544            if loaded.manifest.tier == ComponentTier::Free
545                && child.manifest.tier == ComponentTier::Pro
546            {
547                bail!("Free component `{id}` cannot depend on Pro component `{dependency_id}`");
548            }
549            dependency_ids.push(dependency_id);
550        }
551
552        let files = self.prepare_files(&id, &loaded)?;
553        let rust_modules = self.prepare_rust_modules(&id, &loaded)?;
554        let cargo_dependencies = self.prepare_cargo_dependencies(&id, &loaded)?;
555        let source_hash = hash_component_source(&files, &rust_modules, &cargo_dependencies);
556        let manifest = loaded.manifest;
557        self.stack.pop();
558        self.order.push(id.clone());
559        self.components.insert(
560            id.clone(),
561            PreparedComponent {
562                manifest,
563                files,
564                source_hash,
565                dependency_ids,
566                rust_modules,
567                cargo_dependencies,
568            },
569        );
570        Ok(())
571    }
572
573    fn prepare_files(&mut self, id: &str, loaded: &LoadedManifest) -> Result<Vec<PreparedFile>> {
574        let mut files = Vec::with_capacity(loaded.manifest.files.len());
575        let mut seen_targets = BTreeSet::new();
576
577        for entry in &loaded.manifest.files {
578            let (target, target_relative) = resolve_target(self.root, self.config, &entry.target)?;
579            if !seen_targets.insert(target_relative.clone()) {
580                bail!(
581                    "manifest `{id}` maps more than one artifact to `{}`",
582                    target_relative.display()
583                );
584            }
585            let expected_hash = normalize_sha256(&entry.sha256)
586                .with_context(|| format!("manifest `{id}` target `{}`", entry.target))?;
587            let source = loaded.location.resolve_relative(&entry.source)?;
588            let bytes = self
589                .fetch_bytes(&source, MAX_FILE_BYTES, loaded.manifest.registry.as_str())
590                .map_err(|error| {
591                    fetch_error_to_anyhow(&loaded.manifest.registry, &loaded.manifest.name, error)
592                })?;
593            let actual_hash = sha256_bytes(&bytes);
594            if actual_hash != expected_hash {
595                bail!(
596                    "artifact hash mismatch for `{}` in `{id}`: expected {}, got {}",
597                    entry.target,
598                    expected_hash,
599                    actual_hash
600                );
601            }
602            self.total_bytes = self
603                .total_bytes
604                .checked_add(bytes.len())
605                .ok_or_else(|| anyhow::anyhow!("component transaction size overflow"))?;
606            if self.total_bytes > MAX_TRANSACTION_BYTES {
607                bail!(
608                    "component transaction exceeds the {} MiB safety limit",
609                    MAX_TRANSACTION_BYTES / (1024 * 1024)
610                );
611            }
612            files.push(PreparedFile {
613                target,
614                target_relative,
615                bytes,
616            });
617        }
618
619        Ok(files)
620    }
621
622    fn prepare_rust_modules(
623        &self,
624        id: &str,
625        loaded: &LoadedManifest,
626    ) -> Result<Vec<PreparedRustModules>> {
627        let mut prepared = Vec::with_capacity(loaded.manifest.rust_modules.len());
628        let mut seen_targets = BTreeSet::new();
629        for entry in &loaded.manifest.rust_modules {
630            let (_, target_relative) = resolve_target(self.root, self.config, &entry.target)?;
631            if !seen_targets.insert(target_relative.clone()) {
632                bail!(
633                    "manifest `{id}` declares Rust modules for `{}` more than once",
634                    target_relative.display()
635                );
636            }
637            if entry.modules.is_empty() {
638                bail!(
639                    "manifest `{id}` has an empty Rust module declaration for `{}`",
640                    entry.target
641                );
642            }
643            let mut modules = BTreeSet::new();
644            for module in &entry.modules {
645                validate_rust_module_name(module).with_context(|| {
646                    format!("manifest `{id}` Rust module target `{}`", entry.target)
647                })?;
648                if !modules.insert(module.clone()) {
649                    bail!("manifest `{id}` declares Rust module `{module}` more than once");
650                }
651            }
652            prepared.push(PreparedRustModules {
653                target_relative,
654                modules: modules.into_iter().collect(),
655            });
656        }
657        Ok(prepared)
658    }
659
660    fn prepare_cargo_dependencies(
661        &self,
662        id: &str,
663        loaded: &LoadedManifest,
664    ) -> Result<Vec<PreparedCargoDependency>> {
665        let mut prepared = Vec::with_capacity(loaded.manifest.cargo_dependencies.len());
666        let mut seen = BTreeSet::new();
667        for entry in &loaded.manifest.cargo_dependencies {
668            validate_cargo_dependency_name(&entry.name)
669                .with_context(|| format!("manifest `{id}` Cargo dependency"))?;
670            if !seen.insert(entry.name.clone()) {
671                bail!(
672                    "manifest `{id}` declares Cargo dependency `{}` more than once",
673                    entry.name
674                );
675            }
676            let source = match (&entry.path, &entry.version, &entry.git) {
677                (Some(path), None, None) => {
678                    if entry.registry.is_some() {
679                        bail!(
680                            "manifest `{id}` Cargo dependency `{}` cannot combine `path` and `registry`",
681                            entry.name
682                        );
683                    }
684                    let (_, path_relative) = resolve_target(self.root, self.config, path)?;
685                    PreparedCargoDependencySource::Path(path_relative)
686                }
687                (None, Some(version), None) => {
688                    validate_cargo_version(version)
689                        .with_context(|| format!("manifest `{id}` Cargo dependency `{}`", entry.name))?;
690                    if let Some(registry) = &entry.registry {
691                        validate_cargo_registry_name(registry).with_context(|| {
692                            format!("manifest `{id}` Cargo dependency `{}`", entry.name)
693                        })?;
694                    }
695                    PreparedCargoDependencySource::Version {
696                        version: version.clone(),
697                        registry: entry.registry.clone(),
698                    }
699                }
700                (None, None, Some(git)) => {
701                    if entry.registry.is_some() {
702                        bail!(
703                            "manifest `{id}` Cargo dependency `{}` cannot combine `git` and `registry`",
704                            entry.name
705                        );
706                    }
707                    validate_cargo_git_url(git).with_context(|| {
708                        format!("manifest `{id}` Cargo dependency `{}`", entry.name)
709                    })?;
710                    PreparedCargoDependencySource::Git(git.clone())
711                }
712                (None, None, None) => bail!(
713                    "manifest `{id}` Cargo dependency `{}` must declare `version`",
714                    entry.name
715                ),
716                _ => bail!(
717                    "manifest `{id}` Cargo dependency `{}` must declare exactly one of `path`, `version`, or `git`",
718                    entry.name
719                ),
720            };
721            let mut features = BTreeSet::new();
722            for feature in &entry.features {
723                validate_cargo_feature_name(feature)
724                    .with_context(|| format!("manifest `{id}` Cargo feature"))?;
725                if !features.insert(feature.clone()) {
726                    bail!("manifest `{id}` declares Cargo feature `{feature}` more than once");
727                }
728            }
729            prepared.push(PreparedCargoDependency {
730                name: entry.name.clone(),
731                source,
732                features: features.into_iter().collect(),
733                default_features: entry.default_features,
734            });
735        }
736        Ok(prepared)
737    }
738
739    fn fetch_manifest(
740        &self,
741        registry: &str,
742        slug: &str,
743    ) -> std::result::Result<LoadedManifest, FetchError> {
744        let template = self.config.registries.get(registry).ok_or_else(|| {
745            FetchError::Failed(format!(
746                "registry `{registry}` is not configured in {}",
747                config::CONFIG_FILE
748            ))
749        })?;
750        let location = registry_manifest_location(self.root, template, slug)
751            .map_err(|error| FetchError::Failed(error.to_string()))?;
752        let bytes = self.fetch_bytes(&location, MAX_MANIFEST_BYTES, registry)?;
753        let manifest: ComponentManifest = serde_json::from_slice(&bytes).map_err(|error| {
754            FetchError::Failed(format!(
755                "parse component manifest {}: {error}",
756                location.display()
757            ))
758        })?;
759        Ok(LoadedManifest { location, manifest })
760    }
761
762    fn fetch_bytes(
763        &self,
764        location: &ResourceLocation,
765        limit: usize,
766        registry: &str,
767    ) -> std::result::Result<Vec<u8>, FetchError> {
768        match location {
769            ResourceLocation::File(path) => {
770                let metadata = fs::metadata(path).map_err(|error| {
771                    if error.kind() == std::io::ErrorKind::NotFound {
772                        FetchError::NotFound(format!("{} was not found", path.display()))
773                    } else {
774                        FetchError::Failed(format!("read {}: {error}", path.display()))
775                    }
776                })?;
777                if metadata.len() > limit as u64 {
778                    return Err(FetchError::Failed(format!(
779                        "{} exceeds the {} byte safety limit",
780                        path.display(),
781                        limit
782                    )));
783                }
784                fs::read(path).map_err(|error| {
785                    FetchError::Failed(format!("read {}: {error}", path.display()))
786                })
787            }
788            ResourceLocation::Http(url) => {
789                let mut request = self.client.get(url.clone());
790                if registry == PRO_REGISTRY {
791                    let token = pro_registry_bearer_token()
792                        .map_err(|error| FetchError::Failed(error.to_string()))?;
793                    request = with_registry_bearer_auth(request, registry, token.as_deref());
794                }
795                let response = request
796                    .send()
797                    .map_err(|error| FetchError::Failed(format!("request {url}: {error}")))?;
798                if response.url().origin() != url.origin() {
799                    return Err(FetchError::Failed(format!(
800                        "request {url} redirected across origins to {}",
801                        response.url()
802                    )));
803                }
804                let status = response.status();
805                if status == StatusCode::NOT_FOUND {
806                    return Err(FetchError::NotFound(format!("{url} returned {status}")));
807                }
808                if status == StatusCode::UNAUTHORIZED || status == StatusCode::FORBIDDEN {
809                    return Err(FetchError::Unauthorized(format!("{url} returned {status}")));
810                }
811                let response = response
812                    .error_for_status()
813                    .map_err(|error| FetchError::Failed(format!("request {url}: {error}")))?;
814                if response
815                    .content_length()
816                    .is_some_and(|length| length > limit as u64)
817                {
818                    return Err(FetchError::Failed(format!(
819                        "{url} exceeds the {limit} byte safety limit"
820                    )));
821                }
822                let bytes = response.bytes().map_err(|error| {
823                    FetchError::Failed(format!("read response body from {url}: {error}"))
824                })?;
825                if bytes.len() > limit {
826                    return Err(FetchError::Failed(format!(
827                        "{url} exceeds the {limit} byte safety limit"
828                    )));
829                }
830                Ok(bytes.to_vec())
831            }
832        }
833    }
834}
835
836fn validate_manifest(registry: &str, slug: &str, manifest: &ComponentManifest) -> Result<()> {
837    if manifest.schema != COMPONENT_MANIFEST_SCHEMA {
838        bail!(
839            "manifest `{registry}/{slug}` uses unsupported schema `{}` (expected `{COMPONENT_MANIFEST_SCHEMA}`)",
840            manifest.schema
841        );
842    }
843    if manifest.schema_version != COMPONENT_MANIFEST_VERSION {
844        bail!(
845            "manifest `{registry}/{slug}` uses unsupported schemaVersion {} (expected {})",
846            manifest.schema_version,
847            COMPONENT_MANIFEST_VERSION
848        );
849    }
850    let manifest_slug = validate_slug(&manifest.name)?;
851    if manifest_slug != slug {
852        bail!(
853            "registry returned component `{}` for requested slug `{slug}`",
854            manifest.name
855        );
856    }
857    if manifest.registry != registry {
858        bail!(
859            "manifest `{registry}/{slug}` declares registry `{}`",
860            manifest.registry
861        );
862    }
863    match (registry, manifest.tier) {
864        (PUBLIC_REGISTRY, ComponentTier::Free) | (PRO_REGISTRY, ComponentTier::Pro) => {}
865        (PUBLIC_REGISTRY, ComponentTier::Pro) => {
866            bail!(
867                "Pro component `{slug}` cannot be served from public registry `{PUBLIC_REGISTRY}`"
868            )
869        }
870        (PRO_REGISTRY, ComponentTier::Free) => {
871            bail!("Free component `{slug}` must be served from public registry `{PUBLIC_REGISTRY}`")
872        }
873        _ => bail!("unsupported component registry `{registry}`"),
874    }
875    if manifest.tier == ComponentTier::Free && manifest.license != "MIT OR Apache-2.0" {
876        bail!(
877            "Free component `{registry}/{slug}` must declare license `MIT OR Apache-2.0`, got `{}`",
878            manifest.license
879        );
880    }
881    if manifest.license.trim().is_empty() {
882        bail!("manifest `{registry}/{slug}` has an empty license");
883    }
884    if manifest.version.trim().is_empty() || manifest.version.len() > 128 {
885        bail!("manifest `{registry}/{slug}` has an invalid version");
886    }
887    if manifest.files.is_empty() {
888        bail!("manifest `{registry}/{slug}` contains no files");
889    }
890    if manifest.files.len() > MAX_COMPONENT_FILES {
891        bail!(
892            "manifest `{registry}/{slug}` contains {} files; maximum is {MAX_COMPONENT_FILES}",
893            manifest.files.len()
894        );
895    }
896    Ok(())
897}
898
899/// Rewrite hyphens in the component slug to underscores, leaving any
900/// `@registry/` prefix alone (registry aliases are hyphenated: `@proa-pro`).
901fn canonical_component_reference(input: &str) -> String {
902    match input
903        .strip_prefix('@')
904        .and_then(|rest| rest.split_once('/'))
905    {
906        Some((registry, slug)) => format!("@{registry}/{}", slug.replace('-', "_")),
907        None => input.replace('-', "_"),
908    }
909}
910
911fn parse_component_reference(input: &str) -> Result<(Option<&'static str>, &str)> {
912    if let Some(rest) = input.strip_prefix('@') {
913        let (registry_name, slug) = rest.split_once('/').ok_or_else(|| {
914            anyhow::anyhow!(
915                "qualified component `{input}` must use `@proa/<slug>` or `@proa-pro/<slug>`"
916            )
917        })?;
918        let registry = canonical_registry(&format!("@{registry_name}"))?;
919        return Ok((Some(registry), validate_slug(slug)?));
920    }
921    Ok((None, validate_slug(input)?))
922}
923
924fn parse_dependency_reference<'a>(
925    parent_registry: &'static str,
926    input: &'a str,
927) -> Result<(&'static str, &'a str)> {
928    let (registry, slug) = parse_component_reference(input)?;
929    Ok((registry.unwrap_or(parent_registry), slug))
930}
931
932fn normalize_registry_option(input: Option<&str>) -> Result<Option<&'static str>> {
933    input.map(canonical_registry).transpose()
934}
935
936fn canonical_registry(input: &str) -> Result<&'static str> {
937    match input {
938        PUBLIC_REGISTRY | "proa" => Ok(PUBLIC_REGISTRY),
939        PRO_REGISTRY | "proa-pro" => Ok(PRO_REGISTRY),
940        _ => bail!(
941            "unsupported registry `{input}` (expected `{PUBLIC_REGISTRY}` or `{PRO_REGISTRY}`)"
942        ),
943    }
944}
945
946fn validate_slug(input: &str) -> Result<&str> {
947    if input.is_empty()
948        || input.len() > 128
949        || !input.bytes().all(|byte| {
950            byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-' || byte == b'_'
951        })
952        || !input
953            .as_bytes()
954            .first()
955            .is_some_and(u8::is_ascii_alphanumeric)
956        || !input
957            .as_bytes()
958            .last()
959            .is_some_and(u8::is_ascii_alphanumeric)
960    {
961        bail!("invalid component slug `{input}`; use lowercase ASCII letters, digits, `-`, or `_`");
962    }
963    Ok(input)
964}
965
966fn validate_rust_module_name(input: &str) -> Result<()> {
967    const KEYWORDS: &[&str] = &[
968        "as", "break", "const", "continue", "crate", "else", "enum", "extern", "false", "fn",
969        "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref",
970        "return", "self", "Self", "static", "struct", "super", "trait", "true", "type", "unsafe",
971        "use", "where", "while", "async", "await", "dyn",
972    ];
973    let mut bytes = input.bytes();
974    let Some(first) = bytes.next() else {
975        bail!("Rust module name cannot be empty");
976    };
977    if !(first.is_ascii_lowercase() || first == b'_')
978        || !bytes.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
979        || KEYWORDS.contains(&input)
980    {
981        bail!("invalid Rust module name `{input}`");
982    }
983    Ok(())
984}
985
986fn validate_cargo_dependency_name(input: &str) -> Result<()> {
987    if input.is_empty()
988        || input.len() > 128
989        || !input
990            .bytes()
991            .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_')
992        || !input
993            .as_bytes()
994            .first()
995            .is_some_and(u8::is_ascii_alphanumeric)
996    {
997        bail!("invalid Cargo dependency name `{input}`");
998    }
999    Ok(())
1000}
1001
1002fn validate_cargo_feature_name(input: &str) -> Result<()> {
1003    if input.is_empty()
1004        || input.len() > 128
1005        || !input.bytes().all(|byte| {
1006            byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_' || byte == b'/'
1007        })
1008    {
1009        bail!("invalid Cargo feature name `{input}`");
1010    }
1011    Ok(())
1012}
1013
1014fn validate_cargo_version(input: &str) -> Result<()> {
1015    if input.trim() != input
1016        || input.is_empty()
1017        || input.len() > 128
1018        || !input.bytes().all(|byte| {
1019            byte.is_ascii_alphanumeric()
1020                || matches!(
1021                    byte,
1022                    b'.' | b',' | b'-' | b'+' | b'^' | b'~' | b'<' | b'>' | b'=' | b'*' | b' '
1023                )
1024        })
1025    {
1026        bail!("invalid Cargo version requirement `{input}`");
1027    }
1028    Ok(())
1029}
1030
1031fn validate_cargo_git_url(input: &str) -> Result<()> {
1032    if input.len() > 256 || !input.starts_with("https://") || Url::parse(input).is_err() {
1033        bail!("invalid Cargo git dependency URL `{input}` (https URLs only)");
1034    }
1035    Ok(())
1036}
1037
1038fn validate_cargo_registry_name(input: &str) -> Result<()> {
1039    if input.is_empty()
1040        || input.len() > 64
1041        || !input
1042            .bytes()
1043            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
1044    {
1045        bail!("invalid Cargo registry name `{input}`");
1046    }
1047    Ok(())
1048}
1049
1050fn component_id(registry: &str, slug: &str) -> String {
1051    format!("{registry}/{slug}")
1052}
1053
1054fn registry_manifest_location(root: &Path, template: &str, slug: &str) -> Result<ResourceLocation> {
1055    if !template.contains("{name}") {
1056        bail!("registry template `{template}` must contain `{{name}}`");
1057    }
1058    let rendered = template.replace("{name}", slug);
1059    if rendered.starts_with("https://") || rendered.starts_with("http://") {
1060        let url =
1061            Url::parse(&rendered).with_context(|| format!("parse registry URL `{rendered}`"))?;
1062        ensure_supported_http_url(&url)?;
1063        return Ok(ResourceLocation::Http(url));
1064    }
1065    if rendered.starts_with("file://") {
1066        let url = Url::parse(&rendered)
1067            .with_context(|| format!("parse registry file URL `{rendered}`"))?;
1068        let path = url
1069            .to_file_path()
1070            .map_err(|_| anyhow::anyhow!("invalid registry file URL `{rendered}`"))?;
1071        return Ok(ResourceLocation::File(path));
1072    }
1073    let path = PathBuf::from(rendered);
1074    Ok(ResourceLocation::File(if path.is_absolute() {
1075        path
1076    } else {
1077        root.join(path)
1078    }))
1079}
1080
1081fn ensure_supported_http_url(url: &Url) -> Result<()> {
1082    match url.scheme() {
1083        "https" => Ok(()),
1084        "http" if matches!(url.host_str(), Some("localhost" | "127.0.0.1" | "::1")) => Ok(()),
1085        "http" => {
1086            bail!("registry URL `{url}` is insecure; HTTP is only allowed for localhost fixtures")
1087        }
1088        scheme => bail!("unsupported registry URL scheme `{scheme}` in `{url}`"),
1089    }
1090}
1091
1092fn resolve_target(root: &Path, config: &ProjectConfig, target: &str) -> Result<(PathBuf, PathBuf)> {
1093    let (alias, relative) = target.split_once('/').ok_or_else(|| {
1094        anyhow::anyhow!(
1095            "artifact target `{target}` must use `@components/<path>` or `@assets/<path>`"
1096        )
1097    })?;
1098    if !alias.starts_with('@') {
1099        bail!("artifact target `{target}` must start with a configured `@` alias");
1100    }
1101    let legacy_lib = Path::new("src/lib");
1102    let alias_root = match alias {
1103        "@components" => config.paths.components.as_path(),
1104        "@assets" => config.paths.assets.as_path(),
1105        // Compatibility for already-published v1 manifests. New manifests
1106        // must use the flat @components layout, but retaining this resolver
1107        // keeps Pro installs and rolling deployments from breaking while
1108        // registries migrate independently of the CLI.
1109        "@lib" if relative == "proa_ui" || relative.starts_with("proa_ui/") => legacy_lib,
1110        _ => bail!(
1111            "artifact target `{target}` uses unsupported alias `{alias}`; expected `@components` or `@assets`"
1112        ),
1113    };
1114    validate_relative_path(alias_root, &format!("configured path for `{alias}`"))?;
1115    validate_relative_path(Path::new(relative), "artifact target")?;
1116    let target_relative = alias_root.join(relative);
1117    validate_relative_path(&target_relative, "resolved artifact target")?;
1118    let absolute = root.join(&target_relative);
1119    ensure_no_symlink_path(root, &target_relative)?;
1120    Ok((absolute, target_relative))
1121}
1122
1123fn validate_relative_path(path: &Path, label: &str) -> Result<()> {
1124    if path.as_os_str().is_empty() || path.is_absolute() {
1125        bail!(
1126            "{label} `{}` must be a non-empty relative path",
1127            path.display()
1128        );
1129    }
1130    for component in path.components() {
1131        match component {
1132            Component::Normal(_) => {}
1133            _ => bail!(
1134                "{label} `{}` contains an unsafe path component",
1135                path.display()
1136            ),
1137        }
1138    }
1139    Ok(())
1140}
1141
1142fn ensure_no_symlink_path(root: &Path, relative: &Path) -> Result<()> {
1143    let mut current = root.to_path_buf();
1144    for part in relative.components() {
1145        let Component::Normal(part) = part else {
1146            bail!("unsafe target path `{}`", relative.display());
1147        };
1148        current.push(part);
1149        match fs::symlink_metadata(&current) {
1150            Ok(metadata) if metadata.file_type().is_symlink() => {
1151                bail!(
1152                    "refusing to install through symlink `{}`",
1153                    current.display()
1154                )
1155            }
1156            Ok(_) => {}
1157            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
1158            Err(error) => {
1159                return Err(error)
1160                    .with_context(|| format!("inspect target path {}", current.display()))
1161            }
1162        }
1163    }
1164    Ok(())
1165}
1166
1167fn normalize_sha256(input: &str) -> Result<String> {
1168    let hex = input.strip_prefix("sha256:").unwrap_or(input);
1169    if hex.len() != 64
1170        || !hex
1171            .bytes()
1172            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
1173    {
1174        bail!("invalid SHA-256 `{input}`; expected 64 lowercase hexadecimal characters");
1175    }
1176    Ok(format!("sha256:{hex}"))
1177}
1178
1179fn sha256_bytes(bytes: &[u8]) -> String {
1180    let digest = Sha256::digest(bytes);
1181    format!("sha256:{digest:x}")
1182}
1183
1184fn hash_component_source(
1185    files: &[PreparedFile],
1186    rust_modules: &[PreparedRustModules],
1187    cargo_dependencies: &[PreparedCargoDependency],
1188) -> String {
1189    let mut ordered: Vec<_> = files.iter().collect();
1190    ordered.sort_by(|left, right| left.target_relative.cmp(&right.target_relative));
1191    let mut hasher = Sha256::new();
1192    hasher.update(b"proa-ui-source-v1\0");
1193    for file in ordered {
1194        let path = file.target_relative.to_string_lossy();
1195        hasher.update((path.len() as u64).to_be_bytes());
1196        hasher.update(path.as_bytes());
1197        hasher.update((file.bytes.len() as u64).to_be_bytes());
1198        hasher.update(&file.bytes);
1199    }
1200    let mut modules: Vec<_> = rust_modules.iter().collect();
1201    modules.sort_by(|left, right| left.target_relative.cmp(&right.target_relative));
1202    for entry in modules {
1203        hasher.update(b"modules\0");
1204        hash_path(&mut hasher, &entry.target_relative);
1205        for module in &entry.modules {
1206            hasher.update((module.len() as u64).to_be_bytes());
1207            hasher.update(module.as_bytes());
1208        }
1209    }
1210    let mut dependencies: Vec<_> = cargo_dependencies.iter().collect();
1211    dependencies.sort_by(|left, right| left.name.cmp(&right.name));
1212    for dependency in dependencies {
1213        hasher.update(b"cargo\0");
1214        hasher.update((dependency.name.len() as u64).to_be_bytes());
1215        hasher.update(dependency.name.as_bytes());
1216        match &dependency.source {
1217            PreparedCargoDependencySource::Path(path) => {
1218                hasher.update(b"path\0");
1219                hash_path(&mut hasher, path);
1220            }
1221            PreparedCargoDependencySource::Version { version, registry } => {
1222                hasher.update(b"version\0");
1223                hasher.update((version.len() as u64).to_be_bytes());
1224                hasher.update(version.as_bytes());
1225                if let Some(registry) = registry {
1226                    hasher.update((registry.len() as u64).to_be_bytes());
1227                    hasher.update(registry.as_bytes());
1228                }
1229            }
1230            PreparedCargoDependencySource::Git(url) => {
1231                hasher.update(b"git\0");
1232                hasher.update((url.len() as u64).to_be_bytes());
1233                hasher.update(url.as_bytes());
1234            }
1235        }
1236        for feature in &dependency.features {
1237            hasher.update((feature.len() as u64).to_be_bytes());
1238            hasher.update(feature.as_bytes());
1239        }
1240        hasher.update([u8::from(dependency.default_features.unwrap_or(true))]);
1241    }
1242    format!("sha256:{:x}", hasher.finalize())
1243}
1244
1245fn hash_path(hasher: &mut Sha256, path: &Path) {
1246    let path = path.to_string_lossy();
1247    hasher.update((path.len() as u64).to_be_bytes());
1248    hasher.update(path.as_bytes());
1249}
1250
1251#[derive(Debug)]
1252struct FileMutation {
1253    target: PathBuf,
1254    target_relative: PathBuf,
1255    before: Option<Vec<u8>>,
1256    after: Vec<u8>,
1257}
1258
1259struct PreparedTransaction {
1260    mutations: Vec<FileMutation>,
1261    files_unchanged: Vec<PathBuf>,
1262}
1263
1264fn prepare_transaction(
1265    root: &Path,
1266    current_lock: &ComponentLockFile,
1267    next_lock: &ComponentLockFile,
1268    components: &BTreeMap<String, PreparedComponent>,
1269    order: &[String],
1270    force: bool,
1271) -> Result<PreparedTransaction> {
1272    let mut target_contents: BTreeMap<PathBuf, PreparedFile> = BTreeMap::new();
1273
1274    for id in order {
1275        let component = components
1276            .get(id)
1277            .expect("resolver order only contains resolved components");
1278        if let Some(installed) = current_lock.components.get(id) {
1279            if !force
1280                && (installed.version != component.manifest.version
1281                    || installed.registry != component.manifest.registry
1282                    || installed.source_hash != component.source_hash)
1283            {
1284                // Same version still lands here when only the resolved targets
1285                // moved (an edited `paths.assets`, say), so do not claim an
1286                // upgrade that is not happening.
1287                if installed.version == component.manifest.version {
1288                    bail!(
1289                        "`{id}` is already installed at version {} but resolves to \
1290                         different files now; `proa ui add` will not overwrite it. \
1291                         Pass `--force` to reinstall it.",
1292                        installed.version
1293                    );
1294                }
1295                bail!(
1296                    "`{id}` is already installed at version {}; \
1297                     `proa ui add` will not overwrite or upgrade it. \
1298                     Pass `--force` to reinstall it at {}.",
1299                    installed.version,
1300                    component.manifest.version
1301                );
1302            }
1303        }
1304
1305        for file in &component.files {
1306            if let Some(existing) = target_contents.get(&file.target_relative) {
1307                if existing.bytes != file.bytes {
1308                    bail!(
1309                        "component manifests disagree on shared target `{}`",
1310                        file.target_relative.display()
1311                    );
1312                }
1313                continue;
1314            }
1315            target_contents.insert(file.target_relative.clone(), file.clone());
1316        }
1317    }
1318
1319    let mut mutations = Vec::new();
1320    let mut files_unchanged = Vec::new();
1321    for file in target_contents.values() {
1322        ensure_no_symlink_path(root, &file.target_relative)?;
1323        match fs::read(&file.target) {
1324            Ok(existing) if existing == file.bytes => {
1325                files_unchanged.push(file.target_relative.clone());
1326            }
1327            Ok(_) => {
1328                bail!(
1329                    "refusing to overwrite locally different file `{}`; move it aside or choose another alias path",
1330                    file.target_relative.display()
1331                )
1332            }
1333            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
1334                mutations.push(FileMutation {
1335                    target: file.target.clone(),
1336                    target_relative: file.target_relative.clone(),
1337                    before: None,
1338                    after: file.bytes.clone(),
1339                });
1340            }
1341            Err(error) => {
1342                return Err(error)
1343                    .with_context(|| format!("read install target {}", file.target.display()))
1344            }
1345        }
1346    }
1347
1348    let current_immutable_files = collect_locked_immutable_files(current_lock)?;
1349    let current_modules = collect_locked_modules(current_lock)?;
1350    let next_modules = collect_locked_modules(next_lock)?;
1351    for (target_relative, modules) in &next_modules {
1352        if target_contents.contains_key(target_relative) {
1353            bail!(
1354                "immutable artifact and managed Rust modules both target `{}`",
1355                target_relative.display()
1356            );
1357        }
1358        if current_immutable_files.contains(target_relative) {
1359            bail!(
1360                "managed Rust modules cannot update `{}` because an installed component owns it as an immutable artifact; registries must publish byte-identical shared glue or use managed modules consistently",
1361                target_relative.display()
1362            );
1363        }
1364        validate_relative_path(target_relative, "locked Rust module target")?;
1365        ensure_no_symlink_path(root, target_relative)?;
1366        let target = root.join(target_relative);
1367        let before = match fs::read(&target) {
1368            Ok(bytes) => Some(bytes),
1369            Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
1370            Err(error) => {
1371                return Err(error)
1372                    .with_context(|| format!("read Rust module target {}", target.display()))
1373            }
1374        };
1375        let expected_current = current_modules
1376            .get(target_relative)
1377            .cloned()
1378            .unwrap_or_default();
1379        let after = update_managed_rust_modules(
1380            before.as_deref(),
1381            &expected_current,
1382            modules,
1383            target_relative,
1384        )?;
1385        if before.as_deref() == Some(after.as_slice()) {
1386            files_unchanged.push(target_relative.clone());
1387        } else {
1388            mutations.push(FileMutation {
1389                target,
1390                target_relative: target_relative.clone(),
1391                before,
1392                after,
1393            });
1394        }
1395    }
1396
1397    let cargo_dependencies = collect_locked_cargo_dependencies(next_lock)?;
1398    if !cargo_dependencies.is_empty() {
1399        let cargo_relative = PathBuf::from("Cargo.toml");
1400        if target_contents.contains_key(&cargo_relative)
1401            || next_modules.contains_key(&cargo_relative)
1402        {
1403            bail!("component manifest cannot replace the project Cargo.toml");
1404        }
1405        let cargo_path = root.join(&cargo_relative);
1406        let before = fs::read(&cargo_path)
1407            .with_context(|| format!("read project manifest {}", cargo_path.display()))?;
1408        let after = update_cargo_dependencies(&before, &cargo_dependencies)?;
1409        if before == after {
1410            files_unchanged.push(cargo_relative);
1411        } else {
1412            mutations.push(FileMutation {
1413                target: cargo_path,
1414                target_relative: cargo_relative,
1415                before: Some(before),
1416                after,
1417            });
1418        }
1419    }
1420
1421    let mut seen_mutations = BTreeSet::new();
1422    for mutation in &mutations {
1423        if !seen_mutations.insert(mutation.target_relative.clone()) {
1424            bail!(
1425                "transaction contains multiple writes to `{}`",
1426                mutation.target_relative.display()
1427            );
1428        }
1429    }
1430
1431    Ok(PreparedTransaction {
1432        mutations,
1433        files_unchanged,
1434    })
1435}
1436
1437const MODULES_START: &str = "// proa-ui:modules:start";
1438const MODULES_END: &str = "// proa-ui:modules:end";
1439
1440fn collect_locked_immutable_files(lock: &ComponentLockFile) -> Result<BTreeSet<PathBuf>> {
1441    let mut collected = BTreeSet::new();
1442    for (component_id, component) in &lock.components {
1443        for target in &component.installed_files {
1444            validate_relative_path(
1445                target,
1446                &format!("locked immutable artifact target for `{component_id}`"),
1447            )?;
1448            collected.insert(target.clone());
1449        }
1450    }
1451    Ok(collected)
1452}
1453
1454fn collect_locked_modules(lock: &ComponentLockFile) -> Result<BTreeMap<PathBuf, BTreeSet<String>>> {
1455    let mut collected: BTreeMap<PathBuf, BTreeSet<String>> = BTreeMap::new();
1456    for (component_id, component) in &lock.components {
1457        for entry in &component.rust_modules {
1458            validate_relative_path(
1459                &entry.target,
1460                &format!("locked Rust module target for `{component_id}`"),
1461            )?;
1462            let target_modules = collected.entry(entry.target.clone()).or_default();
1463            for module in &entry.modules {
1464                validate_rust_module_name(module)
1465                    .with_context(|| format!("locked Rust module for `{component_id}`"))?;
1466                target_modules.insert(module.clone());
1467            }
1468        }
1469    }
1470    Ok(collected)
1471}
1472
1473fn update_managed_rust_modules(
1474    existing: Option<&[u8]>,
1475    expected_current: &BTreeSet<String>,
1476    next: &BTreeSet<String>,
1477    target: &Path,
1478) -> Result<Vec<u8>> {
1479    let existing = match existing {
1480        Some(bytes) => std::str::from_utf8(bytes).with_context(|| {
1481            format!("managed Rust module file {} is not UTF-8", target.display())
1482        })?,
1483        None => "",
1484    };
1485    let expected_block = managed_module_block(expected_current);
1486    let next_block = managed_module_block(next);
1487    let start = existing.find(MODULES_START);
1488    let end = existing.find(MODULES_END);
1489
1490    match (start, end) {
1491        (None, None) => {
1492            if !expected_current.is_empty() {
1493                bail!(
1494                    "managed Rust module block is missing from `{}` even though the lock records modules; refusing to reconstruct an edited file",
1495                    target.display()
1496                );
1497            }
1498            let mut output = existing.to_string();
1499            if !output.is_empty() && !output.ends_with('\n') {
1500                output.push('\n');
1501            }
1502            if !output.is_empty() {
1503                output.push('\n');
1504            }
1505            output.push_str(&next_block);
1506            Ok(output.into_bytes())
1507        }
1508        (Some(start), Some(end)) if start < end => {
1509            let end = end + MODULES_END.len();
1510            if existing[start..end] != expected_block {
1511                bail!(
1512                    "managed Rust module block in `{}` was edited locally; refusing to overwrite it",
1513                    target.display()
1514                );
1515            }
1516            if existing[end..].contains(MODULES_START) || existing[end..].contains(MODULES_END) {
1517                bail!(
1518                    "managed Rust module file `{}` contains duplicate marker blocks",
1519                    target.display()
1520                );
1521            }
1522            let mut output =
1523                String::with_capacity(existing.len() - expected_block.len() + next_block.len());
1524            output.push_str(&existing[..start]);
1525            output.push_str(&next_block);
1526            output.push_str(&existing[end..]);
1527            Ok(output.into_bytes())
1528        }
1529        _ => bail!(
1530            "managed Rust module file `{}` has incomplete or out-of-order markers",
1531            target.display()
1532        ),
1533    }
1534}
1535
1536fn managed_module_block(modules: &BTreeSet<String>) -> String {
1537    let mut block = String::from(MODULES_START);
1538    block.push('\n');
1539    for module in modules {
1540        block.push_str("pub mod ");
1541        block.push_str(module);
1542        block.push_str(";\npub use ");
1543        block.push_str(module);
1544        block.push_str("::*;\n");
1545    }
1546    block.push_str(MODULES_END);
1547    block
1548}
1549
1550#[derive(Debug)]
1551struct CargoDependencySpec {
1552    source: CargoDependencySourceSpec,
1553    features: BTreeSet<String>,
1554    default_features: Option<bool>,
1555}
1556
1557#[derive(Debug, Clone, PartialEq, Eq)]
1558enum CargoDependencySourceSpec {
1559    Path(PathBuf),
1560    Version {
1561        version: String,
1562        registry: Option<String>,
1563    },
1564    Git(String),
1565}
1566
1567fn collect_locked_cargo_dependencies(
1568    lock: &ComponentLockFile,
1569) -> Result<BTreeMap<String, CargoDependencySpec>> {
1570    let mut collected: BTreeMap<String, CargoDependencySpec> = BTreeMap::new();
1571    for (component_id, component) in &lock.components {
1572        for dependency in &component.cargo_dependencies {
1573            validate_cargo_dependency_name(&dependency.name)
1574                .with_context(|| format!("locked Cargo dependency for `{component_id}`"))?;
1575            let source = match (&dependency.path, &dependency.version, &dependency.git) {
1576                (Some(path), None, None) => {
1577                    validate_relative_path(
1578                        path,
1579                        &format!("locked Cargo dependency path for `{component_id}`"),
1580                    )?;
1581                    CargoDependencySourceSpec::Path(path.clone())
1582                }
1583                (None, Some(version), None) => {
1584                    validate_cargo_version(version)
1585                        .with_context(|| format!("locked Cargo dependency for `{component_id}`"))?;
1586                    if let Some(registry) = &dependency.registry {
1587                        validate_cargo_registry_name(registry).with_context(|| {
1588                            format!("locked Cargo dependency for `{component_id}`")
1589                        })?;
1590                    }
1591                    CargoDependencySourceSpec::Version {
1592                        version: version.clone(),
1593                        registry: dependency.registry.clone(),
1594                    }
1595                }
1596                (None, None, Some(git)) => {
1597                    if dependency.registry.is_some() {
1598                        bail!(
1599                            "locked Cargo dependency `{}` for `{component_id}` cannot combine `git` and `registry`",
1600                            dependency.name
1601                        );
1602                    }
1603                    validate_cargo_git_url(git)
1604                        .with_context(|| format!("locked Cargo dependency for `{component_id}`"))?;
1605                    CargoDependencySourceSpec::Git(git.clone())
1606                }
1607                _ => bail!(
1608                    "locked Cargo dependency `{}` for `{component_id}` must have exactly one of `path`, `version`, or `git`",
1609                    dependency.name
1610                ),
1611            };
1612            let spec =
1613                collected
1614                    .entry(dependency.name.clone())
1615                    .or_insert_with(|| CargoDependencySpec {
1616                        source: source.clone(),
1617                        features: BTreeSet::new(),
1618                        default_features: dependency.default_features,
1619                    });
1620            if spec.source != source {
1621                bail!(
1622                    "locked components disagree on source for Cargo dependency `{}`",
1623                    dependency.name
1624                );
1625            }
1626            if let (Some(existing), Some(next)) =
1627                (spec.default_features, dependency.default_features)
1628            {
1629                if existing != next {
1630                    bail!(
1631                        "locked components disagree on default features for Cargo dependency `{}`",
1632                        dependency.name
1633                    );
1634                }
1635            } else if spec.default_features.is_none() {
1636                spec.default_features = dependency.default_features;
1637            }
1638            for feature in &dependency.features {
1639                validate_cargo_feature_name(feature)
1640                    .with_context(|| format!("locked Cargo feature for `{component_id}`"))?;
1641                spec.features.insert(feature.clone());
1642            }
1643        }
1644    }
1645    Ok(collected)
1646}
1647
1648fn update_cargo_dependencies(
1649    existing: &[u8],
1650    dependencies: &BTreeMap<String, CargoDependencySpec>,
1651) -> Result<Vec<u8>> {
1652    use toml_edit::{DocumentMut, InlineTable, Item, Table, Value};
1653
1654    let source = std::str::from_utf8(existing).context("project Cargo.toml is not valid UTF-8")?;
1655    let mut document = source
1656        .parse::<DocumentMut>()
1657        .context("parse project Cargo.toml for Proa UI dependency")?;
1658    if !document.as_table().contains_key("dependencies") {
1659        document["dependencies"] = Item::Table(Table::new());
1660    }
1661    let dependency_table = document["dependencies"]
1662        .as_table_mut()
1663        .ok_or_else(|| anyhow::anyhow!("Cargo.toml `[dependencies]` is not a table"))?;
1664
1665    for (name, desired) in dependencies {
1666        let Some(existing) = dependency_table.get_mut(name) else {
1667            let mut table = InlineTable::new();
1668            match &desired.source {
1669                CargoDependencySourceSpec::Path(path) => {
1670                    table.insert("path", Value::from(path_for_toml(path)));
1671                }
1672                CargoDependencySourceSpec::Version { version, registry } => {
1673                    table.insert("version", Value::from(version.as_str()));
1674                    if let Some(registry) = registry {
1675                        table.insert("registry", Value::from(registry.as_str()));
1676                    }
1677                }
1678                CargoDependencySourceSpec::Git(url) => {
1679                    table.insert("git", Value::from(url.as_str()));
1680                }
1681            }
1682            if !desired.features.is_empty() {
1683                table.insert("features", Value::Array(feature_array(&desired.features)));
1684            }
1685            if let Some(default_features) = desired.default_features {
1686                table.insert("default-features", Value::from(default_features));
1687            }
1688            dependency_table.insert(name, Item::Value(Value::InlineTable(table)));
1689            continue;
1690        };
1691
1692        match (&desired.source, existing) {
1693            (
1694                CargoDependencySourceSpec::Path(path),
1695                Item::Value(Value::InlineTable(table)),
1696            ) => {
1697                verify_cargo_dependency_path(name, table.get("path"), path)?;
1698                merge_inline_dependency_options(name, table, desired)?;
1699            }
1700            (CargoDependencySourceSpec::Path(path), Item::Table(table)) => {
1701                let actual = table.get("path").and_then(Item::as_value);
1702                verify_cargo_dependency_path(name, actual, path)?;
1703                merge_table_dependency_options(name, table, desired)?;
1704            }
1705            (CargoDependencySourceSpec::Path(path), _) => bail!(
1706                "Cargo dependency `{name}` already exists but is not the required path dependency `{}`",
1707                path.display()
1708            ),
1709            (
1710                CargoDependencySourceSpec::Version { .. },
1711                Item::Value(Value::String(version)),
1712            ) => {
1713                let version = version.value().to_string();
1714                let mut table = InlineTable::new();
1715                table.insert("version", Value::from(version));
1716                merge_inline_dependency_options(name, &mut table, desired)?;
1717                *dependency_table
1718                    .get_mut(name)
1719                    .expect("dependency still exists") = Item::Value(Value::InlineTable(table));
1720            }
1721            (
1722                CargoDependencySourceSpec::Version { registry, .. },
1723                Item::Value(Value::InlineTable(table)),
1724            ) => {
1725                add_registry_if_unset_inline(table, registry.as_deref());
1726                merge_inline_dependency_options(name, table, desired)?;
1727            }
1728            (
1729                CargoDependencySourceSpec::Version { registry, .. },
1730                Item::Table(table),
1731            ) => {
1732                add_registry_if_unset_table(table, registry.as_deref());
1733                merge_table_dependency_options(name, table, desired)?;
1734            }
1735            (CargoDependencySourceSpec::Version { .. }, _) => {
1736                bail!("Cargo dependency `{name}` has an unsupported declaration")
1737            }
1738            (
1739                CargoDependencySourceSpec::Git(url),
1740                Item::Value(Value::InlineTable(table)),
1741            ) => {
1742                add_git_if_unset_inline(table, url);
1743                merge_inline_dependency_options(name, table, desired)?;
1744            }
1745            (CargoDependencySourceSpec::Git(url), Item::Table(table)) => {
1746                add_git_if_unset_table(table, url);
1747                merge_table_dependency_options(name, table, desired)?;
1748            }
1749            (CargoDependencySourceSpec::Git(_), Item::Value(Value::String(version))) => {
1750                // The host pins this crate by version; keep its choice and only
1751                // merge the requested features.
1752                let version = version.value().to_string();
1753                let mut table = InlineTable::new();
1754                table.insert("version", Value::from(version));
1755                merge_inline_dependency_options(name, &mut table, desired)?;
1756                *dependency_table
1757                    .get_mut(name)
1758                    .expect("dependency still exists") = Item::Value(Value::InlineTable(table));
1759            }
1760            (CargoDependencySourceSpec::Git(_), _) => {
1761                bail!("Cargo dependency `{name}` has an unsupported declaration")
1762            }
1763        }
1764    }
1765    Ok(document.to_string().into_bytes())
1766}
1767
1768fn add_git_if_unset_inline(table: &mut toml_edit::InlineTable, url: &str) {
1769    if table.get("path").is_none()
1770        && table.get("git").is_none()
1771        && table.get("workspace").is_none()
1772        && table.get("version").is_none()
1773        && table.get("registry").is_none()
1774    {
1775        table.insert("git", toml_edit::Value::from(url));
1776    }
1777}
1778
1779fn add_git_if_unset_table(table: &mut toml_edit::Table, url: &str) {
1780    if table.get("path").is_none()
1781        && table.get("git").is_none()
1782        && table.get("workspace").is_none()
1783        && table.get("version").is_none()
1784        && table.get("registry").is_none()
1785    {
1786        table.insert("git", toml_edit::Item::Value(toml_edit::Value::from(url)));
1787    }
1788}
1789
1790fn add_registry_if_unset_inline(table: &mut toml_edit::InlineTable, registry: Option<&str>) {
1791    if table.get("path").is_none()
1792        && table.get("git").is_none()
1793        && table.get("workspace").is_none()
1794        && table.get("registry").is_none()
1795    {
1796        if let Some(registry) = registry {
1797            table.insert("registry", toml_edit::Value::from(registry));
1798        }
1799    }
1800}
1801
1802fn add_registry_if_unset_table(table: &mut toml_edit::Table, registry: Option<&str>) {
1803    if table.get("path").is_none()
1804        && table.get("git").is_none()
1805        && table.get("workspace").is_none()
1806        && table.get("registry").is_none()
1807    {
1808        if let Some(registry) = registry {
1809            table.insert(
1810                "registry",
1811                toml_edit::Item::Value(toml_edit::Value::from(registry)),
1812            );
1813        }
1814    }
1815}
1816
1817fn verify_cargo_dependency_path(
1818    name: &str,
1819    value: Option<&toml_edit::Value>,
1820    desired: &Path,
1821) -> Result<()> {
1822    let Some(path) = value.and_then(toml_edit::Value::as_str) else {
1823        bail!(
1824            "Cargo dependency `{name}` already exists but is not the required path dependency `{}`",
1825            desired.display()
1826        );
1827    };
1828    let actual = normalize_existing_cargo_path(path)
1829        .with_context(|| format!("Cargo dependency `{name}` path"))?;
1830    if actual != desired {
1831        bail!(
1832            "Cargo dependency `{name}` points to `{path}`, but the component registry requires `{}`",
1833            desired.display()
1834        );
1835    }
1836    Ok(())
1837}
1838
1839fn normalize_existing_cargo_path(input: &str) -> Result<PathBuf> {
1840    let path = Path::new(input);
1841    if path.is_absolute() {
1842        bail!("absolute dependency paths are not managed by `proa ui add`");
1843    }
1844    let mut normalized = PathBuf::new();
1845    for component in path.components() {
1846        match component {
1847            Component::CurDir => {}
1848            Component::Normal(part) => normalized.push(part),
1849            _ => bail!("dependency path contains an unsafe path component"),
1850        }
1851    }
1852    if normalized.as_os_str().is_empty() {
1853        bail!("dependency path is empty");
1854    }
1855    Ok(normalized)
1856}
1857
1858fn merge_inline_dependency_options(
1859    name: &str,
1860    table: &mut toml_edit::InlineTable,
1861    desired: &CargoDependencySpec,
1862) -> Result<()> {
1863    let features = merged_feature_set(name, table.get("features"), &desired.features)?;
1864    if !features.is_empty() {
1865        table.insert(
1866            "features",
1867            toml_edit::Value::Array(feature_array(&features)),
1868        );
1869    }
1870    if table.get("default-features").is_none() {
1871        if let Some(default_features) = desired.default_features {
1872            table.insert("default-features", toml_edit::Value::from(default_features));
1873        }
1874    }
1875    Ok(())
1876}
1877
1878fn merge_table_dependency_options(
1879    name: &str,
1880    table: &mut toml_edit::Table,
1881    desired: &CargoDependencySpec,
1882) -> Result<()> {
1883    let existing = table.get("features").and_then(toml_edit::Item::as_value);
1884    let features = merged_feature_set(name, existing, &desired.features)?;
1885    if !features.is_empty() {
1886        table.insert(
1887            "features",
1888            toml_edit::Item::Value(toml_edit::Value::Array(feature_array(&features))),
1889        );
1890    }
1891    if table.get("default-features").is_none() {
1892        if let Some(default_features) = desired.default_features {
1893            table.insert(
1894                "default-features",
1895                toml_edit::Item::Value(toml_edit::Value::from(default_features)),
1896            );
1897        }
1898    }
1899    Ok(())
1900}
1901
1902fn merged_feature_set(
1903    name: &str,
1904    existing: Option<&toml_edit::Value>,
1905    desired: &BTreeSet<String>,
1906) -> Result<BTreeSet<String>> {
1907    let mut merged = desired.clone();
1908    if let Some(existing) = existing {
1909        let array = existing.as_array().ok_or_else(|| {
1910            anyhow::anyhow!("Cargo dependency `{name}` has a non-array `features` value")
1911        })?;
1912        for value in array.iter() {
1913            let feature = value.as_str().ok_or_else(|| {
1914                anyhow::anyhow!("Cargo dependency `{name}` has a non-string feature")
1915            })?;
1916            merged.insert(feature.to_string());
1917        }
1918    }
1919    Ok(merged)
1920}
1921
1922fn feature_array(features: &BTreeSet<String>) -> toml_edit::Array {
1923    let mut array = toml_edit::Array::new();
1924    for feature in features {
1925        array.push(feature.as_str());
1926    }
1927    array
1928}
1929
1930fn path_for_toml(path: &Path) -> String {
1931    path.components()
1932        .filter_map(|component| match component {
1933            Component::Normal(part) => Some(part.to_string_lossy()),
1934            _ => None,
1935        })
1936        .collect::<Vec<_>>()
1937        .join("/")
1938}
1939
1940fn commit_transaction(
1941    root: &Path,
1942    mutations: &[FileMutation],
1943    lock: &ComponentLockFile,
1944) -> Result<()> {
1945    let staging = unique_staging_dir(root)?;
1946    fs::create_dir(&staging)
1947        .with_context(|| format!("create transaction staging {}", staging.display()))?;
1948
1949    let result = (|| -> Result<()> {
1950        let files_dir = staging.join("files");
1951        fs::create_dir(&files_dir)
1952            .with_context(|| format!("create transaction files {}", files_dir.display()))?;
1953        let backups_dir = staging.join("backups");
1954        fs::create_dir(&backups_dir)
1955            .with_context(|| format!("create transaction backups {}", backups_dir.display()))?;
1956
1957        let mut all_mutations = mutations
1958            .iter()
1959            .map(|mutation| FileMutation {
1960                target: mutation.target.clone(),
1961                target_relative: mutation.target_relative.clone(),
1962                before: mutation.before.clone(),
1963                after: mutation.after.clone(),
1964            })
1965            .collect::<Vec<_>>();
1966        let lock_path = root.join(LOCK_FILE);
1967        let lock_before = match fs::read(&lock_path) {
1968            Ok(bytes) => Some(bytes),
1969            Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
1970            Err(error) => {
1971                return Err(error)
1972                    .with_context(|| format!("read component lock {}", lock_path.display()))
1973            }
1974        };
1975        let mut lock_after = serde_json::to_vec_pretty(lock).context("serialize proa.lock.json")?;
1976        lock_after.push(b'\n');
1977        all_mutations.push(FileMutation {
1978            target: lock_path,
1979            target_relative: PathBuf::from(LOCK_FILE),
1980            before: lock_before,
1981            after: lock_after,
1982        });
1983
1984        let mut staged_files = Vec::with_capacity(all_mutations.len());
1985        for (index, mutation) in all_mutations.iter().enumerate() {
1986            let staged = files_dir.join(index.to_string());
1987            write_new_file(&staged, &mutation.after)?;
1988            staged_files.push((staged, mutation));
1989        }
1990
1991        for (_, mutation) in &staged_files {
1992            ensure_no_symlink_path(root, &mutation.target_relative)?;
1993            if let Some(parent) = mutation.target.parent() {
1994                fs::create_dir_all(parent)
1995                    .with_context(|| format!("create install directory {}", parent.display()))?;
1996            }
1997        }
1998
1999        let mut applied: Vec<(PathBuf, Option<PathBuf>)> = Vec::with_capacity(staged_files.len());
2000        for (index, (staged, mutation)) in staged_files.iter().enumerate() {
2001            let current = match fs::read(&mutation.target) {
2002                Ok(bytes) => Some(bytes),
2003                Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
2004                Err(error) => {
2005                    rollback_applied_mutations(&applied);
2006                    return Err(error).with_context(|| {
2007                        format!("recheck install target {}", mutation.target.display())
2008                    });
2009                }
2010            };
2011            if current != mutation.before {
2012                rollback_applied_mutations(&applied);
2013                bail!(
2014                    "install target `{}` changed during the transaction; all published files were rolled back",
2015                    mutation.target_relative.display()
2016                );
2017            }
2018
2019            let backup = if mutation.before.is_some() {
2020                let backup = backups_dir.join(index.to_string());
2021                if let Err(error) = fs::rename(&mutation.target, &backup) {
2022                    rollback_applied_mutations(&applied);
2023                    return Err(error).with_context(|| {
2024                        format!("back up install target {}", mutation.target.display())
2025                    });
2026                }
2027                Some(backup)
2028            } else {
2029                None
2030            };
2031
2032            if let Err(error) = fs::rename(staged, &mutation.target) {
2033                if let Some(backup) = &backup {
2034                    let _ = fs::rename(backup, &mutation.target);
2035                }
2036                rollback_applied_mutations(&applied);
2037                return Err(error).with_context(|| {
2038                    format!(
2039                        "publish staged component file {}",
2040                        mutation.target_relative.display()
2041                    )
2042                });
2043            }
2044            applied.push((mutation.target.clone(), backup));
2045        }
2046        Ok(())
2047    })();
2048
2049    let cleanup = fs::remove_dir_all(&staging);
2050    match (result, cleanup) {
2051        (Err(error), _) => Err(error),
2052        (Ok(()), Err(error)) => {
2053            eprintln!(
2054                "warning: could not remove transaction staging {}: {error}",
2055                staging.display()
2056            );
2057            Ok(())
2058        }
2059        (Ok(()), Ok(())) => Ok(()),
2060    }
2061}
2062
2063fn rollback_applied_mutations(applied: &[(PathBuf, Option<PathBuf>)]) {
2064    for (target, backup) in applied.iter().rev() {
2065        if let Err(error) = fs::remove_file(target) {
2066            eprintln!(
2067                "warning: could not remove transaction output {} during rollback: {error}",
2068                target.display()
2069            );
2070        }
2071        if let Some(backup) = backup {
2072            if let Err(error) = fs::rename(backup, target) {
2073                eprintln!(
2074                    "warning: could not restore {} during rollback: {error}",
2075                    target.display()
2076                );
2077            }
2078        }
2079    }
2080}
2081
2082fn unique_staging_dir(root: &Path) -> Result<PathBuf> {
2083    let nanos = SystemTime::now()
2084        .duration_since(UNIX_EPOCH)
2085        .context("system clock is before Unix epoch")?
2086        .as_nanos();
2087    for attempt in 0..100_u32 {
2088        let candidate = root.join(format!(
2089            ".proa-ui-staging-{}-{nanos}-{attempt}",
2090            std::process::id()
2091        ));
2092        if !candidate.exists() {
2093            return Ok(candidate);
2094        }
2095    }
2096    bail!("could not allocate a unique Proa UI transaction staging directory")
2097}
2098
2099fn write_new_file(path: &Path, bytes: &[u8]) -> Result<()> {
2100    let mut file = fs::OpenOptions::new()
2101        .write(true)
2102        .create_new(true)
2103        .open(path)
2104        .with_context(|| format!("create {}", path.display()))?;
2105    file.write_all(bytes)
2106        .with_context(|| format!("write {}", path.display()))?;
2107    file.sync_all()
2108        .with_context(|| format!("sync {}", path.display()))
2109}
2110
2111fn canonical_project_root(root: &Path) -> Result<PathBuf> {
2112    let metadata =
2113        fs::metadata(root).with_context(|| format!("inspect project root {}", root.display()))?;
2114    if !metadata.is_dir() {
2115        bail!("project root {} is not a directory", root.display());
2116    }
2117    root.canonicalize()
2118        .with_context(|| format!("canonicalize project root {}", root.display()))
2119}
2120
2121fn with_registry_bearer_auth(
2122    request: RequestBuilder,
2123    registry: &str,
2124    token: Option<&str>,
2125) -> RequestBuilder {
2126    if registry != PRO_REGISTRY {
2127        return request;
2128    }
2129    match token.map(str::trim).filter(|token| !token.is_empty()) {
2130        Some(token) => request.bearer_auth(token),
2131        None => request,
2132    }
2133}
2134
2135fn pro_registry_bearer_token() -> Result<Option<String>> {
2136    let environment_token = pro_token_from_environment(|name| env::var(name))?;
2137    let cargo_home = cargo_home_dir();
2138    pro_registry_bearer_token_from_sources(environment_token.as_deref(), cargo_home.as_deref())
2139}
2140
2141fn pro_token_from_environment(
2142    read: impl Fn(&str) -> std::result::Result<String, env::VarError>,
2143) -> Result<Option<String>> {
2144    // Keep the old token variable as a compatibility fallback for Pro catalogs.
2145    for name in ["PROA_PRO_TOKEN", "CARGO_REGISTRIES_PROA_TOKEN"] {
2146        match read(name) {
2147            Ok(token) if !token.trim().is_empty() => return Ok(Some(token)),
2148            Ok(_) | Err(env::VarError::NotPresent) => {}
2149            Err(env::VarError::NotUnicode(_)) => bail!("{name} is not valid UTF-8"),
2150        }
2151    }
2152    Ok(None)
2153}
2154
2155fn cargo_home_dir() -> Option<PathBuf> {
2156    env::var_os("CARGO_HOME")
2157        .filter(|path| !path.is_empty())
2158        .map(PathBuf::from)
2159        .or_else(|| {
2160            env::var_os("HOME")
2161                .filter(|path| !path.is_empty())
2162                .map(|home| PathBuf::from(home).join(".cargo"))
2163        })
2164        .or_else(|| {
2165            env::var_os("USERPROFILE")
2166                .filter(|path| !path.is_empty())
2167                .map(|home| PathBuf::from(home).join(".cargo"))
2168        })
2169}
2170
2171fn pro_registry_bearer_token_from_sources(
2172    environment_token: Option<&str>,
2173    cargo_home: Option<&Path>,
2174) -> Result<Option<String>> {
2175    if let Some(token) = environment_token
2176        .map(str::trim)
2177        .filter(|token| !token.is_empty())
2178    {
2179        return Ok(Some(token.to_string()));
2180    }
2181
2182    let Some(cargo_home) = cargo_home else {
2183        return Ok(None);
2184    };
2185
2186    // Cargo gives the legacy extensionless file precedence when both exist.
2187    // Preserve existing Pro catalog credentials during migration.
2188    for name in ["credentials", "credentials.toml"] {
2189        let path = cargo_home.join(name);
2190        let contents = match fs::read_to_string(&path) {
2191            Ok(contents) => contents,
2192            Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
2193            Err(error) => {
2194                return Err(anyhow::anyhow!(
2195                    "read Cargo credentials file {}: {error}",
2196                    path.display()
2197                ));
2198            }
2199        };
2200        let credentials: toml::Value = contents.parse().map_err(|_| {
2201            // Do not attach the parser's source excerpt: this file contains secrets.
2202            anyhow::anyhow!("parse Cargo credentials file {}", path.display())
2203        })?;
2204        let Some(token) = credentials
2205            .get("registries")
2206            .and_then(|registries| registries.get("proa"))
2207            .and_then(|registry| registry.get("token"))
2208        else {
2209            return Ok(None);
2210        };
2211        let token = token.as_str().ok_or_else(|| {
2212            anyhow::anyhow!(
2213                "Cargo credentials entry `registries.proa.token` in {} must be a string",
2214                path.display()
2215            )
2216        })?;
2217        return Ok((!token.trim().is_empty()).then(|| token.trim().to_string()));
2218    }
2219
2220    Ok(None)
2221}
2222
2223fn bare_registry_fallback_error(
2224    slug: &str,
2225    public_not_found: &str,
2226    pro_error: FetchError,
2227) -> anyhow::Error {
2228    let pro_failure = match pro_error {
2229        FetchError::NotFound(detail) => format!("also returned not found ({detail})"),
2230        FetchError::Unauthorized(detail) => {
2231            format!("rejected the Pro lookup as unauthorized ({detail})")
2232        }
2233        FetchError::Failed(detail) => format!("could not be fetched ({detail})"),
2234    };
2235    anyhow::anyhow!(
2236        "component `{slug}` was not found in the public Free registry `{PUBLIC_REGISTRY}` \
2237         ({public_not_found}). Bare slugs then fall back to the licensed Pro registry \
2238         `{PRO_REGISTRY}`, which {pro_failure}. Free registry access does not require a bearer \
2239         token. To limit resolution to the public registry, use `{PUBLIC_REGISTRY}/{slug}` or \
2240         `--registry {PUBLIC_REGISTRY}`. No project files were changed."
2241    )
2242}
2243
2244fn fetch_error_to_anyhow(registry: &str, slug: &str, error: FetchError) -> anyhow::Error {
2245    match error {
2246        FetchError::Unauthorized(detail) if registry == PRO_REGISTRY => anyhow::anyhow!(
2247            "Pro component `{slug}` requires authenticated `{PRO_REGISTRY}` access ({detail}). \
2248             Provide its bearer token through PROA_PRO_TOKEN. No project files were changed."
2249        ),
2250        FetchError::NotFound(detail) => anyhow::anyhow!(
2251            "component `{registry}/{slug}` was not found ({detail}). No project files were changed."
2252        ),
2253        FetchError::Unauthorized(detail) => anyhow::anyhow!(
2254            "registry `{registry}` rejected component `{slug}` ({detail}). No project files were changed."
2255        ),
2256        FetchError::Failed(detail) => anyhow::anyhow!(
2257            "could not fetch component `{registry}/{slug}`: {detail}. \
2258             Component artifacts may not be published at the configured endpoint yet. \
2259             Check `proa.config.json` with `proa registry list`. No project files were changed."
2260        ),
2261    }
2262}
2263
2264#[cfg(test)]
2265mod tests;