Skip to content

PWA Manifest Generator — Python 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 Python 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.
from __future__ import annotations

import re
from dataclasses import dataclass, field
from typing import List, Optional

_HEX_RE = re.compile(r"^#[0-9a-fA-F]{6}$")


@dataclass
class ManifestInput:
    """Mirrors the ManifestInput interface in src/lib/pwa-manifest.ts."""

    name: str = ""
    short_name: str = ""
    description: str = ""
    start_url: str = ""
    display: str = ""
    orientation: str = ""
    background_color: str = ""
    theme_color: str = ""
    # None (the default) falls back to [192, 512]; an explicit empty list
    # emits an empty icons array — the same distinction the TS lib draws
    # with `??`.
    icon_sizes: Optional[List[int]] = None
    # Marks every icon purpose "maskable" instead of "any".
    maskable: bool = False


@dataclass
class ManifestResult:
    ok: bool
    errors: List[str] = field(default_factory=list)
    warnings: List[str] = field(default_factory=list)
    json: str = ""


def _json_string(s: str) -> str:
    """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."""
    out = ['"']
    for ch in s:
        if ch == '"':
            out.append('\\"')
        elif ch == "\\":
            out.append("\\\\")
        elif ch == "\b":
            out.append("\\b")
        elif ch == "\f":
            out.append("\\f")
        elif ch == "\n":
            out.append("\\n")
        elif ch == "\r":
            out.append("\\r")
        elif ch == "\t":
            out.append("\\t")
        elif ord(ch) < 0x20:
            out.append(f"\\u{ord(ch):04x}")
        else:
            out.append(ch)
    out.append('"')
    return "".join(out)


def build_manifest(input: ManifestInput) -> ManifestResult:
    """The Python twin of buildManifest() in src/lib/pwa-manifest.ts."""
    errors: List[str] = []
    warnings: List[str] = []

    name = input.name.strip()
    short_name = input.short_name.strip()
    description = input.description.strip()
    start_url = input.start_url.strip()
    background_color = input.background_color.strip()
    theme_color = input.theme_color.strip()
    sizes = [192, 512] if input.icon_sizes is None else input.icon_sizes

    if not name:
        errors.append("name is required.")
    if background_color and not _HEX_RE.match(background_color):
        errors.append("background_color must be a #rrggbb hex value.")
    if theme_color and not _HEX_RE.match(theme_color):
        errors.append("theme_color must be a #rrggbb hex value.")
    if any(not isinstance(s, int) or s <= 0 for s in sizes):
        errors.append("icon sizes must be positive integers.")
    seen: set[int] = set()
    for s in sizes:
        if s in seen:
            errors.append(f"icon size {s} is listed twice.")
        seen.add(s)
    if errors:
        return ManifestResult(ok=False, errors=errors, warnings=[], json="")

    if len(short_name) > 12:
        warnings.append(f"short_name is {len(short_name)} characters — home-screen labels truncate around 12.")

    lines: List[str] = []

    def add(key: str, value: str) -> None:
        lines.append("  " + _json_string(key) + ": " + _json_string(value))

    add("name", name)
    if short_name:
        add("short_name", short_name)
    if description:
        add("description", description)
    if start_url:
        add("start_url", start_url)
    if input.display:
        add("display", input.display)
    if input.orientation:
        add("orientation", input.orientation)
    if background_color:
        add("background_color", background_color)
    if theme_color:
        add("theme_color", theme_color)

    purpose = "maskable" if input.maskable else "any"
    icon_entries = [
        "    {\n"
        '      "src": ' + _json_string(f"icons/icon-{s}x{s}.png") + ",\n"
        '      "sizes": ' + _json_string(f"{s}x{s}") + ",\n"
        '      "type": "image/png",\n'
        '      "purpose": ' + _json_string(purpose) + "\n"
        "    }"
        for s in sizes
    ]
    # JSON.stringify renders an empty array inline.
    lines.append("  \"icons\": []" if not icon_entries else "  \"icons\": [\n" + ",\n".join(icon_entries) + "\n  ]")

    return ManifestResult(ok=True, errors=errors, warnings=warnings, json="{\n" + ",\n".join(lines) + "\n}\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 →