Skip to content

PWA Manifest Generator — Rust source

Assemble a valid Web App Manifest — name, colors, display mode, icon sizes, maskable purpose — with a stable key order and instant JSON you can copy or download.

This is the Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.

//! pwa-manifest — build a fixed-key-order manifest.json from form fields.
//! Authored snippet mirroring src/lib/pwa-manifest.ts: same fixed key order
//! (name, short_name, description, start_url, display, orientation,
//! background_color, theme_color, icons), blank optional fields omitted, icon
//! sizes defaulting to [192, 512], hard errors suppressing emission, and the
//! short_name >12 warning never blocking. Same logic as this dir's
//! typescript.ts and the live Go twin at
//! cli/pwa-manifest-generator/pwa-manifest-generator.go.

/// Mirrors the ManifestInput interface in src/lib/pwa-manifest.ts. The
/// Default value matches buildManifest({}): no name, default icon sizes
/// [192, 512], purpose "any". `icon_sizes: None` falls back to the TS
/// default while `Some(vec![])` emits an empty icons array — the same
/// distinction the TS lib draws with `??`.
#[derive(Debug, Clone, Default)]
pub struct ManifestInput {
    pub name: String,
    pub short_name: String,
    pub description: String,
    pub start_url: String,
    pub display: String,
    pub orientation: String,
    pub background_color: String,
    pub theme_color: String,
    pub icon_sizes: Option<Vec<i64>>,
    pub maskable: bool,
}

/// Mirrors the ManifestResult interface in src/lib/pwa-manifest.ts.
#[derive(Debug, Clone, Default)]
pub struct ManifestResult {
    pub ok: bool,
    pub errors: Vec<String>,
    pub warnings: Vec<String>,
    pub json: String,
}

/// Same contract as TS HEX = /^#[0-9a-fA-F]{6}$/.
fn is_hex_color(s: &str) -> bool {
    let b = s.as_bytes();
    b.len() == 7
        && b[0] == b'#'
        && b[1..].iter().all(|&c| c.is_ascii_hexdigit())
}

/// Double-quote s exactly like JavaScript's JSON.stringify: escape ", \, and
/// the control characters (short escapes for \b \f \n \r \t, \u00xx for the
/// rest), leave everything else — including non-ASCII — untouched.
fn json_string(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    out.push('"');
    for ch in s.chars() {
        match ch {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\u{0008}' => out.push_str("\\b"),
            '\u{000c}' => out.push_str("\\f"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
            c => out.push(c),
        }
    }
    out.push('"');
    out
}

/// The Rust twin of buildManifest() in src/lib/pwa-manifest.ts.
pub fn build_manifest(input: &ManifestInput) -> ManifestResult {
    let mut errors: Vec<String> = Vec::new();
    let mut warnings: Vec<String> = Vec::new();

    let name = input.name.trim();
    let short_name = input.short_name.trim();
    let description = input.description.trim();
    let start_url = input.start_url.trim();
    let background_color = input.background_color.trim();
    let theme_color = input.theme_color.trim();
    let default_sizes = [192i64, 512];
    let sizes: &[i64] = input.icon_sizes.as_deref().unwrap_or(&default_sizes);

    if name.is_empty() {
        errors.push("name is required.".to_string());
    }
    if !background_color.is_empty() && !is_hex_color(background_color) {
        errors.push("background_color must be a #rrggbb hex value.".to_string());
    }
    if !theme_color.is_empty() && !is_hex_color(theme_color) {
        errors.push("theme_color must be a #rrggbb hex value.".to_string());
    }
    if sizes.iter().any(|&s| s <= 0) {
        errors.push("icon sizes must be positive integers.".to_string());
    }
    let mut seen: Vec<i64> = Vec::new();
    for &s in sizes {
        if seen.contains(&s) {
            errors.push(format!("icon size {} is listed twice.", s));
        }
        seen.push(s);
    }
    if !errors.is_empty() {
        return ManifestResult { ok: false, errors, warnings: Vec::new(), json: String::new() };
    }

    let short_name_chars = short_name.chars().count();
    if short_name_chars > 12 {
        warnings.push(format!(
            "short_name is {} characters \u{2014} home-screen labels truncate around 12.",
            short_name_chars
        ));
    }

    let mut lines: Vec<String> = Vec::new();
    {
        let mut add = |key: &str, value: &str| {
            lines.push(format!("  {}: {}", json_string(key), json_string(value)));
        };
        add("name", name);
        if !short_name.is_empty() {
            add("short_name", short_name);
        }
        if !description.is_empty() {
            add("description", description);
        }
        if !start_url.is_empty() {
            add("start_url", start_url);
        }
        if !input.display.is_empty() {
            add("display", &input.display);
        }
        if !input.orientation.is_empty() {
            add("orientation", &input.orientation);
        }
        if !background_color.is_empty() {
            add("background_color", background_color);
        }
        if !theme_color.is_empty() {
            add("theme_color", theme_color);
        }
    }

    let purpose = if input.maskable { "maskable" } else { "any" };
    let icon_entries: Vec<String> = sizes
        .iter()
        .map(|&s| {
            format!(
                "    {{\n      \"src\": {},\n      \"sizes\": {},\n      \"type\": \"image/png\",\n      \"purpose\": {}\n    }}",
                json_string(&format!("icons/icon-{}x{}.png", s, s)),
                json_string(&format!("{}x{}", s, s)),
                json_string(purpose),
            )
        })
        .collect();
    // JSON.stringify renders an empty array inline.
    lines.push(if icon_entries.is_empty() {
        "  \"icons\": []".to_string()
    } else {
        format!("  \"icons\": [\n{}\n  ]", icon_entries.join(",\n"))
    });

    ManifestResult {
        ok: true,
        errors,
        warnings,
        json: format!("{{\n{}\n}}\n", lines.join(",\n")),
    }
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →