lighty-loaders 26.9.2

Minecraft mod loaders support for Lighty Launcher
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
use async_trait::async_trait;
use once_cell::sync::Lazy;
use std::{collections::HashMap, fs::File, io::Read, path::PathBuf};
use zip::ZipArchive;

use lighty_core::download::download_file_untracked;
use lighty_core::mkdir;

use crate::loaders::vanilla::vanilla::{
    extract_arguments as vanilla_arguments, extract_main_class as vanilla_main_class,
    VANILLA, VanillaQuery,
};
use crate::types::version_metadata::{Arguments, Library, MainClass, Version, VersionMetaData};
use crate::types::VersionInfo;
use crate::utils::forge_installer::{ForgeInstallProfile, ForgeVersionManifest};
use crate::utils::maven::fetch_maven_sha1;
use lighty_core::QueryError;
use crate::utils::{manifest::ManifestRepository, query::Query};

/// Maven repository for NeoForge artifacts.
pub const NEOFORGE_MAVEN: &str = "https://maven.neoforged.net/releases";
/// Subdirectory under `libraries/` used to cache files extracted from
/// the NeoForge installer JAR (keeps Forge / NeoForge extracts isolated).
pub const NEOFORGE_EXTRACT_SUBDIR: &str = "net/neoforged";

pub type Result<T> = std::result::Result<T, QueryError>;

/// Shared cached repository for NeoForge manifests.
pub static NEOFORGE: Lazy<ManifestRepository<NeoForgeQuery>> = Lazy::new(|| ManifestRepository::new());

/// Sub-queries supported by the NeoForge loader.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum NeoForgeQuery {
    Libraries,
    Arguments,
    MainClass,
    NeoForgeBuilder,
}

#[async_trait]
impl Query for NeoForgeQuery {
    type Query = NeoForgeQuery;
    type Data = VersionMetaData;
    type Raw = ForgeInstallProfile ;

    fn name() -> &'static str {
        "neoforge"
    }

    async fn fetch_full_data<V: VersionInfo>(version: &V) -> Result<ForgeInstallProfile> {
        let installer_url = build_installer_url(version);

        lighty_core::trace_debug!(url = %installer_url, loader = "neoforge", "Installer URL constructed");

        let profiles_dir = version.game_dirs().join(".neoforge");
        mkdir!(profiles_dir);

        let installer_path = profiles_dir.join(format!("neoforge-{}-installer.jar", version.loader_version()));

        let needs_download = if installer_path.exists() {
            match verify_installer_sha1(&installer_path, &installer_url).await {
                Ok(true) => {
                    lighty_core::trace_info!(loader = "neoforge", "Installer already exists and SHA1 is valid");
                    false
                }
                Ok(false) => {
                    lighty_core::trace_warn!(loader = "neoforge", "Installer exists but SHA1 mismatch, re-downloading");
                    true
                }
                Err(_e) => {
                    lighty_core::trace_warn!(error = %_e, loader = "neoforge", "Could not verify SHA1, using existing file");
                    false
                }
            }
        } else {
            true
        };

        if needs_download {
            lighty_core::trace_info!(path = ?installer_path, loader = "neoforge", "Downloading installer");
            download_file_untracked(&installer_url, &installer_path)
                .await
                .map_err(|e| QueryError::Conversion {
                    message: format!("Failed to download installer: {}", e)
                })?;

            if let Ok(valid) = verify_installer_sha1(&installer_path, &installer_url).await {
                if !valid {
                    return Err(QueryError::Conversion {
                        message: "Downloaded installer has invalid SHA1".to_string()
                    });
                }
            }
        }

        let (install_profile, _) = read_jsons_from_jar(&installer_path).await?;

        lighty_core::trace_info!(loader = "neoforge", "Successfully loaded NeoForge metadata");

        Ok(install_profile)
    }

    async fn extract<V: VersionInfo>(version: &V, query: &Self::Query, full_data: &ForgeInstallProfile) -> Result<Self::Data> {
        let result = match query {
            NeoForgeQuery::Libraries => VersionMetaData::Libraries(extract_install_profile_libraries(full_data)),
            NeoForgeQuery::MainClass => {
                let version_meta = read_version_meta(version).await?;
                VersionMetaData::MainClass(main_class(version, &version_meta).await?)
            }
            NeoForgeQuery::Arguments => {
                let version_meta = read_version_meta(version).await?;
                VersionMetaData::Arguments(arguments(version, &version_meta).await?)
            }
            NeoForgeQuery::NeoForgeBuilder => {
                VersionMetaData::Version(Self::version_builder(version, full_data).await?)
            }
        };
        Ok(result)
    }

    async fn version_builder<V: VersionInfo>(version: &V, _full_data: &ForgeInstallProfile) -> Result<Version> {
        let (vanilla_builder, version_meta) = tokio::try_join!(
            async {
                let vanilla_data = VANILLA.get_raw(version).await?;
                VanillaQuery::version_builder(version, &vanilla_data).await
            },
            read_version_meta(version)
        )?;

        // Use ONLY runtime libraries from version.json. install_profile
        // libraries are processor-only and must not end up on the classpath.
        let version_json_libs = extract_libraries_from_version_meta(&version_meta);

        let merged_libs = merge_libraries(vanilla_builder.libraries, version_json_libs);

        Ok(Version {
            main_class: main_class(version, &version_meta).await?,
            java_version: vanilla_builder.java_version,
            arguments: arguments(version, &version_meta).await?,
            libraries: merged_libs,
            mods: None,
            natives: vanilla_builder.natives,
            client: vanilla_builder.client,
            assets_index: vanilla_builder.assets_index,
            assets: vanilla_builder.assets,
        })
    }
}

/// Reads the `version.json` shipped inside the NeoForge installer JAR — the
/// main class and arguments live there, not in the install profile.
async fn read_version_meta<V: VersionInfo>(version: &V) -> Result<ForgeVersionManifest> {
    let installer_path = version
        .game_dirs()
        .join(".neoforge")
        .join(format!("neoforge-{}-installer.jar", version.loader_version()));
    let (_, version_meta) = read_jsons_from_jar(&installer_path).await?;
    Ok(version_meta)
}

/// NeoForge's main class merged with vanilla's, so the standalone query and the
/// builder can never disagree.
async fn main_class<V: VersionInfo>(
    version: &V,
    version_meta: &ForgeVersionManifest,
) -> Result<MainClass> {
    let vanilla_data = VANILLA.get_raw(version).await?;
    Ok(merge_main_class(
        vanilla_main_class(&vanilla_data),
        extract_main_class(version_meta),
    ))
}

/// Same contract as [`main_class`], for the argument lists.
async fn arguments<V: VersionInfo>(
    version: &V,
    version_meta: &ForgeVersionManifest,
) -> Result<Arguments> {
    let vanilla_data = VANILLA.get_raw(version).await?;
    Ok(merge_arguments(
        vanilla_arguments(&vanilla_data),
        extract_arguments(version_meta),
    ))
}

fn merge_main_class(vanilla: MainClass, neoforge: MainClass) -> MainClass {
    if neoforge.main_class.is_empty() {
        vanilla
    } else {
        neoforge
    }
}

fn merge_arguments(vanilla: Arguments, neoforge: Arguments) -> Arguments {
    Arguments {
        game: {
            let mut args = vanilla.game;
            args.extend(neoforge.game);
            args
        },
        jvm: match (vanilla.jvm, neoforge.jvm) {
            (Some(mut v), Some(n)) => {
                v.extend(n);
                Some(v)
            }
            (Some(v), None) => Some(v),
            (None, Some(n)) => Some(n),
            (None, None) => None,
        },
    }
}

/// Merges library lists, de-duplicating by `group:artifact[:classifier]`.
fn merge_libraries(vanilla_libs: Vec<Library>, neoforge_libs: Vec<Library>) -> Vec<Library> {
    let capacity = vanilla_libs.len() + neoforge_libs.len();
    let mut lib_map: HashMap<String, Library> = HashMap::with_capacity(capacity);

    for lib in vanilla_libs {
        let key = extract_artifact_key(&lib.name);
        lib_map.insert(key, lib);
    }

    // NeoForge overrides Vanilla on key collision (typically newer version).
    for lib in neoforge_libs {
        let key = extract_artifact_key(&lib.name);
        lib_map.insert(key, lib);
    }

    lib_map.into_values().collect()
}

/// Extracts the `group:artifact[:classifier]` key used for dedup.
/// The classifier MUST stay in the key — NeoForge's version.json ships
/// two libs with the same coords differing only by classifier
/// (`:universal` and `:client`); collapsing them would drop the FML
/// system mod and crash with "Failed to find system mod".
fn extract_artifact_key(maven_name: &str) -> String {
    let parts: Vec<&str> = maven_name.split(':').collect();
    match parts.as_slice() {
        [group, artifact, _version, classifier, ..] => {
            format!("{}:{}:{}", group, artifact, classifier)
        }
        [group, artifact, ..] => format!("{}:{}", group, artifact),
        _ => maven_name.to_string(),
    }
}

fn extract_main_class(version_meta: &ForgeVersionManifest) -> MainClass {
    MainClass {
        main_class: version_meta.main_class.clone(),
    }
}

fn extract_arguments(version_meta: &ForgeVersionManifest) -> Arguments {
    // NeoForge always ships the structured `arguments` block; the Option
    // here is forced by the shared `ForgeVersionManifest` schema (which
    // also serves back-ported modern Forge installers).
    if let Some(args) = &version_meta.arguments {
        return Arguments {
            game: args.game.clone(),
            jvm: Some(args.jvm.clone()),
        };
    }
    Arguments { game: Vec::new(), jvm: None }
}

/// Returns the install_profile.json libraries as the launcher's pivot
/// [`Library`] type.
///
/// Includes both the processor JARs and the runtime-required artifacts
/// (notably `net.neoforged:forge:VERSION:universal`, referenced at
/// runtime by FML but absent from `version.json`).
pub fn extract_install_profile_libraries(full_data: &ForgeInstallProfile) -> Vec<Library> {
    full_data
        .libraries
        .iter()
        .map(|lib| Library {
            name: lib.name.clone(),
            url: Some(lib.downloads.artifact.url.clone()),
            path: Some(lib.downloads.artifact.path.clone()),
            sha1: Some(lib.downloads.artifact.sha1.clone()),
            size: Some(lib.downloads.artifact.size),
        })
        .collect()
}

fn extract_libraries_from_version_meta(version_meta: &ForgeVersionManifest) -> Vec<Library> {
    version_meta
        .libraries
        .iter()
        .map(|lib| Library {
            name: lib.name.clone(),
            url: Some(lib.downloads.artifact.url.clone()),
            path: Some(lib.downloads.artifact.path.clone()),
            sha1: Some(lib.downloads.artifact.sha1.clone()),
            size: Some(lib.downloads.artifact.size),
        })
        .collect()
}

fn is_old_neoforge<V: VersionInfo>(version: &V) -> bool {
    version_compare::compare_to(version.minecraft_version(), "1.20.1", version_compare::Cmp::Le)
        .unwrap_or(false)
}

/// Builds the Maven URL of the NeoForge installer JAR for `version`.
pub fn build_installer_url<V: VersionInfo>(version: &V) -> String {
    if is_old_neoforge(version) {
        let path_version = format!("{}-{}", version.minecraft_version(), version.loader_version());
        let file_prefix = format!("forge-{}", version.minecraft_version());
        format!(
            "{}/{}/forge/{}/{}-{}-installer.jar",
            NEOFORGE_MAVEN,
            NEOFORGE_EXTRACT_SUBDIR,
            path_version,
            file_prefix,
            version.loader_version()
        )
    } else {
        format!(
            "{}/{}/neoforge/{}/neoforge-{}-installer.jar",
            NEOFORGE_MAVEN,
            NEOFORGE_EXTRACT_SUBDIR,
            version.loader_version(),
            version.loader_version()
        )
    }
}

/// Returns the on-disk path where the NeoForge installer is cached.
pub fn installer_cache_path<V: VersionInfo>(version: &V) -> PathBuf {
    version
        .game_dirs()
        .join(".neoforge")
        .join(format!("neoforge-{}-installer.jar", version.loader_version()))
}

/// Reads `install_profile.json` and `version.json` directly from the
/// installer JAR without extracting anything to disk.
async fn read_jsons_from_jar(installer_path: &PathBuf) -> Result<(ForgeInstallProfile, ForgeVersionManifest)> {
    let path = installer_path.clone();

    tokio::task::spawn_blocking(move || {
        let file = File::open(&path).map_err(|e| QueryError::Conversion {
            message: format!("Failed to open installer JAR: {}", e)
        })?;

        let mut archive = ZipArchive::new(file).map_err(|e| QueryError::Conversion {
            message: format!("Failed to open ZIP archive: {}", e)
        })?;

        let install_profile = {
            let mut file = archive.by_name("install_profile.json").map_err(|_| {
                QueryError::MissingField {
                    field: "install_profile.json in installer JAR".to_string(),
                }
            })?;

            let mut contents = String::new();
            file.read_to_string(&mut contents).map_err(|e| QueryError::Conversion {
                message: format!("Failed to read install_profile.json: {}", e)
            })?;

            serde_json::from_str::<ForgeInstallProfile>(&contents)?
        };

        let version_meta = {
            let mut file = archive.by_name("version.json").map_err(|_| {
                QueryError::MissingField {
                    field: "version.json in installer JAR".to_string(),
                }
            })?;

            let mut contents = String::new();
            file.read_to_string(&mut contents).map_err(|e| QueryError::Conversion {
                message: format!("Failed to read version.json: {}", e)
            })?;

            serde_json::from_str::<ForgeVersionManifest>(&contents)?
        };

        Ok((install_profile, version_meta))
    })
    .await
    .map_err(|e| QueryError::Conversion {
        message: format!("Failed to spawn blocking task: {}", e)
    })?
}

/// Verifies the local installer JAR matches the expected SHA1 from Maven.
async fn verify_installer_sha1(installer_path: &PathBuf, installer_url: &str) -> Result<bool> {
    let expected_sha1 = fetch_maven_sha1(installer_url)
        .await
        .ok_or_else(|| QueryError::Conversion {
            message: "Failed to fetch SHA1 from Maven".to_string()
        })?;

    lighty_core::verify_file_sha1_sync(installer_path, &expected_sha1)
        .map_err(|e| QueryError::Conversion {
            message: format!("Failed to verify SHA1: {}", e)
        })
}