File size: 1,192 Bytes
350392a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Unified escaping helpers for HTML rendering.

Keep all HTML/attribute/script escaping logic in one place to avoid divergence.
"""

import json
from typing import Any


def escape_text_node(text: str) -> str:
    """Escape text for HTML text node insertion."""
    if text is None:
        return ""
    return (
        text.replace("&", "&")
        .replace("<", "&lt;")
        .replace(">", "&gt;")
    )


def escape_attr(text: str) -> str:
    """Escape text for safe placement in HTML attribute values."""
    if text is None:
        return ""
    return (
        text.replace("&", "&amp;")
        .replace('"', "&quot;")
        .replace("'", "&#39;")
        .replace("<", "&lt;")
        .replace(">", "&gt;")
        .replace("\n", "&#10;")
        .replace("\r", "&#13;")
        .replace("\t", "&#9;")
    )


def escape_json_for_script(value: Any) -> str:
    """Serialize JSON for safe embedding inside <script> tags."""
    text = json.dumps(value, ensure_ascii=False)
    # Prevent closing tags or HTML entities from breaking script context.
    return (
        text.replace("<", "\\u003c")
        .replace(">", "\\u003e")
        .replace("&", "\\u0026")
    )