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::{de::Error as _, Deserialize, Serialize};
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}
507
508/// The interface exposed by a [`Module`].
509#[derive(Clone, Debug, PartialEq, Eq)]
510pub enum Bindings {
511    Wit(WitBindings),
512    Wai(WaiBindings),
513}
514
515impl Bindings {
516    /// Get all files that make up this interface.
517    ///
518    /// For all binding types except [`WitBindings`], this will recursively
519    /// look for any files that are imported.
520    ///
521    /// The caller can assume that any path that was referenced exists.
522    pub fn referenced_files(&self, base_directory: &Path) -> Result<Vec<PathBuf>, ImportsError> {
523        match self {
524            Bindings::Wit(WitBindings { wit_exports, .. }) => {
525                // Note: we explicitly don't support imported files with WIT
526                // because wit-bindgen's wit-parser crate isn't on crates.io.
527
528                let path = base_directory.join(wit_exports);
529
530                if path.exists() {
531                    Ok(vec![path])
532                } else {
533                    Err(ImportsError::FileNotFound(path))
534                }
535            }
536            Bindings::Wai(wai) => wai.referenced_files(base_directory),
537        }
538    }
539}
540
541impl Serialize for Bindings {
542    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
543    where
544        S: serde::Serializer,
545    {
546        match self {
547            Bindings::Wit(w) => w.serialize(serializer),
548            Bindings::Wai(w) => w.serialize(serializer),
549        }
550    }
551}
552
553impl<'de> Deserialize<'de> for Bindings {
554    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
555    where
556        D: serde::Deserializer<'de>,
557    {
558        let value = toml::Value::deserialize(deserializer)?;
559
560        let keys = ["wit-bindgen", "wai-version"];
561        let [wit_bindgen, wai_version] = keys.map(|key| value.get(key).is_some());
562
563        match (wit_bindgen, wai_version) {
564            (true, false) => WitBindings::deserialize(value)
565                .map(Bindings::Wit)
566                .map_err(D::Error::custom),
567            (false, true) => WaiBindings::deserialize(value)
568                .map(Bindings::Wai)
569                .map_err(D::Error::custom),
570            (true, true) | (false, false) => {
571                let msg = format!(
572                    "expected one of \"{}\" to be provided, but not both",
573                    keys.join("\" or \""),
574                );
575                Err(D::Error::custom(msg))
576            }
577        }
578    }
579}
580
581#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
582#[serde(rename_all = "kebab-case")]
583pub struct WitBindings {
584    /// The version of the WIT format being used.
585    pub wit_bindgen: Version,
586    /// The `*.wit` file's location on disk.
587    pub wit_exports: PathBuf,
588}
589
590#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
591#[serde(rename_all = "kebab-case")]
592pub struct WaiBindings {
593    /// The version of the WAI format being used.
594    pub wai_version: Version,
595    /// The `*.wai` file defining the interface this package exposes.
596    pub exports: Option<PathBuf>,
597    /// The `*.wai` files for any functionality this package imports from the
598    /// host.
599    #[serde(default, skip_serializing_if = "Vec::is_empty")]
600    pub imports: Vec<PathBuf>,
601}
602
603impl WaiBindings {
604    fn referenced_files(&self, base_directory: &Path) -> Result<Vec<PathBuf>, ImportsError> {
605        let WaiBindings {
606            exports, imports, ..
607        } = self;
608
609        // Note: WAI files may import other WAI files, so we start with all
610        // WAI files mentioned in the wasmer.toml then recursively add their
611        // imports.
612
613        let initial_paths = exports
614            .iter()
615            .chain(imports)
616            .map(|relative_path| base_directory.join(relative_path));
617
618        let mut to_check: Vec<PathBuf> = Vec::new();
619
620        for path in initial_paths {
621            if !path.exists() {
622                return Err(ImportsError::FileNotFound(path));
623            }
624            to_check.push(path);
625        }
626
627        let mut files = BTreeSet::new();
628
629        while let Some(path) = to_check.pop() {
630            if files.contains(&path) {
631                continue;
632            }
633
634            to_check.extend(get_imported_wai_files(&path)?);
635            files.insert(path);
636        }
637
638        Ok(files.into_iter().collect())
639    }
640}
641
642/// Parse a `*.wai` file to find the absolute path for any other `*.wai` files
643/// it may import, relative to the original `*.wai` file.
644///
645/// This function makes sure any imported files exist.
646fn get_imported_wai_files(path: &Path) -> Result<Vec<PathBuf>, ImportsError> {
647    let _wai_src = std::fs::read_to_string(path).map_err(|error| ImportsError::Read {
648        path: path.to_path_buf(),
649        error,
650    })?;
651
652    let parent_dir = path.parent()
653            .expect("All paths should have a parent directory because we joined them relative to the base directory");
654
655    // TODO(Michael-F-Bryan): update the wai-parser crate to give you access to
656    // the imported interfaces. For now, we just pretend there are no import
657    // statements in the *.wai file.
658    let raw_imports: Vec<String> = Vec::new();
659
660    // Note: imported paths in a *.wai file are all relative, so we need to
661    // resolve their absolute path relative to the original *.wai file.
662    let mut resolved_paths = Vec::new();
663
664    for imported in raw_imports {
665        let absolute_path = parent_dir.join(imported);
666
667        if !absolute_path.exists() {
668            return Err(ImportsError::ImportedFileNotFound {
669                path: absolute_path,
670                referenced_by: path.to_path_buf(),
671            });
672        }
673
674        resolved_paths.push(absolute_path);
675    }
676
677    Ok(resolved_paths)
678}
679
680/// Errors that may occur when resolving [`Bindings`] imports.
681#[derive(Debug, thiserror::Error)]
682#[non_exhaustive]
683pub enum ImportsError {
684    #[error(
685        "The \"{}\" mentioned in the manifest doesn't exist",
686        _0.display(),
687    )]
688    FileNotFound(PathBuf),
689    #[error(
690        "The \"{}\" imported by \"{}\" doesn't exist",
691        path.display(),
692        referenced_by.display(),
693    )]
694    ImportedFileNotFound {
695        path: PathBuf,
696        referenced_by: PathBuf,
697    },
698    #[error("Unable to parse \"{}\" as a WAI file", path.display())]
699    WaiParse { path: PathBuf },
700    #[error("Unable to read \"{}\"", path.display())]
701    Read {
702        path: PathBuf,
703        #[source]
704        error: std::io::Error,
705    },
706}
707
708/// The manifest represents the file used to describe a Wasm package.
709#[derive(Clone, Debug, Deserialize, Serialize, derive_builder::Builder)]
710#[non_exhaustive]
711pub struct Manifest {
712    /// Metadata about the package itself.
713    pub package: Option<Package>,
714    /// The package's dependencies.
715    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
716    #[builder(default)]
717    pub dependencies: IndexMap<String, VersionReq>,
718    /// The mappings used when making bundled assets available to WebAssembly
719    /// instances, in the form guest -> host.
720    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
721    #[builder(default)]
722    pub fs: IndexMap<String, PathBuf>,
723    /// WebAssembly modules to be published.
724    #[serde(default, rename = "module", skip_serializing_if = "Vec::is_empty")]
725    #[builder(default)]
726    pub modules: Vec<Module>,
727    /// Commands the package makes available to users.
728    #[serde(default, rename = "command", skip_serializing_if = "Vec::is_empty")]
729    #[builder(default)]
730    pub commands: Vec<Command>,
731}
732
733impl Manifest {
734    pub fn new_empty() -> Self {
735        Self {
736            package: None,
737            dependencies: IndexMap::new(),
738            fs: IndexMap::new(),
739            modules: Vec::new(),
740            commands: Vec::new(),
741        }
742    }
743
744    /// Create a [`ManifestBuilder`] populated with all mandatory fields.
745    pub fn builder(package: Package) -> ManifestBuilder {
746        ManifestBuilder::new(package)
747    }
748
749    /// Parse a [`Manifest`] from its TOML representation.
750    pub fn parse(s: &str) -> Result<Self, toml::de::Error> {
751        toml::from_str(s)
752    }
753
754    /// Construct a manifest by searching in the specified directory for a
755    /// manifest file.
756    pub fn find_in_directory<T: AsRef<Path>>(path: T) -> Result<Self, ManifestError> {
757        let path = path.as_ref();
758
759        if !path.is_dir() {
760            return Err(ManifestError::MissingManifest(path.to_path_buf()));
761        }
762        let manifest_path_buf = path.join(MANIFEST_FILE_NAME);
763        let contents = std::fs::read_to_string(&manifest_path_buf)
764            .map_err(|_e| ManifestError::MissingManifest(manifest_path_buf))?;
765        let mut manifest: Self = toml::from_str(contents.as_str())?;
766
767        if let Some(package) = manifest.package.as_mut() {
768            if package.readme.is_none() {
769                package.readme = locate_file(path, README_PATHS);
770            }
771
772            if package.license_file.is_none() {
773                package.license_file = locate_file(path, LICENSE_PATHS);
774            }
775        }
776        manifest.validate()?;
777
778        Ok(manifest)
779    }
780
781    /// Validate this [`Manifest`] to check for common semantic errors.
782    ///
783    /// Some common error cases are:
784    ///
785    /// - Having multiple modules with the same name
786    /// - Having multiple commands with the same name
787    /// - A [`Command`] that references a non-existent [`Module`] in the current
788    ///   package
789    /// - A [`Package::entrypoint`] which points to a non-existent [`Command`]
790    pub fn validate(&self) -> Result<(), ValidationError> {
791        let mut modules = BTreeMap::new();
792
793        for module in &self.modules {
794            let is_duplicate = modules.insert(&module.name, module).is_some();
795
796            if is_duplicate {
797                return Err(ValidationError::DuplicateModule {
798                    name: module.name.clone(),
799                });
800            }
801        }
802
803        let mut commands = BTreeMap::new();
804
805        for command in &self.commands {
806            let is_duplicate = commands.insert(command.get_name(), command).is_some();
807
808            if is_duplicate {
809                return Err(ValidationError::DuplicateCommand {
810                    name: command.get_name().to_string(),
811                });
812            }
813
814            let module_reference = command.get_module();
815            match &module_reference {
816                ModuleReference::CurrentPackage { module } => {
817                    if let Some(module) = modules.get(&module) {
818                        if module.abi == Abi::None && module.interfaces.is_none() {
819                            return Err(ValidationError::MissingABI {
820                                command: command.get_name().to_string(),
821                                module: module.name.clone(),
822                            });
823                        }
824                    } else {
825                        return Err(ValidationError::MissingModuleForCommand {
826                            command: command.get_name().to_string(),
827                            module: command.get_module().clone(),
828                        });
829                    }
830                }
831                ModuleReference::Dependency { dependency, .. } => {
832                    // We don't have access to the dependency so just assume
833                    // the module is correct.
834                    if !self.dependencies.contains_key(dependency) {
835                        return Err(ValidationError::MissingDependency {
836                            command: command.get_name().to_string(),
837                            dependency: dependency.clone(),
838                            module_ref: module_reference.clone(),
839                        });
840                    }
841                }
842            }
843        }
844
845        if let Some(package) = &self.package {
846            if let Some(entrypoint) = package.entrypoint.as_deref() {
847                if !commands.contains_key(entrypoint) {
848                    return Err(ValidationError::InvalidEntrypoint {
849                        entrypoint: entrypoint.to_string(),
850                        available_commands: commands.keys().map(ToString::to_string).collect(),
851                    });
852                }
853            }
854        }
855
856        Ok(())
857    }
858
859    /// add a dependency
860    pub fn add_dependency(&mut self, dependency_name: String, dependency_version: VersionReq) {
861        self.dependencies
862            .insert(dependency_name, dependency_version);
863    }
864
865    /// remove dependency by package name
866    pub fn remove_dependency(&mut self, dependency_name: &str) -> Option<VersionReq> {
867        self.dependencies.remove(dependency_name)
868    }
869
870    /// Convert a [`Manifest`] to its TOML representation.
871    pub fn to_string(&self) -> anyhow::Result<String> {
872        let repr = toml::to_string_pretty(&self)?;
873        Ok(repr)
874    }
875
876    /// Write the manifest to permanent storage
877    pub fn save(&self, path: impl AsRef<Path>) -> anyhow::Result<()> {
878        let manifest = toml::to_string_pretty(self)?;
879        std::fs::write(path, manifest).map_err(ManifestError::CannotSaveManifest)?;
880        Ok(())
881    }
882}
883
884fn locate_file(path: &Path, candidates: &[&str]) -> Option<PathBuf> {
885    for filename in candidates {
886        let path_buf = path.join(filename);
887        if path_buf.exists() {
888            return Some(filename.into());
889        }
890    }
891    None
892}
893
894impl ManifestBuilder {
895    pub fn new(package: Package) -> Self {
896        let mut builder = ManifestBuilder::default();
897        builder.package(Some(package));
898        builder
899    }
900
901    /// Include a directory on the host in the package and make it available to
902    /// a WebAssembly guest at the `guest` path.
903    pub fn map_fs(&mut self, guest: impl Into<String>, host: impl Into<PathBuf>) -> &mut Self {
904        self.fs
905            .get_or_insert_with(IndexMap::new)
906            .insert(guest.into(), host.into());
907        self
908    }
909
910    /// Add a dependency to the [`Manifest`].
911    pub fn with_dependency(&mut self, name: impl Into<String>, version: VersionReq) -> &mut Self {
912        self.dependencies
913            .get_or_insert_with(IndexMap::new)
914            .insert(name.into(), version);
915        self
916    }
917
918    /// Add a [`Module`] to the [`Manifest`].
919    pub fn with_module(&mut self, module: Module) -> &mut Self {
920        self.modules.get_or_insert_with(Vec::new).push(module);
921        self
922    }
923
924    /// Add a [`Command`] to the [`Manifest`].
925    pub fn with_command(&mut self, command: Command) -> &mut Self {
926        self.commands.get_or_insert_with(Vec::new).push(command);
927        self
928    }
929}
930
931/// Errors that may occur while working with a [`Manifest`].
932#[derive(Debug, Error)]
933#[non_exhaustive]
934pub enum ManifestError {
935    #[error("Manifest file not found at \"{}\"", _0.display())]
936    MissingManifest(PathBuf),
937    #[error("Could not save manifest file: {0}.")]
938    CannotSaveManifest(#[source] std::io::Error),
939    #[error("Could not parse manifest because {0}.")]
940    TomlParseError(#[from] toml::de::Error),
941    #[error("There was an error validating the manifest")]
942    ValidationError(#[from] ValidationError),
943}
944
945/// Errors that may be returned by [`Manifest::validate()`].
946#[derive(Debug, PartialEq, Error)]
947#[non_exhaustive]
948pub enum ValidationError {
949    #[error(
950        "missing ABI field on module, \"{module}\", used by command, \"{command}\"; an ABI of `wasi` is required",
951    )]
952    MissingABI { command: String, module: String },
953    #[error("missing module, \"{module}\", in manifest used by command, \"{command}\"")]
954    MissingModuleForCommand {
955        command: String,
956        module: ModuleReference,
957    },
958    #[error("The \"{command}\" command refers to a nonexistent dependency, \"{dependency}\" in \"{module_ref}\"")]
959    MissingDependency {
960        command: String,
961        dependency: String,
962        module_ref: ModuleReference,
963    },
964    #[error("The entrypoint, \"{entrypoint}\", isn't a valid command (commands: {})", available_commands.join(", "))]
965    InvalidEntrypoint {
966        entrypoint: String,
967        available_commands: Vec<String>,
968    },
969    #[error("Duplicate module, \"{name}\"")]
970    DuplicateModule { name: String },
971    #[error("Duplicate command, \"{name}\"")]
972    DuplicateCommand { name: String },
973}
974
975#[cfg(test)]
976mod tests {
977    use std::fmt::Debug;
978
979    use serde::{de::DeserializeOwned, Deserialize};
980    use toml::toml;
981
982    use super::*;
983
984    #[test]
985    fn test_to_string() {
986        Manifest {
987            package: Some(Package {
988                name: Some("package/name".to_string()),
989                version: Some(Version::parse("1.0.0").unwrap()),
990                description: Some("test".to_string()),
991                license: None,
992                license_file: None,
993                readme: None,
994                repository: None,
995                homepage: None,
996                wasmer_extra_flags: None,
997                disable_command_rename: false,
998                rename_commands_to_raw_command_name: false,
999                entrypoint: None,
1000                private: false,
1001            }),
1002            dependencies: IndexMap::new(),
1003            modules: vec![Module {
1004                name: "test".to_string(),
1005                abi: Abi::Wasi,
1006                bindings: None,
1007                interfaces: None,
1008                kind: Some("https://webc.org/kind/wasi".to_string()),
1009                source: Path::new("test.wasm").to_path_buf(),
1010            }],
1011            commands: Vec::new(),
1012            fs: vec![
1013                ("a".to_string(), Path::new("/a").to_path_buf()),
1014                ("b".to_string(), Path::new("/b").to_path_buf()),
1015            ]
1016            .into_iter()
1017            .collect(),
1018        }
1019        .to_string()
1020        .unwrap();
1021    }
1022
1023    #[test]
1024    fn interface_test() {
1025        let manifest_str = r#"
1026[package]
1027name = "test"
1028version = "0.0.0"
1029description = "This is a test package"
1030license = "MIT"
1031
1032[[module]]
1033name = "mod"
1034source = "target/wasm32-wasip1/release/mod.wasm"
1035interfaces = {"wasi" = "0.0.0-unstable"}
1036
1037[[module]]
1038name = "mod-with-exports"
1039source = "target/wasm32-wasip1/release/mod-with-exports.wasm"
1040bindings = { wit-exports = "exports.wit", wit-bindgen = "0.0.0" }
1041
1042[[command]]
1043name = "command"
1044module = "mod"
1045"#;
1046        let manifest: Manifest = Manifest::parse(manifest_str).unwrap();
1047        let modules = &manifest.modules;
1048        assert_eq!(
1049            modules[0].interfaces.as_ref().unwrap().get("wasi"),
1050            Some(&"0.0.0-unstable".to_string())
1051        );
1052
1053        assert_eq!(
1054            modules[1],
1055            Module {
1056                name: "mod-with-exports".to_string(),
1057                source: PathBuf::from("target/wasm32-wasip1/release/mod-with-exports.wasm"),
1058                abi: Abi::None,
1059                kind: None,
1060                interfaces: None,
1061                bindings: Some(Bindings::Wit(WitBindings {
1062                    wit_exports: PathBuf::from("exports.wit"),
1063                    wit_bindgen: "0.0.0".parse().unwrap()
1064                })),
1065            },
1066        );
1067    }
1068
1069    #[test]
1070    fn parse_wit_bindings() {
1071        let table = toml! {
1072            name = "..."
1073            source = "..."
1074            bindings = { wit-bindgen = "0.1.0", wit-exports = "./file.wit" }
1075        };
1076
1077        let module = Module::deserialize(table).unwrap();
1078
1079        assert_eq!(
1080            module.bindings.as_ref().unwrap(),
1081            &Bindings::Wit(WitBindings {
1082                wit_bindgen: "0.1.0".parse().unwrap(),
1083                wit_exports: PathBuf::from("./file.wit"),
1084            }),
1085        );
1086        assert_round_trippable(&module);
1087    }
1088
1089    #[test]
1090    fn parse_wai_bindings() {
1091        let table = toml! {
1092            name = "..."
1093            source = "..."
1094            bindings = { wai-version = "0.1.0", exports = "./file.wai", imports = ["a.wai", "../b.wai"] }
1095        };
1096
1097        let module = Module::deserialize(table).unwrap();
1098
1099        assert_eq!(
1100            module.bindings.as_ref().unwrap(),
1101            &Bindings::Wai(WaiBindings {
1102                wai_version: "0.1.0".parse().unwrap(),
1103                exports: Some(PathBuf::from("./file.wai")),
1104                imports: vec![PathBuf::from("a.wai"), PathBuf::from("../b.wai")],
1105            }),
1106        );
1107        assert_round_trippable(&module);
1108    }
1109
1110    #[track_caller]
1111    fn assert_round_trippable<T>(value: &T)
1112    where
1113        T: Serialize + DeserializeOwned + PartialEq + Debug,
1114    {
1115        let repr = toml::to_string(value).unwrap();
1116        let round_tripped: T = toml::from_str(&repr).unwrap();
1117        assert_eq!(
1118            round_tripped, *value,
1119            "The value should convert to/from TOML losslessly"
1120        );
1121    }
1122
1123    #[test]
1124    fn imports_and_exports_are_optional_with_wai() {
1125        let table = toml! {
1126            name = "..."
1127            source = "..."
1128            bindings = { wai-version = "0.1.0" }
1129        };
1130
1131        let module = Module::deserialize(table).unwrap();
1132
1133        assert_eq!(
1134            module.bindings.as_ref().unwrap(),
1135            &Bindings::Wai(WaiBindings {
1136                wai_version: "0.1.0".parse().unwrap(),
1137                exports: None,
1138                imports: Vec::new(),
1139            }),
1140        );
1141        assert_round_trippable(&module);
1142    }
1143
1144    #[test]
1145    fn ambiguous_bindings_table() {
1146        let table = toml! {
1147            wai-version = "0.2.0"
1148            wit-bindgen = "0.1.0"
1149        };
1150
1151        let err = Bindings::deserialize(table).unwrap_err();
1152
1153        assert_eq!(
1154            err.to_string(),
1155            "expected one of \"wit-bindgen\" or \"wai-version\" to be provided, but not both\n"
1156        );
1157    }
1158
1159    #[test]
1160    fn bindings_table_that_is_neither_wit_nor_wai() {
1161        let table = toml! {
1162            wai-bindgen = "lol, this should have been wai-version"
1163            exports = "./file.wai"
1164        };
1165
1166        let err = Bindings::deserialize(table).unwrap_err();
1167
1168        assert_eq!(
1169            err.to_string(),
1170            "expected one of \"wit-bindgen\" or \"wai-version\" to be provided, but not both\n"
1171        );
1172    }
1173
1174    #[test]
1175    fn command_v2_isnt_ambiguous_with_command_v1() {
1176        let src = r#"
1177[package]
1178name = "hotg-ai/sine"
1179version = "0.12.0"
1180description = "sine"
1181
1182[dependencies]
1183"hotg-ai/train_test_split" = "0.12.1"
1184"hotg-ai/elastic_net" = "0.12.1"
1185
1186[[module]] # This is the same as atoms
1187name = "sine"
1188kind = "tensorflow-SavedModel" # It can also be "wasm" (default)
1189source = "models/sine"
1190
1191[[command]]
1192name = "run"
1193runner = "rune"
1194module = "sine"
1195annotations = { file = "Runefile.yml", kind = "yaml" }
1196"#;
1197
1198        let manifest: Manifest = toml::from_str(src).unwrap();
1199
1200        let commands = &manifest.commands;
1201        assert_eq!(commands.len(), 1);
1202        assert_eq!(
1203            commands[0],
1204            Command::V2(CommandV2 {
1205                name: "run".into(),
1206                module: "sine".parse().unwrap(),
1207                runner: "rune".into(),
1208                annotations: Some(CommandAnnotations::File(FileCommandAnnotations {
1209                    file: "Runefile.yml".into(),
1210                    kind: FileKind::Yaml,
1211                }))
1212            })
1213        );
1214    }
1215
1216    #[test]
1217    fn get_manifest() {
1218        let wasmer_toml = toml! {
1219            [package]
1220            name = "test"
1221            version = "1.0.0"
1222            repository = "test.git"
1223            homepage = "test.com"
1224            description = "The best package."
1225        };
1226        let manifest: Manifest = wasmer_toml.try_into().unwrap();
1227        if let Some(package) = manifest.package {
1228            assert!(!package.disable_command_rename);
1229        }
1230    }
1231
1232    #[test]
1233    fn parse_manifest_without_package_section() {
1234        let wasmer_toml = toml! {
1235            [[module]]
1236            name = "test-module"
1237            source = "data.wasm"
1238            abi = "wasi"
1239        };
1240        let manifest: Manifest = wasmer_toml.try_into().unwrap();
1241        assert!(manifest.package.is_none());
1242    }
1243
1244    #[test]
1245    fn get_commands() {
1246        let wasmer_toml = toml! {
1247            [package]
1248            name = "test"
1249            version = "1.0.0"
1250            repository = "test.git"
1251            homepage = "test.com"
1252            description = "The best package."
1253            [[module]]
1254            name = "test-pkg"
1255            module = "target.wasm"
1256            source = "source.wasm"
1257            description = "description"
1258            interfaces = {"wasi" = "0.0.0-unstable"}
1259            [[command]]
1260            name = "foo"
1261            module = "test"
1262            [[command]]
1263            name = "baz"
1264            module = "test"
1265            main_args = "$@"
1266        };
1267        let manifest: Manifest = wasmer_toml.try_into().unwrap();
1268        let commands = &manifest.commands;
1269        assert_eq!(2, commands.len());
1270    }
1271
1272    #[test]
1273    fn add_new_dependency() {
1274        let tmp_dir = tempfile::tempdir().unwrap();
1275        let tmp_dir_path: &std::path::Path = tmp_dir.as_ref();
1276        let manifest_path = tmp_dir_path.join(MANIFEST_FILE_NAME);
1277        let wasmer_toml = toml! {
1278            [package]
1279            name = "_/test"
1280            version = "1.0.0"
1281            description = "description"
1282            [[module]]
1283            name = "test"
1284            source = "test.wasm"
1285            interfaces = {}
1286        };
1287        let toml_string = toml::to_string(&wasmer_toml).unwrap();
1288        std::fs::write(manifest_path, toml_string).unwrap();
1289        let mut manifest = Manifest::find_in_directory(tmp_dir).unwrap();
1290
1291        let dependency_name = "dep_pkg";
1292        let dependency_version: VersionReq = "0.1.0".parse().unwrap();
1293
1294        manifest.add_dependency(dependency_name.to_string(), dependency_version.clone());
1295        assert_eq!(1, manifest.dependencies.len());
1296
1297        // adding the same dependency twice changes nothing
1298        manifest.add_dependency(dependency_name.to_string(), dependency_version);
1299        assert_eq!(1, manifest.dependencies.len());
1300
1301        // adding a second different dependency will increase the count
1302        let dependency_name_2 = "dep_pkg_2";
1303        let dependency_version_2: VersionReq = "0.2.0".parse().unwrap();
1304        manifest.add_dependency(dependency_name_2.to_string(), dependency_version_2);
1305        assert_eq!(2, manifest.dependencies.len());
1306    }
1307
1308    #[test]
1309    fn duplicate_modules_are_invalid() {
1310        let wasmer_toml = toml! {
1311            [package]
1312            name = "some/package"
1313            version = "0.0.0"
1314            description = ""
1315            [[module]]
1316            name = "test"
1317            source = "test.wasm"
1318            [[module]]
1319            name = "test"
1320            source = "test.wasm"
1321        };
1322        let manifest = Manifest::deserialize(wasmer_toml).unwrap();
1323
1324        let error = manifest.validate().unwrap_err();
1325
1326        assert_eq!(
1327            error,
1328            ValidationError::DuplicateModule {
1329                name: "test".to_string()
1330            }
1331        );
1332    }
1333
1334    #[test]
1335    fn duplicate_commands_are_invalid() {
1336        let wasmer_toml = toml! {
1337            [package]
1338            name = "some/package"
1339            version = "0.0.0"
1340            description = ""
1341            [[module]]
1342            name = "test"
1343            source = "test.wasm"
1344            abi = "wasi"
1345            [[command]]
1346            name = "cmd"
1347            module = "test"
1348            [[command]]
1349            name = "cmd"
1350            module = "test"
1351        };
1352        let manifest = Manifest::deserialize(wasmer_toml).unwrap();
1353
1354        let error = manifest.validate().unwrap_err();
1355
1356        assert_eq!(
1357            error,
1358            ValidationError::DuplicateCommand {
1359                name: "cmd".to_string()
1360            }
1361        );
1362    }
1363
1364    #[test]
1365    fn nonexistent_entrypoint() {
1366        let wasmer_toml = toml! {
1367            [package]
1368            name = "some/package"
1369            version = "0.0.0"
1370            description = ""
1371            entrypoint = "this-doesnt-exist"
1372            [[module]]
1373            name = "test"
1374            source = "test.wasm"
1375            abi = "wasi"
1376            [[command]]
1377            name = "cmd"
1378            module = "test"
1379        };
1380        let manifest = Manifest::deserialize(wasmer_toml).unwrap();
1381
1382        let error = manifest.validate().unwrap_err();
1383
1384        assert_eq!(
1385            error,
1386            ValidationError::InvalidEntrypoint {
1387                entrypoint: "this-doesnt-exist".to_string(),
1388                available_commands: vec!["cmd".to_string()]
1389            }
1390        );
1391    }
1392
1393    #[test]
1394    fn command_with_nonexistent_module() {
1395        let wasmer_toml = toml! {
1396            [package]
1397            name = "some/package"
1398            version = "0.0.0"
1399            description = ""
1400            [[command]]
1401            name = "cmd"
1402            module = "this-doesnt-exist"
1403        };
1404        let manifest = Manifest::deserialize(wasmer_toml).unwrap();
1405
1406        let error = manifest.validate().unwrap_err();
1407
1408        assert_eq!(
1409            error,
1410            ValidationError::MissingModuleForCommand {
1411                command: "cmd".to_string(),
1412                module: "this-doesnt-exist".parse().unwrap()
1413            }
1414        );
1415    }
1416
1417    #[test]
1418    fn use_builder_api_to_create_simplest_manifest() {
1419        let package =
1420            Package::builder("my/package", "1.0.0".parse().unwrap(), "My awesome package")
1421                .build()
1422                .unwrap();
1423        let manifest = Manifest::builder(package).build().unwrap();
1424
1425        manifest.validate().unwrap();
1426    }
1427
1428    #[test]
1429    fn deserialize_command_referring_to_module_from_dependency() {
1430        let wasmer_toml = toml! {
1431            [package]
1432            name = "some/package"
1433            version = "0.0.0"
1434            description = ""
1435
1436            [dependencies]
1437            dep = "1.2.3"
1438
1439            [[command]]
1440            name = "cmd"
1441            module = "dep:module"
1442        };
1443        let manifest = Manifest::deserialize(wasmer_toml).unwrap();
1444
1445        let command = manifest
1446            .commands
1447            .iter()
1448            .find(|cmd| cmd.get_name() == "cmd")
1449            .unwrap();
1450
1451        assert_eq!(
1452            command.get_module(),
1453            &ModuleReference::Dependency {
1454                dependency: "dep".to_string(),
1455                module: "module".to_string()
1456            }
1457        );
1458    }
1459
1460    #[test]
1461    fn command_with_module_from_nonexistent_dependency() {
1462        let wasmer_toml = toml! {
1463            [package]
1464            name = "some/package"
1465            version = "0.0.0"
1466            description = ""
1467            [[command]]
1468            name = "cmd"
1469            module = "dep:module"
1470        };
1471        let manifest = Manifest::deserialize(wasmer_toml).unwrap();
1472
1473        let error = manifest.validate().unwrap_err();
1474
1475        assert_eq!(
1476            error,
1477            ValidationError::MissingDependency {
1478                command: "cmd".to_string(),
1479                dependency: "dep".to_string(),
1480                module_ref: ModuleReference::Dependency {
1481                    dependency: "dep".to_string(),
1482                    module: "module".to_string()
1483                }
1484            }
1485        );
1486    }
1487
1488    #[test]
1489    fn round_trip_dependency_module_ref() {
1490        let original = ModuleReference::Dependency {
1491            dependency: "my/dep".to_string(),
1492            module: "module".to_string(),
1493        };
1494
1495        let repr = original.to_string();
1496        let round_tripped: ModuleReference = repr.parse().unwrap();
1497
1498        assert_eq!(round_tripped, original);
1499    }
1500}