Coverage for fastblocks/adapters/templates/_filters.py: 0%
49 statements
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-21 04:50 -0700
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-21 04:50 -0700
1import hashlib
2import typing as t
3from urllib.parse import quote_plus
5from acb.config import Config
6from acb.depends import depends
7from fastblocks.actions.minify import minify
9_minification_cache = {}
10_cache_max_size = 1000
13def _cached_minify(
14 content: str,
15 minify_func: t.Callable[[str], str | bytes | bytearray],
16 cache_prefix: str,
17) -> str | bytes | bytearray:
18 content_hash = hashlib.md5(content.encode(), usedforsecurity=False).hexdigest()
19 cache_key = f"{cache_prefix}:{content_hash}"
21 if cache_key in _minification_cache:
22 return _minification_cache[cache_key]
24 result = minify_func(content)
26 if len(_minification_cache) >= _cache_max_size:
27 oldest_key = next(iter(_minification_cache))
28 del _minification_cache[oldest_key]
30 _minification_cache[cache_key] = result
31 return result
34class Filters:
35 config: Config = depends()
37 @classmethod
38 def get_templates(cls) -> t.Any:
39 if not hasattr(cls, "_templates"):
40 cls._templates = depends.get("templates")
41 return cls._templates
43 @staticmethod
44 def map_src(address: str) -> str:
45 return quote_plus(address)
47 @staticmethod
48 def url_encode(text: str) -> str:
49 return quote_plus(text)
51 @staticmethod
52 def minify_html(html: str) -> str | bytes | bytearray:
53 return _cached_minify(html, minify.html, "html")
55 @staticmethod
56 def minify_js(js: str) -> bytearray | bytes | str:
57 return _cached_minify(js, minify.js, "js")
59 @staticmethod
60 def minify_css(css: str) -> bytearray | bytes | str:
61 return _cached_minify(css, minify.css, "css")
63 @classmethod
64 def register_filters(cls) -> None:
65 templates = cls.get_templates()
66 templates.filter()(cls.map_src)
67 templates.filter()(cls.url_encode)
68 templates.filter()(cls.minify_html)
69 templates.filter()(cls.minify_js)
70 templates.filter()(cls.minify_css)