Repository navigation
Expand file tree
/
Copy pathbuild_html.py
More file actions
223 lines (191 loc) · 9.43 KB
/
Copy pathbuild_html.py
File metadata and controls
223 lines (191 loc) · 9.43 KB
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
import os
import re
import sys
import gzip
import hashlib
# PlatformIO runs this from the project root without __file__.
sys.path.insert(0, os.path.abspath(os.path.join("scripts", "vendor")))
from rcssmin import cssmin # noqa: E402
from rjsmin import jsmin # noqa: E402
SRC_DIR = "src"
HTML_EXT = ".html"
JS_EXT = ".js"
ASSET_SUFFIXES = {HTML_EXT: "Html", ".js": "Js", ".css": "Css", ".svg": "Svg"}
HEADER_PREAMBLE = "// THIS FILE IS AUTOGENERATED, DO NOT EDIT MANUALLY\n\n"
HEADER_PRAGMA = "#pragma once\n"
HEADER_INCLUDE = "#include <cstddef>\n\n"
def resolve_includes(html: str, base_dir: str) -> str:
"""Inline <!--#include file="path" --> directives (path relative to base_dir).
Must run BEFORE minify_html, which strips all HTML comments. Includes are
single-level (no included file includes another), so one pass suffices."""
pattern = re.compile(r'<!--\s*#include\s+file="([^"]+)"\s*-->')
def repl(match):
inc_path = os.path.join(base_dir, match.group(1))
with open(inc_path, "r", encoding="utf-8") as f:
return f.read()
return pattern.sub(repl, html)
# rjsmin only treats "/" as a regex literal after one of these or `return`.
RJSMIN_REGEX_PREFIX = set("(,=:[!&|?{};\n+*-")
# JavaScript also starts a regex (not a division) after these.
JS_REGEX_PREFIX = RJSMIN_REGEX_PREFIX | set("%<>~^}")
JS_REGEX_KEYWORDS = {"return", "typeof", "case", "do", "else", "in", "of", "new", "delete", "void", "throw",
"yield", "await", "instanceof"}
def rjsmin_hazard(js: str):
"""Return (line, problem) for JS that rjsmin would silently corrupt, or None.
rjsmin does not support a template literal nested in another one's ${...},
and misreads a regex literal that does not follow RJSMIN_REGEX_PREFIX or
`return` (for example `x => /re/`)."""
i, n, mode, stack = 0, len(js), None, []
prev, prev_raw, word = "", "", "" # last code char, same with "\n" kept, last word
# After a string, template or regex, "x" stands for an operand, so a "/" divides.
prev_at, dotted = 0, False # where prev is; word follows "." (obj.in is not a keyword)
line = lambda pos: js.count("\n", 0, pos) + 1
while i < n:
c = js[i]
if mode is not None: # inside '...', "..." or `...`
if c == "\\":
i += 2
continue
if c == mode or (c == "\n" and mode != "`"):
mode, prev, prev_raw, word = None, "x", "x", ""
elif mode == "`" and js.startswith("${", i):
stack.append("${")
mode, prev, prev_raw, word = None, "{", "{", ""
i += 2
continue
i += 1
continue
if js.startswith("//", i):
i = n if js.find("\n", i) < 0 else js.find("\n", i)
continue
if js.startswith("/*", i):
i = n if js.find("*/", i + 2) < 0 else js.find("*/", i + 2) + 2
continue
if c == "/" and (prev == "" or prev in JS_REGEX_PREFIX or (word in JS_REGEX_KEYWORDS and not dotted)):
if not (prev_raw == "" or prev_raw in RJSMIN_REGEX_PREFIX or word == "return"):
return line(i), "regex literal after '" + (word or prev) + "'; wrap it in parentheses"
in_class, j = False, i + 1
while j < n and js[j] != "\n":
if js[j] == "\\":
j += 1
elif js[j] == "[":
in_class = True
elif js[j] == "]":
in_class = False
elif js[j] == "/" and not in_class:
break
j += 1
i, prev, prev_raw, word = j + 1, "x", "x", ""
continue
if c in "'\"`":
if c == "`" and "${" in stack:
return line(i), "nested template literal"
mode = c
elif c == "{":
stack.append("{")
elif c == "}" and stack and stack.pop() == "${":
mode = "`"
if c.isalnum() or c in "_$":
if i > 0 and (js[i - 1].isalnum() or js[i - 1] in "_$"):
word += c
else:
word, dotted = c, prev == "." and js[prev_at - 1:prev_at] != "." # not ...spread
elif not c.isspace():
word = ""
if not c.isspace():
prev, prev_at = c, i
if not c.isspace() or c == "\n":
prev_raw = c
i += 1
return None
def minify_js(js: str, file_path: str) -> str:
hazard = rjsmin_hazard(js)
if hazard is not None:
sys.exit(f"{file_path}: script line {hazard[0]}: {hazard[1]}; rjsmin cannot minify it")
return jsmin(js)
def minify_inline_assets(html: str, file_path: str) -> str:
"""Minify inline <script> (without src) and <style> blocks."""
def script(match):
return match.group(1) + minify_js(match.group(2), file_path) + match.group(3)
html = re.sub(r'(<script\b(?![^>]*\bsrc=)[^>]*>)(.*?)(</script>)', script, html, flags=re.DOTALL | re.IGNORECASE)
return re.sub(r'(<style\b[^>]*>)(.*?)(</style>)', lambda m: m.group(1) + cssmin(m.group(2)) + m.group(3), html,
flags=re.DOTALL | re.IGNORECASE)
def minify_html(html: str) -> str:
# Tags where whitespace should be preserved
preserve_tags = ['pre', 'code', 'textarea', 'script', 'style']
preserve_regex = '|'.join(preserve_tags)
# Protect preserve blocks with placeholders
preserve_blocks = []
def preserve(match):
preserve_blocks.append(match.group(0))
return f"__PRESERVE_BLOCK_{len(preserve_blocks)-1}__"
html = re.sub(rf'<({preserve_regex})[\s\S]*?</\1>', preserve, html, flags=re.IGNORECASE)
# Remove HTML comments
html = re.sub(r'<!--.*?-->', '', html, flags=re.DOTALL)
# Collapse all whitespace between tags
html = re.sub(r'>\s+<', '><', html)
# Collapse multiple spaces inside tags
html = re.sub(r'\s+', ' ', html)
# Restore preserved blocks
for i, block in enumerate(preserve_blocks):
html = html.replace(f"__PRESERVE_BLOCK_{i}__", block)
return html.strip()
def sanitize_identifier(name: str) -> str:
"""Sanitize a filename to create a valid C identifier.
C identifiers must:
- Start with a letter or underscore
- Contain only letters, digits, and underscores
"""
# Replace non-alphanumeric characters (including hyphens) with underscores
sanitized = re.sub(r'\W', '_', name, flags=re.ASCII)
# Prefix with underscore if starts with a digit
if sanitized and sanitized[0].isdigit():
sanitized = f"_{sanitized}"
return sanitized
for root, _, files in os.walk(SRC_DIR):
for file in files:
if file.endswith(tuple(ASSET_SUFFIXES)):
file_path = os.path.join(root, file)
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
if file.endswith(HTML_EXT):
processed = minify_html(minify_inline_assets(resolve_includes(content, root), file_path))
elif file.endswith(".css"):
processed = cssmin(content)
elif file.endswith(JS_EXT) and not file.endswith(".min.js"):
processed = minify_js(content, file_path)
else:
processed = content # pre-minified (e.g., jszip.min.js) or SVG
# Compress with gzip (compresslevel 9 is maximum compression)
# mtime=0 keeps the output reproducible across builds
# IMPORTANT: we don't use brotli because Firefox doesn't support brotli with insecured context (only supported on HTTPS)
compressed = gzip.compress(processed.encode('utf-8'), compresslevel=9, mtime=0)
# Create valid C identifier from filename
# Use appropriate suffix based on file type
suffix = ASSET_SUFFIXES[os.path.splitext(file)[1]]
base_name = sanitize_identifier(f"{os.path.splitext(file)[0]}{suffix}")
header_path = os.path.join(root, f"{base_name}.generated.h")
with open(header_path, "w", encoding="utf-8") as h:
h.write(HEADER_PREAMBLE)
h.write(HEADER_PRAGMA)
h.write(HEADER_INCLUDE)
# Write the compressed data as a byte array
h.write(f"constexpr char {base_name}[] PROGMEM = {{\n")
# Write bytes in rows of 16
for i in range(0, len(compressed), 16):
chunk = compressed[i:i+16]
hex_values = ', '.join(f'0x{b:02x}' for b in chunk)
h.write(f" {hex_values},\n")
h.write("};\n\n")
h.write(f"constexpr size_t {base_name}CompressedSize = {len(compressed)};\n")
h.write(f"constexpr size_t {base_name}OriginalSize = {len(processed)};\n")
# ETag derived from the compressed payload. The content is
# immutable at runtime (baked into flash at build time), so a
# strong ETag keyed on the bytes is safe and stable. Browsers
# echo it back as If-None-Match, enabling 304 responses.
etag = hashlib.sha256(compressed).hexdigest()[:16]
h.write(f'constexpr const char* {base_name}ETag = "\\"{etag}\\"";\n')
print(f"Generated: {header_path}")
print(f" Original: {len(content)} bytes")
print(f" Minified: {len(processed)} bytes ({100*len(processed)/len(content):.1f}%)")
print(f" Compressed: {len(compressed)} bytes ({100*len(compressed)/len(content):.1f}%)")