997 lines
39 KiB
Bash
Executable File
997 lines
39 KiB
Bash
Executable File
#!/usr/bin/env bash
|
|
|
|
set -euo pipefail
|
|
|
|
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
|
source "$ROOT_DIR/scripts/harness/lib.sh"
|
|
|
|
main() {
|
|
cd "$ROOT_DIR"
|
|
local uv_bin
|
|
uv_bin="$(harness_require_tool uv)"
|
|
|
|
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python - <<'PY'
|
|
import json
|
|
import re
|
|
from pathlib import Path
|
|
from urllib.parse import urlsplit
|
|
|
|
root = Path.cwd()
|
|
failures: list[str] = []
|
|
warnings: list[str] = []
|
|
|
|
|
|
def fail(message: str) -> None:
|
|
failures.append(message)
|
|
|
|
|
|
def warn(message: str) -> None:
|
|
warnings.append(message)
|
|
|
|
|
|
def read_text(path: str) -> str:
|
|
return (root / path).read_text(encoding="utf-8")
|
|
|
|
|
|
def check_package_manager() -> None:
|
|
for path in ("package.json", "frontend/package.json", "client/package.json"):
|
|
payload = json.loads(read_text(path))
|
|
package_manager = payload.get("packageManager", "")
|
|
if not str(package_manager).startswith("bun@"):
|
|
fail(f"{path}: packageManager must stay Bun-only, got {package_manager!r}")
|
|
for script_name, command in payload.get("scripts", {}).items():
|
|
if re.search(r"\b(npm|pnpm|yarn)\b", command):
|
|
fail(f"{path} script {script_name!r} uses a forbidden package manager: {command}")
|
|
|
|
forbidden_lockfiles = [
|
|
"frontend/package-lock.json",
|
|
"frontend/pnpm-lock.yaml",
|
|
"frontend/yarn.lock",
|
|
"client/package-lock.json",
|
|
"client/pnpm-lock.yaml",
|
|
"client/yarn.lock",
|
|
]
|
|
for path in forbidden_lockfiles:
|
|
if (root / path).exists():
|
|
fail(f"{path}: forbidden frontend lockfile; frontend package management is Bun-only")
|
|
|
|
|
|
def extract_admin_routes() -> tuple[set[str], set[str]]:
|
|
admin_routes_text = read_text("frontend/src/admin/AdminRoutes.tsx")
|
|
manifest_text = read_text("frontend/src/admin/routes/manifest.tsx")
|
|
route_paths = set(re.findall(r'<Route\s+path="([^"*][^"]*)"', admin_routes_text))
|
|
route_paths.discard("*")
|
|
manifest_paths = set(re.findall(r"path:\s*'([^']+)'", manifest_text))
|
|
return route_paths, manifest_paths
|
|
|
|
|
|
def check_route_manifest_consistency() -> None:
|
|
route_paths, manifest_paths = extract_admin_routes()
|
|
public_manifest_paths = {"/earth", "/docs"}
|
|
redirect_only_routes = {"/alerts"}
|
|
|
|
missing_routes = sorted(manifest_paths - route_paths - public_manifest_paths)
|
|
if missing_routes:
|
|
fail(
|
|
"admin route manifest points to paths that AdminRoutes does not render: "
|
|
+ ", ".join(missing_routes)
|
|
)
|
|
|
|
missing_manifest = sorted(route_paths - manifest_paths - redirect_only_routes)
|
|
if missing_manifest:
|
|
fail(
|
|
"AdminRoutes renders paths that are missing from admin route manifest: "
|
|
+ ", ".join(missing_manifest)
|
|
)
|
|
|
|
|
|
def known_frontend_routes() -> set[str]:
|
|
app_text = read_text("frontend/src/App.tsx")
|
|
admin_text = read_text("frontend/src/admin/AdminRoutes.tsx")
|
|
manifest_text = read_text("frontend/src/admin/routes/manifest.tsx")
|
|
routes = set(re.findall(r'<Route\s+path="([^"*][^"]*)"', app_text))
|
|
routes.update(re.findall(r'<Route\s+path="([^"*][^"]*)"', admin_text))
|
|
routes.update(re.findall(r"path:\s*'([^']+)'", manifest_text))
|
|
routes.update({"/", "/docs/:slug"})
|
|
routes.discard("*")
|
|
routes.discard("/*")
|
|
return routes
|
|
|
|
|
|
def check_literal_internal_links() -> None:
|
|
routes = known_frontend_routes()
|
|
allowed_prefixes = (
|
|
"/api/",
|
|
"/ws",
|
|
"/assets/",
|
|
"/earth/",
|
|
)
|
|
literal_link_pattern = re.compile(r"\b(?:to|href)\s*=\s*['\"](/[^'\"#]+(?:#[^'\"]*)?)['\"]")
|
|
for path in (root / "frontend/src").rglob("*.tsx"):
|
|
text = path.read_text(encoding="utf-8")
|
|
rel = path.relative_to(root)
|
|
for match in literal_link_pattern.finditer(text):
|
|
href = match.group(1)
|
|
route_path = urlsplit(href).path
|
|
if route_path in routes:
|
|
continue
|
|
if route_path.startswith("/docs/"):
|
|
continue
|
|
if any(route_path.startswith(prefix) for prefix in allowed_prefixes):
|
|
continue
|
|
line_no = jsx_line_number(text, match.start())
|
|
fail(f"{rel}:{line_no}: literal internal link points to an unknown frontend route: {href}")
|
|
|
|
|
|
def check_admin_search_route_targets() -> None:
|
|
routes = known_frontend_routes()
|
|
text = read_text("frontend/src/admin/search/indexers.ts")
|
|
for match in re.finditer(r"\broutePath:\s*'([^']+)'", text):
|
|
route_path = match.group(1)
|
|
if route_path in routes:
|
|
continue
|
|
line_no = jsx_line_number(text, match.start())
|
|
fail(
|
|
"frontend/src/admin/search/indexers.ts:"
|
|
f"{line_no}: admin search routePath points to an unknown frontend route: {route_path}"
|
|
)
|
|
|
|
|
|
def iter_frontend_src_files() -> list[Path]:
|
|
return [
|
|
path
|
|
for path in (root / "frontend/src").rglob("*")
|
|
if path.is_file() and path.suffix in {".ts", ".tsx", ".js", ".jsx", ".css"}
|
|
]
|
|
|
|
|
|
def collect_inline_style_context(lines: list[str], start_index: int) -> str:
|
|
block = []
|
|
for line in lines[start_index:start_index + 8]:
|
|
block.append(line.strip())
|
|
if "}}" in line or "} as CSSProperties" in line:
|
|
break
|
|
return " ".join(block)
|
|
|
|
|
|
def inline_style_is_dynamic(context: str) -> bool:
|
|
dynamic_needles = (
|
|
"--",
|
|
"CSSProperties",
|
|
"transform:",
|
|
"translate",
|
|
"scale(",
|
|
"width:",
|
|
"height:",
|
|
"thumbSize",
|
|
"thumbOffset",
|
|
"trackSize",
|
|
"header.getSize",
|
|
"summaryWidth",
|
|
"detailWidth",
|
|
"progress",
|
|
"pan.x",
|
|
"pan.y",
|
|
"zoom",
|
|
)
|
|
return any(needle in context for needle in dynamic_needles)
|
|
|
|
|
|
def iter_css_blocks(text: str) -> list[tuple[int, str, str]]:
|
|
text = re.sub(r"/\*.*?\*/", "", text, flags=re.S)
|
|
blocks = []
|
|
start_line = 1
|
|
selector_lines = []
|
|
body_lines = []
|
|
in_block = False
|
|
for line_no, line in enumerate(text.splitlines(), 1):
|
|
if not in_block:
|
|
selector_lines.append(line)
|
|
if "{" in line:
|
|
in_block = True
|
|
start_line = line_no
|
|
before, after = line.split("{", 1)
|
|
selector_lines[-1] = before
|
|
body_lines = [after]
|
|
continue
|
|
|
|
if "}" in line:
|
|
before, _after = line.split("}", 1)
|
|
body_lines.append(before)
|
|
blocks.append((start_line, " ".join(selector_lines).strip(), "\n".join(body_lines)))
|
|
selector_lines = []
|
|
body_lines = []
|
|
in_block = False
|
|
else:
|
|
body_lines.append(line)
|
|
return blocks
|
|
|
|
|
|
def overflow_hidden_has_explicit_owner(selector: str, body: str) -> bool:
|
|
owner_needles = (
|
|
"min-height: 0",
|
|
"height: 100%",
|
|
"height: 100vh",
|
|
"display: grid",
|
|
"display: flex",
|
|
"text-overflow: ellipsis",
|
|
"border-radius:",
|
|
"position: fixed",
|
|
"position: absolute",
|
|
"scrollbar",
|
|
)
|
|
selector_needles = (
|
|
"html",
|
|
"body",
|
|
"#root",
|
|
"tui-scrollbar",
|
|
"table-scroll",
|
|
"segmented-control__label",
|
|
"docs-page",
|
|
"docs-shell",
|
|
"docs-content-layout",
|
|
"docs-toc",
|
|
"admin",
|
|
"an-page",
|
|
"an-resource",
|
|
"an-data",
|
|
"an-panel",
|
|
"an-playground",
|
|
"markdown-renderer",
|
|
"meta",
|
|
"select",
|
|
)
|
|
return any(needle in body for needle in owner_needles) or any(
|
|
needle in selector for needle in selector_needles
|
|
)
|
|
|
|
|
|
def css_block_for_selector(text: str, wanted_selector: str) -> tuple[int, str] | None:
|
|
for line_no, selector, body in iter_css_blocks(text):
|
|
selectors = [item.strip() for item in selector.split(",")]
|
|
if wanted_selector in selectors:
|
|
return line_no, body
|
|
return None
|
|
|
|
|
|
def css_has_declaration(body: str, prop: str, value_pattern: str) -> bool:
|
|
return re.search(rf"(^|[;\n])\s*{re.escape(prop)}\s*:\s*{value_pattern}\s*;", body) is not None
|
|
|
|
|
|
def check_admin_shell_height_chain() -> None:
|
|
text = read_text("frontend/src/admin/styles.css")
|
|
required: dict[str, dict[str, str]] = {
|
|
".admin-theme-root": {
|
|
"min-height": r"0",
|
|
"height": r"100%",
|
|
"overflow": r"hidden",
|
|
},
|
|
".admin": {
|
|
"min-height": r"0",
|
|
"height": r"100%",
|
|
"display": r"grid",
|
|
"overflow": r"hidden",
|
|
},
|
|
".admin__sider": {
|
|
"min-height": r"0",
|
|
"height": r"100%",
|
|
"display": r"flex",
|
|
"overflow": r"hidden",
|
|
},
|
|
".admin__nav-scroll": {
|
|
"flex": r"1\s+1\s+auto",
|
|
"min-height": r"0",
|
|
"overflow": r"hidden",
|
|
},
|
|
".admin__account": {
|
|
"flex": r"0\s+0\s+auto",
|
|
},
|
|
".admin__content": {
|
|
"min-height": r"0",
|
|
"height": r"100%",
|
|
"display": r"grid",
|
|
"overflow": r"hidden",
|
|
},
|
|
".admin__content-inner": {
|
|
"min-height": r"0",
|
|
"height": r"100%",
|
|
"overflow": r"hidden",
|
|
},
|
|
}
|
|
|
|
for selector, declarations in required.items():
|
|
block = css_block_for_selector(text, selector)
|
|
if block is None:
|
|
fail(f"frontend/src/admin/styles.css: admin shell one-screen rule requires {selector}")
|
|
continue
|
|
line_no, body = block
|
|
for prop, value_pattern in declarations.items():
|
|
if css_has_declaration(body, prop, value_pattern):
|
|
continue
|
|
friendly_value = re.sub(r"\\s\+", " ", value_pattern)
|
|
fail(
|
|
"frontend/src/admin/styles.css:"
|
|
f"{line_no}: admin shell one-screen rule requires {selector} "
|
|
f"to declare {prop}: {friendly_value}"
|
|
)
|
|
|
|
|
|
def has_zero_horizontal_padding(body: str) -> bool:
|
|
for match in re.finditer(r"(?:^|[;\n])\s*padding-(left|right)\s*:\s*([^;\n}]+)", body):
|
|
if match.group(2).strip() in {"0", "0px"}:
|
|
return True
|
|
pad_match = re.search(r"(?:^|[;\n])\s*padding\s*:\s*([^;\n}]+)", body)
|
|
if not pad_match:
|
|
return False
|
|
tokens = pad_match.group(1).strip().split()
|
|
horizontal = (
|
|
tokens[0]
|
|
if len(tokens) == 1
|
|
else tokens[1]
|
|
if len(tokens) in {2, 3}
|
|
else tokens[1] if tokens[1] in {"0", "0px"} else tokens[3]
|
|
) if tokens else ""
|
|
return horizontal in {"0", "0px"}
|
|
|
|
|
|
def check_admin_header_and_focus_safety() -> None:
|
|
css_text = read_text("frontend/src/admin/styles.css")
|
|
layout_text = read_text("frontend/src/admin/components/layout/AdminLayout.tsx")
|
|
|
|
theme_root = css_block_for_selector(css_text, ".admin-theme-root")
|
|
if theme_root is None or not css_has_declaration(theme_root[1], "--an-header-height", r"[^;]+"):
|
|
fail("frontend/src/admin/styles.css: .admin-theme-root must define --an-header-height")
|
|
|
|
brand = css_block_for_selector(css_text, ".admin__brand")
|
|
if brand is None:
|
|
fail("frontend/src/admin/styles.css: missing .admin__brand block")
|
|
else:
|
|
line_no, brand_body = brand
|
|
if not css_has_declaration(brand_body, "flex", r"0\s+0\s+var\(--an-header-height\)"):
|
|
fail(
|
|
f"frontend/src/admin/styles.css:{line_no}: .admin__brand must declare "
|
|
"flex: 0 0 var(--an-header-height)"
|
|
)
|
|
if not css_has_declaration(brand_body, "height", r"var\(--an-header-height\)"):
|
|
fail(
|
|
f"frontend/src/admin/styles.css:{line_no}: .admin__brand must declare "
|
|
"height: var(--an-header-height)"
|
|
)
|
|
|
|
content = css_block_for_selector(css_text, ".admin__content")
|
|
if content is None or not css_has_declaration(
|
|
content[1], "grid-template-rows", r"var\(--an-header-height\)\s+minmax\(0,\s*1fr\)"
|
|
):
|
|
fail(
|
|
"frontend/src/admin/styles.css: .admin__content must declare "
|
|
"grid-template-rows: var(--an-header-height) minmax(0, 1fr)"
|
|
)
|
|
|
|
topbar = css_block_for_selector(css_text, ".admin__topbar")
|
|
if topbar is None or not css_has_declaration(topbar[1], "height", r"var\(--an-header-height\)"):
|
|
fail("frontend/src/admin/styles.css: .admin__topbar must declare height: var(--an-header-height)")
|
|
|
|
if "AdminSearchSpotlight" not in layout_text:
|
|
fail(
|
|
"frontend/src/admin/components/layout/AdminLayout.tsx: "
|
|
"admin search highlights must use shell-level AdminSearchSpotlight"
|
|
)
|
|
|
|
for line_no, selector, body in iter_css_blocks(css_text):
|
|
if ".an-search-hit" in selector:
|
|
fail(
|
|
f"frontend/src/admin/styles.css:{line_no}: remove .an-search-hit; "
|
|
"use shell-level .an-search-spotlight__frame so search rings never clip"
|
|
)
|
|
if ":focus-visible" in selector:
|
|
offset_match = re.search(r"\boutline-offset\s*:\s*([^;\n}]+)", body)
|
|
if offset_match:
|
|
raw_offset = offset_match.group(1).strip()
|
|
if not raw_offset.startswith("-") and raw_offset not in {"0", "0px"}:
|
|
fail(
|
|
f"frontend/src/admin/styles.css:{line_no}: {selector} uses positive "
|
|
f"outline-offset ({raw_offset}) inside clipped admin scrollports; use <= 0"
|
|
)
|
|
|
|
section_tabs = css_block_for_selector(css_text, ".an-section-tabs")
|
|
if section_tabs is not None:
|
|
line_no, body = section_tabs
|
|
if css_has_declaration(body, "overflow-x", r"auto") and has_zero_horizontal_padding(body):
|
|
fail(
|
|
f"frontend/src/admin/styles.css:{line_no}: .an-section-tabs with overflow-x: auto "
|
|
"must keep non-zero horizontal padding (e.g. margin: -4px; padding: 4px;)"
|
|
)
|
|
|
|
|
|
def check_debug_output() -> None:
|
|
for path in iter_frontend_src_files():
|
|
text = path.read_text(encoding="utf-8")
|
|
rel = path.relative_to(root)
|
|
for line_no, line in enumerate(text.splitlines(), 1):
|
|
if "console.log(" in line or re.search(r"\bdebugger\b", line):
|
|
fail(f"{rel}:{line_no}: remove console.log/debugger from frontend source")
|
|
if "console." in line and "token" in line.lower():
|
|
fail(f"{rel}:{line_no}: console output must not include token material")
|
|
|
|
|
|
EARTH_RUNTIME_COPY_FILES = (
|
|
"frontend/public/earth/js/main.js",
|
|
"frontend/public/earth/js/controls.js",
|
|
"frontend/public/earth/js/cables.js",
|
|
"frontend/public/earth/js/news.js",
|
|
"frontend/public/earth/js/tv.js",
|
|
"frontend/public/earth/js/info-card.js",
|
|
"frontend/public/earth/js/layer-startup-tasks.js",
|
|
"frontend/public/earth/js/i18n.js",
|
|
)
|
|
|
|
EARTH_RUNTIME_COPY_ENTRYPOINTS = (
|
|
"showStatusMessage",
|
|
"queueStatusMessage",
|
|
"showGestureStatusMessage",
|
|
"showError",
|
|
"setLoadingMessage",
|
|
"resolveStartupMessage",
|
|
)
|
|
|
|
CJK_PATTERN = re.compile(r"[\u3400-\u9fff]")
|
|
|
|
|
|
def collect_balanced_js(text: str, start_index: int, opener: str, closer: str) -> str:
|
|
depth = 0
|
|
quote: str | None = None
|
|
template_depth = 0
|
|
cursor = start_index
|
|
while cursor < len(text):
|
|
char = text[cursor]
|
|
if quote:
|
|
if char == "\\":
|
|
cursor += 2
|
|
continue
|
|
if quote == "`" and char == "$" and cursor + 1 < len(text) and text[cursor + 1] == "{":
|
|
template_depth += 1
|
|
cursor += 2
|
|
continue
|
|
if template_depth > 0 and char == "}":
|
|
template_depth -= 1
|
|
cursor += 1
|
|
continue
|
|
if char == quote and template_depth == 0:
|
|
quote = None
|
|
cursor += 1
|
|
continue
|
|
|
|
if char in ("'", '"', "`"):
|
|
quote = char
|
|
elif char == opener:
|
|
depth += 1
|
|
elif char == closer:
|
|
depth -= 1
|
|
if depth == 0:
|
|
return text[start_index:cursor + 1]
|
|
cursor += 1
|
|
return text[start_index:]
|
|
|
|
|
|
def collect_js_call(text: str, start_index: int) -> str:
|
|
open_index = text.find("(", start_index)
|
|
if open_index == -1:
|
|
return text[start_index:]
|
|
return collect_balanced_js(text, open_index, "(", ")")
|
|
|
|
|
|
def collect_js_value(text: str, start_index: int) -> str:
|
|
cursor = start_index
|
|
while cursor < len(text) and text[cursor].isspace():
|
|
cursor += 1
|
|
if cursor >= len(text):
|
|
return ""
|
|
char = text[cursor]
|
|
if char == "{":
|
|
return collect_balanced_js(text, cursor, "{", "}")
|
|
if char == "[":
|
|
return collect_balanced_js(text, cursor, "[", "]")
|
|
if text.startswith("earthMessage", cursor):
|
|
open_index = text.find("(", cursor)
|
|
if open_index == -1:
|
|
return text[cursor:]
|
|
return text[cursor:open_index] + collect_balanced_js(text, open_index, "(", ")")
|
|
if char in ("'", '"', "`"):
|
|
quote = char
|
|
cursor += 1
|
|
while cursor < len(text):
|
|
if text[cursor] == "\\":
|
|
cursor += 2
|
|
continue
|
|
if text[cursor] == quote:
|
|
return text[start_index:cursor + 1]
|
|
cursor += 1
|
|
return text[start_index:]
|
|
|
|
end_candidates = [
|
|
index for index in (text.find(",", cursor), text.find("\n", cursor)) if index != -1
|
|
]
|
|
end_index = min(end_candidates) if end_candidates else len(text)
|
|
return text[start_index:end_index]
|
|
|
|
|
|
def check_earth_runtime_copy_entrypoints() -> None:
|
|
i18n_text = read_text("frontend/public/earth/js/i18n.js")
|
|
for token in ("EARTH_MESSAGE_TEMPLATES", "export function earthMessage", "export function formatEarthMessage"):
|
|
if token not in i18n_text:
|
|
fail(f"frontend/public/earth/js/i18n.js: missing centralized Earth runtime copy token {token}")
|
|
|
|
direct_literal_pattern = re.compile(r"^\(\s*['\"`]")
|
|
for file_path in EARTH_RUNTIME_COPY_FILES:
|
|
text = read_text(file_path)
|
|
for entrypoint in EARTH_RUNTIME_COPY_ENTRYPOINTS:
|
|
pattern = re.compile(rf"\b{re.escape(entrypoint)}\s*\(")
|
|
for match in pattern.finditer(text):
|
|
call = collect_js_call(text, match.start())
|
|
if direct_literal_pattern.search(call):
|
|
fail(
|
|
f"{file_path}:{jsx_line_number(text, match.start())}: "
|
|
f"Earth runtime copy entrypoint {entrypoint} must use earthMessage(...), not a direct string literal"
|
|
)
|
|
if CJK_PATTERN.search(call) and "earthMessage(" not in call:
|
|
fail(
|
|
f"{file_path}:{jsx_line_number(text, match.start())}: "
|
|
f"Earth runtime copy entrypoint {entrypoint} contains CJK without earthMessage(...)"
|
|
)
|
|
|
|
for match in re.finditer(r"\bstartupMessage\s*:\s*", text):
|
|
value = collect_js_value(text, match.end()).strip()
|
|
if value in {'""', "''", "``"}:
|
|
continue
|
|
if "earthMessage(" not in value:
|
|
fail(
|
|
f"{file_path}:{jsx_line_number(text, match.start())}: "
|
|
"Earth layer startupMessage must use earthMessage(...) so startup copy has one i18n entrypoint"
|
|
)
|
|
|
|
for match in re.finditer(r"new\s+CustomEvent\(\s*['\"]earth:status['\"]", text):
|
|
call = collect_js_call(text, match.start())
|
|
if re.search(r"\bmessage\s*:\s*['\"`]", call):
|
|
fail(
|
|
f"{file_path}:{jsx_line_number(text, match.start())}: "
|
|
"earth:status event messages must use earthMessage(...) instead of direct strings"
|
|
)
|
|
if CJK_PATTERN.search(call) and "earthMessage(" not in call:
|
|
fail(
|
|
f"{file_path}:{jsx_line_number(text, match.start())}: "
|
|
"earth:status event contains CJK without earthMessage(...)"
|
|
)
|
|
|
|
|
|
def jsx_line_number(text: str, index: int) -> int:
|
|
return text.count("\n", 0, index) + 1
|
|
|
|
|
|
def iter_opening_tags(text: str, tag_name: str) -> list[tuple[int, str]]:
|
|
tags: list[tuple[int, str]] = []
|
|
needle = f"<{tag_name}"
|
|
index = 0
|
|
while True:
|
|
start = text.find(needle, index)
|
|
if start == -1:
|
|
return tags
|
|
next_char_index = start + len(needle)
|
|
if next_char_index < len(text) and (text[next_char_index].isalnum() or text[next_char_index] in "_-"):
|
|
index = next_char_index
|
|
continue
|
|
|
|
quote: str | None = None
|
|
brace_depth = 0
|
|
cursor = next_char_index
|
|
while cursor < len(text):
|
|
char = text[cursor]
|
|
if quote:
|
|
if char == "\\":
|
|
cursor += 2
|
|
continue
|
|
if char == quote:
|
|
quote = None
|
|
cursor += 1
|
|
continue
|
|
if char in ('"', "'", "`"):
|
|
quote = char
|
|
elif char == "{":
|
|
brace_depth += 1
|
|
elif char == "}":
|
|
brace_depth = max(0, brace_depth - 1)
|
|
elif char == ">" and brace_depth == 0:
|
|
tags.append((start, text[start:cursor + 1]))
|
|
index = cursor + 1
|
|
break
|
|
cursor += 1
|
|
else:
|
|
return tags
|
|
|
|
|
|
def check_native_button_safety() -> None:
|
|
for path in (root / "frontend/src").rglob("*.tsx"):
|
|
text = path.read_text(encoding="utf-8")
|
|
rel = path.relative_to(root)
|
|
for start, tag in iter_opening_tags(text, "button"):
|
|
line_no = jsx_line_number(text, start)
|
|
if not re.search(r"\btype\s*=", tag):
|
|
fail(f"{rel}:{line_no}: native <button> must declare an explicit type")
|
|
if re.search(r"\bdisabled\s*=", tag) and re.search(r"\{\s*\.\.\.", tag):
|
|
spread_index = tag.find("{...")
|
|
disabled_index = tag.find("disabled")
|
|
if disabled_index < spread_index:
|
|
fail(
|
|
f"{rel}:{line_no}: button disabled state can be overridden by a later props spread"
|
|
)
|
|
|
|
|
|
def check_icon_button_accessibility() -> None:
|
|
for path in (root / "frontend/src").rglob("*.tsx"):
|
|
text = path.read_text(encoding="utf-8")
|
|
rel = path.relative_to(root)
|
|
for start, tag in iter_opening_tags(text, "Button"):
|
|
if not re.search(r"\bsize\s*=\s*['\"]icon['\"]", tag):
|
|
continue
|
|
if "aria-label" not in tag and "ariaLabel" not in tag:
|
|
fail(f"{rel}:{jsx_line_number(text, start)}: icon Button must include aria-label")
|
|
if not re.search(r"\btitle\s*=", tag):
|
|
fail(f"{rel}:{jsx_line_number(text, start)}: icon Button must include title")
|
|
|
|
|
|
def check_no_nested_cards() -> None:
|
|
for path in (root / "frontend/src").rglob("*.tsx"):
|
|
text = path.read_text(encoding="utf-8")
|
|
rel = path.relative_to(root)
|
|
depth = 0
|
|
for match in re.finditer(r"</?Card\b", text):
|
|
token = match.group(0)
|
|
if token.startswith("</"):
|
|
depth = max(0, depth - 1)
|
|
continue
|
|
line_no = jsx_line_number(text, match.start())
|
|
if depth > 0:
|
|
fail(f"{rel}:{line_no}: do not nest Card components inside other Cards")
|
|
tag_end = text.find(">", match.start())
|
|
tag = text[match.start():tag_end + 1] if tag_end != -1 else ""
|
|
if not tag.rstrip().endswith("/>"):
|
|
depth += 1
|
|
|
|
|
|
def check_no_antd_layout_primitives() -> None:
|
|
for path in (root / "frontend/src").rglob("*.tsx"):
|
|
text = path.read_text(encoding="utf-8")
|
|
rel = path.relative_to(root)
|
|
if re.search(r"\bfrom\s+['\"]antd['\"]", text):
|
|
fail(f"{rel}: active frontend must not import AntD; use Tactile UI/Radix project components")
|
|
for match in re.finditer(r"<Space\b", text):
|
|
line_no = jsx_line_number(text, match.start())
|
|
fail(f"{rel}:{line_no}: avoid implicit Space layout primitives in height-critical UI")
|
|
|
|
|
|
def check_connection_test_input_pattern() -> None:
|
|
text = read_text("frontend/src/admin/pages/PlainResourcePages.tsx")
|
|
if "function ConnectionTestInput" not in text:
|
|
fail("AI/WebSearch connection tests must use the shared ConnectionTestInput pattern")
|
|
|
|
for label in ("测试 AI Provider 连通性", "测试 Web Search 连通性"):
|
|
if re.search(rf"<Button\b(?=[^>]*\btitle=['\"]{re.escape(label)}['\"])", text):
|
|
fail(f"{label}: connection test must be attached to the Base URL input suffix, not a standalone Button")
|
|
|
|
provider_pattern = re.compile(
|
|
r"key:\s*'base_url'[\s\S]{0,260}inputAction:[\s\S]{0,260}"
|
|
r"title:\s*'测试 AI Provider 连通性'",
|
|
)
|
|
if not provider_pattern.search(text):
|
|
fail("AI Provider Base URL field must expose its connection test through inputAction")
|
|
|
|
web_pattern = re.compile(
|
|
r"key:\s*'base_url'[\s\S]{0,320}disabled:\s*webSearchDisabled[\s\S]{0,260}"
|
|
r"title:\s*'测试 Web Search 连通性'",
|
|
)
|
|
if not web_pattern.search(text):
|
|
fail("WebSearch Base URL field must expose a disabled-aware connection test through inputAction")
|
|
|
|
|
|
def check_uiux_static_warnings() -> None:
|
|
viewport_font_pattern = re.compile(r"\b(?:font-size|fontSize)\s*[:=]\s*[^;\n}]*(?:vw|vmin|vmax|cqw|cqi)")
|
|
letter_spacing_pattern = re.compile(r"\b(?:letter-spacing|letterSpacing)\s*[:=]\s*([^;\n}]+)")
|
|
shell_viewport_height_pattern = re.compile(r"\b(?:height|min-height)\s*:\s*100v[hw]\s*;")
|
|
for path in iter_frontend_src_files():
|
|
text = path.read_text(encoding="utf-8")
|
|
rel = path.relative_to(root)
|
|
for match in viewport_font_pattern.finditer(text):
|
|
line_no = jsx_line_number(text, match.start())
|
|
fail(f"{rel}:{line_no}: font size must not scale with viewport width units under uiux rules")
|
|
for match in letter_spacing_pattern.finditer(text):
|
|
value = match.group(1).strip().strip("'\"")
|
|
allowed = (
|
|
value in {"0", "0em", "0rem", "normal", "inherit", "initial", "unset"}
|
|
or re.fullmatch(r"var\([^,]+,\s*0(?:em|rem)?\s*\)", value)
|
|
)
|
|
if allowed:
|
|
continue
|
|
line_no = jsx_line_number(text, match.start())
|
|
fail(f"{rel}:{line_no}: letter spacing must stay 0 under uiux rules, got {value!r}")
|
|
if str(rel) in {"frontend/src/admin/styles.css", "frontend/src/pages/Docs/Docs.css"}:
|
|
for match in shell_viewport_height_pattern.finditer(text):
|
|
line_no = jsx_line_number(text, match.start())
|
|
fail(
|
|
f"{rel}:{line_no}: admin/docs shells must use the root 100% height chain, "
|
|
"not exact 100vh/100vw sizing"
|
|
)
|
|
|
|
if path.suffix == ".css":
|
|
continue
|
|
lines = text.splitlines()
|
|
for line_no, line in enumerate(lines, 1):
|
|
if "style={{" not in line:
|
|
continue
|
|
context = collect_inline_style_context(lines, line_no - 1)
|
|
if not inline_style_is_dynamic(context):
|
|
warn(f"{rel}:{line_no}: inline style found; rules prefer CSS classes unless values are truly dynamic")
|
|
if re.search(r"\bas\s+any\b|<any>", text):
|
|
warn(f"{rel}: broad TypeScript cast found; prefer specific types where practical")
|
|
|
|
for path in (root / "frontend/src").rglob("*.css"):
|
|
text = path.read_text(encoding="utf-8")
|
|
rel = path.relative_to(root)
|
|
for line_no, selector, body in iter_css_blocks(text):
|
|
if "overflow: hidden" not in body:
|
|
continue
|
|
if not overflow_hidden_has_explicit_owner(selector, body):
|
|
warn(
|
|
f"{rel}:{line_no}: overflow:hidden needs an explicit child scroll owner "
|
|
f"or a documented clipping reason under uiux rules"
|
|
)
|
|
|
|
|
|
def check_earth_hud_baseline() -> None:
|
|
hud_css = read_text("frontend/public/earth/css/hud.css")
|
|
for required in (
|
|
"--panel-glow-x:",
|
|
"--panel-glow-y:",
|
|
"--panel-glow-opacity:",
|
|
".hud-panel::before",
|
|
".hud-panel::after",
|
|
):
|
|
if required not in hud_css:
|
|
fail(f"frontend/public/earth/css/hud.css: missing shared HUD baseline rule {required}")
|
|
|
|
controls_js = read_text("frontend/public/earth/js/controls.js")
|
|
if "function setupLiquidGlassInteractions" not in controls_js:
|
|
fail("frontend/public/earth/js/controls.js: missing setupLiquidGlassInteractions")
|
|
else:
|
|
fn_block = controls_js.split("function setupLiquidGlassInteractions", 1)[1][:4500]
|
|
if ".hud-panel" not in fn_block or "MutationObserver" not in fn_block:
|
|
fail(
|
|
"frontend/public/earth/js/controls.js: setupLiquidGlassInteractions must bind "
|
|
".hud-panel with a MutationObserver so dynamic HUD cards inherit cursor glow"
|
|
)
|
|
|
|
card_roots = (
|
|
".compute-card",
|
|
".news-region-card",
|
|
".situational-copilot",
|
|
".stage-narrative-bar",
|
|
".compute-picker",
|
|
".compute-evidence",
|
|
"#situational-copilot",
|
|
"#stage-narrative-bar",
|
|
"#compute-picker",
|
|
"#compute-evidence",
|
|
)
|
|
workspace_wrappers = {"#earth-region-callouts", "#news-region-workspace", "#compute-workspace"}
|
|
viewport_font_re = re.compile(
|
|
r"\bfont-size\s*:\s*[^;\n}]*(?:vw|vmin|vmax|cqw|cqi)"
|
|
)
|
|
letter_spacing_re = re.compile(r"\bletter-spacing\s*:\s*([^;\n}]+)")
|
|
bg_decl_re = re.compile(r"(?<![-\w])background(?:-color|-image)?\s*:\s*([^;]+);")
|
|
rgba_alpha_re = re.compile(
|
|
r"rgba\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*,\s*([0-9.]+)\s*\)"
|
|
)
|
|
|
|
for css_path in sorted((root / "frontend/public/earth/css").glob("*.css")):
|
|
if css_path.name == "hud.css":
|
|
continue
|
|
rel = css_path.relative_to(root)
|
|
raw_text = css_path.read_text(encoding="utf-8")
|
|
for line_no, selector, body in iter_css_blocks(raw_text):
|
|
if "hud-panel-brand" in selector or "#brand-panel" in selector:
|
|
continue
|
|
parts = [part.strip() for part in selector.split(",") if part.strip()]
|
|
for part in parts:
|
|
if part in workspace_wrappers:
|
|
z_match = re.search(r"\bz-index\s*:\s*([^;\n}]+)", body)
|
|
if z_match and z_match.group(1).strip() != "auto":
|
|
fail(
|
|
f"{rel}:{line_no}: {part} must keep z-index: auto so child HUD cards "
|
|
"participate in sharedHudFocusStack"
|
|
)
|
|
is_card_root = any(
|
|
part == r
|
|
or part.startswith(f"{r}.")
|
|
or part.startswith(f"{r}:")
|
|
or part.startswith(f"{r}[")
|
|
for r in card_roots
|
|
)
|
|
if not is_card_root:
|
|
continue
|
|
if "::before" in part or "::after" in part:
|
|
fail(
|
|
f"{rel}:{line_no}: {part} must not override .hud-panel::before/::after "
|
|
"specular sheen or masked border hotspot"
|
|
)
|
|
for bg_match in bg_decl_re.finditer(body):
|
|
bg_val = " ".join(bg_match.group(1).split())
|
|
if bg_val in {"transparent", "none", "transparent !important", "none !important"}:
|
|
continue
|
|
if "var(--panel-glow-x)" not in bg_val:
|
|
fail(
|
|
f"{rel}:{line_no}: {part} overrides .hud-panel background without "
|
|
"preserving var(--panel-glow-x) cursor spotlight glow"
|
|
)
|
|
|
|
if css_path.name in {"compute-topic.css", "news-region-cards.css"}:
|
|
if ".compute-mobile" not in selector and ":hover" not in selector and ".is-active" not in selector:
|
|
for bg_match in bg_decl_re.finditer(body):
|
|
bg_val = " ".join(bg_match.group(1).split())
|
|
alphas = [float(a) for a in rgba_alpha_re.findall(bg_val)]
|
|
if any(alpha > 0.35 for alpha in alphas):
|
|
fail(
|
|
f"{rel}:{line_no}: {selector} uses high-opacity interior background "
|
|
f"({bg_val}); keep alpha <= 0.35 so .hud-panel cursor glow shines through"
|
|
)
|
|
|
|
if css_path.name in {"compute-topic.css", "news-region-cards.css"}:
|
|
clean_text = re.sub(r"/\*.*?\*/", "", raw_text, flags=re.S)
|
|
for match in viewport_font_re.finditer(clean_text):
|
|
line_no = jsx_line_number(clean_text, match.start())
|
|
fail(f"{rel}:{line_no}: font size must not scale with viewport width units")
|
|
for match in letter_spacing_re.finditer(clean_text):
|
|
val = match.group(1).strip()
|
|
if val not in {"0", "0em", "0rem", "normal", "inherit", "initial", "unset"}:
|
|
line_no = jsx_line_number(clean_text, match.start())
|
|
fail(f"{rel}:{line_no}: letter-spacing must stay 0 under uiux rules, got {val!r}")
|
|
|
|
earth_hud_modules = (
|
|
"frontend/public/earth/js/compute-topic.js",
|
|
"frontend/public/earth/js/situational-copilot.js",
|
|
"frontend/public/earth/js/stage-narrative-player.js",
|
|
"frontend/public/earth/js/news-region-cards.js",
|
|
)
|
|
button_tag_re = re.compile(r"<button\b[^>]*>", re.S)
|
|
for js_rel in earth_hud_modules:
|
|
js_text = read_text(js_rel)
|
|
for match in button_tag_re.finditer(js_text):
|
|
tag = match.group(0)
|
|
if not re.search(r"\btype\s*=", tag):
|
|
line_no = jsx_line_number(js_text, match.start())
|
|
fail(f"{js_rel}:{line_no}: Earth HUD <button> must declare an explicit type attribute")
|
|
if "sharedHudFocusStack" not in js_text:
|
|
fail(f"{js_rel}: floating Earth HUD controller must integrate with sharedHudFocusStack")
|
|
|
|
|
|
def check_earth_icon_consistency() -> None:
|
|
index_html = read_text("frontend/public/earth/index.html")
|
|
stylesheet_order = re.findall(
|
|
r'<link[^>]+rel=["\']stylesheet["\'][^>]+href=["\']([^"\'?]+)',
|
|
index_html,
|
|
)
|
|
try:
|
|
fonts_index = stylesheet_order.index("css/fonts.css")
|
|
except ValueError:
|
|
fail("frontend/public/earth/index.html: must include css/fonts.css for Material Symbols Rounded")
|
|
return
|
|
|
|
guarded_css = {
|
|
"css/compute-topic.css",
|
|
"css/news-region-cards.css",
|
|
}
|
|
single_class_re = re.compile(r"^\.[A-Za-z0-9_-]+$")
|
|
font_size_decl_re = re.compile(r"\bfont-size\s*:\s*([^;]+);")
|
|
|
|
covered_css_selectors: list[str] = []
|
|
for href in stylesheet_order:
|
|
if href not in guarded_css:
|
|
continue
|
|
loads_before_fonts = stylesheet_order.index(href) < fonts_index
|
|
css_rel = f"frontend/public/earth/{href}"
|
|
css_text = read_text(css_rel)
|
|
for line_no, selector, body in iter_css_blocks(css_text):
|
|
parts = [part.strip() for part in selector.split(",") if part.strip()]
|
|
has_icon_selector = any(
|
|
".material-symbols-rounded" in part or part.endswith("icon")
|
|
for part in parts
|
|
)
|
|
if not has_icon_selector:
|
|
continue
|
|
|
|
if "font-size" in body and "!important" in (font_size_decl_re.search(body) or re.match("", "")).group(0):
|
|
fail(
|
|
f"{css_rel}:{line_no}: avoid !important in icon font-size rules ({selector}); "
|
|
"use >= (0,2,0) .material-symbols-rounded selector specificity instead"
|
|
)
|
|
|
|
if loads_before_fonts and "font-size" in body:
|
|
for part in parts:
|
|
if single_class_re.fullmatch(part) and (part.endswith("icon") or part == ".material-symbols-rounded"):
|
|
fail(
|
|
f"{css_rel}:{line_no}: bare single-class icon rule {part} loads before css/fonts.css "
|
|
"and loses (0,1,0) cascade to .material-symbols-rounded { font-size: 24px }; "
|
|
"scope it as a compound/descendant .material-symbols-rounded rule"
|
|
)
|
|
|
|
for part in parts:
|
|
if ".material-symbols-rounded" in part:
|
|
covered_css_selectors.append(part)
|
|
if "font-size" in body and "font-variation-settings" not in body:
|
|
fail(
|
|
f"{css_rel}:{line_no}: {part} sizes a Material Symbols icon without "
|
|
"font-variation-settings ('FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20)"
|
|
)
|
|
|
|
icon_tag_re = re.compile(r'class=["\']([^"\']*\bmaterial-symbols-rounded\b[^"\']*)["\']')
|
|
modern_earth_icon_modules = (
|
|
"frontend/public/earth/js/situational-copilot.js",
|
|
"frontend/public/earth/js/workbench-blocks.js",
|
|
"frontend/public/earth/js/stage-narrative-player.js",
|
|
"frontend/public/earth/js/compute-topic.js",
|
|
)
|
|
emoji_re = re.compile(r"[\U0001F300-\U0001FAFF\u2600-\u27BF]")
|
|
|
|
for js_rel in modern_earth_icon_modules:
|
|
js_text = read_text(js_rel)
|
|
if js_rel != "frontend/public/earth/js/compute-topic.js" and emoji_re.search(js_text):
|
|
fail(f"{js_rel}: desktop HUD panels must use Material Symbols Rounded glyphs, not raw Unicode emojis")
|
|
for match in icon_tag_re.finditer(js_text):
|
|
classes = [c.strip() for c in match.group(1).split() if c.strip()]
|
|
custom_icon_classes = [c for c in classes if c != "material-symbols-rounded" and c.endswith("icon")]
|
|
for cls_name in custom_icon_classes:
|
|
if any(f".{cls_name}.material-symbols-rounded" in sel for sel in covered_css_selectors):
|
|
continue
|
|
line_no = jsx_line_number(js_text, match.start())
|
|
fail(
|
|
f"{js_rel}:{line_no}: custom icon class .{cls_name} lacks a high-specificity "
|
|
f".{cls_name}.material-symbols-rounded CSS rule in guarded Earth stylesheets"
|
|
)
|
|
|
|
for tsx_path in (root / "frontend/src").rglob("*.tsx"):
|
|
tsx_rel = tsx_path.relative_to(root)
|
|
tsx_text = tsx_path.read_text(encoding="utf-8")
|
|
if emoji_re.search(tsx_text):
|
|
fail(f"{tsx_rel}: React admin/docs UI should use lucide-react icons instead of raw Unicode emojis")
|
|
|
|
|
|
def main() -> None:
|
|
check_package_manager()
|
|
check_route_manifest_consistency()
|
|
check_literal_internal_links()
|
|
check_admin_search_route_targets()
|
|
check_debug_output()
|
|
check_earth_runtime_copy_entrypoints()
|
|
check_native_button_safety()
|
|
check_icon_button_accessibility()
|
|
check_no_nested_cards()
|
|
check_no_antd_layout_primitives()
|
|
check_connection_test_input_pattern()
|
|
check_admin_shell_height_chain()
|
|
check_admin_header_and_focus_safety()
|
|
check_earth_hud_baseline()
|
|
check_earth_icon_consistency()
|
|
check_uiux_static_warnings()
|
|
|
|
for message in warnings:
|
|
print(f"warn: {message}")
|
|
if failures:
|
|
for message in failures:
|
|
print(f"fail: {message}")
|
|
raise SystemExit(f"frontend rules check failed: {len(failures)} failure(s), {len(warnings)} warning(s)")
|
|
print(f"frontend rules check passed: {len(warnings)} warning(s)")
|
|
|
|
|
|
main()
|
|
PY
|
|
}
|
|
|
|
main "$@"
|