#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 00_lint_dist.py — UniCut 站点 dist 产物静态 lint(断网可用检查) 对构建产物做全量静态扫描,回答三个问题: 1. 还有哪些外部 URL?(按 host 聚合 + file:line 明细,区分「会真发起请求」与 「只是字符串/命名空间/文档」) 2. 懒加载 chunk 的 import 指向哪里?有没有指向外域的 chunk? 3. 音视频 / 字体 / SDK 的引用位置与当前取值是什么?本地文件是否齐全? 用法: python3 data-quality/scripts/site/00_lint_dist.py [--dist dist] [--out 报告.md] [--json 报告.json] [--no-fail] 退出码:外部网络引用(external_refs)为 0 时 0,否则 1(--no-fail 时恒 0)。 报告里的「不可消除项」= external_ref_allowlist.txt 里登记的、位于第三方压缩产物内部、 无法在不改动 vendored 代码的前提下删除的字符串,每条都带原因。 """ import argparse import bisect import json import os import re import sys import time from collections import Counter, defaultdict from urllib.parse import urlparse HERE = os.path.dirname(os.path.abspath(__file__)) REPO = os.path.dirname(os.path.dirname(os.path.dirname(HERE))) ALLOWLIST = os.path.join(HERE, 'external_ref_allowlist.txt') # 二进制扩展名:直接跳过(不解码扫描) BIN_EXT = { '.png', '.jpg', '.jpeg', '.gif', '.webp', '.ico', '.bmp', '.avif', '.mp4', '.webm', '.mov', '.m4v', '.mp3', '.m4a', '.aac', '.wav', '.ogg', '.flac', '.woff', '.woff2', '.ttf', '.otf', '.eot', '.wasm', '.data', '.bin', '.onnx', '.tflite', '.task', '.glb', '.gltf', '.zip', '.gz', '.br', '.pak', '.db', '.ico', } TEXT_EXT = { '.html', '.htm', '.js', '.mjs', '.cjs', '.css', '.less', '.json', '.svg', '.txt', '.md', '.webmanifest', '.map', '.xml', '.ts', '.tsx', '.conf', '.csv', } # 少量无扩展名但其实是文本的文件 TEXT_NAMES = {'LICENSE', 'README', 'Makefile', 'CNAME', '.well-known'} # 会真发起网络请求才算「外部依赖」的已知远程域(无 scheme 命中也算) KNOWN_HOST_RE = None # main() 里编译 KNOWN_REMOTE_HOSTS = [ 'esm.video.h5ds.com', 'esm-debug.video.h5ds.com', # video-core-sdk 远程 CDN 前缀 'audio01.h5ds.com', 'qkgzjp.h5ds.com', # 远程音频域 'cdn.h5ds.com', 'video.h5ds.com', 'fvideo.h5ds.com', 'videomix.h5ds.com', 'water.i.h5ds.com', 'lf3-static.bytednsdoc.com', 'byteblacksmith.com', 'unpkg.com', 'cdn.jsdelivr.net', 'registry.npmmirror.com', 'cdnjs.cloudflare.com', 'fonts.googleapis.com', 'fonts.gstatic.com', 'map.qq.com', 'apis.map.qq.com', 'player.bilibili.com', 'player.vimeo.com', 'www.youtube.com', ] URL_RE = re.compile(r'https?://[^\s"\'`<>()\[\]{}\\,;]+') # 字面量里带 scheme 的资源引用(含模板字符串里的完整地址) ASSET_URL_RE = re.compile( r'(?类别原因""" rules = [] if not os.path.exists(ALLOWLIST): return rules for raw in open(ALLOWURLS_FILE if False else ALLOWLIST, encoding='utf-8'): line = raw.strip() if not line or line.startswith('#'): continue parts = line.split('\t') if len(parts) < 3: continue try: rules.append((re.compile(parts[0]), parts[1], parts[2])) except re.error: print('[warn] allowlist 正则无效:', parts[0], file=sys.stderr) return rules NAMESPACE_HOSTS = {'www.w3.org', 'purl.org', 'schemas.openxmlformats.org', 'www.opengis.net', # pdf.js XFA/XMP:XML 命名空间与 schema 标识符(xmlns:xfa=...、startsWith判断), # 浏览器不会发起请求,与 w3.org 同类 'www.xfa.org', 'ns.adobe.com'} DOC_EXT = {'.md', '.map', '.txt'} def ext_of(relpath): return os.path.splitext(relpath)[1].lower() def classify(url, relpath, allow_rules): """返回 (category, reason)。category ∈ namespace|local|lan|doc|sourcemap|allow|net""" try: host = urlparse(url).netloc.lower().split('@')[-1].split(':')[0] except Exception: host = '' ext = os.path.splitext(relpath)[1].lower() if host in NAMESPACE_HOSTS: return 'namespace', 'XML/SVG 命名空间 URI,浏览器不发起请求' if host in ('localhost', '127.0.0.1', '0.0.0.0', '::1', '[::1]'): if os.path.splitext(relpath)[1].lower() in DOC_EXT: return 'doc', '文档里写的本机示例地址,不会发起请求' return 'local', '本机地址(残留的开发期配置)' if re.match(r'^(192\.168\.\d+|10\.\d+|172\.(1[6-9]|2\d|3[01])|169\.254)\.\d+$', host): return 'lan', '内网地址,仍会发起网络请求' if ext in DOC_EXT: return 'doc', '文档/Source Map 文件' if relpath in ('stats.html',) or relpath.endswith('/stats.html'): return 'sourcemap', 'rollup 可视化报告,不被页面引用' for rx, cat, reason in allow_rules: if rx.search(url): return cat, reason return 'net', '未登记的外部 URL' class LineIndex: """O(log n) 行号查询:大体积压缩产物(单行几 MB 的 JS)上避免 O(n^2)。""" def __init__(self, text): self.nl = [m.start() for m in re.finditer('\n', text)] def line(self, pos): return bisect.bisect_right(self.nl, pos) + 1 def line_of(text, pos): return text.count('\n', 0, pos) + 1 def snippet(text, pos, width=70): a, b = max(0, pos - width), min(len(text), pos + width) return text[a:b].replace('\n', '\\n') def main(): ap = argparse.ArgumentParser() ap.add_argument('--dist', default=os.path.join(REPO, 'dist')) ap.add_argument('--out', default=None) ap.add_argument('--json', dest='json_out', default=None) ap.add_argument('--no-fail', action='store_true') ap.add_argument('--max-rows', type=int, default=200) args = ap.parse_args() dist = os.path.abspath(args.dist) if not os.path.isdir(dist): print('dist 不存在:', dist, file=sys.stderr) return 2 t0 = time.time() allow_rules = load_allowlist() # 预先收集 dist 内所有文件,避免上万次 os.path.exists 系统调用 dist_files = set() for root, dirs, files in os.walk(dist): for fn in files: dist_files.add(os.path.relpath(os.path.join(root, fn), dist).replace(os.sep, '/')) global KNOWN_HOST_RE KNOWN_HOST_RE = re.compile(r'(? args.max_rows: A('') A('> 其余 %d 行见 JSON 报告。' % (len(ext_refs) - args.max_rows)) else: A('无。') A('') A('## 3. 懒加载 chunk import') A('') A('共 %d 处动态 import / Worker 创建。' % len(lazy_imports)) A('') external_chunks = [x for x in lazy_imports if x['target'].startswith('http')] if external_chunks: A('⚠️ 指向外域的 chunk:') for x in external_chunks[:50]: A('- `%s:%s` %s → `%s`' % (x['file'], x['line'], x['kind'], x['target'])) else: A('全部指向同源相对路径(`/homeAssets/...` 等),无外域 chunk。') A('') A('
完整清单(前 200 条)') A('') for x in rows(lazy_imports, 200): A('- `%s:%s` %s → `%s`' % (x['file'], x['line'], x['kind'], x['target'])) A('') A('
') A('') A('## 4. 音视频 / 字体 / SDK 引用') A('') A('扩展名分布:' + ', '.join('%s×%d' % (k, v) for k, v in ext_counter.most_common())) A('') A('### 4.1 指向外域(必须为 0)') A('') ext_media = [r for r in media_refs if r['state'] == 'external'] if ext_media: for r in rows(ext_media, args.max_rows): A('- `%s:%s` → `%s`' % (r['file'], r['line'], r['value'])) else: A('无。') A('') A('### 4.2 本地路径但文件缺失(功能降级 / TODO)') A('') if missing_local: for r in rows(missing_local, args.max_rows): A('- `%s:%s` → `%s`' % (r['file'], r['line'], r['value'])) else: A('无。') A('') A('### 4.3 字体 / 音视频 / 关键 SDK 取值抽样') A('') A('| file:line | 取值 | 状态 |') A('| --- | --- | --- |') for r in rows(media_font_refs, 80): A('| `%s:%s` | `%s` | %s |' % (r['file'], r['line'], r['value'], r['state'])) A('') A('
SDK 相关引用(%d 条)' % len(sdk_refs)) A('') for r in rows(sdk_refs, 120): A('- `%s:%s` → `%s`(%s)' % (r['file'], r['line'], r['value'], r['state'])) A('') A('
') A('') A('## 5. assets/manifest.json 远程前缀') A('') if manifest_info: for m in manifest_info: A('- `%s`:' % m['file']) if 'error' in m: A(' - 解析失败:%s' % m['error']) elif m.get('keys'): for k, v in m['keys'].items(): A(' - `%s` = `%s`' % (k, v)) else: A(' - 无 remote_prefix / preview_prefix 等远程前缀字段') else: A('dist 内没有 `assets/manifest.json`(video-core-sdk 未随包发布远程前缀清单)。') A('') A('## 6. TODO 与不可消除项') A('') A('### 6.1 allowlist(vendored 产物内、无法在不改第三方代码的前提下删除的字符串)') A('') allow_by_reason = defaultdict(Counter) for h in url_hits: if h['cat'] == 'allow': allow_by_reason[h['reason']][h['host']] += 1 if allow_by_reason: for reason, hosts in allow_by_reason.items(): A('- %s:%s' % (reason, ', '.join('%s×%d' % (k, v) for k, v in hosts.most_common()))) else: A('无。') A('') A('### 6.2 本地资源缺失 / 功能降级(详见 4.2)') A('') if missing_local: for r in rows(missing_local, 60): A('- [ ] `%s`(`%s:%s`)' % (r['value'], r['file'], r['line'])) else: A('- [x] 无缺失的本地音视频/字体/SDK 资源。') A('') A('## 附录:报告文件') A('') A('- JSON:`%s`' % os.path.relpath(out_json, REPO)) A('- 允许清单:`%s`' % os.path.relpath(ALLOWLIST, REPO)) A('') os.makedirs(os.path.dirname(out_md), exist_ok=True) open(out_md, 'w', encoding='utf-8').write('\n'.join(L)) json.dump({ 'dist': dist, 'external_refs': external_refs, 'by_category': dict(by_cat), 'known_host_hits': known_host_hits, 'url_hits': url_hits, 'lazy_imports': lazy_imports, 'media_refs': media_refs, 'missing_local': missing_local, 'manifest': manifest_info, 'files': {'text': text_files, 'binary_skipped': skipped_bin}, 'report_md': out_md, }, open(out_json, 'w', encoding='utf-8'), ensure_ascii=False, indent=2) print('external_refs = %d' % external_refs) print('报告:', out_md) return 0 if (external_refs == 0 or args.no_fail) else 1 if __name__ == '__main__': sys.exit(main())