fob_cli/cli/
validation.rs

1/// Parse and validate a global variable name for IIFE bundles.
2///
3/// Ensures the name is a valid JavaScript identifier:
4/// - Must start with a letter, underscore, or dollar sign
5/// - Can contain letters, numbers, underscores, or dollar signs
6/// - Cannot be empty
7///
8/// # Examples
9///
10/// Valid identifiers: MyLibrary, _internal, $jquery, lib123
11/// Invalid identifiers: 123abc, my-lib, my.lib, ""
12///
13/// # Errors
14///
15/// Returns an error message if the identifier is invalid.
16pub fn parse_global(s: &str) -> Result<String, String> {
17    if s.is_empty() {
18        return Err("Global name cannot be empty".to_string());
19    }
20
21    let first = s.chars().next().unwrap();
22    if !first.is_alphabetic() && first != '_' && first != '$' {
23        return Err(format!(
24            "Global name must start with a letter, underscore, or dollar sign: '{}'",
25            s
26        ));
27    }
28
29    for c in s.chars() {
30        if !c.is_alphanumeric() && c != '_' && c != '$' {
31            return Err(format!(
32                "Global name can only contain letters, numbers, underscores, or dollar signs: '{}'",
33                s
34            ));
35        }
36    }
37
38    Ok(s.to_string())
39}