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. Most games have one; a few add a dedicated-server
250  /// profile whose install rules match the primary profile's.
251  #[serde(rename = "r2modman", default, deserialize_with = "null_as_default")]
252  pub profiles: Vec<GameProfile>,
253}
254
255impl GameDef {
256  /// The human-readable display name of the game.
257  pub fn display_name(&self) -> &str {
258    &self.meta.display_name
259  }
260
261  /// Returns the primary profile to route against: the first `game`-instance
262  /// profile, or the first profile of any kind.
263  pub fn profile(&self) -> Option<&GameProfile> {
264    self
265      .profiles
266      .iter()
267      .find(|p| p.instance_type == InstanceType::Game)
268      .or_else(|| self.profiles.first())
269  }
270
271  /// The Thunderstore community of the primary [`profile`](Self::profile).
272  ///
273  /// See [`GameProfile::community`].
274  pub fn community(&self) -> Option<&str> {
275    self.profile()?.community()
276  }
277}
278
279/// A per-manager profile for a game: its loader, install rules, and metadata.
280///
281/// `#[non_exhaustive]`: fields may be added as the ecosystem schema grows.
282#[derive(Debug, Clone, Serialize, Deserialize)]
283#[non_exhaustive]
284pub struct GameProfile {
285  /// Display metadata for this profile.
286  #[serde(default)]
287  pub meta: Meta,
288  /// The mod-loader family this profile uses.
289  #[serde(
290    rename = "packageLoader",
291    default,
292    deserialize_with = "null_as_default"
293  )]
294  pub package_loader: LoaderKind,
295  /// Whether this profile targets the game or a dedicated server.
296  #[serde(
297    rename = "gameInstanceType",
298    default,
299    deserialize_with = "null_as_default"
300  )]
301  pub instance_type: InstanceType,
302  /// Candidate executable names for game-directory validation.
303  #[serde(rename = "exeNames", default, deserialize_with = "null_as_default")]
304  pub exe_names: Vec<String>,
305  /// Store distributions for this profile.
306  #[serde(default, deserialize_with = "null_as_default")]
307  pub distributions: Vec<Distribution>,
308  /// Filenames to skip when copying a package's contents (e.g. `manifest.json`).
309  /// A JSON `null` is normalized to an empty list.
310  #[serde(
311    rename = "relativeFileExclusions",
312    default,
313    deserialize_with = "null_as_default"
314  )]
315  pub relative_file_exclusions: Vec<String>,
316  /// The routing rules for a regular mod's files (a recursive forest).
317  #[serde(rename = "installRules", default, deserialize_with = "null_as_default")]
318  pub install_rules: Vec<InstallRule>,
319  /// The loader-specific data subdirectory, when the schema records one.
320  #[serde(rename = "dataFolderName", default)]
321  pub data_folder_name: Option<String>,
322  /// The manager's settings identifier for this profile.
323  #[serde(rename = "settingsIdentifier", default)]
324  pub settings_identifier: Option<String>,
325  /// The package-index URL for this community.
326  #[serde(rename = "packageIndex", default)]
327  pub package_index: Option<String>,
328}
329
330impl GameProfile {
331  /// The Steam application id, parsed from the profile's distributions, if any.
332  pub fn steam_app_id(&self) -> Option<u32> {
333    self
334      .distributions
335      .iter()
336      .find(|d| d.platform == "steam")
337      .and_then(|d| d.identifier.parse().ok())
338  }
339
340  /// The Thunderstore community slug this profile's packages come from, read
341  /// from the `/c/<community>/` segment of [`package_index`](Self::package_index).
342  ///
343  /// The slug can differ from the profile's own identifiers: the Outward
344  /// Definitive profile (`OutwardDe`) and the Valheim dedicated server
345  /// (`ValheimServer`) both use their game's community. Returns `None` when the
346  /// profile has no package index or its path is not `/c/<slug>/...`.
347  ///
348  /// # Examples
349  ///
350  /// ```
351  /// use thunderstore_engine::ecosystem::Ecosystem;
352  ///
353  /// let eco = Ecosystem::bundled();
354  /// let valheim = eco.game("valheim").unwrap().profile().unwrap();
355  ///
356  /// assert_eq!(valheim.community(), Some("valheim"));
357  /// ```
358  pub fn community(&self) -> Option<&str> {
359    let url = self.package_index.as_deref()?;
360    let after_scheme = url.split_once("://").map_or(url, |(_, rest)| rest);
361    let (_, path) = after_scheme.split_once('/')?;
362    let (community, _) = path.strip_prefix("c/")?.split_once('/')?;
363    let is_slug = !community.is_empty()
364      && community
365        .chars()
366        .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
367
368    is_slug.then_some(community)
369  }
370}
371
372/// Display metadata (name and icon) attached to a game or profile.
373#[derive(Debug, Clone, Default, Serialize, Deserialize)]
374#[non_exhaustive]
375pub struct Meta {
376  /// Human-readable display name.
377  #[serde(rename = "displayName", default, deserialize_with = "null_as_default")]
378  pub display_name: String,
379  /// Relative URL to the icon asset.
380  #[serde(rename = "iconUrl", default, deserialize_with = "null_as_default")]
381  pub icon_url: String,
382}
383
384/// A store distribution: which platform lists the game and under what id.
385#[derive(Debug, Clone, Serialize, Deserialize)]
386#[non_exhaustive]
387pub struct Distribution {
388  /// The platform, e.g. `"steam"`, `"epic-games-store"`, `"xbox-game-pass"`.
389  #[serde(default, deserialize_with = "null_as_default")]
390  pub platform: String,
391  /// The platform-specific identifier (e.g. a Steam app id as a string). May be
392  /// `null` upstream (normalized to an empty string).
393  #[serde(default, deserialize_with = "null_as_default")]
394  pub identifier: String,
395}
396
397/// A package that is itself a mod-loader pack.
398///
399/// Membership in the registry is how the engine decides a package unpacks to the
400/// profile root rather than being routed as a regular mod.
401///
402/// `#[non_exhaustive]`: fields may be added as the ecosystem schema grows.
403#[derive(Debug, Clone, Serialize, Deserialize)]
404#[non_exhaustive]
405pub struct ModloaderPackage {
406  /// The package's `Owner-Name` identifier.
407  #[serde(rename = "packageId", default, deserialize_with = "null_as_default")]
408  pub package_id: String,
409  /// The subfolder within the pack whose *contents* unpack to the root, or an
410  /// empty string when the pack's own root should be copied directly.
411  #[serde(rename = "rootFolder", default, deserialize_with = "null_as_default")]
412  pub root_folder: String,
413  /// The loader family this pack provides.
414  #[serde(default, deserialize_with = "null_as_default")]
415  pub loader: LoaderKind,
416}
417
418/// How files matched by an [`InstallRule`] are placed and tracked under its route.
419///
420/// `#[non_exhaustive]`: new tracking methods may be added without a breaking
421/// change, so downstream `match`es must include a wildcard arm.
422#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
423#[serde(rename_all = "kebab-case")]
424#[non_exhaustive]
425pub enum TrackingMethod {
426  /// Namespaced under `route/<Owner-Name>/`. The contents of a matched override
427  /// folder keep their structure; a file reached outside one (by extension or
428  /// the default location) is flattened to its base name. The default.
429  #[default]
430  Subdir,
431  /// Written directly under `route/`, shared and untracked (e.g. config).
432  None,
433  /// Written directly under `route/`, shared, but each file recorded for
434  /// exact uninstall.
435  State,
436  /// Namespaced under `route/<Owner-Name>/`, preserving internal structure.
437  SubdirNoFlatten,
438  /// The package archive is copied into `route/` as a zip.
439  PackageZip,
440  /// An unrecognized tracking method from a newer schema.
441  #[serde(other)]
442  Other,
443}
444
445impl TrackingMethod {
446  /// Whether files routed via this method live in a per-mod `<Owner-Name>/`
447  /// folder (and are therefore reconciled by directory in [`crate::install`]).
448  pub fn is_namespaced(self) -> bool {
449    matches!(
450      self,
451      TrackingMethod::Subdir | TrackingMethod::SubdirNoFlatten
452    )
453  }
454}
455
456/// A single, possibly nested, routing rule for a regular mod's files.
457///
458/// `#[non_exhaustive]`: fields may be added as the ecosystem schema grows.
459#[derive(Debug, Clone, Serialize, Deserialize)]
460#[non_exhaustive]
461pub struct InstallRule {
462  /// Destination path relative to the profile root, e.g. `"BepInEx/plugins"`.
463  /// The final path segment is the override-folder name matched at a package's
464  /// root (e.g. `plugins`).
465  #[serde(default, deserialize_with = "null_as_default")]
466  pub route: String,
467  /// Extensions (matched as filename suffixes) that route a loose file here.
468  /// When several rules match, the longest suffix wins.
469  #[serde(
470    rename = "defaultFileExtensions",
471    default,
472    deserialize_with = "null_as_default"
473  )]
474  pub default_file_extensions: Vec<String>,
475  /// How matched files are placed and tracked under [`InstallRule::route`].
476  #[serde(
477    rename = "trackingMethod",
478    default,
479    deserialize_with = "null_as_default"
480  )]
481  pub tracking_method: TrackingMethod,
482  /// Nested rules applied within this rule's route.
483  #[serde(rename = "subRoutes", default, deserialize_with = "null_as_default")]
484  pub sub_routes: Vec<InstallRule>,
485  /// Whether this rule is the catch-all for files matching no other rule.
486  /// At most one rule per profile is the default location; some have none.
487  #[serde(
488    rename = "isDefaultLocation",
489    default,
490    deserialize_with = "null_as_default"
491  )]
492  pub is_default_location: bool,
493}
494
495/// Whether a [`GameProfile`] targets the game itself or a dedicated server.
496#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
497#[serde(rename_all = "lowercase")]
498#[non_exhaustive]
499pub enum InstanceType {
500  /// The playable game (the default).
501  #[default]
502  Game,
503  /// A dedicated server build.
504  Server,
505  /// An unrecognized instance type from a newer schema.
506  #[serde(other)]
507  Other,
508}
509
510/// The mod-loader family. Unknown values deserialize to [`LoaderKind::Other`].
511///
512/// `#[non_exhaustive]`: new loader families may be added without a breaking
513/// change, so downstream `match`es must include a wildcard arm.
514#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
515#[non_exhaustive]
516pub enum LoaderKind {
517  /// BepInEx (`bepinex`), injected through Unity Doorstop.
518  #[serde(rename = "bepinex")]
519  BepInEx,
520  /// BepisLoader (`bepisloader`), the BepInEx successor, which takes its own
521  /// argument set rather than Doorstop's.
522  #[serde(rename = "bepisloader")]
523  BepisLoader,
524  /// GDWeave (`gdweave`), pointed at its mod folder with
525  /// `--gdweave-folder-override`.
526  #[serde(rename = "gdweave")]
527  GdWeave,
528  /// Godot Mod Loader (`godotml`), driven by a `--script` entry point plus
529  /// `--mods-path`.
530  #[serde(rename = "godotml")]
531  GodotMl,
532  /// Lovely (`lovely`), pointed at its mod folder with `--mod-dir`.
533  #[serde(rename = "lovely")]
534  Lovely,
535  /// MelonLoader (`melonloader`).
536  #[serde(rename = "melonloader")]
537  MelonLoader,
538  /// MelonLoader shipped in a nested package layout (`recursive-melonloader`).
539  /// Injects identically to [`LoaderKind::MelonLoader`]; only the package's file
540  /// layout differs.
541  #[serde(rename = "recursive-melonloader")]
542  RecursiveMelonLoader,
543  /// Northstar (`northstar`), selected with `-northstar` and a `-profile=`
544  /// directory.
545  #[serde(rename = "northstar")]
546  Northstar,
547  /// ReturnOfModding (`return-of-modding`), pointed at its root with
548  /// `--rom_modding_root_folder`.
549  #[serde(rename = "return-of-modding")]
550  ReturnOfModding,
551  /// Rivet (`rivet`), enabled with `-rivetEnable` plus explicit loader and mod
552  /// paths.
553  #[serde(rename = "rivet")]
554  Rivet,
555  /// Shimloader (`shimloader`), which takes separate mod, pak, cfg, and overlay
556  /// directories.
557  #[serde(rename = "shimloader")]
558  Shimloader,
559  /// Unity Mod Manager (`umm`), injected through Unity Doorstop like
560  /// [`LoaderKind::BepInEx`].
561  #[serde(rename = "umm")]
562  Umm,
563  /// A community with no mod loader.
564  #[serde(rename = "none")]
565  None,
566  /// An unrecognized loader family from a newer schema, or an absent value.
567  #[default]
568  #[serde(other)]
569  Other,
570}
571
572/// Normalizes a JSON `null` (or absent value) to `T::default()` during
573/// deserialization, so a nullable list field becomes an empty `Vec`.
574fn null_as_default<'de, D, T>(deserializer: D) -> std::result::Result<T, D::Error>
575where
576  D: Deserializer<'de>,
577  T: Deserialize<'de> + Default,
578{
579  let opt = Option::<T>::deserialize(deserializer)?;
580
581  Ok(opt.unwrap_or_default())
582}
583
584#[cfg(test)]
585mod tests {
586  use super::*;
587
588  #[test]
589  fn test_bundled_parses() {
590    let eco = Ecosystem::bundled();
591
592    assert!(!eco.games.is_empty());
593    assert!(!eco.modloader_packages.is_empty());
594    assert_eq!(eco.schema_version, "0.3.0");
595  }
596
597  #[test]
598  fn test_valheim_bepinex() {
599    let eco = Ecosystem::bundled();
600    let valheim = eco.game("valheim").expect("valheim present");
601
602    assert_eq!(valheim.slug, "valheim");
603    assert_eq!(valheim.display_name(), "Valheim");
604
605    let profile = valheim.profile().expect("a profile");
606
607    assert_eq!(profile.package_loader, LoaderKind::BepInEx);
608    assert_eq!(profile.instance_type, InstanceType::Game);
609    assert_eq!(profile.steam_app_id(), Some(892970));
610    assert!(!profile.install_rules.is_empty());
611
612    let plugins = profile
613      .install_rules
614      .iter()
615      .find(|r| r.route == "BepInEx/plugins")
616      .expect("plugins rule");
617
618    assert_eq!(plugins.tracking_method, TrackingMethod::Subdir);
619    assert!(plugins.tracking_method.is_namespaced());
620
621    let monomod = profile
622      .install_rules
623      .iter()
624      .find(|r| r.route == "BepInEx/monomod")
625      .expect("monomod rule");
626
627    assert!(
628      monomod
629        .default_file_extensions
630        .iter()
631        .any(|e| e == ".mm.dll")
632    );
633
634    let config = profile
635      .install_rules
636      .iter()
637      .find(|r| r.route == "BepInEx/config")
638      .expect("config rule");
639
640    assert!(!config.tracking_method.is_namespaced());
641  }
642
643  #[test]
644  fn community_comes_from_the_profile_package_index() {
645    let eco = Ecosystem::bundled();
646    let outward = eco.game("outward").expect("outward present");
647    let definitive = outward
648      .profiles
649      .iter()
650      .find(|p| p.settings_identifier.as_deref() == Some("OutwardDe"))
651      .expect("Outward Definitive profile");
652
653    assert_eq!(definitive.community(), Some("outward"));
654    assert_eq!(outward.community(), Some("outward"));
655
656    let server = eco
657      .game("valheim")
658      .expect("valheim present")
659      .profiles
660      .iter()
661      .find(|p| p.instance_type == InstanceType::Server)
662      .expect("valheim server profile");
663
664    assert_eq!(server.settings_identifier.as_deref(), Some("ValheimServer"));
665    assert_eq!(server.community(), Some("valheim"));
666  }
667
668  #[test]
669  fn community_is_none_without_a_usable_package_index() {
670    let community_of = |index: Option<&str>| {
671      let json = serde_json::json!({
672        "games": { "g": { "r2modman": [{ "packageIndex": index }] } }
673      });
674      let eco = Ecosystem::from_json(&json.to_string()).unwrap();
675
676      eco.game("g").unwrap().community().map(str::to_string)
677    };
678
679    assert_eq!(
680      community_of(Some("https://example.com/c/my-game/api/v1/package/")),
681      Some("my-game".to_string())
682    );
683    assert_eq!(community_of(None), None);
684    assert_eq!(
685      community_of(Some("https://thunderstore.io/api/v1/package/")),
686      None
687    );
688    assert_eq!(
689      community_of(Some("https://thunderstore.io/c/../api/v1/package/")),
690      None
691    );
692    assert_eq!(community_of(Some("https://thunderstore.io/c/")), None);
693  }
694
695  #[test]
696  fn test_modloader_registry_lookup() {
697    let eco = Ecosystem::bundled();
698
699    let pack = eco
700      .modloader_package("denikson-BepInExPack_Valheim")
701      .expect("valheim loader pack present");
702
703    assert_eq!(pack.root_folder, "BepInExPack_Valheim");
704    assert_eq!(pack.loader, LoaderKind::BepInEx);
705
706    assert!(eco.modloader_package("Author-SomeMod").is_none());
707  }
708
709  #[test]
710  fn test_melonloader_game_present() {
711    let eco = Ecosystem::bundled();
712
713    let game = eco
714      .games()
715      .find(|g| {
716        g.profile()
717          .map(|p| p.package_loader == LoaderKind::MelonLoader)
718          .unwrap_or(false)
719      })
720      .expect("at least one MelonLoader game");
721
722    assert!(game.profile().is_some());
723  }
724
725  #[test]
726  fn test_unknown_loader_falls_back_to_other() {
727    let json = r#"{
728      "schemaVersion": "9.9.9",
729      "games": {
730        "x": { "label": "x", "meta": {"displayName": "X"},
731               "r2modman": [ { "packageLoader": "someNewLoader", "installRules": [] } ] }
732      },
733      "modloaderPackages": []
734    }"#;
735
736    let eco = Ecosystem::from_json(json).unwrap();
737    let profile = eco.game("x").unwrap().profile().unwrap();
738
739    assert_eq!(profile.package_loader, LoaderKind::Other);
740  }
741
742  #[test]
743  fn require_profile_tells_an_unknown_game_from_one_without_a_profile() {
744    let json = r#"{
745      "games": {
746        "bare": { "label": "bare", "r2modman": [] },
747        "x": { "label": "x", "r2modman": [ { "packageLoader": "bepinex", "installRules": [] } ] }
748      }
749    }"#;
750    let eco = Ecosystem::from_json(json).unwrap();
751
752    assert!(eco.require_profile("x").is_ok());
753    assert!(matches!(
754      eco.require_profile("ghost"),
755      Err(Error::UnknownGame { game }) if game == "ghost"
756    ));
757    assert!(matches!(
758      eco.require_profile("bare"),
759      Err(Error::NoGameProfile { game }) if game == "bare"
760    ));
761  }
762
763  #[test]
764  fn test_null_relative_file_exclusions_normalizes_to_empty() {
765    let json = r#"{
766      "games": {
767        "x": { "label": "x",
768               "r2modman": [ { "packageLoader": "bepinex", "relativeFileExclusions": null, "installRules": [] } ] }
769      }
770    }"#;
771
772    let eco = Ecosystem::from_json(json).unwrap();
773    let profile = eco.game("x").unwrap().profile().unwrap();
774
775    assert!(profile.relative_file_exclusions.is_empty());
776  }
777
778  #[test]
779  fn test_null_enum_and_bool_fields_normalize_to_defaults() {
780    let json = r#"{
781      "games": {
782        "x": { "label": "x",
783               "r2modman": [ { "packageLoader": null, "gameInstanceType": null,
784                 "installRules": [ { "route": "Mods", "trackingMethod": null, "isDefaultLocation": null } ] } ] }
785      }
786    }"#;
787
788    let eco = Ecosystem::from_json(json).unwrap();
789    let profile = eco.game("x").unwrap().profile().unwrap();
790
791    assert_eq!(profile.package_loader, LoaderKind::Other);
792    assert_eq!(profile.instance_type, InstanceType::Game);
793
794    let rule = &profile.install_rules[0];
795
796    assert_eq!(rule.tracking_method, TrackingMethod::Subdir);
797    assert!(!rule.is_default_location);
798  }
799
800  #[test]
801  fn test_unknown_tracking_method_falls_back_to_other() {
802    let json = r#"{
803      "games": {
804        "x": { "label": "x",
805               "r2modman": [ { "packageLoader": "bepinex",
806                 "installRules": [ { "route": "Mods", "trackingMethod": "brand-new-method" } ] } ] }
807      }
808    }"#;
809
810    let eco = Ecosystem::from_json(json).unwrap();
811    let rule = &eco.game("x").unwrap().profile().unwrap().install_rules[0];
812
813    assert_eq!(rule.tracking_method, TrackingMethod::Other);
814    assert!(!rule.tracking_method.is_namespaced());
815  }
816
817  #[test]
818  #[cfg(feature = "io")]
819  fn test_fetch_latest_rejects_declared_oversize_body() {
820    let mut server = mockito::Server::new();
821    let body = "x".repeat(1000);
822
823    let mock = server
824      .mock("GET", "/schema")
825      .with_status(200)
826      .with_body(&body)
827      .create();
828
829    let url = format!("{}/schema", server.url());
830    let rt = tokio::runtime::Runtime::new().unwrap();
831    let client = reqwest::Client::new();
832
833    let result = rt.block_on(Ecosystem::fetch_latest_bounded(
834      &client,
835      &url,
836      16,
837      &RetryPolicy::none(),
838    ));
839
840    assert!(matches!(result, Err(Error::SizeLimitExceeded { .. })));
841
842    mock.assert();
843  }
844
845  #[test]
846  #[cfg(feature = "io")]
847  fn test_fetch_latest_rejects_streamed_oversize_body() {
848    let mut server = mockito::Server::new();
849
850    // A chunked body carries no Content-Length, so the cap must be enforced from
851    // the actual streamed bytes.
852    let mock = server
853      .mock("GET", "/schema")
854      .with_status(200)
855      .with_chunked_body(|w| w.write_all(&vec![b'x'; 1000]))
856      .create();
857
858    let url = format!("{}/schema", server.url());
859    let rt = tokio::runtime::Runtime::new().unwrap();
860    let client = reqwest::Client::new();
861
862    let result = rt.block_on(Ecosystem::fetch_latest_bounded(
863      &client,
864      &url,
865      16,
866      &RetryPolicy::none(),
867    ));
868
869    assert!(matches!(result, Err(Error::SizeLimitExceeded { .. })));
870
871    mock.assert();
872  }
873
874  #[test]
875  #[cfg(feature = "io")]
876  fn test_fetch_latest_parses_network_schema() {
877    let mut server = mockito::Server::new();
878
879    let body = r#"{
880      "schemaVersion": "0.3.0",
881      "games": {
882        "valheim": { "label": "valheim", "meta": {"displayName": "Valheim"},
883          "r2modman": [ { "packageLoader": "bepinex",
884            "installRules": [ { "route": "BepInEx/plugins", "trackingMethod": "subdir",
885              "isDefaultLocation": true, "defaultFileExtensions": [".dll"] } ] } ] }
886      },
887      "modloaderPackages": [
888        { "packageId": "denikson-BepInExPack_Valheim", "rootFolder": "BepInExPack_Valheim", "loader": "bepinex" }
889      ]
890    }"#;
891
892    let mock = server
893      .mock("GET", "/schema")
894      .with_status(200)
895      .with_header("Content-Type", "application/json")
896      .with_body(body)
897      .create();
898
899    let url = format!("{}/schema", server.url());
900    let rt = tokio::runtime::Runtime::new().unwrap();
901    let client = reqwest::Client::new();
902    let eco = rt.block_on(Ecosystem::fetch_latest(&client, &url)).unwrap();
903
904    assert_eq!(eco.schema_version, "0.3.0");
905
906    let profile = eco.game("valheim").unwrap().profile().unwrap();
907
908    assert_eq!(profile.package_loader, LoaderKind::BepInEx);
909    assert!(
910      eco
911        .modloader_package("denikson-BepInExPack_Valheim")
912        .is_some()
913    );
914
915    mock.assert();
916  }
917
918  #[test]
919  fn steam_app_id_none_when_missing_or_unparseable() {
920    // No steam distribution => None.
921    let no_steam: GameProfile = serde_json::from_str(
922      r#"{"distributions":[{"platform":"epic-games-store","identifier":"abc"}]}"#,
923    )
924    .unwrap();
925
926    assert_eq!(no_steam.steam_app_id(), None);
927
928    // A steam distribution whose id is not numeric => None.
929    let bad_steam: GameProfile =
930      serde_json::from_str(r#"{"distributions":[{"platform":"steam","identifier":"nope"}]}"#)
931        .unwrap();
932
933    assert_eq!(bad_steam.steam_app_id(), None);
934
935    // A steam distribution with a numeric id => Some.
936    let steam: GameProfile =
937      serde_json::from_str(r#"{"distributions":[{"platform":"steam","identifier":"892970"}]}"#)
938        .unwrap();
939
940    assert_eq!(steam.steam_app_id(), Some(892970));
941  }
942
943  #[test]
944  fn game_profile_prefers_game_instance_then_falls_back() {
945    // Only a server-instance profile: `profile()` falls back to the first one.
946    let server_only: GameDef =
947      serde_json::from_str(r#"{"r2modman":[{"gameInstanceType":"server"}]}"#).unwrap();
948
949    assert_eq!(
950      server_only.profile().unwrap().instance_type,
951      InstanceType::Server
952    );
953
954    // A game-instance profile is preferred over a server one, whatever the order.
955    let mixed: GameDef = serde_json::from_str(
956      r#"{"r2modman":[{"gameInstanceType":"server"},{"gameInstanceType":"game"}]}"#,
957    )
958    .unwrap();
959
960    assert_eq!(mixed.profile().unwrap().instance_type, InstanceType::Game);
961
962    // No profiles at all => None.
963    let empty: GameDef = serde_json::from_str(r#"{"r2modman":[]}"#).unwrap();
964
965    assert!(empty.profile().is_none());
966  }
967}