File size: 8,593 Bytes
29e1b52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import math
import re
from xml.etree import ElementTree as ET

from defusedxml import ElementTree as safe_xml
from defusedxml.common import DefusedXmlException

SVG_NS = "http://www.w3.org/2000/svg"
NS = f"{{{SVG_NS}}}"
MAX_SVG_BYTES = 100_000
ET.register_namespace("", SVG_NS)

NUMBER = r"[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?"
ID = r"[A-Za-z_][\w.:-]*"
LOCAL_URL = re.compile(rf"url\(\s*#{ID}\s*\)")
COLOR = re.compile(r"#[0-9a-fA-F]{3,8}|[A-Za-z]+|(?:rgb|hsl)a?\([0-9.,% +/\-]+\)")
CLOCK = re.compile(r"(\d+(?:\.\d+)?|\.\d+)(ms|s)")

PAINT = {"fill", "stroke", "color", "stop-color"}
PRESENTATION = PAINT | {
    "fill-opacity", "fill-rule", "stroke-opacity", "stroke-width",
    "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-dasharray",
    "stroke-dashoffset", "opacity", "transform", "clip-path", "clip-rule",
    "vector-effect", "font-family", "font-size", "font-weight",
    "text-anchor", "dominant-baseline",
}
ELEMENTS = {
    "svg": {"viewBox", "width", "height", "preserveAspectRatio", "version"},
    "g": set(),
    "path": {"d", "pathLength"},
    "rect": {"x", "y", "width", "height", "rx", "ry", "pathLength"},
    "circle": {"cx", "cy", "r", "pathLength"},
    "ellipse": {"cx", "cy", "rx", "ry", "pathLength"},
    "line": {"x1", "y1", "x2", "y2", "pathLength"},
    "polyline": {"points", "pathLength"},
    "polygon": {"points", "pathLength"},
    "text": {"x", "y", "dx", "dy", "rotate"},
    "tspan": {"x", "y", "dx", "dy", "rotate"},
    "defs": set(),
    "linearGradient": {"x1", "y1", "x2", "y2", "gradientUnits", "gradientTransform", "spreadMethod"},
    "radialGradient": {"cx", "cy", "r", "fx", "fy", "fr", "gradientUnits", "gradientTransform", "spreadMethod"},
    "stop": {"offset", "stop-opacity"},
    "clipPath": {"clipPathUnits"},
    "title": set(),
    "desc": set(),
}
TIMING = {
    "attributeName", "values", "from", "to", "by", "dur", "begin",
    "repeatCount", "fill", "calcMode", "keyTimes", "keySplines",
}
ANIMATIONS = {
    "animate": TIMING,
    "animateTransform": TIMING | {"type"},
    "animateMotion": (TIMING - {"attributeName"}) | {"path", "rotate", "keyPoints"},
}
ANIMATABLE = PAINT | {
    "opacity", "fill-opacity", "stroke-opacity", "stroke-width", "stroke-dashoffset",
    "stop-opacity", "offset", "x", "y", "width", "height", "cx", "cy", "r", "rx",
    "ry", "x1", "x2", "y1", "y2", "d", "points",
}
GRAPHICS = {
    "g", "path", "rect", "circle", "ellipse", "line", "polyline",
    "polygon", "text", "tspan",
}


class SVGError(ValueError):
    """The source SVG is invalid or outside the supported subset."""


def seconds(value: str) -> float:
    match = CLOCK.fullmatch(value)
    if match is None:
        raise SVGError("μ• λ‹ˆλ©”μ΄μ…˜ μ‹œκ°„μ— s λ˜λŠ” ms λ‹¨μœ„λ₯Ό μ‚¬μš©ν•΄ μ£Όμ„Έμš”.")
    amount, unit = match.groups()
    number = float(amount) / (1000 if unit == "ms" else 1)
    if not math.isfinite(number):
        raise SVGError("μ• λ‹ˆλ©”μ΄μ…˜ μ‹œκ°„μ„ 확인해 μ£Όμ„Έμš”.")
    return number


def view_box(root: ET.Element) -> tuple[float, float, float, float]:
    raw = root.get("viewBox")
    if raw is None:
        dimensions = [root.get(axis, "") for axis in ("width", "height")]
        raw = "0 0 " + " ".join(d.removesuffix("px") for d in dimensions)
    parts = re.split(r"[\s,]+", raw.strip())
    if len(parts) != 4 or any(re.fullmatch(NUMBER, part) is None for part in parts):
        raise SVGError("SVG에 μ˜¬λ°”λ₯Έ viewBox λ˜λŠ” ν”½μ…€ λ‹¨μœ„ λ„ˆλΉ„μ™€ 높이λ₯Ό λ„£μ–΄ μ£Όμ„Έμš”.")
    x, y, width, height = map(float, parts)
    if not all(math.isfinite(n) and abs(n) <= 100_000 for n in (x, y, width, height)):
        raise SVGError("SVG의 viewBox λ²”μœ„λ₯Ό 확인해 μ£Όμ„Έμš”.")
    if width <= 0 or height <= 0:
        raise SVGError("SVG의 λ„ˆλΉ„μ™€ λ†’μ΄λŠ” μ–‘μˆ˜μ—¬μ•Ό ν•©λ‹ˆλ‹€.")
    return x, y, width, height


def _validate_animation(element: ET.Element, kind: str, parent: str | None) -> None:
    target = element.get("attributeName", "")
    if parent not in (GRAPHICS | {"svg", "stop"}):
        raise SVGError("μ• λ‹ˆλ©”μ΄μ…˜μ€ 움직일 λ„ν˜• μ•ˆμ— λ„£μ–΄ μ£Όμ„Έμš”.")
    if kind == "animate" and target not in ANIMATABLE:
        raise SVGError(f"μ§€μ›ν•˜μ§€ μ•ŠλŠ” μ• λ‹ˆλ©”μ΄μ…˜ μ†μ„±μž…λ‹ˆλ‹€ ({target}).")
    if kind == "animateTransform" and (
        target != "transform"
        or element.get("type") not in {"translate", "scale", "rotate", "skewX", "skewY"}
    ):
        raise SVGError("μ• λ‹ˆλ©”μ΄μ…˜μ˜ transform μœ ν˜•μ„ 확인해 μ£Όμ„Έμš”.")
    if not 0.001 <= seconds(element.get("dur", "")) <= 600:
        raise SVGError("μ• λ‹ˆλ©”μ΄μ…˜ κΈΈμ΄λŠ” 1ms 이상 600초 μ΄ν•˜μ—¬μ•Ό ν•©λ‹ˆλ‹€.")
    begin = element.get("begin")
    if begin is not None and begin != "0" and not 0 <= seconds(begin) <= 600:
        raise SVGError("μ• λ‹ˆλ©”μ΄μ…˜ μ‹œμž‘ μ‹œκ°„μ„ 확인해 μ£Όμ„Έμš”.")
    repeat = element.get("repeatCount", "1")
    if repeat != "indefinite" and not (
        re.fullmatch(NUMBER, repeat) and 0 < float(repeat) <= 100
    ):
        raise SVGError("μ• λ‹ˆλ©”μ΄μ…˜ 반볡 횟수λ₯Ό 확인해 μ£Όμ„Έμš”.")
    if element.get("fill", "remove") not in {"freeze", "remove"}:
        raise SVGError("μ• λ‹ˆλ©”μ΄μ…˜ μ’…λ£Œ μƒνƒœλ₯Ό 확인해 μ£Όμ„Έμš”.")
    value_attrs = {"values", "from", "to", "by"}
    if kind == "animateMotion":
        value_attrs.add("path")
    if not any(element.get(name) for name in value_attrs):
        raise SVGError("μ• λ‹ˆλ©”μ΄μ…˜μ— μ›€μ§μž„ 값이 ν•„μš”ν•©λ‹ˆλ‹€.")
    if target in PAINT:
        for name in value_attrs:
            if name in element.attrib and any(
                not COLOR.fullmatch(value.strip()) for value in element.attrib[name].split(";")
            ):
                raise SVGError("μ• λ‹ˆλ©”μ΄μ…˜ 색상 값을 확인해 μ£Όμ„Έμš”.")


def parse_svg(source: str, *, require_animation: bool = False) -> ET.Element:
    if len(source.encode("utf-8")) > MAX_SVG_BYTES:
        raise SVGError("SVGλŠ” 100 KB μ΄ν•˜μ—¬μ•Ό ν•©λ‹ˆλ‹€.")
    try:
        root = safe_xml.fromstring(source.strip(), forbid_dtd=True)
    except (ET.ParseError, DefusedXmlException) as exc:
        raise SVGError("μ˜¬λ°”λ₯Έ SVG XML을 읽을 수 μ—†μŠ΅λ‹ˆλ‹€.") from exc
    if root.tag not in {"svg", NS + "svg"}:
        raise SVGError("SVG 파일 λ˜λŠ” SVG μ½”λ“œκ°€ ν•„μš”ν•©λ‹ˆλ‹€.")
    view_box(root)

    # Rebuild the namespace and accept only standalone SVG drawing primitives.
    stack = [(root, None, 0)]
    ids = set()
    has_animation = False
    has_graphics = False
    count = 0
    while stack:
        node, parent, depth = stack.pop()
        kind = node.tag.removeprefix(NS)
        count += 1
        if depth > 35 or count > 1200:
            raise SVGError("SVG에 λ„ˆλ¬΄ λ§Žμ€ λ„ν˜• λ˜λŠ” 쀑첩이 μžˆμŠ΅λ‹ˆλ‹€.")
        if kind in ANIMATIONS:
            allowed = ANIMATIONS[kind]
            _validate_animation(node, kind, parent)
            has_animation = True
        elif kind in ELEMENTS and (kind != "svg" or parent is None):
            allowed = ELEMENTS[kind] | PRESENTATION
            has_graphics |= kind in GRAPHICS - {"g", "tspan"}
        else:
            raise SVGError(f"μ§€μ›ν•˜μ§€ μ•ŠλŠ” SVG μš”μ†Œμž…λ‹ˆλ‹€ ({kind}).")
        for attr, value in node.attrib.items():
            if attr == "id":
                if not re.fullmatch(ID, value) or value in ids:
                    raise SVGError("SVG μš”μ†Œ IDκ°€ 잘λͺ»λ˜μ—ˆκ±°λ‚˜ μ€‘λ³΅λ©λ‹ˆλ‹€.")
                ids.add(value)
            elif attr not in allowed:
                raise SVGError(f"μ§€μ›ν•˜μ§€ μ•ŠλŠ” SVG μ†μ„±μž…λ‹ˆλ‹€ ({attr}).")
            elif kind not in ANIMATIONS and attr in PAINT:
                if not (COLOR.fullmatch(value) or LOCAL_URL.fullmatch(value)):
                    raise SVGError("SVG μƒ‰μƒμ—λŠ” 색상 κ°’ λ˜λŠ” λ‚΄λΆ€ ID만 μ‚¬μš©ν•  수 μžˆμŠ΅λ‹ˆλ‹€.")
            elif attr == "clip-path" and value != "none" and not LOCAL_URL.fullmatch(value):
                raise SVGError("clip-pathμ—λŠ” SVG λ‚΄λΆ€ ID만 μ‚¬μš©ν•  수 μžˆμŠ΅λ‹ˆλ‹€.")
        node.tag = NS + kind
        stack.extend((child, kind, depth + 1) for child in node)

    if not has_graphics:
        raise SVGError("SVG에 ν‘œμ‹œν•  λ„ν˜•μ΄ ν•„μš”ν•©λ‹ˆλ‹€.")
    if require_animation and not has_animation:
        raise SVGError("SVG에 SMIL μ• λ‹ˆλ©”μ΄μ…˜μ΄ ν•„μš”ν•©λ‹ˆλ‹€.")
    if root.get("viewBox") is None:
        root.set("viewBox", " ".join(f"{value:g}" for value in view_box(root)))
    return root


def svg_text(root: ET.Element) -> str:
    return ET.tostring(root, encoding="unicode")