Skip to content

Commit 888006e

Browse files
committed
Give render validation and export separate owners
Keep browser checks and preview servers in render_gate, and put standalone page export in exporting.
1 parent f4d7c12 commit 888006e

20 files changed

Lines changed: 277 additions & 259 deletions

‎plugins/leaf/skills/leaf/CLAUDE.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2212,7 +2212,7 @@ A local browser check is required after changing `leaf.js`, a widget module, the
22122212
registry, or the theme.
22132213

22142214
The named JavaScript exports in `leaf/render-checks.js`, invoked by
2215-
`leaf/render_checks.py` and composed by `leaf/rendering.py`, each answer one failure
2215+
`leaf/render_checks.py` and composed by `leaf/render_gate.py`, each answer one failure
22162216
class. The served module imports the public widget API statically, so the JavaScript
22172217
parser and module loader validate its syntax, dependencies, and named exports.
22182218
`coveredWords` is reexported from the import-free `render-checks-standalone.js`, which

‎plugins/leaf/skills/leaf/scripts/CLAUDE.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@ The main owners are:
1616
- `registry_contract`, `schema`, `structure`, `styles`, and `validation`: the
1717
merged vocabulary contract and authored-page gates;
1818
- `passages`: the file-side text reading and anchor capture;
19-
- `render_checks` and `rendering`: browser validation and export;
19+
- `render_checks`, `render_gate`, and `exporting`: browser probes, validation,
20+
and standalone export;
2021
- `data`, `media`, and `publishing`: page-bound inputs and deployment outputs.
2122

2223
Do not put domain logic back into `interact.py` or branch across these owners in

‎plugins/leaf/skills/leaf/scripts/leaf/checking.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -399,7 +399,7 @@ def cmd_check(
399399
for line in result.advice:
400400
print(f" · {line}")
401401
if render:
402-
from leaf.rendering import render_check
402+
from leaf.render_gate import render_check
403403

404404
revisions = list_revisions(page_dir)
405405
active = revisions[-1] if revisions else 0

‎plugins/leaf/skills/leaf/scripts/leaf/cli.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,14 @@
99
from leaf.checking import cmd_check
1010
from leaf.conversation import cmd_comment, cmd_edit, cmd_reply, cmd_report, cmd_resolve
1111
from leaf.data import cmd_data_clear, cmd_data_set
12+
from leaf.exporting import cmd_export
1213
from leaf.hooks import cmd_hook, unanswered_asks
1314
from leaf.hosting import cmd_serve, cmd_stop, start_server
1415
from leaf.layer import cmd_init, cmd_package_check, cmd_package_init
1516
from leaf.media import cmd_media
1617
from leaf.page import cmd_catalog, cmd_guidance, cmd_page_state
1718
from leaf.passages import active_enclosing
1819
from leaf.publishing import cmd_stamp
19-
from leaf.rendering import cmd_export
2020
from leaf.schema import (
2121
ACK_BATCH_INSTRUCTION,
2222
ANSWER_ASK_INSTRUCTION,
Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
"""Standalone export of a fully rendered page."""
2+
3+
import base64
4+
import re
5+
import sys
6+
from pathlib import Path
7+
8+
from leaf.data import read_data
9+
from leaf.event_log import read_events
10+
from leaf.files import published_versions, version_name
11+
from leaf.render_checks import RENDER_VIEWPORT, evaluate_probe, wait_for_probe
12+
from leaf.render_gate import preview_server
13+
from leaf.schema import _DIR_FILES, MEDIA_DIR, MEDIA_TYPES
14+
from leaf.structure import parse_structure
15+
16+
17+
def inline_assets(html: str, page_dir: Path) -> str:
18+
"""Fold the served assets into the markup. The theme's link becomes the stylesheet
19+
itself and each image becomes its own bytes, which is everything the document still
20+
reaches the server for: the runtime's stylesheet arrived as a `<style>` in the DOM,
21+
the widget modules were imports rather than elements, and a `lf-ref`'s link was
22+
always somewhere else."""
23+
theme = (page_dir / "theme.css").read_text(encoding="utf-8")
24+
html, n = re.subn(
25+
r'<link[^>]+href="/theme\.css"[^>]*>',
26+
lambda _: f"<style>{theme}</style>",
27+
html,
28+
count=1,
29+
)
30+
if not n:
31+
sys.exit(
32+
"the rendered page carried no /theme.css link — it would open unstyled"
33+
)
34+
# References from the parsed reading, never a scan of the text: a path standing
35+
# in prose is the reader's words — the lesson `media_refs` itself carries — and
36+
# a text scan crashed the export on a documented path no file answers. The
37+
# attribute harvest is media_refs; a page <style>'s url(/media/…) is the one
38+
# reference an attribute harvest can't see, so it is read from the parsed css.
39+
# The substitution then rewrites only the two serialized forms a reference
40+
# takes (`="…"`, `url(…)`); prose quoting the exact string of a path the page
41+
# also really uses is the residual, and it is the author quoting live markup.
42+
parsed = parse_structure(html)
43+
css_refs = set(
44+
re.findall(rf"url\((/{MEDIA_DIR}/{_DIR_FILES[MEDIA_DIR]})\)", parsed.css)
45+
)
46+
for src in sorted(set(parsed.media_refs) | css_refs):
47+
file = page_dir / src.lstrip("/")
48+
data = base64.b64encode(file.read_bytes()).decode()
49+
uri = f"data:{MEDIA_TYPES[file.suffix]};base64,{data}"
50+
html = html.replace(f'="{src}"', f'="{uri}"').replace(
51+
f"url({src})", f"url({uri})"
52+
)
53+
return html
54+
55+
56+
def export_page(browser, url: str, page_dir: Path) -> str:
57+
"""The served version at `url`, copied as one self-contained document.
58+
59+
One implementation has two callers, as `render_version` does: `version export`
60+
supplies installed Chrome, while the suite drives this over the shipped
61+
examples with its Chromium headless shell. That keeps the export behavior in
62+
one function without claiming that the two browser launch paths are identical.
63+
64+
The user's decisions come with it. Replay is what puts them on the page, so
65+
this waits for the runtime's caught-up stamp exactly as the gate does, and a page
66+
whose board was rearranged copies rearranged."""
67+
from playwright.sync_api import Error as PlaywrightError
68+
from playwright.sync_api import TimeoutError as PlaywrightTimeout
69+
70+
page = browser.new_page(viewport=RENDER_VIEWPORT)
71+
try:
72+
# See the gate: a page listening for news is never network-idle. The
73+
# stamps below are the arrival signal, and they are the precise one.
74+
page.goto(url, wait_until="load")
75+
try:
76+
wait_for_probe(page, "upgraded")
77+
wait_for_probe(page, "dataApplied", read_data(page_dir)["revision"])
78+
# Both replayed kinds, as the render gate counts them: the caught-up
79+
# stamp counts reports beside actions, and a page whose only recorded
80+
# state is a worker's report would otherwise copy before it painted.
81+
n_replayed = len(
82+
[e for e in read_events(page_dir) if e["kind"] in ("action", "report")]
83+
)
84+
if n_replayed:
85+
wait_for_probe(page, "logApplied", n_replayed)
86+
return inline_assets(evaluate_probe(page, "bake"), page_dir)
87+
except PlaywrightTimeout:
88+
sys.exit(
89+
f"{url.rsplit('/', 1)[-1]} never finished applying its live state in "
90+
"the browser, so a copy would be half-drawn. `leaf version check "
91+
"<page> --render` says what is wrong with it."
92+
)
93+
except PlaywrightError as error:
94+
sys.exit(
95+
f"{url.rsplit('/', 1)[-1]} could not load its browser probe module "
96+
f"({str(error).strip().splitlines()[0]}), so Leaf could not make a "
97+
"trustworthy copy."
98+
)
99+
finally:
100+
page.close()
101+
102+
103+
def cmd_export(page_dir: Path, out: Path, version, *, preview=None) -> int:
104+
"""One stamped version as a standalone HTML file.
105+
106+
The copy is the page as the browser finished drawing it, which is the only way to
107+
get one: half the document is written by the widget layer at runtime, a mermaid
108+
diagram becomes an SVG only once mermaid has drawn it, and a code block is colored
109+
by the vendored tokenizer in the page rather than by anything that can read the
110+
file. So Chrome is not an optimisation here and no `x-` key exempts a widget from
111+
it; without a browser there is nothing to copy at all."""
112+
preview = preview_server if preview is None else preview
113+
try:
114+
from playwright.sync_api import Error as PlaywrightError
115+
from playwright.sync_api import sync_playwright
116+
except ImportError:
117+
sys.exit(
118+
"export needs Playwright; run it as\n"
119+
" leaf version export <page> -o <file>\n"
120+
"or, from a checkout,\n"
121+
" plugins/leaf/bin/leaf version export <page> -o <file>"
122+
)
123+
published = published_versions(page_dir, read_events(page_dir))
124+
if not published:
125+
sys.exit(
126+
f"{page_dir} has no stamped version to export; "
127+
"run `leaf version stamp` first"
128+
)
129+
version = version if version else published[-1]
130+
if version not in published:
131+
sys.exit(
132+
f"v{version} is not stamped — stamped: "
133+
+ ", ".join(f"v{v}" for v in published)
134+
)
135+
name = version_name(version)
136+
137+
with preview(page_dir, version) as url, sync_playwright() as p:
138+
try:
139+
browser = p.chromium.launch(channel="chrome")
140+
except PlaywrightError as e:
141+
sys.exit(
142+
f"export needs Chrome, and it didn't launch ({str(e).strip().splitlines()[0]}). "
143+
"A copy is the drawn page, so there is nothing to write without one."
144+
)
145+
try:
146+
html = export_page(browser, url, page_dir)
147+
finally:
148+
browser.close()
149+
150+
out.parent.mkdir(parents=True, exist_ok=True)
151+
out.write_text(html, encoding="utf-8")
152+
print(f"✓ {name} → {out} ({out.stat().st_size // 1024} KB, opens with no server)")
153+
return 0

plugins/leaf/skills/leaf/scripts/leaf/rendering.py renamed to plugins/leaf/skills/leaf/scripts/leaf/render_gate.py

Lines changed: 2 additions & 147 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,15 @@
1-
"""Browser-backed render checks and standalone page export."""
1+
"""Browser-backed validation of served pages."""
22

3-
import base64
43
import contextlib
54
import json
6-
import re
75
import secrets
86
import sys
97
import threading
108
from pathlib import Path
119
from urllib.parse import urljoin, urlsplit
1210

13-
from leaf.data import read_data
1411
from leaf.event_log import flocked, now_iso, read_events
15-
from leaf.files import published_versions, revision_label, version_name, version_num
12+
from leaf.files import revision_label, version_name, version_num
1613
from leaf.hosting import LeafHTTPServer
1714
from leaf.http import handler_for
1815
from leaf.passages import EMPTY, spoken
@@ -25,9 +22,7 @@
2522
install_window_errors,
2623
wait_for_probe,
2724
)
28-
from leaf.schema import _DIR_FILES, MEDIA_DIR, MEDIA_TYPES
2925
from leaf.service import transition_lock
30-
from leaf.structure import parse_structure
3126
from leaf.validation import thread_universe
3227

3328
# ---------- check --render: the browser half of the gate ----------
@@ -748,143 +743,3 @@ def render_check(
748743
"column, no sideways scroll"
749744
)
750745
return 0
751-
752-
753-
# ---------- export: the page as one file ----------
754-
def inline_assets(html: str, page_dir: Path) -> str:
755-
"""Fold the served assets into the markup. The theme's link becomes the stylesheet
756-
itself and each image becomes its own bytes, which is everything the document still
757-
reaches the server for: the runtime's stylesheet arrived as a `<style>` in the DOM,
758-
the widget modules were imports rather than elements, and a `lf-ref`'s link was
759-
always somewhere else."""
760-
theme = (page_dir / "theme.css").read_text(encoding="utf-8")
761-
html, n = re.subn(
762-
r'<link[^>]+href="/theme\.css"[^>]*>',
763-
lambda _: f"<style>{theme}</style>",
764-
html,
765-
count=1,
766-
)
767-
if not n:
768-
sys.exit(
769-
"the rendered page carried no /theme.css link — it would open unstyled"
770-
)
771-
# References from the parsed reading, never a scan of the text: a path standing
772-
# in prose is the reader's words — the lesson `media_refs` itself carries — and
773-
# a text scan crashed the export on a documented path no file answers. The
774-
# attribute harvest is media_refs; a page <style>'s url(/media/…) is the one
775-
# reference an attribute harvest can't see, so it is read from the parsed css.
776-
# The substitution then rewrites only the two serialized forms a reference
777-
# takes (`="…"`, `url(…)`); prose quoting the exact string of a path the page
778-
# also really uses is the residual, and it is the author quoting live markup.
779-
parsed = parse_structure(html)
780-
css_refs = set(
781-
re.findall(rf"url\((/{MEDIA_DIR}/{_DIR_FILES[MEDIA_DIR]})\)", parsed.css)
782-
)
783-
for src in sorted(set(parsed.media_refs) | css_refs):
784-
file = page_dir / src.lstrip("/")
785-
data = base64.b64encode(file.read_bytes()).decode()
786-
uri = f"data:{MEDIA_TYPES[file.suffix]};base64,{data}"
787-
html = html.replace(f'="{src}"', f'="{uri}"').replace(
788-
f"url({src})", f"url({uri})"
789-
)
790-
return html
791-
792-
793-
def export_page(browser, url: str, page_dir: Path) -> str:
794-
"""The served version at `url`, copied as one self-contained document.
795-
796-
One implementation has two callers, as `render_version` does: `version export`
797-
supplies installed Chrome, while the suite drives this over the shipped
798-
examples with its Chromium headless shell. That keeps the export behavior in
799-
one function without claiming that the two browser launch paths are identical.
800-
801-
The user's decisions come with it. Replay is what puts them on the page, so
802-
this waits for the runtime's caught-up stamp exactly as the gate does, and a page
803-
whose board was rearranged copies rearranged."""
804-
from playwright.sync_api import Error as PlaywrightError
805-
from playwright.sync_api import TimeoutError as PlaywrightTimeout
806-
807-
page = browser.new_page(viewport=RENDER_VIEWPORT)
808-
try:
809-
# See the gate: a page listening for news is never network-idle. The
810-
# stamps below are the arrival signal, and they are the precise one.
811-
page.goto(url, wait_until="load")
812-
try:
813-
wait_for_probe(page, "upgraded")
814-
wait_for_probe(page, "dataApplied", read_data(page_dir)["revision"])
815-
# Both replayed kinds, as the render gate counts them: the caught-up
816-
# stamp counts reports beside actions, and a page whose only recorded
817-
# state is a worker's report would otherwise copy before it painted.
818-
n_replayed = len(
819-
[e for e in read_events(page_dir) if e["kind"] in ("action", "report")]
820-
)
821-
if n_replayed:
822-
wait_for_probe(page, "logApplied", n_replayed)
823-
return inline_assets(evaluate_probe(page, "bake"), page_dir)
824-
except PlaywrightTimeout:
825-
sys.exit(
826-
f"{url.rsplit('/', 1)[-1]} never finished applying its live state in "
827-
"the browser, so a copy would be half-drawn. `leaf version check "
828-
"<page> --render` says what is wrong with it."
829-
)
830-
except PlaywrightError as error:
831-
sys.exit(
832-
f"{url.rsplit('/', 1)[-1]} could not load its browser probe module "
833-
f"({str(error).strip().splitlines()[0]}), so Leaf could not make a "
834-
"trustworthy copy."
835-
)
836-
finally:
837-
page.close()
838-
839-
840-
def cmd_export(page_dir: Path, out: Path, version, *, preview=None) -> int:
841-
"""One stamped version as a standalone HTML file.
842-
843-
The copy is the page as the browser finished drawing it, which is the only way to
844-
get one: half the document is written by the widget layer at runtime, a mermaid
845-
diagram becomes an SVG only once mermaid has drawn it, and a code block is colored
846-
by the vendored tokenizer in the page rather than by anything that can read the
847-
file. So Chrome is not an optimisation here and no `x-` key exempts a widget from
848-
it; without a browser there is nothing to copy at all."""
849-
preview = preview_server if preview is None else preview
850-
try:
851-
from playwright.sync_api import Error as PlaywrightError
852-
from playwright.sync_api import sync_playwright
853-
except ImportError:
854-
sys.exit(
855-
"export needs Playwright; run it as\n"
856-
" leaf version export <page> -o <file>\n"
857-
"or, from a checkout,\n"
858-
" plugins/leaf/bin/leaf version export <page> -o <file>"
859-
)
860-
published = published_versions(page_dir, read_events(page_dir))
861-
if not published:
862-
sys.exit(
863-
f"{page_dir} has no stamped version to export; "
864-
"run `leaf version stamp` first"
865-
)
866-
version = version if version else published[-1]
867-
if version not in published:
868-
sys.exit(
869-
f"v{version} is not stamped — stamped: "
870-
+ ", ".join(f"v{v}" for v in published)
871-
)
872-
name = version_name(version)
873-
874-
with preview(page_dir, version) as url, sync_playwright() as p:
875-
try:
876-
browser = p.chromium.launch(channel="chrome")
877-
except PlaywrightError as e:
878-
sys.exit(
879-
f"export needs Chrome, and it didn't launch ({str(e).strip().splitlines()[0]}). "
880-
"A copy is the drawn page, so there is nothing to write without one."
881-
)
882-
try:
883-
html = export_page(browser, url, page_dir)
884-
finally:
885-
browser.close()
886-
887-
out.parent.mkdir(parents=True, exist_ok=True)
888-
out.write_text(html, encoding="utf-8")
889-
print(f"✓ {name} → {out} ({out.stat().st_size // 1024} KB, opens with no server)")
890-
return 0

‎tests/CLAUDE.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,7 @@ is written over, and a ring has two.
200200
Prefer the public route through the product. A CLI test should invoke the command
201201
or the same command function used by the entry point. A browser test should serve a
202202
vendored page and use its HTTP API. A render-gate test should call
203-
`leaf.rendering.render_version`, not reproduce one of its probes. Test a helper directly
203+
`leaf.render_gate.render_version`, not reproduce one of its probes. Test a helper directly
204204
only when the helper itself carries a contract that would otherwise be hard to
205205
diagnose, such as the traffic wait reaching its deadline.
206206

‎tests/render_cases_layout.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
from leaf import http as http_model
2020
from leaf import registry as registry_model
2121
from leaf import render_checks as render_checks_model
22-
from leaf import rendering as rendering_model
22+
from leaf import render_gate as render_gate_model
2323
from leaf import service as service_model
2424
from playwright.sync_api import TimeoutError as PlaywrightTimeout
2525
from playwright.sync_api import expect
@@ -110,7 +110,7 @@ def console_message(message):
110110
if message.type != "error":
111111
return
112112
target = (
113-
notices if rendering_model.resize_observer_error(message.text) else errors
113+
notices if render_gate_model.resize_observer_error(message.text) else errors
114114
)
115115
target.append(message.text)
116116

0 commit comments

Comments
 (0)