nex_animation/reports/ui_evidence/nex-p11/chunkbytes.py

99 lines
3.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
把 chunk 的**产物字节**按 sourcemap 的 mappings 归到每个源模块上。
不用 sourcesContent 的长度近似——那是源码大小,和压缩后的产物不成比例。
"""
import base64, glob, json, os, sys, collections
CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
def vlq(seg):
out, shift, val = [], 0, 0
for c in seg:
d = CHARS.index(c)
val += (d & 31) << shift
if d & 32:
shift += 5; continue
out.append(-(val >> 1) if val & 1 else val >> 1)
val, shift = 0, 0
return out
def norm(src: str) -> str:
s = src
while s.startswith("../"):
s = s[3:]
s = s.lstrip("./")
if "node_modules/" in s:
tail = s.split("node_modules/", 1)[1]
parts = tail.split("/")
pkg = "/".join(parts[:2]) if parts[0].startswith("@") else parts[0]
return "npm:" + pkg
if s.startswith("src/"):
return "src:" + "/".join(s.split("/")[:2]) if len(s.split("/")) > 2 else "src:" + s
return "other:" + s
def analyze(js_path, minmod=400):
mp = js_path + ".map"
if not os.path.exists(mp):
return None
m = json.load(open(mp))
srcs = m.get("sources") or []
code = open(js_path, encoding="utf-8").read()
lines = code.split("\n")
agg = collections.Counter(); mods = collections.Counter()
raw = {}
for li, line in enumerate(m.get("mappings", "").split(";")):
if not line:
continue
segs = []
gc = si = sl = sc = 0
for part in line.split(","):
if not part:
continue
f = vlq(part)
gc += f[0]
if len(f) >= 2: si += f[1]
if len(f) >= 3: sl += f[2]
if len(f) >= 4: sc += f[3]
if len(f) >= 2:
segs.append((gc, si))
text = lines[li] if li < len(lines) else ""
for i, (col, si) in enumerate(segs):
nxt = segs[i + 1][0] if i + 1 < len(segs) else len(text)
n = len(text[col:nxt].encode())
if n <= 0:
continue
src = srcs[si] if si < len(srcs) else "?"
g = norm(src)
agg[g] += n
mods[g] += 1
key = src.split("node_modules/", 1)[-1] if "node_modules/" in src else src.split("../../")[-1]
raw[key] = raw.get(key, 0) + n
total = sum(agg.values())
return total, agg, mods, raw
if __name__ == "__main__":
SM = os.environ.get("SM_DIR", "frontend/dist-sm/assets")
targets = sys.argv[1:] or ["ui"]
allrows = []
for path in sorted(glob.glob(f"{SM}/*.js")):
if os.path.basename(path).startswith(tuple(targets)) is False and not any(t in os.path.basename(path) for t in targets):
continue
r = analyze(path)
if not r:
continue
total, agg, mods, raw = r
size = os.path.getsize(path)
name = os.path.basename(path)
print(f"\n=== {name} 产物 {size/1024:.1f} KiB · 可归属 {total/1024:.1f} KiB({total*100/size:.0f}%)· 源模块 {len(raw)} 个 ===")
print(f"{'分组(按包)':32} {'产物 KiB':>9} {'占比':>7} {'模块数':>7}")
for g, n in agg.most_common(14):
print(f"{g:32} {n/1024:9.1f} {n*100/total:6.1f}% {mods[g]:7}")
allrows.append((name, size, agg, raw))
print("\n=== 单模块 Top 20(ui-*)===")
for name, size, agg, raw in allrows:
if not name.startswith("ui-"):
continue
for src, n in sorted(raw.items(), key=lambda x: -x[1])[:20]:
print(f"{n/1024:8.1f} KiB {src[:96]}")