ltk_modpkg 0.5.0

League Toolkit mod package (.modpkg) reader/writer and utilities
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
use crate::{
    chunk::{NO_LAYER_INDEX, NO_WAD_INDEX},
    error::ModpkgError,
    license::ModpkgLicense,
    Modpkg,
};
use semver::Version;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::io::{Cursor, Read, Seek, Write};

/// The path to the info.msgpack chunk.
pub const METADATA_CHUNK_PATH: &str = "_meta_/info.msgpack";

impl<TSource: Read + Seek> Modpkg<TSource> {
    /// Load the metadata chunk from the mod package.
    pub fn load_metadata(&mut self) -> Result<ModpkgMetadata, ModpkgError> {
        let chunk = *self.get_chunk(METADATA_CHUNK_PATH, None)?;

        if chunk.layer_index != NO_LAYER_INDEX || chunk.wad_index != NO_WAD_INDEX {
            return Err(ModpkgError::InvalidMetaChunk);
        }

        ModpkgMetadata::read(&mut Cursor::new(self.load_chunk_decompressed(&chunk)?))
    }
}

/// Information about the distributor site and mod ID.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[cfg_attr(test, derive(proptest_derive::Arbitrary))]
pub struct DistributorInfo {
    /// The identifier of the distributor site (e.g., "runeforge").
    pub site_id: String,
    /// The display name of the distributor site (e.g., "Runeforge").
    pub site_name: String,
    /// The base URL of the distributor site (e.g., "https://runeforge.dev").
    pub site_url: String,
    /// The mod ID on the distributor site.
    pub mod_id: String,
}

impl DistributorInfo {
    /// Create a new distributor info.
    pub fn new(site_id: String, site_name: String, site_url: String, mod_id: String) -> Self {
        Self {
            site_id,
            site_name,
            site_url,
            mod_id,
        }
    }

    /// Get the distributor site ID.
    pub fn site_id(&self) -> &str {
        &self.site_id
    }

    /// Get the display name of the distributor site.
    pub fn site_name(&self) -> &str {
        &self.site_name
    }

    /// Get the base URL of the distributor site.
    pub fn site_url(&self) -> &str {
        &self.site_url
    }

    /// Get the mod ID on the distributor site.
    pub fn mod_id(&self) -> &str {
        &self.mod_id
    }
}

/// Per-layer metadata that can be stored inside the mod package metadata.
///
/// Added in schema version 2: the `string_overrides` field allows mods to
/// customise in-game text without shipping the entire `lol.stringtable` file.
///
/// # Example
///
/// ```
/// use std::collections::HashMap;
/// use ltk_modpkg::ModpkgLayerMetadata;
///
/// let mut en_us_overrides = HashMap::new();
/// en_us_overrides.insert("game_character_displayname_Ahri".to_string(), "Fox Spirit".to_string());
///
/// let layer = ModpkgLayerMetadata {
///     name: "base".to_string(),
///     display_name: None,
///     priority: 0,
///     description: Some("Base layer".to_string()),
///     string_overrides: HashMap::from([
///         ("en_us".to_string(), en_us_overrides),
///     ]),
/// };
///
/// assert_eq!(layer.string_overrides.len(), 1);
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[cfg_attr(test, derive(proptest_derive::Arbitrary))]
pub struct ModpkgLayerMetadata {
    /// The name of the layer (e.g. "base", "chroma1").
    pub name: String,
    /// Optional human-readable display name for the layer.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub display_name: Option<String>,
    /// The priority of the layer as stored in the modpkg header.
    pub priority: i32,
    /// Optional human-readable description of the layer.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// String overrides for this layer (added in schema v2), organized by locale.
    ///
    /// Outer key: locale (e.g., "en_us", "ko_kr", "zh_cn", or "default" for all locales)
    /// Inner map: field name (from `data/menu/{locale}/lol.stringtable`) -> replacement string
    ///
    /// Only the overrides are stored — not the full stringtable — so the
    /// mod stays compatible across game patches.
    /// Empty maps are omitted during serialization.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    #[cfg_attr(
        test,
        proptest(strategy = "proptest::collection::hash_map(\
                \"[a-z]{2}_[a-z]{2}\", \
                proptest::collection::hash_map(\"[a-z_]{1,30}\", \"[a-zA-Z0-9 ]{0,50}\", 0..3), \
                0..2\
            )")
    )]
    pub string_overrides: HashMap<String, HashMap<String, String>>,
}

/// The metadata of a mod package.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[cfg_attr(test, derive(proptest_derive::Arbitrary))]
pub struct ModpkgMetadata {
    /// The schema version of this metadata structure.
    #[serde(default = "default_schema_version")]
    pub schema_version: u32,

    pub name: String,
    pub display_name: String,
    pub description: Option<String>,
    #[cfg_attr(test, proptest(value = "Version::new(0, 1, 0)"))]
    pub version: Version,
    pub distributor: Option<DistributorInfo>,
    #[cfg_attr(
        test,
        proptest(
            strategy = "proptest::collection::vec(proptest::prelude::any::<ModpkgAuthor>(), 0..3)"
        )
    )]
    pub authors: Vec<ModpkgAuthor>,
    pub license: ModpkgLicense,

    /// Tags/categories for the mod (e.g., "champion-skin", "sfx").
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    #[cfg_attr(
        test,
        proptest(strategy = "proptest::collection::vec(\"[a-z][a-z-]{0,20}\", 0..3)")
    )]
    pub tags: Vec<String>,

    /// Champions this mod targets (e.g., "Aatrox", "Ahri").
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    #[cfg_attr(
        test,
        proptest(strategy = "proptest::collection::vec(\"[A-Z][a-z]{2,10}\", 0..3)")
    )]
    pub champions: Vec<String>,

    /// Maps this mod targets (e.g., "Summoner's Rift", "Howling Abyss").
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    #[cfg_attr(
        test,
        proptest(strategy = "proptest::collection::vec(\"[A-Z][a-z]{2,10}\", 0..3)")
    )]
    pub maps: Vec<String>,

    /// This is purely informational and does not affect how the modpkg loader
    /// resolves layers; the canonical source of truth for layer priority is
    /// still the modpkg header.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    #[cfg_attr(
        test,
        proptest(
            strategy = "proptest::collection::vec(proptest::prelude::any::<ModpkgLayerMetadata>(), 0..3)"
        )
    )]
    pub layers: Vec<ModpkgLayerMetadata>,
}

impl Default for ModpkgMetadata {
    fn default() -> Self {
        Self {
            schema_version: default_schema_version(),
            name: String::new(),
            display_name: String::new(),
            description: None,
            version: Version::new(0, 0, 0),
            distributor: None,
            authors: Vec::new(),
            license: ModpkgLicense::None,
            tags: Vec::new(),
            champions: Vec::new(),
            maps: Vec::new(),
            layers: Vec::new(),
        }
    }
}

/// Current metadata schema version.
pub const CURRENT_SCHEMA_VERSION: u32 = 2;

fn default_schema_version() -> u32 {
    2
}

impl ModpkgMetadata {
    /// Get the path to the metadata chunk.
    pub fn path(&self) -> &str {
        METADATA_CHUNK_PATH
    }
}

impl ModpkgMetadata {
    /// Read metadata from a reader using msgpack encoding.
    pub fn read<R: Read>(reader: &mut R) -> Result<Self, crate::error::ModpkgError> {
        rmp_serde::from_read(reader).map_err(crate::error::ModpkgError::from)
    }

    /// Write metadata to a writer using msgpack encoding.
    pub fn write<W: Write>(&self, writer: &mut W) -> Result<(), crate::error::ModpkgError> {
        let encoded = rmp_serde::to_vec_named(self).map_err(crate::error::ModpkgError::from)?;
        writer
            .write_all(&encoded)
            .map_err(crate::error::ModpkgError::from)?;
        Ok(())
    }

    pub fn size(&self) -> usize {
        rmp_serde::to_vec_named(self).map(|v| v.len()).unwrap_or(0)
    }
}

impl ModpkgMetadata {
    /// Get the name of the mod package.
    pub fn name(&self) -> &str {
        &self.name
    }
    /// Get the display name of the mod package.
    pub fn display_name(&self) -> &str {
        &self.display_name
    }
    /// Get the description of the mod package.
    pub fn description(&self) -> Option<&str> {
        self.description.as_deref()
    }
    /// Get the version of the mod package.
    pub fn version(&self) -> &Version {
        &self.version
    }
    /// Get the distributor info of the mod package.
    pub fn distributor(&self) -> Option<&DistributorInfo> {
        self.distributor.as_ref()
    }
    /// Get the authors of the mod package.
    pub fn authors(&self) -> &[ModpkgAuthor] {
        &self.authors
    }
    /// Get the license of the mod package.
    pub fn license(&self) -> &ModpkgLicense {
        &self.license
    }

    /// Get the tags/categories of the mod package.
    pub fn tags(&self) -> &[String] {
        &self.tags
    }
    /// Get the champions this mod targets.
    pub fn champions(&self) -> &[String] {
        &self.champions
    }
    /// Get the maps this mod targets.
    pub fn maps(&self) -> &[String] {
        &self.maps
    }

    /// Get the per-layer metadata entries, if any.
    pub fn layers(&self) -> &[ModpkgLayerMetadata] {
        &self.layers
    }
}

/// The author of a mod package.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[cfg_attr(test, derive(proptest_derive::Arbitrary))]
pub struct ModpkgAuthor {
    pub name: String,
    pub role: Option<String>,
}

impl ModpkgAuthor {
    pub fn new(name: String, role: Option<String>) -> Self {
        Self { name, role }
    }
    pub fn name(&self) -> &str {
        &self.name
    }
    pub fn role(&self) -> Option<&str> {
        self.role.as_deref()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use proptest::prelude::*;
    use std::io::Cursor;

    proptest! {
        // Reduce test cases for CI performance (8 instead of default 256)
        // The nested HashMap structure makes this test slow
        #![proptest_config(ProptestConfig::with_cases(8))]

        #[test]
        fn test_metadata_roundtrip(metadata: ModpkgMetadata) {
            let mut cursor = Cursor::new(Vec::new());
            metadata.write(&mut cursor).unwrap();

            cursor.set_position(0);
            let read_metadata = ModpkgMetadata::read(&mut cursor).unwrap();
            prop_assert_eq!(metadata, read_metadata);
        }

        #[test]
        fn test_author_roundtrip(author: ModpkgAuthor) {
            let encoded = rmp_serde::to_vec_named(&author).unwrap();
            let decoded: ModpkgAuthor = rmp_serde::from_slice(&encoded).unwrap();
            prop_assert_eq!(author, decoded);
        }
    }

    #[test]
    fn test_modpkg_metadata_read() {
        let metadata = ModpkgMetadata {
            schema_version: 1,
            name: "test".to_string(),
            display_name: "test".to_string(),
            description: Some("test".to_string()),
            version: Version::parse("1.0.0").unwrap(),
            distributor: Some(DistributorInfo {
                site_id: "test_site".to_string(),
                site_name: "Test Site".to_string(),
                site_url: "https://test-site.com".to_string(),
                mod_id: "12345".to_string(),
            }),
            authors: vec![ModpkgAuthor {
                name: "test".to_string(),
                role: Some("test".to_string()),
            }],
            license: ModpkgLicense::Spdx {
                spdx_id: "MIT".to_string(),
            },
            tags: vec![],
            champions: vec![],
            maps: vec![],
            layers: vec![],
        };
        let mut cursor = Cursor::new(Vec::new());
        metadata.write(&mut cursor).unwrap();

        cursor.set_position(0);
        let read_metadata = ModpkgMetadata::read(&mut cursor).unwrap();
        assert_eq!(metadata, read_metadata);
    }

    #[test]
    fn test_msgpack_format_visualization() {
        // This test shows what the msgpack encoding looks like with named fields (maps)
        let metadata = ModpkgMetadata {
            schema_version: 1,
            name: "TestMod".to_string(),
            display_name: "Test Mod".to_string(),
            description: Some("A test mod".to_string()),
            version: Version::parse("1.0.0").unwrap(),
            distributor: Some(DistributorInfo {
                site_id: "nexus".to_string(),
                site_name: "Nexus Mods".to_string(),
                site_url: "https://www.nexusmods.com".to_string(),
                mod_id: "12345".to_string(),
            }),
            authors: vec![ModpkgAuthor {
                name: "Author1".to_string(),
                role: Some("Developer".to_string()),
            }],
            license: ModpkgLicense::Spdx {
                spdx_id: "MIT".to_string(),
            },
            tags: vec![],
            champions: vec![],
            maps: vec![],
            layers: vec![],
        };

        let encoded = rmp_serde::to_vec_named(&metadata).unwrap();
        println!("\nMsgpack encoded bytes (hex): {:02x?}", encoded);
        println!("Size: {} bytes", encoded.len());

        // Test all license variants
        let license_none = ModpkgLicense::None;
        let license_spdx = ModpkgLicense::Spdx {
            spdx_id: "MIT".to_string(),
        };
        let license_custom = ModpkgLicense::Custom {
            name: "MyLicense".to_string(),
            url: "https://example.com".to_string(),
        };

        println!(
            "\nLicense::None: {:02x?}",
            rmp_serde::to_vec_named(&license_none).unwrap()
        );
        println!(
            "License::Spdx: {:02x?}",
            rmp_serde::to_vec_named(&license_spdx).unwrap()
        );
        println!(
            "License::Custom: {:02x?}",
            rmp_serde::to_vec_named(&license_custom).unwrap()
        );
    }

    #[test]
    fn test_layer_string_overrides_roundtrip() {
        let layer = ModpkgLayerMetadata {
            name: "base".to_string(),
            display_name: None,
            priority: 0,
            description: Some("Base layer".to_string()),
            string_overrides: HashMap::from([(
                "en_us".to_string(),
                HashMap::from([
                    ("field_a".to_string(), "New Value A".to_string()),
                    ("field_b".to_string(), "New Value B".to_string()),
                ]),
            )]),
        };

        let encoded = rmp_serde::to_vec_named(&layer).unwrap();
        let decoded: ModpkgLayerMetadata = rmp_serde::from_slice(&encoded).unwrap();
        assert_eq!(layer, decoded);
    }

    #[test]
    fn test_layer_empty_overrides_skipped_in_serialization() {
        let layer = ModpkgLayerMetadata {
            name: "base".to_string(),
            display_name: None,
            priority: 0,
            description: None,
            string_overrides: HashMap::new(),
        };

        let encoded = rmp_serde::to_vec_named(&layer).unwrap();
        // Empty string_overrides should not appear in encoded bytes
        let as_str = String::from_utf8_lossy(&encoded);
        assert!(!as_str.contains("string_overrides"));

        // Should still decode correctly
        let decoded: ModpkgLayerMetadata = rmp_serde::from_slice(&encoded).unwrap();
        assert_eq!(layer, decoded);
    }

    #[test]
    fn test_v1_metadata_backward_compat() {
        // Simulate a v1 metadata without string_overrides on layers
        let v1_metadata = ModpkgMetadata {
            schema_version: 1,
            name: "old-mod".to_string(),
            display_name: "Old Mod".to_string(),
            description: None,
            version: Version::parse("1.0.0").unwrap(),
            distributor: None,
            authors: vec![],
            license: ModpkgLicense::None,
            tags: vec![],
            champions: vec![],
            maps: vec![],
            layers: vec![ModpkgLayerMetadata {
                name: "base".to_string(),
                display_name: None,
                priority: 0,
                description: None,
                string_overrides: HashMap::new(),
            }],
        };

        let mut cursor = Cursor::new(Vec::new());
        v1_metadata.write(&mut cursor).unwrap();
        cursor.set_position(0);

        let read = ModpkgMetadata::read(&mut cursor).unwrap();
        assert_eq!(v1_metadata, read);
        assert!(read.layers[0].string_overrides.is_empty());
    }

    #[test]
    fn test_v2_metadata_with_string_overrides() {
        let metadata = ModpkgMetadata {
            schema_version: CURRENT_SCHEMA_VERSION,
            name: "test-mod".to_string(),
            display_name: "Test Mod".to_string(),
            description: Some("A mod with string overrides".to_string()),
            version: Version::parse("2.0.0").unwrap(),
            distributor: None,
            authors: vec![ModpkgAuthor {
                name: "Author".to_string(),
                role: None,
            }],
            license: ModpkgLicense::None,
            tags: vec![],
            champions: vec![],
            maps: vec![],
            layers: vec![
                ModpkgLayerMetadata {
                    name: "base".to_string(),
                    display_name: None,
                    priority: 0,
                    description: None,
                    string_overrides: HashMap::from([(
                        "en_us".to_string(),
                        HashMap::from([("game_stat_name".to_string(), "Custom Stat".to_string())]),
                    )]),
                },
                ModpkgLayerMetadata {
                    name: "chroma1".to_string(),
                    display_name: Some("Pink chroma".to_string()),
                    priority: 10,
                    description: Some("Pink chroma".to_string()),
                    string_overrides: HashMap::from([(
                        "en_us".to_string(),
                        HashMap::from([
                            ("champion_name".to_string(), "Custom Name".to_string()),
                            ("ability_desc".to_string(), "Custom Description".to_string()),
                        ]),
                    )]),
                },
            ],
        };

        let mut cursor = Cursor::new(Vec::new());
        metadata.write(&mut cursor).unwrap();
        cursor.set_position(0);

        let read = ModpkgMetadata::read(&mut cursor).unwrap();
        assert_eq!(metadata, read);
        assert_eq!(read.schema_version, CURRENT_SCHEMA_VERSION);
        assert_eq!(read.layers[0].string_overrides.len(), 1); // 1 locale
        assert_eq!(read.layers[1].string_overrides.len(), 1); // 1 locale
        assert_eq!(
            read.layers[0]
                .string_overrides
                .get("en_us")
                .and_then(|m| m.get("game_stat_name")),
            Some(&"Custom Stat".to_string())
        );
    }
}