Skip to main content

thunderstore_engine/
ecosystem.rs

1//! The Thunderstore ecosystem schema: games, mod loaders, and install rules.
2//!
3//! This mirrors Thunderstore's upstream ecosystem schema — the same data that
4//! drives r2modman — rather than a bespoke normalized copy. Each game carries
5//! one or more profiles (`r2modman[]`) with a [`LoaderKind`](crate::ecosystem::LoaderKind),
6//! recursive [`InstallRule`](crate::ecosystem::InstallRule)s that route a package's
7//! files, and metadata (executables, store distributions). A top-level
8//! [`ModloaderPackage`](crate::ecosystem::ModloaderPackage) registry names every
9//! package that *is* a loader pack (and the subfolder of it that unpacks to the
10//! root), so the engine never hard-codes per-game loader facts.
11//!
12//! The canonical source is the Thunderstore ecosystem schema, published as JSON
13//! at [`DEFAULT_ECOSYSTEM_URL`](crate::ecosystem::DEFAULT_ECOSYSTEM_URL). A
14//! compressed snapshot is embedded at compile time as a fallback
15//! ([`Ecosystem::bundled`](crate::ecosystem::Ecosystem::bundled));
16//! [`Ecosystem::fetch_latest`](crate::ecosystem::Ecosystem::fetch_latest) refreshes
17//! it from the network. Parsing is intentionally defensive (`#[serde(default)]`,
18//! unknown loaders/tracking methods fall back to `Other`) because this is an
19//! external, evolving contract.
20
21#![deny(missing_docs)]
22
23use crate::error::{Error, Result};
24#[cfg(feature = "io")]
25use crate::retry::{RetryPolicy, retry_http};
26#[cfg(feature = "io")]
27use crate::util::SizeCap;
28use serde::{Deserialize, Deserializer, Serialize};
29use std::collections::HashMap;
30
31/// Compressed (`zstd`) snapshot of the ecosystem schema embedded at compile time
32/// as an offline fallback. Regenerate with the command documented in `README.md`.
33const BUNDLED_ECOSYSTEM: &[u8] = include_bytes!("../assets/ecosystem-schema.json.zst");
34
35/// The default URL used by [`Ecosystem::fetch_latest`] to refresh the snapshot.
36///
37/// # Trust
38///
39/// This is Thunderstore's official (experimental) schema endpoint — the same
40/// one r2modman consumes. Because the ecosystem drives install *routing* (where
41/// a package's files land on disk), whatever this endpoint returns is fully
42/// trusted; only refresh from a source you trust. Being an *experimental*
43/// endpoint, its shape may change over time, so parsing is defensive.
44///
45/// [`Ecosystem::fetch_latest`] returns an `Err` on any refresh failure and does
46/// *not* fall back on its own; a caller that wants stale-over-broken behavior
47/// should use [`Ecosystem::bundled`] (or a previously fetched value) when the
48/// refresh fails.
49pub const DEFAULT_ECOSYSTEM_URL: &str =
50  "https://thunderstore.io/api/experimental/schema/dev/latest/";
51
52/// Maximum size of an ecosystem schema fetched over the network. The real schema
53/// is small relative to this generous cap, which bounds the memory a misbehaving or
54/// compromised endpoint can force [`Ecosystem::fetch_latest`] to allocate.
55#[cfg(feature = "io")]
56const MAX_ECOSYSTEM_BYTES: u64 = 64 * 1024 * 1024;
57
58/// A parsed ecosystem schema: the known games plus the mod-loader package registry.
59#[derive(Debug, Clone, Serialize, Deserialize)]
60#[non_exhaustive]
61pub struct Ecosystem {
62  /// The schema version string reported by the source (e.g. `"0.3.0"`).
63  #[serde(
64    rename = "schemaVersion",
65    default,
66    deserialize_with = "null_as_default"
67  )]
68  pub schema_version: String,
69  /// All known games, keyed by their community slug.
70  #[serde(default, deserialize_with = "null_as_default")]
71  pub games: HashMap<String, GameDef>,
72  /// Every package that is itself a mod-loader pack, with its unpack root.
73  #[serde(
74    rename = "modloaderPackages",
75    default,
76    deserialize_with = "null_as_default"
77  )]
78  pub modloader_packages: Vec<ModloaderPackage>,
79}
80
81impl Ecosystem {
82  /// Loads the bundled ecosystem snapshot embedded in the binary.
83  ///
84  /// # Panics
85  ///
86  /// Panics if the bundled snapshot fails to decompress or parse, which is a
87  /// build-time invariant. Use [`Ecosystem::try_bundled`] to handle the error.
88  ///
89  /// # Examples
90  ///
91  /// Routing works offline with no network call, which is the point of the
92  /// bundled snapshot:
93  ///
94  /// ```
95  /// use thunderstore_engine::ecosystem::Ecosystem;
96  ///
97  /// let eco = Ecosystem::bundled();
98  ///
99  /// assert!(eco.games().count() > 0);
100  /// assert!(eco.game("valheim").is_some());
101  /// ```
102  pub fn bundled() -> Self {
103    Self::try_bundled()
104      .expect("bundled ecosystem snapshot must be valid; this is a build-time invariant")
105  }
106
107  /// Loads the bundled ecosystem snapshot, returning an error instead of
108  /// panicking if it cannot be decompressed or parsed.
109  pub fn try_bundled() -> Result<Self> {
110    let json = zstd::decode_all(BUNDLED_ECOSYSTEM)
111      .map_err(|e| Error::Ecosystem(format!("failed to decompress bundled schema: {}", e)))?;
112
113    Self::from_json_slice(&json)
114  }
115
116  /// Parses an ecosystem snapshot from a JSON string.
117  pub fn from_json(json: &str) -> Result<Self> {
118    Self::from_json_slice(json.as_bytes())
119  }
120
121  /// Parses an ecosystem snapshot from JSON bytes.
122  fn from_json_slice(bytes: &[u8]) -> Result<Self> {
123    serde_json::from_slice(bytes).map_err(|e| Error::Ecosystem(format!("failed to parse: {}", e)))
124  }
125
126  /// Fetches the latest ecosystem snapshot from `url` and parses it.
127  ///
128  /// Use [`DEFAULT_ECOSYSTEM_URL`] for the default location. The response is
129  /// fully trusted to define install routing, so only fetch from a source you
130  /// trust — see the [`DEFAULT_ECOSYSTEM_URL`] trust note. The response body is
131  /// size-bounded (see `MAX_ECOSYSTEM_BYTES`) so a misbehaving endpoint cannot
132  /// force unbounded allocation.
133  #[cfg(feature = "io")]
134  pub async fn fetch_latest(client: &reqwest::Client, url: &str) -> Result<Self> {
135    Self::fetch_latest_bounded(client, url, MAX_ECOSYSTEM_BYTES, &RetryPolicy::default()).await
136  }
137
138  /// [`fetch_latest`](Self::fetch_latest) with an explicit body-size cap and
139  /// retry policy. Transient network failures are retried; a size-cap breach or
140  /// a parse failure is terminal.
141  #[cfg(feature = "io")]
142  async fn fetch_latest_bounded(
143    client: &reqwest::Client,
144    url: &str,
145    max_bytes: u64,
146    retry: &RetryPolicy,
147  ) -> Result<Self> {
148    use futures::StreamExt;
149
150    let body = retry_http(retry, async || {
151      let response = client.get(url).send().await?.error_for_status()?;
152
153      let mut cap = SizeCap::new("ecosystem schema", max_bytes);
154
155      // Reject a declared-oversize body up front, before streaming a single byte,
156      // then enforce the cap against the actual streamed bytes.
157      cap.check_declared(response.content_length())?;
158
159      let mut stream = response.bytes_stream();
160      let mut body: Vec<u8> = Vec::new();
161
162      while let Some(chunk) = stream.next().await {
163        let chunk = chunk?;
164
165        cap.add(chunk.len() as u64)?;
166
167        body.extend_from_slice(&chunk);
168      }
169
170      Ok(body)
171    })
172    .await?;
173
174    Self::from_json_slice(&body)
175  }
176
177  /// Returns the game definition for a community slug, if known.
178  pub fn game(&self, slug: &str) -> Option<&GameDef> {
179    self.games.get(slug)
180  }
181
182  /// Returns the primary profile for a game (see [`GameDef::profile`]), the
183  /// lookup every install, uninstall, and launch operation starts from.
184  ///
185  /// # Errors
186  ///
187  /// [`Error::UnknownGame`] if no game has the slug `game`, and
188  /// [`Error::NoGameProfile`] if the game is known but has no profile.
189  ///
190  /// # Examples
191  ///
192  /// ```
193  /// use thunderstore_engine::Error;
194  /// use thunderstore_engine::ecosystem::Ecosystem;
195  ///
196  /// let eco = Ecosystem::bundled();
197  ///
198  /// assert!(eco.require_profile("valheim").is_ok());
199  /// assert!(matches!(eco.require_profile("not-a-game"), Err(Error::UnknownGame { .. })));
200  /// ```
201  pub fn require_profile(&self, game: &str) -> Result<&GameProfile> {
202    let def = self.game(game).ok_or_else(|| Error::UnknownGame {
203      game: game.to_string(),
204    })?;
205
206    def.profile().ok_or_else(|| Error::NoGameProfile {
207      game: game.to_string(),
208    })
209  }
210
211  /// Iterates over all known games.
212  pub fn games(&self) -> impl Iterator<Item = &GameDef> {
213    self.games.values()
214  }
215
216  /// Looks up a package in the mod-loader registry by its `Owner-Name`
217  /// identifier, returning its entry if the package is a loader pack.
218  ///
219  /// This is the reverse lookup that replaces per-game loader configuration: a
220  /// package that appears here is unpacked to the profile root (see
221  /// [`ModloaderPackage::root_folder`]); anything else is routed as a regular
222  /// mod via the game's [`InstallRule`]s.
223  pub fn modloader_package(&self, package_full_name: &str) -> Option<&ModloaderPackage> {
224    self
225      .modloader_packages
226      .iter()
227      .find(|m| m.package_id == package_full_name)
228  }
229}
230
231/// A single game's definition.
232///
233/// `#[non_exhaustive]`: fields may be added as the ecosystem schema grows.
234#[derive(Debug, Clone, Serialize, Deserialize)]
235#[non_exhaustive]
236pub struct GameDef {
237  /// The Thunderstore community slug.
238  #[serde(rename = "label", default, deserialize_with = "null_as_default")]
239  pub slug: String,
240  /// The schema's stable identifier for this game.
241  #[serde(default, deserialize_with = "null_as_default")]
242  pub uuid: String,
243  /// Display metadata (name, icon).
244  #[serde(default)]
245  pub meta: Meta,
246  /// Store distributions (Steam/Epic/etc.) at the game level.
247  #[serde(default, deserialize_with = "null_as_default")]
248  pub distributions: Vec<Distribution>,
249  /// Per-manager profiles, one per r2modman entry. Most games have one. A few
250  /// have more: a dedicated server (Risk of Rain 2, Valheim) or a second game
251  /// edition with its own folder (Outward's `OutwardDe`).
252  #[serde(rename = "r2modman", default, deserialize_with = "null_as_default")]
253  pub profiles: Vec<GameProfile>,
254}
255
256impl GameDef {
257  /// The human-readable display name of the game.
258  pub fn display_name(&self) -> &str {
259    &self.meta.display_name
260  }
261
262  /// Returns the primary profile to route against: the first `game`-instance
263  /// profile, or the first profile of any kind.
264  pub fn profile(&self) -> Option<&GameProfile> {
265    self
266      .profiles
267      .iter()
268      .find(|p| p.instance_type == InstanceType::Game)
269      .or_else(|| self.profiles.first())
270  }
271
272  /// The Thunderstore community of the primary [`profile`](Self::profile).
273  ///
274  /// See [`GameProfile::community`].
275  pub fn community(&self) -> Option<&str> {
276    self.profile()?.community()
277  }
278
279  /// Every distinct r2modman data folder this game's profiles use (see
280  /// [`GameProfile::internal_folder_name`]), in entry order.
281  ///
282  /// An importer of r2modman data reads `<data root>/<folder>/profiles/` for
283  /// each one. A server entry can share its game's folder (Risk of Rain 2,
284  /// Valheim), which then holds the profiles of both, while a second edition
285  /// can have its own (Outward has `Outward` and `OutwardDe`), so reading only
286  /// the primary profile's folder misses profiles.
287  ///
288  /// # Examples
289  ///
290  /// ```
291  /// use thunderstore_engine::ecosystem::Ecosystem;
292  ///
293  /// let eco = Ecosystem::bundled();
294  ///
295  /// assert_eq!(eco.game("valheim").unwrap().r2modman_folders(), ["Valheim"]);
296  /// assert_eq!(eco.game("outward").unwrap().r2modman_folders(), ["Outward", "OutwardDe"]);
297  /// ```
298  pub fn r2modman_folders(&self) -> Vec<&str> {
299    let mut folders: Vec<&str> = Vec::new();
300
301    for folder in self
302      .profiles
303      .iter()
304      .filter_map(|p| p.internal_folder_name.as_deref())
305    {
306      if !folders.contains(&folder) {
307        folders.push(folder);
308      }
309    }
310
311    folders
312  }
313}
314
315/// A per-manager profile for a game: its loader, install rules, and metadata.
316///
317/// `#[non_exhaustive]`: fields may be added as the ecosystem schema grows.
318#[derive(Debug, Clone, Serialize, Deserialize)]
319#[non_exhaustive]
320pub struct GameProfile {
321  /// Display metadata for this profile.
322  #[serde(default)]
323  pub meta: Meta,
324  /// The mod-loader family this profile uses.
325  #[serde(
326    rename = "packageLoader",
327    default,
328    deserialize_with = "null_as_default"
329  )]
330  pub package_loader: LoaderKind,
331  /// Whether this profile targets the game or a dedicated server.
332  #[serde(
333    rename = "gameInstanceType",
334    default,
335    deserialize_with = "null_as_default"
336  )]
337  pub instance_type: InstanceType,
338  /// Candidate executable names for game-directory validation.
339  #[serde(rename = "exeNames", default, deserialize_with = "null_as_default")]
340  pub exe_names: Vec<String>,
341  /// Store distributions for this profile.
342  #[serde(default, deserialize_with = "null_as_default")]
343  pub distributions: Vec<Distribution>,
344  /// Filenames to skip when copying a package's contents (e.g. `manifest.json`).
345  /// A JSON `null` is normalized to an empty list.
346  #[serde(
347    rename = "relativeFileExclusions",
348    default,
349    deserialize_with = "null_as_default"
350  )]
351  pub relative_file_exclusions: Vec<String>,
352  /// The routing rules for a regular mod's files (a recursive forest).
353  #[serde(rename = "installRules", default, deserialize_with = "null_as_default")]
354  pub install_rules: Vec<InstallRule>,
355  /// The loader-specific data subdirectory, when the schema records one.
356  #[serde(rename = "dataFolderName", default)]
357  pub data_folder_name: Option<String>,
358  /// The manager's settings identifier for this profile. Unique per entry, but
359  /// not the name of r2modman's data folder; that is
360  /// [`internal_folder_name`](Self::internal_folder_name).
361  #[serde(rename = "settingsIdentifier", default)]
362  pub settings_identifier: Option<String>,
363  /// The folder under r2modman's data root that holds this profile's package
364  /// cache and profiles: `<data root>/<internal_folder_name>/profiles/<name>/`.
365  ///
366  /// It differs from [`settings_identifier`](Self::settings_identifier) for
367  /// several games (`ETG` vs `EnterTheGungeon`, `DiscoElysium` vs
368  /// `Disco Elysium`), and a server entry can share its game's folder.
369  #[serde(rename = "internalFolderName", default)]
370  pub internal_folder_name: Option<String>,
371  /// The package-index URL for this community.
372  #[serde(rename = "packageIndex", default)]
373  pub package_index: Option<String>,
374}
375
376impl GameProfile {
377  /// The Steam application id, parsed from the profile's distributions, if any.
378  pub fn steam_app_id(&self) -> Option<u32> {
379    self
380      .distributions
381      .iter()
382      .find(|d| d.platform == "steam")
383      .and_then(|d| d.identifier.parse().ok())
384  }
385
386  /// The Thunderstore community slug this profile's packages come from, read
387  /// from the `/c/<community>/` segment of [`package_index`](Self::package_index).
388  ///
389  /// The slug can differ from the profile's own identifiers: the Outward
390  /// Definitive profile (`OutwardDe`) and the Valheim dedicated server
391  /// (`ValheimServer`) both use their game's community. Returns `None` when the
392  /// profile has no package index or its path is not `/c/<slug>/...`.
393  ///
394  /// # Examples
395  ///
396  /// ```
397  /// use thunderstore_engine::ecosystem::Ecosystem;
398  ///
399  /// let eco = Ecosystem::bundled();
400  /// let valheim = eco.game("valheim").unwrap().profile().unwrap();
401  ///
402  /// assert_eq!(valheim.community(), Some("valheim"));
403  /// ```
404  pub fn community(&self) -> Option<&str> {
405    let url = self.package_index.as_deref()?;
406    let after_scheme = url.split_once("://").map_or(url, |(_, rest)| rest);
407    let (_, path) = after_scheme.split_once('/')?;
408    let (community, _) = path.strip_prefix("c/")?.split_once('/')?;
409    let is_slug = !community.is_empty()
410      && community
411        .chars()
412        .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
413
414    is_slug.then_some(community)
415  }
416}
417
418/// Display metadata (name and icon) attached to a game or profile.
419#[derive(Debug, Clone, Default, Serialize, Deserialize)]
420#[non_exhaustive]
421pub struct Meta {
422  /// Human-readable display name.
423  #[serde(rename = "displayName", default, deserialize_with = "null_as_default")]
424  pub display_name: String,
425  /// Relative URL to the icon asset.
426  #[serde(rename = "iconUrl", default, deserialize_with = "null_as_default")]
427  pub icon_url: String,
428}
429
430/// A store distribution: which platform lists the game and under what id.
431#[derive(Debug, Clone, Serialize, Deserialize)]
432#[non_exhaustive]
433pub struct Distribution {
434  /// The platform, e.g. `"steam"`, `"epic-games-store"`, `"xbox-game-pass"`.
435  #[serde(default, deserialize_with = "null_as_default")]
436  pub platform: String,
437  /// The platform-specific identifier (e.g. a Steam app id as a string). May be
438  /// `null` upstream (normalized to an empty string).
439  #[serde(default, deserialize_with = "null_as_default")]
440  pub identifier: String,
441}
442
443/// A package that is itself a mod-loader pack.
444///
445/// Membership in the registry is how the engine decides a package unpacks to the
446/// profile root rather than being routed as a regular mod.
447///
448/// `#[non_exhaustive]`: fields may be added as the ecosystem schema grows.
449#[derive(Debug, Clone, Serialize, Deserialize)]
450#[non_exhaustive]
451pub struct ModloaderPackage {
452  /// The package's `Owner-Name` identifier.
453  #[serde(rename = "packageId", default, deserialize_with = "null_as_default")]
454  pub package_id: String,
455  /// The subfolder within the pack whose *contents* unpack to the root, or an
456  /// empty string when the pack's own root should be copied directly.
457  #[serde(rename = "rootFolder", default, deserialize_with = "null_as_default")]
458  pub root_folder: String,
459  /// The loader family this pack provides.
460  #[serde(default, deserialize_with = "null_as_default")]
461  pub loader: LoaderKind,
462}
463
464/// How files matched by an [`InstallRule`] are placed and tracked under its route.
465///
466/// `#[non_exhaustive]`: new tracking methods may be added without a breaking
467/// change, so downstream `match`es must include a wildcard arm.
468#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
469#[serde(rename_all = "kebab-case")]
470#[non_exhaustive]
471pub enum TrackingMethod {
472  /// Namespaced under `route/<Owner-Name>/`. The contents of a matched override
473  /// folder keep their structure; a file reached outside one (by extension or
474  /// the default location) is flattened to its base name. The default.
475  #[default]
476  Subdir,
477  /// Written directly under `route/`, shared and untracked (e.g. config).
478  None,
479  /// Written directly under `route/`, shared, but each file recorded for
480  /// exact uninstall.
481  State,
482  /// Namespaced under `route/<Owner-Name>/`, preserving internal structure.
483  SubdirNoFlatten,
484  /// The package archive is copied into `route/` as a zip.
485  PackageZip,
486  /// An unrecognized tracking method from a newer schema.
487  #[serde(other)]
488  Other,
489}
490
491impl TrackingMethod {
492  /// Whether files routed via this method live in a per-mod `<Owner-Name>/`
493  /// folder (and are therefore reconciled by directory in [`crate::install`]).
494  pub fn is_namespaced(self) -> bool {
495    matches!(
496      self,
497      TrackingMethod::Subdir | TrackingMethod::SubdirNoFlatten
498    )
499  }
500}
501
502/// A single, possibly nested, routing rule for a regular mod's files.
503///
504/// `#[non_exhaustive]`: fields may be added as the ecosystem schema grows.
505#[derive(Debug, Clone, Serialize, Deserialize)]
506#[non_exhaustive]
507pub struct InstallRule {
508  /// Destination path relative to the profile root, e.g. `"BepInEx/plugins"`.
509  /// The final path segment is the override-folder name matched at a package's
510  /// root (e.g. `plugins`).
511  #[serde(default, deserialize_with = "null_as_default")]
512  pub route: String,
513  /// Extensions (matched as filename suffixes) that route a loose file here.
514  /// When several rules match, the longest suffix wins.
515  #[serde(
516    rename = "defaultFileExtensions",
517    default,
518    deserialize_with = "null_as_default"
519  )]
520  pub default_file_extensions: Vec<String>,
521  /// How matched files are placed and tracked under [`InstallRule::route`].
522  #[serde(
523    rename = "trackingMethod",
524    default,
525    deserialize_with = "null_as_default"
526  )]
527  pub tracking_method: TrackingMethod,
528  /// Nested rules applied within this rule's route.
529  #[serde(rename = "subRoutes", default, deserialize_with = "null_as_default")]
530  pub sub_routes: Vec<InstallRule>,
531  /// Whether this rule is the catch-all for files matching no other rule.
532  /// At most one rule per profile is the default location; some have none.
533  #[serde(
534    rename = "isDefaultLocation",
535    default,
536    deserialize_with = "null_as_default"
537  )]
538  pub is_default_location: bool,
539}
540
541/// Whether a [`GameProfile`] targets the game itself or a dedicated server.
542#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
543#[serde(rename_all = "lowercase")]
544#[non_exhaustive]
545pub enum InstanceType {
546  /// The playable game (the default).
547  #[default]
548  Game,
549  /// A dedicated server build.
550  Server,
551  /// An unrecognized instance type from a newer schema.
552  #[serde(other)]
553  Other,
554}
555
556/// The mod-loader family. Unknown values deserialize to [`LoaderKind::Other`].
557///
558/// `#[non_exhaustive]`: new loader families may be added without a breaking
559/// change, so downstream `match`es must include a wildcard arm.
560#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
561#[non_exhaustive]
562pub enum LoaderKind {
563  /// BepInEx (`bepinex`), injected through Unity Doorstop.
564  #[serde(rename = "bepinex")]
565  BepInEx,
566  /// BepisLoader (`bepisloader`), the BepInEx successor, which takes its own
567  /// argument set rather than Doorstop's.
568  #[serde(rename = "bepisloader")]
569  BepisLoader,
570  /// GDWeave (`gdweave`), pointed at its mod folder with
571  /// `--gdweave-folder-override`.
572  #[serde(rename = "gdweave")]
573  GdWeave,
574  /// Godot Mod Loader (`godotml`), driven by a `--script` entry point plus
575  /// `--mods-path`.
576  #[serde(rename = "godotml")]
577  GodotMl,
578  /// Lovely (`lovely`), pointed at its mod folder with `--mod-dir`.
579  #[serde(rename = "lovely")]
580  Lovely,
581  /// MelonLoader (`melonloader`).
582  #[serde(rename = "melonloader")]
583  MelonLoader,
584  /// MelonLoader shipped in a nested package layout (`recursive-melonloader`).
585  /// Injects identically to [`LoaderKind::MelonLoader`]; only the package's file
586  /// layout differs.
587  #[serde(rename = "recursive-melonloader")]
588  RecursiveMelonLoader,
589  /// Northstar (`northstar`), selected with `-northstar` and a `-profile=`
590  /// directory.
591  #[serde(rename = "northstar")]
592  Northstar,
593  /// ReturnOfModding (`return-of-modding`), pointed at its root with
594  /// `--rom_modding_root_folder`.
595  #[serde(rename = "return-of-modding")]
596  ReturnOfModding,
597  /// Rivet (`rivet`), enabled with `-rivetEnable` plus explicit loader and mod
598  /// paths.
599  #[serde(rename = "rivet")]
600  Rivet,
601  /// Shimloader (`shimloader`), which takes separate mod, pak, cfg, and overlay
602  /// directories.
603  #[serde(rename = "shimloader")]
604  Shimloader,
605  /// Unity Mod Manager (`umm`), injected through Unity Doorstop like
606  /// [`LoaderKind::BepInEx`].
607  #[serde(rename = "umm")]
608  Umm,
609  /// A community with no mod loader.
610  #[serde(rename = "none")]
611  None,
612  /// An unrecognized loader family from a newer schema, or an absent value.
613  #[default]
614  #[serde(other)]
615  Other,
616}
617
618/// Normalizes a JSON `null` (or absent value) to `T::default()` during
619/// deserialization, so a nullable list field becomes an empty `Vec`.
620fn null_as_default<'de, D, T>(deserializer: D) -> std::result::Result<T, D::Error>
621where
622  D: Deserializer<'de>,
623  T: Deserialize<'de> + Default,
624{
625  let opt = Option::<T>::deserialize(deserializer)?;
626
627  Ok(opt.unwrap_or_default())
628}
629
630#[cfg(test)]
631mod tests {
632  use super::*;
633
634  #[test]
635  fn test_bundled_parses() {
636    let eco = Ecosystem::bundled();
637
638    assert!(!eco.games.is_empty());
639    assert!(!eco.modloader_packages.is_empty());
640    assert_eq!(eco.schema_version, "0.3.0");
641  }
642
643  #[test]
644  fn test_valheim_bepinex() {
645    let eco = Ecosystem::bundled();
646    let valheim = eco.game("valheim").expect("valheim present");
647
648    assert_eq!(valheim.slug, "valheim");
649    assert_eq!(valheim.display_name(), "Valheim");
650
651    let profile = valheim.profile().expect("a profile");
652
653    assert_eq!(profile.package_loader, LoaderKind::BepInEx);
654    assert_eq!(profile.instance_type, InstanceType::Game);
655    assert_eq!(profile.steam_app_id(), Some(892970));
656    assert!(!profile.install_rules.is_empty());
657
658    let plugins = profile
659      .install_rules
660      .iter()
661      .find(|r| r.route == "BepInEx/plugins")
662      .expect("plugins rule");
663
664    assert_eq!(plugins.tracking_method, TrackingMethod::Subdir);
665    assert!(plugins.tracking_method.is_namespaced());
666
667    let monomod = profile
668      .install_rules
669      .iter()
670      .find(|r| r.route == "BepInEx/monomod")
671      .expect("monomod rule");
672
673    assert!(
674      monomod
675        .default_file_extensions
676        .iter()
677        .any(|e| e == ".mm.dll")
678    );
679
680    let config = profile
681      .install_rules
682      .iter()
683      .find(|r| r.route == "BepInEx/config")
684      .expect("config rule");
685
686    assert!(!config.tracking_method.is_namespaced());
687  }
688
689  #[test]
690  fn community_comes_from_the_profile_package_index() {
691    let eco = Ecosystem::bundled();
692    let outward = eco.game("outward").expect("outward present");
693    let definitive = outward
694      .profiles
695      .iter()
696      .find(|p| p.settings_identifier.as_deref() == Some("OutwardDe"))
697      .expect("Outward Definitive profile");
698
699    assert_eq!(definitive.community(), Some("outward"));
700    assert_eq!(outward.community(), Some("outward"));
701
702    let server = eco
703      .game("valheim")
704      .expect("valheim present")
705      .profiles
706      .iter()
707      .find(|p| p.instance_type == InstanceType::Server)
708      .expect("valheim server profile");
709
710    assert_eq!(server.settings_identifier.as_deref(), Some("ValheimServer"));
711    assert_eq!(server.community(), Some("valheim"));
712  }
713
714  #[test]
715  fn r2modman_folder_differs_from_settings_identifier_where_the_schema_says() {
716    let eco = Ecosystem::bundled();
717    let cases = [
718      ("disco-elysium", "Disco Elysium", "DiscoElysium"),
719      ("enter-the-gungeon", "EnterTheGungeon", "ETG"),
720      ("i-am-your-beast", "I Am Your Beast", "IAmYourBeast"),
721      (
722        "old-market-simulator",
723        "Old Market Simulator",
724        "OldMarketSimulator",
725      ),
726      ("peaks-of-yore", "Peaks of Yore", "PeaksOfYore"),
727      (
728        "tcg-card-shop-simulator",
729        "TCG Card Shop Simulator",
730        "TCGCardShopSimulator",
731      ),
732      (
733        "totally-accurate-battle-simulator",
734        "TotallyAccurateBattleSimulator",
735        "TABS",
736      ),
737    ];
738
739    for (slug, settings, folder) in cases {
740      let profile = eco.require_profile(slug).unwrap();
741
742      assert_eq!(
743        profile.settings_identifier.as_deref(),
744        Some(settings),
745        "{slug}"
746      );
747      assert_eq!(
748        profile.internal_folder_name.as_deref(),
749        Some(folder),
750        "{slug}"
751      );
752      assert_eq!(
753        eco.game(slug).unwrap().r2modman_folders(),
754        [folder],
755        "{slug}"
756      );
757    }
758  }
759
760  #[test]
761  fn a_server_entry_shares_its_games_r2modman_folder() {
762    let eco = Ecosystem::bundled();
763
764    for (slug, server_settings, folder) in [
765      ("riskofrain2", "RiskOfRain2Server", "RiskOfRain2"),
766      ("valheim", "ValheimServer", "Valheim"),
767    ] {
768      let game = eco.game(slug).unwrap();
769      let server = game
770        .profiles
771        .iter()
772        .find(|p| p.instance_type == InstanceType::Server)
773        .unwrap();
774
775      assert_eq!(
776        server.settings_identifier.as_deref(),
777        Some(server_settings),
778        "{slug}"
779      );
780      assert_eq!(
781        server.internal_folder_name.as_deref(),
782        Some(folder),
783        "{slug}"
784      );
785      assert_eq!(
786        game.profile().unwrap().internal_folder_name.as_deref(),
787        Some(folder),
788        "{slug}"
789      );
790      assert_eq!(game.r2modman_folders(), [folder], "{slug}");
791    }
792  }
793
794  #[test]
795  fn outward_editions_each_have_their_own_r2modman_folder() {
796    let eco = Ecosystem::bundled();
797    let outward = eco.game("outward").unwrap();
798
799    assert!(
800      outward
801        .profiles
802        .iter()
803        .all(|p| p.instance_type == InstanceType::Game)
804    );
805    assert_eq!(outward.r2modman_folders(), ["Outward", "OutwardDe"]);
806  }
807
808  #[test]
809  fn every_bundled_r2modman_entry_names_its_folder() {
810    let eco = Ecosystem::bundled();
811    let unnamed: Vec<&str> = eco
812      .games()
813      .filter(|g| {
814        g.profiles
815          .iter()
816          .any(|p| p.internal_folder_name.as_deref().is_none_or(str::is_empty))
817      })
818      .map(|g| g.slug.as_str())
819      .collect();
820
821    assert!(unnamed.is_empty(), "{unnamed:?}");
822  }
823
824  #[test]
825  fn r2modman_folders_is_empty_without_r2modman_entries() {
826    let eco = Ecosystem::bundled();
827
828    assert!(
829      eco
830        .game("phasmophobia")
831        .unwrap()
832        .r2modman_folders()
833        .is_empty()
834    );
835  }
836
837  #[test]
838  fn community_is_none_without_a_usable_package_index() {
839    let community_of = |index: Option<&str>| {
840      let json = serde_json::json!({
841        "games": { "g": { "r2modman": [{ "packageIndex": index }] } }
842      });
843      let eco = Ecosystem::from_json(&json.to_string()).unwrap();
844
845      eco.game("g").unwrap().community().map(str::to_string)
846    };
847
848    assert_eq!(
849      community_of(Some("https://example.com/c/my-game/api/v1/package/")),
850      Some("my-game".to_string())
851    );
852    assert_eq!(community_of(None), None);
853    assert_eq!(
854      community_of(Some("https://thunderstore.io/api/v1/package/")),
855      None
856    );
857    assert_eq!(
858      community_of(Some("https://thunderstore.io/c/../api/v1/package/")),
859      None
860    );
861    assert_eq!(community_of(Some("https://thunderstore.io/c/")), None);
862  }
863
864  #[test]
865  fn test_modloader_registry_lookup() {
866    let eco = Ecosystem::bundled();
867
868    let pack = eco
869      .modloader_package("denikson-BepInExPack_Valheim")
870      .expect("valheim loader pack present");
871
872    assert_eq!(pack.root_folder, "BepInExPack_Valheim");
873    assert_eq!(pack.loader, LoaderKind::BepInEx);
874
875    assert!(eco.modloader_package("Author-SomeMod").is_none());
876  }
877
878  #[test]
879  fn test_melonloader_game_present() {
880    let eco = Ecosystem::bundled();
881
882    let game = eco
883      .games()
884      .find(|g| {
885        g.profile()
886          .map(|p| p.package_loader == LoaderKind::MelonLoader)
887          .unwrap_or(false)
888      })
889      .expect("at least one MelonLoader game");
890
891    assert!(game.profile().is_some());
892  }
893
894  #[test]
895  fn test_unknown_loader_falls_back_to_other() {
896    let json = r#"{
897      "schemaVersion": "9.9.9",
898      "games": {
899        "x": { "label": "x", "meta": {"displayName": "X"},
900               "r2modman": [ { "packageLoader": "someNewLoader", "installRules": [] } ] }
901      },
902      "modloaderPackages": []
903    }"#;
904
905    let eco = Ecosystem::from_json(json).unwrap();
906    let profile = eco.game("x").unwrap().profile().unwrap();
907
908    assert_eq!(profile.package_loader, LoaderKind::Other);
909  }
910
911  #[test]
912  fn require_profile_tells_an_unknown_game_from_one_without_a_profile() {
913    let json = r#"{
914      "games": {
915        "bare": { "label": "bare", "r2modman": [] },
916        "x": { "label": "x", "r2modman": [ { "packageLoader": "bepinex", "installRules": [] } ] }
917      }
918    }"#;
919    let eco = Ecosystem::from_json(json).unwrap();
920
921    assert!(eco.require_profile("x").is_ok());
922    assert!(matches!(
923      eco.require_profile("ghost"),
924      Err(Error::UnknownGame { game }) if game == "ghost"
925    ));
926    assert!(matches!(
927      eco.require_profile("bare"),
928      Err(Error::NoGameProfile { game }) if game == "bare"
929    ));
930  }
931
932  #[test]
933  fn test_null_relative_file_exclusions_normalizes_to_empty() {
934    let json = r#"{
935      "games": {
936        "x": { "label": "x",
937               "r2modman": [ { "packageLoader": "bepinex", "relativeFileExclusions": null, "installRules": [] } ] }
938      }
939    }"#;
940
941    let eco = Ecosystem::from_json(json).unwrap();
942    let profile = eco.game("x").unwrap().profile().unwrap();
943
944    assert!(profile.relative_file_exclusions.is_empty());
945  }
946
947  #[test]
948  fn test_null_enum_and_bool_fields_normalize_to_defaults() {
949    let json = r#"{
950      "games": {
951        "x": { "label": "x",
952               "r2modman": [ { "packageLoader": null, "gameInstanceType": null,
953                 "installRules": [ { "route": "Mods", "trackingMethod": null, "isDefaultLocation": null } ] } ] }
954      }
955    }"#;
956
957    let eco = Ecosystem::from_json(json).unwrap();
958    let profile = eco.game("x").unwrap().profile().unwrap();
959
960    assert_eq!(profile.package_loader, LoaderKind::Other);
961    assert_eq!(profile.instance_type, InstanceType::Game);
962
963    let rule = &profile.install_rules[0];
964
965    assert_eq!(rule.tracking_method, TrackingMethod::Subdir);
966    assert!(!rule.is_default_location);
967  }
968
969  #[test]
970  fn test_unknown_tracking_method_falls_back_to_other() {
971    let json = r#"{
972      "games": {
973        "x": { "label": "x",
974               "r2modman": [ { "packageLoader": "bepinex",
975                 "installRules": [ { "route": "Mods", "trackingMethod": "brand-new-method" } ] } ] }
976      }
977    }"#;
978
979    let eco = Ecosystem::from_json(json).unwrap();
980    let rule = &eco.game("x").unwrap().profile().unwrap().install_rules[0];
981
982    assert_eq!(rule.tracking_method, TrackingMethod::Other);
983    assert!(!rule.tracking_method.is_namespaced());
984  }
985
986  #[test]
987  #[cfg(feature = "io")]
988  fn test_fetch_latest_rejects_declared_oversize_body() {
989    let mut server = mockito::Server::new();
990    let body = "x".repeat(1000);
991
992    let mock = server
993      .mock("GET", "/schema")
994      .with_status(200)
995      .with_body(&body)
996      .create();
997
998    let url = format!("{}/schema", server.url());
999    let rt = tokio::runtime::Runtime::new().unwrap();
1000    let client = reqwest::Client::new();
1001
1002    let result = rt.block_on(Ecosystem::fetch_latest_bounded(
1003      &client,
1004      &url,
1005      16,
1006      &RetryPolicy::none(),
1007    ));
1008
1009    assert!(matches!(result, Err(Error::SizeLimitExceeded { .. })));
1010
1011    mock.assert();
1012  }
1013
1014  #[test]
1015  #[cfg(feature = "io")]
1016  fn test_fetch_latest_rejects_streamed_oversize_body() {
1017    let mut server = mockito::Server::new();
1018
1019    // A chunked body carries no Content-Length, so the cap must be enforced from
1020    // the actual streamed bytes.
1021    let mock = server
1022      .mock("GET", "/schema")
1023      .with_status(200)
1024      .with_chunked_body(|w| w.write_all(&vec![b'x'; 1000]))
1025      .create();
1026
1027    let url = format!("{}/schema", server.url());
1028    let rt = tokio::runtime::Runtime::new().unwrap();
1029    let client = reqwest::Client::new();
1030
1031    let result = rt.block_on(Ecosystem::fetch_latest_bounded(
1032      &client,
1033      &url,
1034      16,
1035      &RetryPolicy::none(),
1036    ));
1037
1038    assert!(matches!(result, Err(Error::SizeLimitExceeded { .. })));
1039
1040    mock.assert();
1041  }
1042
1043  #[test]
1044  #[cfg(feature = "io")]
1045  fn test_fetch_latest_parses_network_schema() {
1046    let mut server = mockito::Server::new();
1047
1048    let body = r#"{
1049      "schemaVersion": "0.3.0",
1050      "games": {
1051        "valheim": { "label": "valheim", "meta": {"displayName": "Valheim"},
1052          "r2modman": [ { "packageLoader": "bepinex",
1053            "installRules": [ { "route": "BepInEx/plugins", "trackingMethod": "subdir",
1054              "isDefaultLocation": true, "defaultFileExtensions": [".dll"] } ] } ] }
1055      },
1056      "modloaderPackages": [
1057        { "packageId": "denikson-BepInExPack_Valheim", "rootFolder": "BepInExPack_Valheim", "loader": "bepinex" }
1058      ]
1059    }"#;
1060
1061    let mock = server
1062      .mock("GET", "/schema")
1063      .with_status(200)
1064      .with_header("Content-Type", "application/json")
1065      .with_body(body)
1066      .create();
1067
1068    let url = format!("{}/schema", server.url());
1069    let rt = tokio::runtime::Runtime::new().unwrap();
1070    let client = reqwest::Client::new();
1071    let eco = rt.block_on(Ecosystem::fetch_latest(&client, &url)).unwrap();
1072
1073    assert_eq!(eco.schema_version, "0.3.0");
1074
1075    let profile = eco.game("valheim").unwrap().profile().unwrap();
1076
1077    assert_eq!(profile.package_loader, LoaderKind::BepInEx);
1078    assert!(
1079      eco
1080        .modloader_package("denikson-BepInExPack_Valheim")
1081        .is_some()
1082    );
1083
1084    mock.assert();
1085  }
1086
1087  #[test]
1088  fn steam_app_id_none_when_missing_or_unparseable() {
1089    // No steam distribution => None.
1090    let no_steam: GameProfile = serde_json::from_str(
1091      r#"{"distributions":[{"platform":"epic-games-store","identifier":"abc"}]}"#,
1092    )
1093    .unwrap();
1094
1095    assert_eq!(no_steam.steam_app_id(), None);
1096
1097    // A steam distribution whose id is not numeric => None.
1098    let bad_steam: GameProfile =
1099      serde_json::from_str(r#"{"distributions":[{"platform":"steam","identifier":"nope"}]}"#)
1100        .unwrap();
1101
1102    assert_eq!(bad_steam.steam_app_id(), None);
1103
1104    // A steam distribution with a numeric id => Some.
1105    let steam: GameProfile =
1106      serde_json::from_str(r#"{"distributions":[{"platform":"steam","identifier":"892970"}]}"#)
1107        .unwrap();
1108
1109    assert_eq!(steam.steam_app_id(), Some(892970));
1110  }
1111
1112  #[test]
1113  fn game_profile_prefers_game_instance_then_falls_back() {
1114    // Only a server-instance profile: `profile()` falls back to the first one.
1115    let server_only: GameDef =
1116      serde_json::from_str(r#"{"r2modman":[{"gameInstanceType":"server"}]}"#).unwrap();
1117
1118    assert_eq!(
1119      server_only.profile().unwrap().instance_type,
1120      InstanceType::Server
1121    );
1122
1123    // A game-instance profile is preferred over a server one, whatever the order.
1124    let mixed: GameDef = serde_json::from_str(
1125      r#"{"r2modman":[{"gameInstanceType":"server"},{"gameInstanceType":"game"}]}"#,
1126    )
1127    .unwrap();
1128
1129    assert_eq!(mixed.profile().unwrap().instance_type, InstanceType::Game);
1130
1131    // No profiles at all => None.
1132    let empty: GameDef = serde_json::from_str(r#"{"r2modman":[]}"#).unwrap();
1133
1134    assert!(empty.profile().is_none());
1135  }
1136}