A reload kept using app.js?v=ee6ab2354fa3 from cache. That body was index.html, saved while every lex path was rewritten to the page, so the new router never saw a request. The script URL changed, and dossier responses are no-store so Gitea's six-hour asset cache cannot keep the wrong body.
223 lines
8.6 KiB
Python
223 lines
8.6 KiB
Python
"""Build the lex app shell page: the fhirworx design system inlined, no data.
|
|
|
|
lex (Latin for law) is the legal-epidemiology workbench at ``lex.<domain>``.
|
|
Gitea serves this page from its bind-mounted custom directory (Traefik
|
|
routers ``lex*``, behind ``git-sso``; see infra/traefik/dynamic/services.yml).
|
|
The page carries no data: ``app.js`` and the other ES modules next to it in
|
|
``infra/gitea/custom/public/assets/dossier/`` load the stored dossiers from
|
|
the policy API (``/api/policy/…``, lex S1 D2/D5) and render each view.
|
|
|
|
uv run --no-sync python -I dev/scripts/dossier_page/build.py [--out PATH]
|
|
|
|
Writes one HTML document (template.html, filled) to --out, by default the
|
|
served page infra/gitea/custom/public/assets/dossier/index.html (gitignored),
|
|
atomically, and prints ``wrote <path> (<n> bytes) v=<version>``. Stdlib only:
|
|
it reads no database.
|
|
|
|
Design (R85): lex is a fhirworx (HTI-5) page built from the system's sources,
|
|
so it follows them on every rebuild. The page inlines assets/css/fhirworx.css
|
|
(palette, fonts, base classes), the fhirworx dark palette from the Gitea theme
|
|
(infra/gitea/theme/theme-fhirworx-dark.css) mapped onto the same token names
|
|
(opt-in, as in Gitea), the logo (assets/icons/logo.svg, as an SVG symbol) and
|
|
the favicon set (assets/icons). The template uses only those tokens.
|
|
|
|
Cache: ``/*__VERSION__*/`` is the first 12 hex digits of a sha256 over the
|
|
sorted (name, bytes) of the ``*.js`` modules, plus ``CACHE_EPOCH``, stamped
|
|
on the entry script (``app.js?v=…``). The query string is the cache key.
|
|
``CACHE_EPOCH`` moved the key off a URL whose cached body was ``index.html``
|
|
(the lex catch-all rewrote every path there). Imported modules are not
|
|
stored: ``dossier-nocache`` sends ``Cache-Control: no-store``.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import base64
|
|
import hashlib
|
|
import html
|
|
import os
|
|
import re
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
HERE = Path(__file__).resolve().parent
|
|
ROOT = HERE.parents[2]
|
|
ASSETS = ROOT / "infra/gitea/custom/public/assets/dossier"
|
|
FHIRWORX_CSS = ROOT / "assets/css/fhirworx.css" # single source of the palette
|
|
GITEA_DARK = ROOT / "infra/gitea/theme/theme-fhirworx-dark.css" # the dark palette
|
|
ICONS = ROOT / "assets/icons"
|
|
|
|
# fhirworx.css token -> the Gitea fhirworx-dark variable that plays the same
|
|
# role. chart-1..3 (the indigo scale) have no dark counterpart in the system,
|
|
# so they keep their fhirworx.css values; the template picks the step that
|
|
# reads on the dark card.
|
|
DARK_ROLES = {
|
|
"background": "--fw-background",
|
|
"foreground": "--fw-foreground",
|
|
"card": "--fw-card",
|
|
"card-foreground": "--fw-foreground",
|
|
"popover": "--fw-card",
|
|
"popover-foreground": "--fw-foreground",
|
|
"primary": "--fw-primary",
|
|
"primary-foreground": "--fw-primary-foreground",
|
|
"secondary": "--fw-secondary",
|
|
"secondary-foreground": "--color-text-light",
|
|
"muted": "--fw-secondary",
|
|
"muted-foreground": "--fw-muted-foreground",
|
|
"accent": "--fw-secondary",
|
|
"accent-foreground": "--fw-foreground",
|
|
"destructive": "--fw-destructive",
|
|
"destructive-foreground": "--fw-primary-foreground",
|
|
"border": "--fw-border",
|
|
"input": "--fw-border",
|
|
"ring": "--fw-primary",
|
|
"sidebar": "--fw-nav-bg",
|
|
"sidebar-foreground": "--fw-nav-text",
|
|
"sidebar-primary": "--fw-link",
|
|
"sidebar-primary-foreground": "--fw-primary-foreground",
|
|
"sidebar-accent": "--fw-nav-hover-bg",
|
|
"sidebar-accent-foreground": "--fw-nav-text",
|
|
"sidebar-border": "--fw-nav-hover-bg",
|
|
"sidebar-ring": "--fw-link",
|
|
"chart-4": "--color-green",
|
|
"chart-5": "--fw-chart-5",
|
|
}
|
|
|
|
#: navbar links back to Gitea, the masthead and footer address, the
|
|
#: dashboard link
|
|
DOMAIN_FILLS = 5
|
|
#: the entry script and the footer
|
|
VERSION_FILLS = 2
|
|
|
|
|
|
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
|
ap = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])
|
|
ap.add_argument(
|
|
"--out",
|
|
type=Path,
|
|
default=ASSETS / "index.html",
|
|
help="page to write (default: %(default)s)",
|
|
)
|
|
return ap.parse_args(argv)
|
|
|
|
|
|
def _fill(tpl: str, marker: str, value: str, count: int = 1) -> str:
|
|
if tpl.count(marker) != count:
|
|
raise SystemExit(
|
|
f"template.html: expected {count} {marker!r}, found {tpl.count(marker)}"
|
|
)
|
|
return tpl.replace(marker, value)
|
|
|
|
|
|
# Bumped so browsers drop app.js?v=ee6ab2354fa3. That URL was cached as the
|
|
# HTML page while lex-page rewrote every path to index.html, and a reload
|
|
# kept using it without asking the server again.
|
|
CACHE_EPOCH = b"lex-assets\n"
|
|
|
|
|
|
def module_version(directory: Path) -> str:
|
|
"""sha256 over CACHE_EPOCH and the sorted (name, bytes) of ``*.js``, [:12]."""
|
|
files = sorted(p for p in Path(directory).glob("*.js") if p.is_file())
|
|
if not files:
|
|
raise SystemExit(f"{directory}: no *.js modules")
|
|
h = hashlib.sha256()
|
|
h.update(CACHE_EPOCH)
|
|
for p in files:
|
|
data = p.read_bytes()
|
|
name = p.name.encode()
|
|
h.update(len(name).to_bytes(4, "big") + name)
|
|
h.update(len(data).to_bytes(8, "big") + data)
|
|
return h.hexdigest()[:12]
|
|
|
|
|
|
def _root_vars(path: Path) -> dict[str, str]:
|
|
"""Custom properties of the stylesheet's first :root block (raw values)."""
|
|
m = re.search(r"^:root\s*\{(.*?)^\}", path.read_text(encoding="utf-8"), re.S | re.M)
|
|
if not m:
|
|
raise SystemExit(f"{path}: no :root block")
|
|
body = re.sub(r"/\*.*?\*/", "", m.group(1), flags=re.S)
|
|
return {k: v.strip() for k, v in re.findall(r"(--[\w-]+)\s*:\s*([^;]+);", body)}
|
|
|
|
|
|
def _resolve(raw: dict[str, str], name: str, where: Path, depth: int = 0) -> str:
|
|
"""The value of one custom property, following var(--x) references."""
|
|
if depth > 8 or name not in raw:
|
|
raise SystemExit(f"{where}: cannot resolve {name}")
|
|
return re.sub(
|
|
r"var\((--[\w-]+)\)",
|
|
lambda r: _resolve(raw, r.group(1), where, depth + 1),
|
|
raw[name],
|
|
)
|
|
|
|
|
|
def _dark_palette() -> str:
|
|
light = _root_vars(FHIRWORX_CSS)
|
|
dark = _root_vars(GITEA_DARK)
|
|
lines = []
|
|
for token, src in DARK_ROLES.items():
|
|
if f"--{token}" not in light:
|
|
raise SystemExit(
|
|
f"{FHIRWORX_CSS}: token --{token} is gone; update DARK_ROLES"
|
|
)
|
|
value = _resolve(dark, src, GITEA_DARK)
|
|
if not re.fullmatch(r"#[0-9A-Fa-f]{6}", value):
|
|
raise SystemExit(f"{GITEA_DARK}: {src} is {value!r}, expected a hex colour")
|
|
lines.append(f" --{token}: {value}; /* {src} */")
|
|
return ':root[data-theme="dark"] {\n' + "\n".join(lines) + "\n}"
|
|
|
|
|
|
def _data_uri(path: Path, mime: str) -> str:
|
|
return f"data:{mime};base64," + base64.b64encode(path.read_bytes()).decode("ascii")
|
|
|
|
|
|
def _logo_symbol() -> str:
|
|
"""assets/icons/logo.svg as an SVG <symbol id="fw-logo">, used by <use>."""
|
|
svg = (ICONS / "logo.svg").read_text(encoding="utf-8")
|
|
m = re.fullmatch(r"\s*<svg\b([^>]*)>(.*)</svg>\s*", svg, re.S)
|
|
vb = re.search(r'viewBox="([^"]+)"', m.group(1)) if m else None
|
|
if not (m and vb):
|
|
raise SystemExit(
|
|
f"{ICONS / 'logo.svg'}: expected one <svg viewBox=...> element"
|
|
)
|
|
return f'<symbol id="fw-logo" viewBox="{vb.group(1)}">{m.group(2).strip()}</symbol>'
|
|
|
|
|
|
def build_page(domain: str, version: str) -> str:
|
|
fw_css = FHIRWORX_CSS.read_text(encoding="utf-8")
|
|
if "</" in fw_css:
|
|
raise SystemExit(f"{FHIRWORX_CSS}: '</' would end the inline <style>")
|
|
page = (HERE / "template.html").read_text(encoding="utf-8")
|
|
page = _fill(page, "/*__FHIRWORX_CSS__*/", fw_css)
|
|
page = _fill(page, "/*__FHIRWORX_DARK__*/", _dark_palette())
|
|
page = _fill(page, "<!--__FW_LOGO__-->", _logo_symbol())
|
|
page = _fill(
|
|
page, "/*__FAVICON_SVG__*/", _data_uri(ICONS / "favicon.svg", "image/svg+xml")
|
|
)
|
|
page = _fill(
|
|
page, "/*__FAVICON_PNG__*/", _data_uri(ICONS / "fav32.png", "image/png")
|
|
)
|
|
page = _fill(
|
|
page,
|
|
"/*__APPLE_TOUCH_ICON__*/",
|
|
_data_uri(ICONS / "apple-touch-icon.png", "image/png"),
|
|
)
|
|
page = _fill(page, "/*__DOMAIN__*/", html.escape(domain), count=DOMAIN_FILLS)
|
|
return _fill(page, "/*__VERSION__*/", version, count=VERSION_FILLS)
|
|
|
|
|
|
def main(argv: list[str] | None = None) -> int:
|
|
args = parse_args(argv)
|
|
version = module_version(ASSETS)
|
|
page = build_page(os.environ.get("DOMAIN") or "fhirworx.io", version)
|
|
dst: Path = args.out
|
|
dst.parent.mkdir(parents=True, exist_ok=True)
|
|
tmp = dst.with_name(f".{dst.name}.tmp")
|
|
tmp.write_text(page, encoding="utf-8")
|
|
os.replace(tmp, dst) # Gitea serves dst live: never expose a half-written page
|
|
print(f"wrote {dst} ({dst.stat().st_size:,} bytes) v={version}")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|