wasmer_config/package/
mod.rs

1//! Wasmer package definitions.
2//!
3//! Describes the contents of a `wasmer.toml` file.
4
5#![allow(deprecated)]
6
7mod error;
8mod named_package_ident;
9mod package_hash;
10mod package_id;
11mod package_ident;
12mod package_source;
13
14pub use self::{
15    error::PackageParseError,
16    named_package_ident::{NamedPackageIdent, Tag},
17    package_hash::PackageHash,
18    package_id::{NamedPackageId, PackageId},
19    package_ident::PackageIdent,
20    package_source::PackageSource,
21};
22
23use std::{
24    borrow::Cow,
25    collections::{BTreeMap, BTreeSet},
26    fmt::{self, Display},
27    path::{Path, PathBuf},
28    str::FromStr,
29};
30
31use indexmap::IndexMap;
32use semver::{Version, VersionReq};
33use serde::{Deserialize, Serialize, de::Error as _};
34use thiserror::Error;
35
36/// The ABI is a hint to WebAssembly runtimes about what additional imports to
37/// insert and how a module may be run.
38///
39/// If not specified, [`Abi::None`] is the default.
40#[derive(Clone, Copy, Default, Debug, Deserialize, Serialize, PartialEq, Eq)]
41#[non_exhaustive]
42pub enum Abi {
43    #[default]
44    #[serde(rename = "none")]
45    None,
46    #[serde(rename = "wasi")]
47    Wasi,
48    #[serde(rename = "wasm4")]
49    WASM4,
50}
51
52impl Abi {
53    /// Get the ABI's human-friendly name.
54    pub fn to_str(&self) -> &str {
55        match self {
56            Abi::Wasi => "wasi",
57            Abi::WASM4 => "wasm4",
58            Abi::None => "generic",
59        }
60    }
61
62    /// Is this a [`Abi::None`]?
63    pub fn is_none(&self) -> bool {
64        matches!(self, Abi::None)
65    }
66
67    /// Create an [`Abi`] from its human-friendly name.
68    pub fn from_name(name: &str) -> Self {
69        name.parse().unwrap_or(Abi::None)
70    }
71}
72
73impl fmt::Display for Abi {
74    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
75        write!(f, "{}", self.to_str())
76    }
77}
78
79impl FromStr for Abi {
80    type Err = Box<dyn std::error::Error + Send + Sync>;
81
82    fn from_str(s: &str) -> Result<Self, Self::Err> {
83        match s.to_lowercase().as_str() {
84            "wasi" => Ok(Abi::Wasi),
85            "wasm4" => Ok(Abi::WASM4),
86            "generic" => Ok(Abi::None),
87            _ => Err(format!("Unknown ABI, \"{s}\"").into()),
88        }
89    }
90}
91
92/// The default name for the manifest file.
93pub static MANIFEST_FILE_NAME: &str = "wasmer.toml";
94
95const README_PATHS: &[&str; 5] = &[
96    "README",
97    "README.md",
98    "README.markdown",
99    "README.mdown",
100    "README.mkdn",
101];
102
103const LICENSE_PATHS: &[&str; 3] = &["LICENSE", "LICENSE.md", "COPYING"];
104
105/// Package definition for a Wasmer package.
106///
107/// Usually stored in a `wasmer.toml` file.
108#[derive(Clone, Debug, Deserialize, Serialize, derive_builder::Builder)]
109#[non_exhaustive]
110pub struct Package {
111    /// The package's name in the form `namespace/name`.
112    #[builder(setter(into, strip_option), default)]
113    pub name: Option<String>,
114    /// The package's version number.
115    #[builder(setter(into, strip_option), default)]
116    pub version: Option<Version>,
117    /// A brief description of the package.
118    #[builder(setter(into, strip_option), default)]
119    pub description: Option<String>,
120    /// A SPDX license specifier for this package.
121    #[builder(setter(into, strip_option), default)]
122    pub license: Option<String>,
123    /// The location of the license file, useful for non-standard licenses
124    #[serde(rename = "license-file")]
125    #[builder(setter(into, strip_option), default)]
126    pub license_file: Option<PathBuf>,
127    /// The package's README file.
128    #[serde(skip_serializing_if = "Option::is_none")]
129    #[builder(setter(into, strip_option), default)]
130    pub readme: Option<PathBuf>,
131    /// A URL pointing to the package's source code.
132    #[serde(skip_serializing_if = "Option::is_none")]
133    #[builder(setter(into, strip_option), default)]
134    pub repository: Option<String>,
135    /// The website used as the package's homepage.
136    #[serde(skip_serializing_if = "Option::is_none")]
137    #[builder(setter(into, strip_option), default)]
138    pub homepage: Option<String>,
139    #[serde(rename = "wasmer-extra-flags")]
140    #[builder(setter(into, strip_option), default)]
141    #[deprecated(
142        since = "0.9.2",
143        note = "Use runner-specific command attributes instead"
144    )]
145    pub wasmer_extra_flags: Option<String>,
146    #[serde(
147        rename = "disable-command-rename",
148        default,
149        skip_serializing_if = "std::ops::Not::not"
150    )]
151    #[builder(default)]
152    #[deprecated(
153        since = "0.9.2",
154        note = "Does nothing. Prefer a runner-specific command attribute instead"
155    )]
156    pub disable_command_rename: bool,
157    /// Unlike, `disable-command-rename` which prevents `wasmer run <Module name>`,
158    /// this flag enables the command rename of `wasmer run <COMMAND_NAME>` into
159    /// just `<COMMAND_NAME>`. This is useful for programs that need to inspect
160    /// their `argv[0]` names and when the command name matches their executable
161    /// name.
162    #[serde(
163        rename = "rename-commands-to-raw-command-name",
164        default,
165        skip_serializing_if = "std::ops::Not::not"
166    )]
167    #[builder(default)]
168    #[deprecated(
169        since = "0.9.2",
170        note = "Does nothing. Prefer a runner-specific command attribute instead"
171    )]
172    pub rename_commands_to_raw_command_name: bool,
173    /// The name of the command that should be used by `wasmer run` by default.
174    #[serde(skip_serializing_if = "Option::is_none")]
175    #[builder(setter(into, strip_option), default)]
176    pub entrypoint: Option<String>,
177    /// Mark this as a private package
178    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
179    #[builder(default)]
180    pub private: bool,
181}
182
183impl Package {
184    pub fn new_empty() -> Self {
185        PackageBuilder::default().build().unwrap()
186    }
187
188    /// Create a [`PackageBuilder`] populated with all mandatory fields.
189    pub fn builder(
190        name: impl Into<String>,
191        version: Version,
192        description: impl Into<String>,
193    ) -> PackageBuilder {
194        PackageBuilder::new(name, version, description)
195    }
196}
197
198impl PackageBuilder {
199    pub fn new(name: impl Into<String>, version: Version, description: impl Into<String>) -> Self {
200        let mut builder = PackageBuilder::default();
201        builder.name(name).version(version).description(description);
202        builder
203    }
204}
205
206#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
207#[serde(untagged)]
208pub enum Command {
209    V1(CommandV1),
210    V2(CommandV2),
211}
212
213impl Command {
214    /// Get the command's name.
215    pub fn get_name(&self) -> &str {
216        match self {
217            Self::V1(c) => &c.name,
218            Self::V2(c) => &c.name,
219        }
220    }
221
222    /// Get the module this [`Command`] refers to.
223    pub fn get_module(&self) -> &ModuleReference {
224        match self {
225            Self::V1(c) => &c.module,
226            Self::V2(c) => &c.module,
227        }
228    }
229}
230
231/// Describes a command for a wasmer module.
232///
233/// When a command is deserialized using [`CommandV1`], the runner is inferred
234/// by looking at the [`Abi`] from the [`Module`] it refers to.
235///
236/// If possible, prefer to use the [`CommandV2`] format.
237#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
238#[serde(deny_unknown_fields)] // Note: needed to prevent accidentally parsing
239// a CommandV2 as a CommandV1
240#[deprecated(since = "0.9.2", note = "Prefer the CommandV2 syntax")]
241pub struct CommandV1 {
242    pub name: String,
243    pub module: ModuleReference,
244    pub main_args: Option<String>,
245    pub package: Option<String>,
246}
247
248/// An executable command.
249#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
250pub struct CommandV2 {
251    /// The name of the command.
252    pub name: String,
253    /// The module containing this command's executable.
254    pub module: ModuleReference,
255    /// The runner to use when running this command.
256    ///
257    /// This may be a URL, or the well-known runners `wasi` or `wcgi`
258    pub runner: String,
259    /// Extra annotations that will be consumed by the runner.
260    pub annotations: Option<CommandAnnotations>,
261}
262
263impl CommandV2 {
264    /// Get annotations, automatically loading them from a file relative to the
265    /// `wasmer.toml`'s directory, if necessary.
266    pub fn get_annotations(&self, basepath: &Path) -> Result<Option<ciborium::Value>, String> {
267        match self.annotations.as_ref() {
268            Some(CommandAnnotations::Raw(v)) => Ok(Some(toml_to_cbor_value(v))),
269            Some(CommandAnnotations::File(FileCommandAnnotations { file, kind })) => {
270                let path = basepath.join(file.clone());
271                let file = std::fs::read_to_string(&path).map_err(|e| {
272                    format!(
273                        "Error reading {:?}.annotation ({:?}): {e}",
274                        self.name,
275                        path.display()
276                    )
277                })?;
278                match kind {
279                    FileKind::Json => {
280                        let value: serde_json::Value =
281                            serde_json::from_str(&file).map_err(|e| {
282                                format!(
283                                    "Error reading {:?}.annotation ({:?}): {e}",
284                                    self.name,
285                                    path.display()
286                                )
287                            })?;
288                        Ok(Some(json_to_cbor_value(&value)))
289                    }
290                    FileKind::Yaml => {
291                        let value: serde_yaml::Value =
292                            serde_yaml::from_str(&file).map_err(|e| {
293                                format!(
294                                    "Error reading {:?}.annotation ({:?}): {e}",
295                                    self.name,
296                                    path.display()
297                                )
298                            })?;
299                        Ok(Some(yaml_to_cbor_value(&value)))
300                    }
301                }
302            }
303            None => Ok(None),
304        }
305    }
306}
307
308/// A reference to a module which may or may not come from another package.
309///
310/// # Serialization
311///
312/// A [`ModuleReference`] is serialized via its [`String`] representation.
313#[derive(Clone, Debug, PartialEq)]
314pub enum ModuleReference {
315    /// A module in the current package.
316    CurrentPackage {
317        /// The name of the module.
318        module: String,
319    },
320    /// A module that will be provided by a dependency, in `dependency:module`
321    /// form.
322    Dependency {
323        /// The name of the dependency the module comes from.
324        dependency: String,
325        /// The name of the module.
326        module: String,
327    },
328}
329
330impl Serialize for ModuleReference {
331    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
332    where
333        S: serde::Serializer,
334    {
335        self.to_string().serialize(serializer)
336    }
337}
338
339impl<'de> Deserialize<'de> for ModuleReference {
340    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
341    where
342        D: serde::Deserializer<'de>,
343    {
344        let repr: Cow<'de, str> = Cow::deserialize(deserializer)?;
345        repr.parse().map_err(D::Error::custom)
346    }
347}
348
349impl FromStr for ModuleReference {
350    type Err = Box<dyn std::error::Error + Send + Sync>;
351
352    fn from_str(s: &str) -> Result<Self, Self::Err> {
353        match s.split_once(':') {
354            Some((dependency, module)) => {
355                if module.contains(':') {
356                    return Err("Invalid format".into());
357                }
358
359                Ok(ModuleReference::Dependency {
360                    dependency: dependency.to_string(),
361                    module: module.to_string(),
362                })
363            }
364            None => Ok(ModuleReference::CurrentPackage {
365                module: s.to_string(),
366            }),
367        }
368    }
369}
370
371impl Display for ModuleReference {
372    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
373        match self {
374            ModuleReference::CurrentPackage { module } => Display::fmt(module, f),
375            ModuleReference::Dependency { dependency, module } => {
376                write!(f, "{dependency}:{module}")
377            }
378        }
379    }
380}
381
382fn toml_to_cbor_value(val: &toml::Value) -> ciborium::Value {
383    match val {
384        toml::Value::String(s) => ciborium::Value::Text(s.clone()),
385        toml::Value::Integer(i) => ciborium::Value::Integer(ciborium::value::Integer::from(*i)),
386        toml::Value::Float(f) => ciborium::Value::Float(*f),
387        toml::Value::Boolean(b) => ciborium::Value::Bool(*b),
388        toml::Value::Datetime(d) => ciborium::Value::Text(format!("{d}")),
389        toml::Value::Array(sq) => {
390            ciborium::Value::Array(sq.iter().map(toml_to_cbor_value).collect())
391        }
392        toml::Value::Table(m) => ciborium::Value::Map(
393            m.iter()
394                .map(|(k, v)| (ciborium::Value::Text(k.clone()), toml_to_cbor_value(v)))
395                .collect(),
396        ),
397    }
398}
399
400fn json_to_cbor_value(val: &serde_json::Value) -> ciborium::Value {
401    match val {
402        serde_json::Value::Null => ciborium::Value::Null,
403        serde_json::Value::Bool(b) => ciborium::Value::Bool(*b),
404        serde_json::Value::Number(n) => {
405            if let Some(i) = n.as_i64() {
406                ciborium::Value::Integer(ciborium::value::Integer::from(i))
407            } else if let Some(u) = n.as_u64() {
408                ciborium::Value::Integer(ciborium::value::Integer::from(u))
409            } else if let Some(f) = n.as_f64() {
410                ciborium::Value::Float(f)
411            } else {
412                ciborium::Value::Null
413            }
414        }
415        serde_json::Value::String(s) => ciborium::Value::Text(s.clone()),
416        serde_json::Value::Array(sq) => {
417            ciborium::Value::Array(sq.iter().map(json_to_cbor_value).collect())
418        }
419        serde_json::Value::Object(m) => ciborium::Value::Map(
420            m.iter()
421                .map(|(k, v)| (ciborium::Value::Text(k.clone()), json_to_cbor_value(v)))
422                .collect(),
423        ),
424    }
425}
426
427fn yaml_to_cbor_value(val: &serde_yaml::Value) -> ciborium::Value {
428    match val {
429        serde_yaml::Value::Null => ciborium::Value::Null,
430        serde_yaml::Value::Bool(b) => ciborium::Value::Bool(*b),
431        serde_yaml::Value::Number(n) => {
432            if let Some(i) = n.as_i64() {
433                ciborium::Value::Integer(ciborium::value::Integer::from(i))
434            } else if let Some(u) = n.as_u64() {
435                ciborium::Value::Integer(ciborium::value::Integer::from(u))
436            } else if let Some(f) = n.as_f64() {
437                ciborium::Value::Float(f)
438            } else {
439                ciborium::Value::Null
440            }
441        }
442        serde_yaml::Value::String(s) => ciborium::Value::Text(s.clone()),
443        serde_yaml::Value::Sequence(sq) => {
444            ciborium::Value::Array(sq.iter().map(yaml_to_cbor_value).collect())
445        }
446        serde_yaml::Value::Mapping(m) => ciborium::Value::Map(
447            m.iter()
448                .map(|(k, v)| (yaml_to_cbor_value(k), yaml_to_cbor_value(v)))
449                .collect(),
450        ),
451        serde_yaml::Value::Tagged(tag) => yaml_to_cbor_value(&tag.value),
452    }
453}
454
455/// Annotations for a command.
456#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
457#[serde(untagged)]
458#[repr(C)]
459pub enum CommandAnnotations {
460    /// Annotations that will be read from a file on disk.
461    File(FileCommandAnnotations),
462    /// Annotations that are specified inline.
463    Raw(toml::Value),
464}
465
466/// Annotations on disk.
467#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
468pub struct FileCommandAnnotations {
469    /// The path to the annotations file.
470    pub file: PathBuf,
471    /// Which format are the annotations saved in?
472    pub kind: FileKind,
473}
474
475/// The different formats that [`FileCommandAnnotations`] can be saved in.
476#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Ord, Eq, Deserialize, Serialize)]
477pub enum FileKind {
478    /// A `*.yaml` file that will be deserialized using [`serde_yaml`].
479    #[serde(rename = "yaml")]
480    Yaml,
481    /// A `*.json` file that will be deserialized using [`serde_json`].
482    #[serde(rename = "json")]
483    Json,
484}
485
486/// A file which may be executed by a [`Command`]. Sometimes also referred to as
487/// an "atom".
488#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
489pub struct Module {
490    /// The name used to refer to this module.
491    pub name: String,
492    /// The location of the module file on disk, relative to the manifest
493    /// directory.
494    pub source: PathBuf,
495    /// The ABI this module satisfies.
496    #[serde(default = "Abi::default", skip_serializing_if = "Abi::is_none")]
497    pub abi: Abi,
498    #[serde(default)]
499    pub kind: Option<String>,
500    /// WebAssembly interfaces this module requires.
501    #[serde(skip_serializing_if = "Option::is_none")]
502    pub interfaces: Option<IndexMap<String, String>>,
503    /// Interface definitions that can be used to generate bindings to this
504    /// module.
505    pub bindings: Option<Bindings>,
506    /// Miscellaneous annotations from the user.
507    #[serde(skip_serializing_if = "Option::is_none")]
508    pub annotations: Option<UserAnnotations>,
509}
510
511/// Miscellaneous annotations specified by the user.
512#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize, Default)]
513pub struct UserAnnotations {
514    pub suggested_compiler_optimizations: SuggestedCompilerOptimizations,
515}
516
517/// Suggested optimization that might be operated on the module when (and if) compiled.
518#[derive(Clone, Debug, PartialEq, Eq, Hash, Deserialize, Serialize, Default)]
519pub struct SuggestedCompilerOptimizations {
520    pub pass_params: Option<bool>,
521}
522
523impl SuggestedCompilerOptimizations {
524    pub const KEY: &'static str = "suggested_compiler_optimizations";
525    pub const PASS_PARAMS_KEY: &'static str = "pass_params";
526}
527
528/// The interface exposed by a [`Module`].
529#[derive(Clone, Debug, PartialEq, Eq)]
530pub enum Bindings {
531    Wit(WitBindings),
532    Wai(WaiBindings),
533}
534
535impl Bindings {
536    /// Get all files that make up this interface.
537    ///
538    /// For all binding types except [`WitBindings`], this will recursively
539    /// look for any files that are imported.
540    ///
541    /// The caller can assume that any path that was referenced exists.
542    pub fn referenced_files(&self, base_directory: &Path) -> Result<Vec<PathBuf>, ImportsError> {
543        match self {
544            Bindings::Wit(WitBindings { wit_exports, .. }) => {
545                // Note: we explicitly don't support imported files with WIT
546                // because wit-bindgen's wit-parser crate isn't on crates.io.
547
548                let path = base_directory.join(wit_exports);
549
550                if path.exists() {
551                    Ok(vec![path])
552                } else {
553                    Err(ImportsError::FileNotFound(path))
554                }
555            }
556            Bindings::Wai(wai) => wai.referenced_files(base_directory),
557        }
558    }
559}
560
561impl Serialize for Bindings {
562    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
563    where
564        S: serde::Serializer,
565    {
566        match self {
567            Bindings::Wit(w) => w.serialize(serializer),
568            Bindings::Wai(w) => w.serialize(serializer),
569        }
570    }
571}
572
573impl<'de> Deserialize<'de> for Bindings {
574    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
575    where
576        D: serde::Deserializer<'de>,
577    {
578        let value = toml::Value::deserialize(deserializer)?;
579
580        let keys = ["wit-bindgen", "wai-version"];
581        let [wit_bindgen, wai_version] = keys.map(|key| value.get(key).is_some());
582
583        match (wit_bindgen, wai_version) {
584            (true, false) => WitBindings::deserialize(value)
585                .map(Bindings::Wit)
586                .map_err(D::Error::custom),
587            (false, true) => WaiBindings::deserialize(value)
588                .map(Bindings::Wai)
589                .map_err(D::Error::custom),
590            (true, true) | (false, false) => {
591                let msg = format!(
592                    "expected one of \"{}\" to be provided, but not both",
593                    keys.join("\" or \""),
594                );
595                Err(D::Error::custom(msg))
596            }
597        }
598    }
599}
600
601#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
602#[serde(rename_all = "kebab-case")]
603pub struct WitBindings {
604    /// The version of the WIT format being used.
605    pub wit_bindgen: Version,
606    /// The `*.wit` file's location on disk.
607    pub wit_exports: PathBuf,
608}
609
610#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
611#[serde(rename_all = "kebab-case")]
612pub struct WaiBindings {
613    /// The version of the WAI format being used.
614    pub wai_version: Version,
615    /// The `*.wai` file defining the interface this package exposes.
616    pub exports: Option<PathBuf>,
617    /// The `*.wai` files for any functionality this package imports from the
618    /// host.
619    #[serde(default, skip_serializing_if = "Vec::is_empty")]
620    pub imports: Vec<PathBuf>,
621}
622
623impl WaiBindings {
624    fn referenced_files(&self, base_directory: &Path) -> Result<Vec<PathBuf>, ImportsError> {
625        let WaiBindings {
626            exports, imports, ..
627        } = self;
628
629        // Note: WAI files may import other WAI files, so we start with all
630        // WAI files mentioned in the wasmer.toml then recursively add their
631        // imports.
632
633        let initial_paths = exports
634            .iter()
635            .chain(imports)
636            .map(|relative_path| base_directory.join(relative_path));
637
638        let mut to_check: Vec<PathBuf> = Vec::new();
639
640        for path in initial_paths {
641            if !path.exists() {
642                return Err(ImportsError::FileNotFound(path));
643            }
644            to_check.push(path);
645        }
646
647        let mut files = BTreeSet::new();
648
649        while let Some(path) = to_check.pop() {
650            if files.contains(&path) {
651                continue;
652            }
653
654            to_check.extend(get_imported_wai_files(&path)?);
655            files.insert(path);
656        }
657
658        Ok(files.into_iter().collect())
659    }
660}
661
662/// Parse a `*.wai` file to find the absolute path for any other `*.wai` files
663/// it may import, relative to the original `*.wai` file.
664///
665/// This function makes sure any imported files exist.
666fn get_imported_wai_files(path: &Path) -> Result<Vec<PathBuf>, ImportsError> {
667    let _wai_src = std::fs::read_to_string(path).map_err(|error| ImportsError::Read {
668        path: path.to_path_buf(),
669        error,
670    })?;
671
672    let parent_dir = path.parent()
673            .expect("All paths should have a parent directory because we joined them relative to the base directory");
674
675    // TODO(Michael-F-Bryan): update the wai-parser crate to give you access to
676    // the imported interfaces. For now, we just pretend there are no import
677    // statements in the *.wai file.
678    let raw_imports: Vec<String> = Vec::new();
679
680    // Note: imported paths in a *.wai file are all relative, so we need to
681    // resolve their absolute path relative to the original *.wai file.
682    let mut resolved_paths = Vec::new();
683
684    for imported in raw_imports {
685        let absolute_path = parent_dir.join(imported);
686
687        if !absolute_path.exists() {
688            return Err(ImportsError::ImportedFileNotFound {
689                path: absolute_path,
690                referenced_by: path.to_path_buf(),
691            });
692        }
693
694        resolved_paths.push(absolute_path);
695    }
696
697    Ok(resolved_paths)
698}
699
700/// Errors that may occur when resolving [`Bindings`] imports.
701#[derive(Debug, thiserror::Error)]
702#[non_exhaustive]
703pub enum ImportsError {
704    #[error(
705        "The \"{}\" mentioned in the manifest doesn't exist",
706        _0.display(),
707    )]
708    FileNotFound(PathBuf),
709    #[error(
710        "The \"{}\" imported by \"{}\" doesn't exist",
711        path.display(),
712        referenced_by.display(),
713    )]
714    ImportedFileNotFound {
715        path: PathBuf,
716        referenced_by: PathBuf,
717    },
718    #[error("Unable to parse \"{}\" as a WAI file", path.display())]
719    WaiParse { path: PathBuf },
720    #[error("Unable to read \"{}\"", path.display())]
721    Read {
722        path: PathBuf,
723        #[source]
724        error: std::io::Error,
725    },
726}
727
728/// The manifest represents the file used to describe a Wasm package.
729#[derive(Clone, Debug, Deserialize, Serialize, derive_builder::Builder)]
730#[non_exhaustive]
731pub struct Manifest {
732    /// Metadata about the package itself.
733    pub package: Option<Package>,
734    /// The package's dependencies.
735    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
736    #[builder(default)]
737    pub dependencies: IndexMap<String, VersionReq>,
738    /// The mappings used when making bundled assets available to WebAssembly
739    /// instances, in the form guest -> host.
740    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
741    #[builder(default)]
742    pub fs: IndexMap<String, PathBuf>,
743    /// WebAssembly modules to be published.
744    #[serde(default, rename = "module", skip_serializing_if = "Vec::is_empty")]
745    #[builder(default)]
746    pub modules: Vec<Module>,
747    /// Commands the package makes available to users.
748    #[serde(default, rename = "command", skip_serializing_if = "Vec::is_empty")]
749    #[builder(default)]
750    pub commands: Vec<Command>,
751}
752
753impl Manifest {
754    pub fn new_empty() -> Self {
755        Self {
756            package: None,
757            dependencies: IndexMap::new(),
758            fs: IndexMap::new(),
759            modules: Vec::new(),
760            commands: Vec::new(),
761        }
762    }
763
764    /// Create a [`ManifestBuilder`] populated with all mandatory fields.
765    pub fn builder(package: Package) -> ManifestBuilder {
766        ManifestBuilder::new(package)
767    }
768
769    /// Parse a [`Manifest`] from its TOML representation.
770    pub fn parse(s: &str) -> Result<Self, toml::de::Error> {
771        toml::from_str(s)
772    }
773
774    /// Construct a manifest by searching in the specified directory for a
775    /// manifest file.
776    pub fn find_in_directory<T: AsRef<Path>>(path: T) -> Result<Self, ManifestError> {
777        let path = path.as_ref();
778
779        if !path.is_dir() {
780            return Err(ManifestError::MissingManifest(path.to_path_buf()));
781        }
782        let manifest_path_buf = path.join(MANIFEST_FILE_NAME);
783        let contents = std::fs::read_to_string(&manifest_path_buf)
784            .map_err(|_e| ManifestError::MissingManifest(manifest_path_buf))?;
785        let mut manifest: Self = toml::from_str(contents.as_str())?;
786
787        if let Some(package) = manifest.package.as_mut() {
788            if package.readme.is_none() {
789                package.readme = locate_file(path, README_PATHS);
790            }
791
792            if package.license_file.is_none() {
793                package.license_file = locate_file(path, LICENSE_PATHS);
794            }
795        }
796        manifest.validate()?;
797
798        Ok(manifest)
799    }
800
801    /// Validate this [`Manifest`] to check for common semantic errors.
802    ///
803    /// Some common error cases are:
804    ///
805    /// - Having multiple modules with the same name
806    /// - Having multiple commands with the same name
807    /// - A [`Command`] that references a non-existent [`Module`] in the current
808    ///   package
809    /// - A [`Package::entrypoint`] which points to a non-existent [`Command`]
810    pub fn validate(&self) -> Result<(), ValidationError> {
811        let mut modules = BTreeMap::new();
812
813        for module in &self.modules {
814            let is_duplicate = modules.insert(&module.name, module).is_some();
815
816            if is_duplicate {
817                return Err(ValidationError::DuplicateModule {
818                    name: module.name.clone(),
819                });
820            }
821        }
822
823        let mut commands = BTreeMap::new();
824
825        for command in &self.commands {
826            let is_duplicate = commands.insert(command.get_name(), command).is_some();
827
828            if is_duplicate {
829                return Err(ValidationError::DuplicateCommand {
830                    name: command.get_name().to_string(),
831                });
832            }
833
834            let module_reference = command.get_module();
835            match &module_reference {
836                ModuleReference::CurrentPackage { module } => {
837                    if let Some(module) = modules.get(&module) {
838                        if module.abi == Abi::None && module.interfaces.is_none() {
839                            return Err(ValidationError::MissingABI {
840                                command: command.get_name().to_string(),
841                                module: module.name.clone(),
842                            });
843                        }
844                    } else {
845                        return Err(ValidationError::MissingModuleForCommand {
846                            command: command.get_name().to_string(),
847                            module: command.get_module().clone(),
848                        });
849                    }
850                }
851                ModuleReference::Dependency { dependency, .. } => {
852                    // We don't have access to the dependency so just assume
853                    // the module is correct.
854                    if !self.dependencies.contains_key(dependency) {
855                        return Err(ValidationError::MissingDependency {
856                            command: command.get_name().to_string(),
857                            dependency: dependency.clone(),
858                            module_ref: module_reference.clone(),
859                        });
860                    }
861                }
862            }
863        }
864
865        if let Some(package) = &self.package
866            && let Some(entrypoint) = package.entrypoint.as_deref()
867            && !commands.contains_key(entrypoint)
868        {
869            return Err(ValidationError::InvalidEntrypoint {
870                entrypoint: entrypoint.to_string(),
871                available_commands: commands.keys().map(ToString::to_string).collect(),
872            });
873        }
874
875        Ok(())
876    }
877
878    /// add a dependency
879    pub fn add_dependency(&mut self, dependency_name: String, dependency_version: VersionReq) {
880        self.dependencies
881            .insert(dependency_name, dependency_version);
882    }
883
884    /// remove dependency by package name
885    pub fn remove_dependency(&mut self, dependency_name: &str) -> Option<VersionReq> {
886        self.dependencies.remove(dependency_name)
887    }
888
889    /// Convert a [`Manifest`] to its TOML representation.
890    pub fn to_string(&self) -> anyhow::Result<String> {
891        let repr = toml::to_string_pretty(&self)?;
892        Ok(repr)
893    }
894
895    /// Write the manifest to permanent storage
896    pub fn save(&self, path: impl AsRef<Path>) -> anyhow::Result<()> {
897        let manifest = toml::to_string_pretty(self)?;
898        std::fs::write(path, manifest).map_err(ManifestError::CannotSaveManifest)?;
899        Ok(())
900    }
901}
902
903fn locate_file(path: &Path, candidates: &[&str]) -> Option<PathBuf> {
904    for filename in candidates {
905        let path_buf = path.join(filename);
906        if path_buf.exists() {
907            return Some(filename.into());
908        }
909    }
910    None
911}
912
913impl ManifestBuilder {
914    pub fn new(package: Package) -> Self {
915        let mut builder = ManifestBuilder::default();
916        builder.package(Some(package));
917        builder
918    }
919
920    /// Include a directory on the host in the package and make it available to
921    /// a WebAssembly guest at the `guest` path.
922    pub fn map_fs(&mut self, guest: impl Into<String>, host: impl Into<PathBuf>) -> &mut Self {
923        self.fs
924            .get_or_insert_with(IndexMap::new)
925            .insert(guest.into(), host.into());
926        self
927    }
928
929    /// Add a dependency to the [`Manifest`].
930    pub fn with_dependency(&mut self, name: impl Into<String>, version: VersionReq) -> &mut Self {
931        self.dependencies
932            .get_or_insert_with(IndexMap::new)
933            .insert(name.into(), version);
934        self
935    }
936
937    /// Add a [`Module`] to the [`Manifest`].
938    pub fn with_module(&mut self, module: Module) -> &mut Self {
939        self.modules.get_or_insert_with(Vec::new).push(module);
940        self
941    }
942
943    /// Add a [`Command`] to the [`Manifest`].
944    pub fn with_command(&mut self, command: Command) -> &mut Self {
945        self.commands.get_or_insert_with(Vec::new).push(command);
946        self
947    }
948}
949
950/// Errors that may occur while working with a [`Manifest`].
951#[derive(Debug, Error)]
952#[non_exhaustive]
953pub enum ManifestError {
954    #[error("Manifest file not found at \"{}\"", _0.display())]
955    MissingManifest(PathBuf),
956    #[error("Could not save manifest file: {0}.")]
957    CannotSaveManifest(#[source] std::io::Error),
958    #[error("Could not parse manifest because {0}.")]
959    TomlParseError(#[from] toml::de::Error),
960    #[error("There was an error validating the manifest")]
961    ValidationError(#[from] ValidationError),
962}
963
964/// Errors that may be returned by [`Manifest::validate()`].
965#[derive(Debug, PartialEq, Error)]
966#[non_exhaustive]
967pub enum ValidationError {
968    #[error(
969        "missing ABI field on module, \"{module}\", used by command, \"{command}\"; an ABI of `wasi` is required"
970    )]
971    MissingABI { command: String, module: String },
972    #[error("missing module, \"{module}\", in manifest used by command, \"{command}\"")]
973    MissingModuleForCommand {
974        command: String,
975        module: ModuleReference,
976    },
977    #[error(
978        "The \"{command}\" command refers to a nonexistent dependency, \"{dependency}\" in \"{module_ref}\""
979    )]
980    MissingDependency {
981        command: String,
982        dependency: String,
983        module_ref: ModuleReference,
984    },
985    #[error("The entrypoint, \"{entrypoint}\", isn't a valid command (commands: {})", available_commands.join(", "))]
986    InvalidEntrypoint {
987        entrypoint: String,
988        available_commands: Vec<String>,
989    },
990    #[error("Duplicate module, \"{name}\"")]
991    DuplicateModule { name: String },
992    #[error("Duplicate command, \"{name}\"")]
993    DuplicateCommand { name: String },
994}
995
996#[cfg(test)]
997mod tests {
998    use std::fmt::Debug;
999
1000    use serde::{Deserialize, de::DeserializeOwned};
1001    use toml::toml;
1002
1003    use super::*;
1004
1005    #[test]
1006    fn test_to_string() {
1007        Manifest {
1008            package: Some(Package {
1009                name: Some("package/name".to_string()),
1010                version: Some(Version::parse("1.0.0").unwrap()),
1011                description: Some("test".to_string()),
1012                license: None,
1013                license_file: None,
1014                readme: None,
1015                repository: None,
1016                homepage: None,
1017                wasmer_extra_flags: None,
1018                disable_command_rename: false,
1019                rename_commands_to_raw_command_name: false,
1020                entrypoint: None,
1021                private: false,
1022            }),
1023            dependencies: IndexMap::new(),
1024            modules: vec![Module {
1025                name: "test".to_string(),
1026                abi: Abi::Wasi,
1027                bindings: None,
1028                interfaces: None,
1029                kind: Some("https://webc.org/kind/wasi".to_string()),
1030                source: Path::new("test.wasm").to_path_buf(),
1031                annotations: None,
1032            }],
1033            commands: Vec::new(),
1034            fs: vec![
1035                ("a".to_string(), Path::new("/a").to_path_buf()),
1036                ("b".to_string(), Path::new("/b").to_path_buf()),
1037            ]
1038            .into_iter()
1039            .collect(),
1040        }
1041        .to_string()
1042        .unwrap();
1043    }
1044
1045    #[test]
1046    fn interface_test() {
1047        let manifest_str = r#"
1048[package]
1049name = "test"
1050version = "0.0.0"
1051description = "This is a test package"
1052license = "MIT"
1053
1054[[module]]
1055name = "mod"
1056source = "target/wasm32-wasip1/release/mod.wasm"
1057interfaces = {"wasi" = "0.0.0-unstable"}
1058
1059[[module]]
1060name = "mod-with-exports"
1061source = "target/wasm32-wasip1/release/mod-with-exports.wasm"
1062bindings = { wit-exports = "exports.wit", wit-bindgen = "0.0.0" }
1063
1064[[command]]
1065name = "command"
1066module = "mod"
1067"#;
1068        let manifest: Manifest = Manifest::parse(manifest_str).unwrap();
1069        let modules = &manifest.modules;
1070        assert_eq!(
1071            modules[0].interfaces.as_ref().unwrap().get("wasi"),
1072            Some(&"0.0.0-unstable".to_string())
1073        );
1074
1075        assert_eq!(
1076            modules[1],
1077            Module {
1078                name: "mod-with-exports".to_string(),
1079                source: PathBuf::from("target/wasm32-wasip1/release/mod-with-exports.wasm"),
1080                abi: Abi::None,
1081                kind: None,
1082                interfaces: None,
1083                bindings: Some(Bindings::Wit(WitBindings {
1084                    wit_exports: PathBuf::from("exports.wit"),
1085                    wit_bindgen: "0.0.0".parse().unwrap()
1086                })),
1087                annotations: None
1088            },
1089        );
1090    }
1091
1092    #[test]
1093    fn parse_wit_bindings() {
1094        let table = toml! {
1095            name = "..."
1096            source = "..."
1097            bindings = { wit-bindgen = "0.1.0", wit-exports = "./file.wit" }
1098        };
1099
1100        let module = Module::deserialize(table).unwrap();
1101
1102        assert_eq!(
1103            module.bindings.as_ref().unwrap(),
1104            &Bindings::Wit(WitBindings {
1105                wit_bindgen: "0.1.0".parse().unwrap(),
1106                wit_exports: PathBuf::from("./file.wit"),
1107            }),
1108        );
1109        assert_round_trippable(&module);
1110    }
1111
1112    #[test]
1113    fn parse_wai_bindings() {
1114        let table = toml! {
1115            name = "..."
1116            source = "..."
1117            bindings = { wai-version = "0.1.0", exports = "./file.wai", imports = ["a.wai", "../b.wai"] }
1118        };
1119
1120        let module = Module::deserialize(table).unwrap();
1121
1122        assert_eq!(
1123            module.bindings.as_ref().unwrap(),
1124            &Bindings::Wai(WaiBindings {
1125                wai_version: "0.1.0".parse().unwrap(),
1126                exports: Some(PathBuf::from("./file.wai")),
1127                imports: vec![PathBuf::from("a.wai"), PathBuf::from("../b.wai")],
1128            }),
1129        );
1130        assert_round_trippable(&module);
1131    }
1132
1133    #[track_caller]
1134    fn assert_round_trippable<T>(value: &T)
1135    where
1136        T: Serialize + DeserializeOwned + PartialEq + Debug,
1137    {
1138        let repr = toml::to_string(value).unwrap();
1139        let round_tripped: T = toml::from_str(&repr).unwrap();
1140        assert_eq!(
1141            round_tripped, *value,
1142            "The value should convert to/from TOML losslessly"
1143        );
1144    }
1145
1146    #[test]
1147    fn imports_and_exports_are_optional_with_wai() {
1148        let table = toml! {
1149            name = "..."
1150            source = "..."
1151            bindings = { wai-version = "0.1.0" }
1152        };
1153
1154        let module = Module::deserialize(table).unwrap();
1155
1156        assert_eq!(
1157            module.bindings.as_ref().unwrap(),
1158            &Bindings::Wai(WaiBindings {
1159                wai_version: "0.1.0".parse().unwrap(),
1160                exports: None,
1161                imports: Vec::new(),
1162            }),
1163        );
1164        assert_round_trippable(&module);
1165    }
1166
1167    #[test]
1168    fn ambiguous_bindings_table() {
1169        let table = toml! {
1170            wai-version = "0.2.0"
1171            wit-bindgen = "0.1.0"
1172        };
1173
1174        let err = Bindings::deserialize(table).unwrap_err();
1175
1176        assert_eq!(
1177            err.to_string(),
1178            "expected one of \"wit-bindgen\" or \"wai-version\" to be provided, but not both\n"
1179        );
1180    }
1181
1182    #[test]
1183    fn bindings_table_that_is_neither_wit_nor_wai() {
1184        let table = toml! {
1185            wai-bindgen = "lol, this should have been wai-version"
1186            exports = "./file.wai"
1187        };
1188
1189        let err = Bindings::deserialize(table).unwrap_err();
1190
1191        assert_eq!(
1192            err.to_string(),
1193            "expected one of \"wit-bindgen\" or \"wai-version\" to be provided, but not both\n"
1194        );
1195    }
1196
1197    #[test]
1198    fn command_v2_isnt_ambiguous_with_command_v1() {
1199        let src = r#"
1200[package]
1201name = "hotg-ai/sine"
1202version = "0.12.0"
1203description = "sine"
1204
1205[dependencies]
1206"hotg-ai/train_test_split" = "0.12.1"
1207"hotg-ai/elastic_net" = "0.12.1"
1208
1209[[module]] # This is the same as atoms
1210name = "sine"
1211kind = "tensorflow-SavedModel" # It can also be "wasm" (default)
1212source = "models/sine"
1213
1214[[command]]
1215name = "run"
1216runner = "rune"
1217module = "sine"
1218annotations = { file = "Runefile.yml", kind = "yaml" }
1219"#;
1220
1221        let manifest: Manifest = toml::from_str(src).unwrap();
1222
1223        let commands = &manifest.commands;
1224        assert_eq!(commands.len(), 1);
1225        assert_eq!(
1226            commands[0],
1227            Command::V2(CommandV2 {
1228                name: "run".into(),
1229                module: "sine".parse().unwrap(),
1230                runner: "rune".into(),
1231                annotations: Some(CommandAnnotations::File(FileCommandAnnotations {
1232                    file: "Runefile.yml".into(),
1233                    kind: FileKind::Yaml,
1234                }))
1235            })
1236        );
1237    }
1238
1239    #[test]
1240    fn get_manifest() {
1241        let wasmer_toml = toml! {
1242            [package]
1243            name = "test"
1244            version = "1.0.0"
1245            repository = "test.git"
1246            homepage = "test.com"
1247            description = "The best package."
1248        };
1249        let manifest: Manifest = wasmer_toml.try_into().unwrap();
1250        if let Some(package) = manifest.package {
1251            assert!(!package.disable_command_rename);
1252        }
1253    }
1254
1255    #[test]
1256    fn parse_manifest_without_package_section() {
1257        let wasmer_toml = toml! {
1258            [[module]]
1259            name = "test-module"
1260            source = "data.wasm"
1261            abi = "wasi"
1262        };
1263        let manifest: Manifest = wasmer_toml.try_into().unwrap();
1264        assert!(manifest.package.is_none());
1265    }
1266
1267    #[test]
1268    fn get_commands() {
1269        let wasmer_toml = toml! {
1270            [package]
1271            name = "test"
1272            version = "1.0.0"
1273            repository = "test.git"
1274            homepage = "test.com"
1275            description = "The best package."
1276            [[module]]
1277            name = "test-pkg"
1278            module = "target.wasm"
1279            source = "source.wasm"
1280            description = "description"
1281            interfaces = {"wasi" = "0.0.0-unstable"}
1282            [[command]]
1283            name = "foo"
1284            module = "test"
1285            [[command]]
1286            name = "baz"
1287            module = "test"
1288            main_args = "$@"
1289        };
1290        let manifest: Manifest = wasmer_toml.try_into().unwrap();
1291        let commands = &manifest.commands;
1292        assert_eq!(2, commands.len());
1293    }
1294
1295    #[test]
1296    fn add_new_dependency() {
1297        let tmp_dir = tempfile::tempdir().unwrap();
1298        let tmp_dir_path: &std::path::Path = tmp_dir.as_ref();
1299        let manifest_path = tmp_dir_path.join(MANIFEST_FILE_NAME);
1300        let wasmer_toml = toml! {
1301            [package]
1302            name = "_/test"
1303            version = "1.0.0"
1304            description = "description"
1305            [[module]]
1306            name = "test"
1307            source = "test.wasm"
1308            interfaces = {}
1309        };
1310        let toml_string = toml::to_string(&wasmer_toml).unwrap();
1311        std::fs::write(manifest_path, toml_string).unwrap();
1312        let mut manifest = Manifest::find_in_directory(tmp_dir).unwrap();
1313
1314        let dependency_name = "dep_pkg";
1315        let dependency_version: VersionReq = "0.1.0".parse().unwrap();
1316
1317        manifest.add_dependency(dependency_name.to_string(), dependency_version.clone());
1318        assert_eq!(1, manifest.dependencies.len());
1319
1320        // adding the same dependency twice changes nothing
1321        manifest.add_dependency(dependency_name.to_string(), dependency_version);
1322        assert_eq!(1, manifest.dependencies.len());
1323
1324        // adding a second different dependency will increase the count
1325        let dependency_name_2 = "dep_pkg_2";
1326        let dependency_version_2: VersionReq = "0.2.0".parse().unwrap();
1327        manifest.add_dependency(dependency_name_2.to_string(), dependency_version_2);
1328        assert_eq!(2, manifest.dependencies.len());
1329    }
1330
1331    #[test]
1332    fn duplicate_modules_are_invalid() {
1333        let wasmer_toml = toml! {
1334            [package]
1335            name = "some/package"
1336            version = "0.0.0"
1337            description = ""
1338            [[module]]
1339            name = "test"
1340            source = "test.wasm"
1341            [[module]]
1342            name = "test"
1343            source = "test.wasm"
1344        };
1345        let manifest = Manifest::deserialize(wasmer_toml).unwrap();
1346
1347        let error = manifest.validate().unwrap_err();
1348
1349        assert_eq!(
1350            error,
1351            ValidationError::DuplicateModule {
1352                name: "test".to_string()
1353            }
1354        );
1355    }
1356
1357    #[test]
1358    fn duplicate_commands_are_invalid() {
1359        let wasmer_toml = toml! {
1360            [package]
1361            name = "some/package"
1362            version = "0.0.0"
1363            description = ""
1364            [[module]]
1365            name = "test"
1366            source = "test.wasm"
1367            abi = "wasi"
1368            [[command]]
1369            name = "cmd"
1370            module = "test"
1371            [[command]]
1372            name = "cmd"
1373            module = "test"
1374        };
1375        let manifest = Manifest::deserialize(wasmer_toml).unwrap();
1376
1377        let error = manifest.validate().unwrap_err();
1378
1379        assert_eq!(
1380            error,
1381            ValidationError::DuplicateCommand {
1382                name: "cmd".to_string()
1383            }
1384        );
1385    }
1386
1387    #[test]
1388    fn nonexistent_entrypoint() {
1389        let wasmer_toml = toml! {
1390            [package]
1391            name = "some/package"
1392            version = "0.0.0"
1393            description = ""
1394            entrypoint = "this-doesnt-exist"
1395            [[module]]
1396            name = "test"
1397            source = "test.wasm"
1398            abi = "wasi"
1399            [[command]]
1400            name = "cmd"
1401            module = "test"
1402        };
1403        let manifest = Manifest::deserialize(wasmer_toml).unwrap();
1404
1405        let error = manifest.validate().unwrap_err();
1406
1407        assert_eq!(
1408            error,
1409            ValidationError::InvalidEntrypoint {
1410                entrypoint: "this-doesnt-exist".to_string(),
1411                available_commands: vec!["cmd".to_string()]
1412            }
1413        );
1414    }
1415
1416    #[test]
1417    fn command_with_nonexistent_module() {
1418        let wasmer_toml = toml! {
1419            [package]
1420            name = "some/package"
1421            version = "0.0.0"
1422            description = ""
1423            [[command]]
1424            name = "cmd"
1425            module = "this-doesnt-exist"
1426        };
1427        let manifest = Manifest::deserialize(wasmer_toml).unwrap();
1428
1429        let error = manifest.validate().unwrap_err();
1430
1431        assert_eq!(
1432            error,
1433            ValidationError::MissingModuleForCommand {
1434                command: "cmd".to_string(),
1435                module: "this-doesnt-exist".parse().unwrap()
1436            }
1437        );
1438    }
1439
1440    #[test]
1441    fn use_builder_api_to_create_simplest_manifest() {
1442        let package =
1443            Package::builder("my/package", "1.0.0".parse().unwrap(), "My awesome package")
1444                .build()
1445                .unwrap();
1446        let manifest = Manifest::builder(package).build().unwrap();
1447
1448        manifest.validate().unwrap();
1449    }
1450
1451    #[test]
1452    fn deserialize_command_referring_to_module_from_dependency() {
1453        let wasmer_toml = toml! {
1454            [package]
1455            name = "some/package"
1456            version = "0.0.0"
1457            description = ""
1458
1459            [dependencies]
1460            dep = "1.2.3"
1461
1462            [[command]]
1463            name = "cmd"
1464            module = "dep:module"
1465        };
1466        let manifest = Manifest::deserialize(wasmer_toml).unwrap();
1467
1468        let command = manifest
1469            .commands
1470            .iter()
1471            .find(|cmd| cmd.get_name() == "cmd")
1472            .unwrap();
1473
1474        assert_eq!(
1475            command.get_module(),
1476            &ModuleReference::Dependency {
1477                dependency: "dep".to_string(),
1478                module: "module".to_string()
1479            }
1480        );
1481    }
1482
1483    #[test]
1484    fn command_with_module_from_nonexistent_dependency() {
1485        let wasmer_toml = toml! {
1486            [package]
1487            name = "some/package"
1488            version = "0.0.0"
1489            description = ""
1490            [[command]]
1491            name = "cmd"
1492            module = "dep:module"
1493        };
1494        let manifest = Manifest::deserialize(wasmer_toml).unwrap();
1495
1496        let error = manifest.validate().unwrap_err();
1497
1498        assert_eq!(
1499            error,
1500            ValidationError::MissingDependency {
1501                command: "cmd".to_string(),
1502                dependency: "dep".to_string(),
1503                module_ref: ModuleReference::Dependency {
1504                    dependency: "dep".to_string(),
1505                    module: "module".to_string()
1506                }
1507            }
1508        );
1509    }
1510
1511    #[test]
1512    fn round_trip_dependency_module_ref() {
1513        let original = ModuleReference::Dependency {
1514            dependency: "my/dep".to_string(),
1515            module: "module".to_string(),
1516        };
1517
1518        let repr = original.to_string();
1519        let round_tripped: ModuleReference = repr.parse().unwrap();
1520
1521        assert_eq!(round_tripped, original);
1522    }
1523}