roblox-slang 2.0.4

Type-safe internationalization for Roblox experiences
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
//! Configuration management
//!
//! This module handles loading, validating, and creating configuration files
//! for roblox-slang projects.

mod defaults;
mod schema;

pub use schema::*;

use anyhow::{bail, Result};
use std::path::Path;

/// Load configuration from a YAML file
pub fn load_config(path: &Path) -> Result<Config> {
    // Check if config file exists
    if !path.exists() {
        bail!(
            "Configuration file not found: {}\n\
             \n\
             Hint: Run `slang-roblox init` to create a default configuration.\n\
             Or create the file manually with:\n\
             \n\
             base_locale: en\n\
             supported_locales:\n\
               - en\n\
             input_directory: translations\n\
             output_directory: output",
            path.display()
        );
    }

    // Read config file
    let content = std::fs::read_to_string(path).map_err(|e| {
        anyhow::anyhow!(
            "Failed to read configuration file: {}\n\
             Error: {}\n\
             \n\
             Hint: Check file permissions and ensure the file is readable.",
            path.display(),
            e
        )
    })?;

    // Check if file is empty
    if content.trim().is_empty() {
        bail!(
            "Configuration file is empty: {}\n\
             \n\
             Hint: Run `slang-roblox init` to create a default configuration.",
            path.display()
        );
    }

    // Parse YAML config
    let config: Config = serde_yaml::from_str(&content).map_err(|e| {
        let location = e.location();
        let (line, column) = if let Some(loc) = location {
            (loc.line(), loc.column())
        } else {
            (0, 0)
        };

        // Try to extract the problematic line
        let lines: Vec<&str> = content.lines().collect();
        let context_line = if line > 0 && line <= lines.len() {
            lines[line - 1]
        } else {
            ""
        };

        anyhow::anyhow!(
            "Failed to parse configuration file: {}\n\
             Error at line {}, column {}: {}\n\
             \n\
             Problematic line:\n\
             {}\n\
             {}^\n\
             \n\
             Common configuration errors:\n\
             - Incorrect indentation (use 2 spaces)\n\
             - Missing colon after key\n\
             - Wrong field names (check spelling)\n\
             \n\
             Hint: Compare with the example in the documentation or run `slang-roblox init`.",
            path.display(),
            line,
            column,
            e,
            context_line,
            " ".repeat(column.saturating_sub(1))
        )
    })?;

    // Validate config
    config.validate().map_err(|e| {
        anyhow::anyhow!(
            "{}\n\
             \n\
             Configuration file: {}",
            e,
            path.display()
        )
    })?;

    Ok(config)
}

/// Create a default configuration file
pub fn create_default_config(path: &Path) -> Result<()> {
    let yaml = r#"# Roblox Slang Configuration
# Documentation: https://github.com/mathtechstudio/roblox-slang

# Base locale (fallback when translation is missing)
base_locale: en

# Supported locales for your game
supported_locales:
  - en

# Directory containing translation files (JSON/YAML)
input_directory: translations

# Directory for generated Luau code
output_directory: output

# Optional: Namespace for generated module (null = no namespace)
namespace: null

# Localization mode
# Controls how translations are loaded at runtime
localization:
  # Mode: embedded (default) - Translations embedded in generated code, no cloud dependency
  # Other options:
  #   - cloud: Use Roblox Cloud LocalizationService only (requires cloud upload)
  #   - hybrid: Try cloud first, fallback to embedded (best of both worlds)
  mode: embedded

# Optional: Translation overrides
# overrides:
#   enabled: true
#   file: overrides.yaml

# Optional: Analytics for tracking missing translations
# analytics:
#   enabled: true
#   track_missing: true
#   track_usage: true

# Optional: Roblox Cloud integration for syncing translations
# Enables upload, download, and bidirectional sync with Roblox Cloud Localization Tables
# cloud:
#   # Localization table ID (UUID format)
#   # Get from: Creator Dashboard > Localization > Table Settings
#   table_id: "your-table-id-here"
#   
#   # Game/Universe ID (numeric)
#   # Get from: Creator Dashboard > Game Settings > Basic Info
#   game_id: "your-game-id-here"
#   
#   # API Key (RECOMMENDED: Use environment variable instead)
#   # Set via: export ROBLOX_CLOUD_API_KEY=your_key_here
#   # Get from: https://create.roblox.com/credentials
#   # api_key: "your-api-key-here"
#   
#   # Default merge strategy for sync command
#   # Options:
#   #   - merge: Upload local-only, download cloud-only, prefer cloud for conflicts (recommended)
#   #   - overwrite: Replace all cloud translations with local (destructive)
#   #   - skip-conflicts: Only sync non-conflicting entries
#   strategy: merge
"#;

    std::fs::write(path, yaml).map_err(|e| {
        anyhow::anyhow!(
            "Failed to write configuration file: {}\n\
             Error: {}\n\
             \n\
             Hint: Check directory permissions and ensure you have write access.",
            path.display(),
            e
        )
    })?;

    Ok(())
}

/// Create a default overrides file
pub fn create_default_overrides(path: &Path) -> Result<()> {
    let yaml = r#"# Translation Overrides
# Override specific translations per locale without modifying source files
# Useful for A/B testing, seasonal events, or quick fixes

# Example overrides:
# en:
#   ui.buttons.buy: "Purchase Now!"
#   ui.messages.greeting: "Hey there, {name}!"
#
# es:
#   ui.buttons.buy: "¡Comprar Ahora!"
#
# id:
#   ui.buttons.buy: "Beli Sekarang!"
"#;

    std::fs::write(path, yaml).map_err(|e| {
        anyhow::anyhow!(
            "Failed to write overrides file: {}\n\
             Error: {}\n\
             \n\
             Hint: Check directory permissions and ensure you have write access.",
            path.display(),
            e
        )
    })?;

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn test_load_config_valid() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("slang-roblox.yaml");

        let yaml = r#"
base_locale: en
supported_locales:
  - en
  - id
input_directory: translations
output_directory: output
"#;
        fs::write(&config_path, yaml).unwrap();

        let config = load_config(&config_path).unwrap();
        assert_eq!(config.base_locale, "en");
        assert_eq!(config.supported_locales, vec!["en", "id"]);
        assert_eq!(config.input_directory, "translations");
        assert_eq!(config.output_directory, "output");
    }

    #[test]
    fn test_load_config_file_not_found() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("nonexistent.yaml");

        let result = load_config(&config_path);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Configuration file not found"));
    }

    #[test]
    fn test_load_config_empty_file() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("empty.yaml");

        fs::write(&config_path, "").unwrap();

        let result = load_config(&config_path);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Configuration file is empty"));
    }

    #[test]
    fn test_load_config_invalid_yaml() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("invalid.yaml");

        let yaml = r#"
base_locale: en
supported_locales:
  - en
  invalid yaml syntax here
"#;
        fs::write(&config_path, yaml).unwrap();

        let result = load_config(&config_path);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Failed to parse configuration file"));
    }

    #[test]
    fn test_load_config_validation_error() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("invalid_config.yaml");

        let yaml = r#"
base_locale: en
supported_locales:
  - id
input_directory: translations
output_directory: output
"#;
        fs::write(&config_path, yaml).unwrap();

        let result = load_config(&config_path);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("must be included in supported_locales"));
    }

    #[test]
    fn test_create_default_config() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("slang-roblox.yaml");

        create_default_config(&config_path).unwrap();

        assert!(config_path.exists());
        let content = fs::read_to_string(&config_path).unwrap();
        assert!(content.contains("base_locale: en"));
        assert!(content.contains("supported_locales:"));
        assert!(content.contains("input_directory: translations"));
        assert!(content.contains("output_directory: output"));
    }

    #[test]
    fn test_create_default_overrides() {
        let temp_dir = TempDir::new().unwrap();
        let overrides_path = temp_dir.path().join("overrides.yaml");

        create_default_overrides(&overrides_path).unwrap();

        assert!(overrides_path.exists());
        let content = fs::read_to_string(&overrides_path).unwrap();
        assert!(content.contains("Translation Overrides"));
        assert!(content.contains("Example overrides:"));
    }

    #[test]
    fn test_load_config_with_namespace() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config.yaml");

        let yaml = r#"
base_locale: en
supported_locales:
  - en
input_directory: translations
output_directory: output
namespace: MyGame
"#;
        fs::write(&config_path, yaml).unwrap();

        let config = load_config(&config_path).unwrap();
        assert_eq!(config.namespace, Some("MyGame".to_string()));
    }

    #[test]
    fn test_load_config_with_overrides() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config.yaml");

        let yaml = r#"
base_locale: en
supported_locales:
  - en
input_directory: translations
output_directory: output
overrides:
  enabled: true
  file: custom_overrides.yaml
"#;
        fs::write(&config_path, yaml).unwrap();

        let config = load_config(&config_path).unwrap();
        assert!(config.overrides.is_some());
        let overrides = config.overrides.unwrap();
        assert!(overrides.enabled);
        assert_eq!(overrides.file, "custom_overrides.yaml");
    }

    #[test]
    fn test_load_config_with_analytics() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("config.yaml");

        let yaml = r#"
base_locale: en
supported_locales:
  - en
input_directory: translations
output_directory: output
analytics:
  enabled: true
  track_missing: true
  track_usage: false
  callback: game.Analytics.Track
"#;
        fs::write(&config_path, yaml).unwrap();

        let config = load_config(&config_path).unwrap();
        assert!(config.analytics.is_some());
        let analytics = config.analytics.unwrap();
        assert!(analytics.enabled);
        assert!(analytics.track_missing);
        assert!(!analytics.track_usage);
        assert_eq!(analytics.callback, Some("game.Analytics.Track".to_string()));
    }
}