Integrate Content Editor and Publication workflow

This commit is contained in:
2026-11-17 11:43:53 +03:00
parent f18bc9a4fd
commit c3938f24d8
55 changed files with 6207 additions and 203 deletions
+10 -10
View File
@@ -57,7 +57,7 @@ def main():
work = Path(temp)
site = work / "site"
shutil.copytree(
ROOT / "examples/studio-site", site, ignore=shutil.ignore_patterns(".engine")
ROOT / "examples/site-studio", site, ignore=shutil.ignore_patterns(".engine")
)
env = {
"SITE_ROOT": str(site),
@@ -69,7 +69,7 @@ def main():
"SITE_COOKIE_SECURE": "0",
}
with patch.dict(os.environ, env), serve(create_app()) as origin, sync_playwright() as pw:
browser = pw.chromium.launch(headless=True, args=["--no-sandbox"])
browser = pw.chromium.launch(channel="chromium", headless=True, args=["--no-sandbox", "--no-proxy-server"])
page = browser.new_page(viewport={"width": 1440, "height": 960})
page.on("pageerror", lambda exc: results["console_errors"].append(str(exc)))
page.goto(origin + "/admin/login")
@@ -82,7 +82,7 @@ def main():
("/admin/", "overview"),
("/admin/pages", "pages"),
("/admin/pages/index", "page"),
("/admin/pages/index/blocks/b_hero", "block"),
("/admin/pages/index/blocks/hero_home", "block"),
("/admin/content", "collections"),
("/admin/content/services", "entries"),
("/admin/content/services/bots", "entry"),
@@ -140,24 +140,24 @@ def main():
results["widths"].append([mode + "-dark", width])
page.screenshot(path=str(args.out / "expert-dark-mobile.png"))
page.goto(origin + "/admin/publish")
invoker = page.get_by_role(
"button", name="Опубликовать текущий черновик сайта", exact=True
)
page.locator('[data-pub-action=candidate]').first.click()
page.locator('[data-publication-root][aria-busy=false]').wait_for()
invoker = page.locator('[data-pub-action=publish]')
invoker.click()
page.locator("#confirm-dialog").wait_for(state="visible")
page.locator("#publication-modal-root dialog[open]").wait_for(state="visible")
for _ in range(4):
page.keyboard.press("Tab")
assert page.locator("#confirm-dialog").evaluate(
assert page.locator("#publication-modal-root dialog").evaluate(
"(e)=>e.contains(document.activeElement)"
)
page.keyboard.press("Escape")
assert not page.locator("#confirm-dialog").is_visible()
assert not page.locator("#publication-modal-root dialog").is_visible()
assert invoker.evaluate("(e)=>e===document.activeElement")
assert not results["console_errors"], results["console_errors"]
browser.close()
# Reference is rendered from its own assets, independent of the runtime package.
with sync_playwright() as pw:
browser = pw.chromium.launch(headless=True, args=["--no-sandbox"])
browser = pw.chromium.launch(channel="chromium", headless=True, args=["--no-sandbox", "--no-proxy-server"])
page = browser.new_page(viewport={"width": 1440, "height": 960})
page.goto((ROOT / "design/antirion-rework.html").as_uri())
page.screenshot(path=str(args.out / "reference-antirion.png"), full_page=True)
+468
View File
@@ -0,0 +1,468 @@
"""Original Content design versus real FastAPI: geometry, flows and both preview origins."""
from __future__ import annotations
import asyncio
import json
import os
import shutil
import tempfile
from contextlib import ExitStack
from pathlib import Path
from unittest.mock import patch
from playwright.sync_api import expect, sync_playwright
from qa_001 import PASSWORD, ROOT, serve
from qa_editor_updates import idle, reserve
from starlette.applications import Starlette
from starlette.routing import Mount
from starlette.staticfiles import StaticFiles
from site_engine.build.pipeline import build_site
from site_engine.services.auth import hash_password
from site_engine.web.app import create_app
from site_engine.web.preview_app import create_preview_app
OUT = Path(os.environ.get("QA_CONTENT_OUT", "/tmp/site-engine-content-001"))
def metrics(page, selectors):
return page.evaluate(
"""selectors=>Object.fromEntries(selectors.map(s=>{
const e=document.querySelector(s),c=getComputedStyle(e),r=e.getBoundingClientRect();
return [s,{width:r.width,height:r.height,font:c.fontSize,padding:c.padding,
color:c.color,background:c.backgroundColor,columns:c.gridTemplateColumns}];
}))""",
selectors,
)
def main():
OUT.mkdir(parents=True, exist_ok=True)
report = {
"runs": [],
"comparisons": [],
"page_errors": [],
"native_dialogs": [],
"console_errors": [],
"expected_errors": [],
}
with sync_playwright() as pw:
browser = pw.chromium.launch(
channel="chromium", headless=True, args=["--no-sandbox", "--no-proxy-server"]
)
for interactive in (False, True):
run = {"interactive": interactive, "checks": []}
report["runs"].append(run)
with (
tempfile.TemporaryDirectory(prefix="content-design-qa-") as tmp,
ExitStack() as stack,
):
work, site = Path(tmp), Path(tmp) / "site"
shutil.copytree(
ROOT / "examples/site-studio", site, ignore=shutil.ignore_patterns(".engine")
)
original_file = (site / "content/services/bots.md").read_bytes()
build_site(site, work / "dist")
admin_socket, preview_socket = reserve(), reserve()
admin = "http://127.0.0.1:" + str(admin_socket.getsockname()[1])
preview = "http://127.0.0.1:" + str(preview_socket.getsockname()[1])
stack.enter_context(
patch.dict(
os.environ,
{
"SITE_ROOT": str(site),
"SITE_DIST": str(work / "dist"),
"SITE_STATE_DIR": str(work / "state"),
"SITE_ADMIN_LOGIN": "admin",
"SITE_ADMIN_PASSWORD_HASH": hash_password(PASSWORD, n=2**10),
"SITE_SECRET_KEY": "content-browser-secret-" * 4,
"SITE_COOKIE_SECURE": "0",
"SITE_ADMIN_ORIGIN": admin if interactive else "",
"SITE_PREVIEW_ORIGIN": preview if interactive else "",
},
)
)
app, gate = create_app(), {"delay": 0}
@app.middleware("http")
async def delay(request, call_next, gate=gate):
if (
request.url.path.endswith("/update")
and request.url.path.startswith("/admin/editor/")
and gate["delay"]
):
delay, gate["delay"] = gate["delay"], 0
await asyncio.sleep(delay)
return await call_next(request)
stack.enter_context(serve(app, admin_socket))
if interactive:
stack.enter_context(serve(create_preview_app(), preview_socket))
else:
preview_socket.close()
design_origin = stack.enter_context(
serve(
Starlette(
routes=[Mount("/", StaticFiles(directory=ROOT / "design", html=True))]
)
)
)
context = browser.new_context(
viewport={"width": 1440, "height": 1050}, reduced_motion="reduce"
)
stack.callback(context.close)
page, ref = context.new_page(), context.new_page()
page.set_default_timeout(10000)
page.on("pageerror", lambda e: report["page_errors"].append(str(e)))
def console(message):
if message.type != "error":
return
expected = (
any(str(code) in message.text for code in (401, 403, 409, 422, 500))
or "net::ERR_FAILED" in message.text
)
report["expected_errors" if expected else "console_errors"].append(
{"message": message.text, "url": message.location.get("url")}
)
page.on("console", console)
page.on(
"dialog", lambda d: (report["native_dialogs"].append(d.message), d.dismiss())
)
posts = []
page.on(
"request",
lambda r, posts=posts: posts.append(r.url) if r.method == "POST" else None,
)
page.goto(admin + "/admin/login")
page.locator("[name=login]").fill("admin")
page.locator("[name=password]").fill(PASSWORD)
page.get_by_role("button", name="Войти", exact=True).click()
page.goto(admin + "/admin/content/services/bots")
idle(page)
ref.goto(design_origin + "/content-antirion.html")
if not interactive:
selectors = [
".entry-workspace",
".collection-pane .pane-title",
".entry-pane .pane-title",
".entry-tabs button",
".field-label",
".preview-pane .pane-title",
".workspace-footer",
]
for skin in ("light", "dark"):
page.evaluate("(skin)=>{document.body.dataset.skin=skin}", skin)
# Approved dark Antirion tokens; the source has no Antirion dark palette.
for width in (1440, 1280, 1024, 768, 390, 360):
page.set_viewport_size({"width": width, "height": 1050})
ref.set_viewport_size({"width": width, "height": 1050})
actual, original = metrics(page, selectors), metrics(ref, selectors)
assert not page.evaluate(
"document.documentElement.scrollWidth>innerWidth+1"
), (skin, width)
for selector in selectors[1:]:
assert actual[selector]["font"] == original[selector]["font"], (
selector,
width,
)
assert (
actual[selector]["padding"] == original[selector]["padding"]
), (selector, width)
if width >= 1280:
a, b = (
actual[".entry-workspace"]["columns"].split(),
original[".entry-workspace"]["columns"].split(),
)
for i in (0, 1, 3):
assert a[i] == b[i], (width, a, b)
if skin == "light":
for selector in selectors[1:]:
assert (
actual[selector]["background"]
== original[selector]["background"]
), (selector, width)
report["comparisons"].append(
{
"skin": skin,
"width": width,
"runtime": actual,
"reference": original,
}
)
page.screenshot(
path=str(OUT / f"content-{skin}-{width}.png"), full_page=True
)
if skin == "light":
ref.screenshot(
path=str(OUT / f"reference-{width}.png"), full_page=True
)
page.evaluate("document.body.dataset.skin='light'")
page.set_viewport_size({"width": 1440, "height": 1050})
print("PASS", interactive, len(run["checks"]) + 1, flush=True)
run["checks"].append("original_geometry_fonts_padding_palette_and_responsive")
# Local filters/tabs send no requests, retain keyboard focus.
before = len(posts)
page.locator("#entry-query").fill("nothing-matches")
expect(page.locator("[data-content-list-empty]")).to_be_visible()
assert page.locator("#entry-query").evaluate("e=>e===document.activeElement")
page.locator("#entry-query").fill("")
page.locator("[data-content-filter=draft]").click()
expect(page.locator("[data-entry=automation]")).to_be_visible()
expect(page.locator("[data-entry=bots]")).to_be_hidden()
page.locator("[data-content-filter=all]").click()
for tab in ("relations", "usage", "schema", "fields"):
page.locator("[data-content-tab=" + tab + "]").click()
expect(page.locator("[data-content-panel=" + tab + "]")).to_be_visible()
assert len(posts) == before
print("PASS", interactive, len(run["checks"]) + 1, flush=True)
run["checks"].append("local_filter_tabs_and_real_metadata")
field = page.locator('[name="p.title"]')
field.evaluate("e=>e.__qaInput=true")
page.locator("#preview-result iframe").evaluate("e=>e.__qaFrame=true")
before = len(posts)
field.fill("One background content update")
idle(page)
expect(page.frame_locator("#preview-result iframe").locator("strong")).to_have_text(
"One background content update"
)
assert posts[before:] == [admin + "/admin/editor/content/services/bots/update"], (
posts[before:]
)
assert field.evaluate("e=>e.__qaInput===true&&document.activeElement===e")
assert page.locator("#preview-result iframe").evaluate("e=>e.__qaFrame===true")
assert (site / "content/services/bots.md").read_bytes() == original_file
print("PASS", interactive, len(run["checks"]) + 1, flush=True)
run["checks"].append("one_post_keeps_field_frame_and_no_autosave")
gate["delay"] = 1
field.fill("Delayed candidate")
page.wait_for_function(
"()=>document.getElementById('document-editor').dataset.updating==='true'"
)
field.fill("Latest candidate during pending POST")
page.locator("[data-content-tab=relations]").click()
expect(page.locator("[data-content-panel=relations]")).to_be_visible()
idle(page)
page.locator("[data-content-tab=fields]").click()
expect(field).to_have_value("Latest candidate during pending POST")
print("PASS", interactive, len(run["checks"]) + 1, flush=True)
run["checks"].append("typing_and_tabs_do_not_wait_for_delayed_post")
# Asset/ref dialogs have real options and restore focus with Escape.
picker = page.locator('[data-content-picker="p.hero_asset"]')
picker.click()
expect(page.locator("dialog[open] .asset-option").first).to_be_visible()
page.keyboard.press("Escape")
assert picker.evaluate("e=>e===document.activeElement")
page.locator('[data-content-picker="p.related_scenarios"]').click()
expect(page.locator("dialog[open] .ref-choice")).to_have_count(3)
page.locator("dialog[open] input[type=checkbox]").first.uncheck()
page.locator("dialog[open]").get_by_role(
"button", name="Применить", exact=True
).click()
idle(page)
page.locator('[data-content-bool="p.featured"]').uncheck()
idle(page)
assert page.evaluate("window.siteDocument.state.model.meta.featured") is False
print("PASS", interactive, len(run["checks"]) + 1, flush=True)
run["checks"].append("real_asset_ref_picker_and_boolean")
# Explicit add and remove list rows preserve names and field focus.
page.locator('[data-content-add="p.benefits"]').click()
row = page.locator('[data-list-row="p.benefits.2"] textarea')
row.fill("New list item")
idle(page)
expect(page.locator('[data-list-row="p.benefits.3"]')).to_be_hidden()
page.locator('[data-content-remove="p.benefits.0"]').click()
idle(page)
assert page.evaluate("window.siteDocument.state.model.meta.benefits.length") == 2
expect(page.locator('[name="p.benefits.1"]')).to_have_value("New list item")
print("PASS", interactive, len(run["checks"]) + 1, flush=True)
run["checks"].append("explicit_list_add_delete_reindexes_controls")
page.locator("[data-content-preview=page]").click()
idle(page)
expect(page.frame_locator("#preview-result iframe").locator("h1")).to_have_text(
"Latest candidate during pending POST"
)
page.locator("[data-content-version=live]").click()
idle(page)
expect(page.frame_locator("#preview-result iframe").locator("h1")).to_have_text(
"Telegram-боты"
)
page.locator("[data-content-preview=card]").click()
idle(page)
expect(page.locator("#preview-result .preview-empty")).to_contain_text("карточка")
page.locator("[data-content-version=workspace]").click()
idle(page)
print("PASS", interactive, len(run["checks"]) + 1, flush=True)
run["checks"].append("real_workspace_card_page_and_immutable_live_page")
page.locator("[data-content-validate]").first.click()
expect(page.locator("dialog[open] .review-summary")).to_be_visible()
page.screenshot(path=str(OUT / f"review-{interactive}.png"))
page.keyboard.press("Escape")
page.locator("[data-editor-mode=expert]").click()
expect(page.locator("#expert-pane")).to_be_visible()
page.locator("[data-content-diff]").click()
expect(page.locator("dialog[open] .diff-row.changed").first).to_be_visible()
page.keyboard.press("Escape")
source = page.locator("#document-source").input_value()
page.locator("#document-source").fill("---\ntitle: [\n---\nKeep this source")
page.wait_for_timeout(450)
page.wait_for_function("()=>!window.siteDocument.state.busy")
expect(page.locator("#document-source")).to_have_value(
"---\ntitle: [\n---\nKeep this source"
)
expect(page.locator("[data-content-source-errors]")).not_to_be_empty()
page.locator("#document-source").fill(source)
idle(page)
page.locator("[data-content-find]").click()
page.locator("[data-source-query]").fill("Latest candidate")
page.locator("dialog[open]").get_by_role("button", name="Найти", exact=True).click()
assert page.locator("#document-source").evaluate(
"e=>e.selectionEnd>e.selectionStart"
)
page.locator("[data-editor-mode=constructor]").click()
print("PASS", interactive, len(run["checks"]) + 1, flush=True)
run["checks"].append("review_expert_diff_find_invalid_yaml_recovery")
# Navigation confirmation uses the original dialog, Escape retains edits.
page.locator("[data-entry=ai]").click()
expect(page.locator("dialog[open]")).to_contain_text("несохранённые")
page.keyboard.press("Escape")
assert page.url.endswith("/services/bots")
page.locator("[data-save-document]").click()
page.wait_for_function(
"()=>!window.siteDocument.state.dirty&&!window.siteDocument.state.busy"
)
assert b"Latest candidate" in (site / "content/services/bots.md").read_bytes()
assert (work / "dist/current").exists()
print("PASS", interactive, len(run["checks"]) + 1, flush=True)
run["checks"].append("leave_confirmation_explicit_save_no_publish")
# Real CAS conflict; local unsaved text survives.
field.fill("My conflict candidate")
idle(page)
server_source = (
(site / "content/services/bots.md")
.read_text()
.replace("Latest candidate during pending POST", "Server concurrent title")
)
(site / "content/services/bots.md").write_text(server_source)
page.locator("[data-save-document]").click()
expect(page.locator("dialog[open] .conflict-grid")).to_be_visible()
expect(field).to_have_value("My conflict candidate")
page.screenshot(path=str(OUT / f"conflict-{interactive}.png"))
page.keyboard.press("Escape")
print("PASS", interactive, len(run["checks"]) + 1, flush=True)
run["checks"].append("real_409_preserves_unsaved_source")
# Reload is intentional and has no system dialog.
page.reload()
idle(page)
field = page.locator('[name="p.title"]')
field.fill("Copied current editor")
idle(page)
page.locator("[data-content-duplicate]").click()
page.wait_for_url("**/bots-copy")
idle(page)
expect(page.locator('[name="p.title"]')).to_have_value(
"Copied current editor (копия)"
)
assert "status: draft" in (site / "content/services/bots-copy.md").read_text()
page.locator("[data-content-delete]").click()
expect(page.locator("dialog[open]")).to_contain_text("Удалить запись?")
page.keyboard.press("Escape")
assert (site / "content/services/bots-copy.md").exists()
page.locator("[data-content-delete]").click()
page.locator("dialog[open]").get_by_role(
"button", name="Удалить из workspace", exact=True
).click()
page.wait_for_url("**/services/ai")
assert not (site / "content/services/bots-copy.md").exists()
idle(page)
page.locator("[data-content-delete]").click()
expect(page.locator("#request-error")).to_contain_text("архивируйте")
page.locator("[data-close-request-error]").click()
print("PASS", interactive, len(run["checks"]) + 1, flush=True)
run["checks"].append(
"duplicate_current_candidate_delete_confirmation_and_published_guard"
)
# Empty/off collections and a real new draft in an enabled collection.
page.goto(admin + "/admin/content/posts")
expect(page.locator("[data-content-list-empty]")).to_contain_text(
"Записей пока нет"
)
expect(
page.get_by_role("button", name="Создать запись", exact=True)
).to_be_disabled()
page.goto(admin + "/admin/content/services")
idle(page)
page.get_by_role("button", name="Создать запись", exact=True).click()
page.wait_for_url("**/services/entry-*")
idle(page)
assert page.locator("#entry-slug").input_value().startswith("entry-")
print("PASS", interactive, len(run["checks"]) + 1, flush=True)
run["checks"].append("empty_disabled_collection_and_create_real_draft")
# HTTP and network errors keep the active fields and show a message.
field = page.locator('[name="p.title"]')
page.route(
"**/admin/editor/**/update",
lambda route: route.fulfill(
status=500,
content_type="application/json",
body=json.dumps(
{
"error": {
"code": "qa_failure",
"message": "Проверка HTTP 500",
"request_id": "content-qa",
}
}
),
),
)
field.fill("Keep text after error")
expect(page.locator("#request-error")).to_contain_text("Проверка HTTP 500")
expect(field).to_have_value("Keep text after error")
page.unroute("**/admin/editor/**/update")
field.fill("Recovery after 500")
idle(page)
page.route("**/admin/editor/**/update", lambda route: route.abort())
field.fill("Keep text offline")
expect(page.locator("#request-error")).to_contain_text("Нет связи")
expect(field).to_have_value("Keep text offline")
page.unroute("**/admin/editor/**/update")
field.fill("Recovered connection")
idle(page)
print("PASS", interactive, len(run["checks"]) + 1, flush=True)
run["checks"].append("500_and_network_errors_visible_and_recoverable")
ref.close()
assert not report["page_errors"], report["page_errors"]
assert not report["native_dialogs"], report["native_dialogs"]
assert not report["console_errors"], report["console_errors"]
browser.close()
(OUT / "report.json").write_text(json.dumps(report, ensure_ascii=False, indent=2))
print(
json.dumps(
{
"comparisons": len(report["comparisons"]),
"runs": report["runs"],
"errors": report["page_errors"],
},
ensure_ascii=False,
indent=2,
)
)
if __name__ == "__main__":
main()
+2
View File
@@ -317,6 +317,8 @@ def main():
page.goto(admin + '/admin/content/services/bots')
idle(page)
page.locator('[data-content-preview=page]').click()
idle(page)
entry = page.locator('[data-inspector] [name="p.title"]')
entry.fill('Entry background update')
idle(page)
+15 -11
View File
@@ -36,7 +36,7 @@ def main():
work = Path(temp)
site, dist = work / "site", work / "dist"
shutil.copytree(
ROOT / "examples/ai-studio", site, ignore=shutil.ignore_patterns(".engine")
ROOT / "examples/site-studio", site, ignore=shutil.ignore_patterns(".engine")
)
build_site(site, dist)
live = (dist / "current").resolve()
@@ -61,6 +61,7 @@ def main():
options = {"headless": True}
if kind.name == "chromium":
options["args"] = ["--no-sandbox", "--no-proxy-server"]
options["channel"] = "chromium"
if kind.name == "firefox":
options["firefox_user_prefs"] = {"network.proxy.type": 0}
if os.environ.get("QA_BROWSER_EXECUTABLE"):
@@ -84,16 +85,13 @@ def main():
page.wait_for_url(origin + "/admin/")
page.goto(origin + "/admin/publish")
with patch(
"site_engine.web.api.routes.publish",
"site_engine.services.publication.build_site",
side_effect=PermissionError("QA publish denied"),
):
page.get_by_role("button", name="Опубликовать текущий черновик сайта").click()
with page.expect_response(
lambda r: r.url.endswith("/admin/publish") and r.request.method == "POST"
lambda r: r.url.endswith("/admin/publication/build") and r.request.method == "POST"
) as failed:
page.locator("#confirm-dialog").get_by_role(
"button", name="Продолжить"
).click()
page.locator('[data-pub-action=candidate]').first.click()
response = failed.value
assert response.status == 500
correlation = response.headers["x-request-id"]
@@ -146,16 +144,22 @@ def main():
page.unroute("**/admin/editor/pages/index/save")
checks.append("network_failure_is_visible_and_preserves_unsaved_source")
page.get_by_role("button", name="Сохранить документ", exact=True).click()
expect(page.locator("#editor-result")).to_have_attribute("data-saved", "1")
page.wait_for_function(
"expected => window.siteDocument?.state?.saved === expected && !window.siteDocument.state.dirty",
arg=edited,
)
assert (site / "pages/index.md").read_text() == edited
assert (dist / "current").resolve() == live
checks.append("save_recovers_after_failure_without_publishing")
page.goto(origin + "/admin/publish")
page.get_by_role("button", name="Опубликовать текущий черновик сайта").click()
page.locator('[data-pub-action=candidate]').first.click()
page.locator('[data-publication-root][aria-busy=false]').wait_for()
page.locator('[data-pub-action=publish]').click()
page.locator('#release-comment').fill('Error recovery QA release')
with page.expect_response(
lambda r: r.url.endswith("/admin/publish") and r.request.method == "POST"
lambda r: r.url.endswith("/admin/publication/activate") and r.request.method == "POST"
) as published:
page.locator("#confirm-dialog").get_by_role("button", name="Продолжить").click()
page.locator('[data-pub-action=confirm-publish]').click()
assert published.value.status == 200
assert (dist / "current").resolve() != live
expect(page.locator("#request-error")).to_be_hidden()
+376
View File
@@ -0,0 +1,376 @@
"""Real publication workflow and original design in Chromium; isolated temporary sites."""
from __future__ import annotations
import asyncio
import json
import os
import shutil
import tempfile
from contextlib import ExitStack
from pathlib import Path
from unittest.mock import patch
from playwright.sync_api import expect, sync_playwright
from qa_001 import PASSWORD, ROOT, serve
from qa_editor_updates import reserve
from starlette.applications import Starlette
from starlette.routing import Mount
from starlette.staticfiles import StaticFiles
from site_engine.build.pipeline import hash_tree
from site_engine.services.auth import hash_password
from site_engine.web.app import create_app
from site_engine.web.preview_app import create_preview_app
OUT = Path(os.environ.get("QA_PUBLICATION_OUT", "/tmp/site-engine-publication-001"))
def metrics(page, selectors):
return page.evaluate(
"""selectors=>Object.fromEntries(selectors.map(s=>{
const e=document.querySelector(s),r=e.getBoundingClientRect(),c=getComputedStyle(e);
return [s,{width:r.width,font:c.fontSize,padding:c.padding,background:c.backgroundColor,columns:c.gridTemplateColumns}];
}))""",
selectors,
)
def main():
OUT.mkdir(parents=True, exist_ok=True)
report = {
"comparisons": [],
"runs": [],
"page_errors": [],
"console_errors": [],
"expected_errors": [],
"native_dialogs": [],
}
with sync_playwright() as pw:
browser = pw.chromium.launch(
channel="chromium", headless=True, args=["--no-sandbox", "--no-proxy-server"]
)
for interactive in (False, True):
with tempfile.TemporaryDirectory(prefix="publication-qa-") as tmp, ExitStack() as stack:
work = Path(tmp)
site = work / "site"
dist = work / "dist"
shutil.copytree(
ROOT / "examples/site-studio", site, ignore=shutil.ignore_patterns(".engine")
)
admin_socket, preview_socket = reserve(), reserve()
admin = f"http://127.0.0.1:{admin_socket.getsockname()[1]}"
preview = f"http://127.0.0.1:{preview_socket.getsockname()[1]}"
stack.enter_context(
patch.dict(
os.environ,
{
"SITE_ROOT": str(site),
"SITE_DIST": str(dist),
"SITE_STATE_DIR": str(work / "state"),
"SITE_ADMIN_LOGIN": "admin",
"SITE_ADMIN_PASSWORD_HASH": hash_password(PASSWORD, n=2**10),
"SITE_SECRET_KEY": "publication-browser-secret-" * 3,
"SITE_COOKIE_SECURE": "0",
"SITE_ADMIN_ORIGIN": admin if interactive else "",
"SITE_PREVIEW_ORIGIN": preview if interactive else "",
},
)
)
app = create_app()
gate = {"delay": 0}
@app.middleware("http")
async def delay(request, call_next, gate=gate):
if request.url.path == "/admin/publication/build" and gate["delay"]:
value, gate["delay"] = gate["delay"], 0
await asyncio.sleep(value)
return await call_next(request)
stack.enter_context(serve(app, admin_socket))
if interactive:
stack.enter_context(serve(create_preview_app(), preview_socket))
else:
preview_socket.close()
reference = stack.enter_context(
serve(
Starlette(
routes=[Mount("/", StaticFiles(directory=ROOT / "design", html=True))]
)
)
)
context = browser.new_context(
viewport={"width": 1440, "height": 1050}, reduced_motion="reduce"
)
stack.callback(context.close)
page, ref = context.new_page(), context.new_page()
page.set_default_timeout(12000)
page.on("pageerror", lambda e: report["page_errors"].append(str(e)))
def console(message):
if message.type != "error":
return
expected = (
any(str(code) in message.text for code in (401, 403, 409, 422, 500))
or "net::ERR_FAILED" in message.text
)
report["expected_errors" if expected else "console_errors"].append(
{"message": message.text, "url": message.location.get("url")}
)
page.on("console", console)
page.on(
"dialog", lambda d: (report["native_dialogs"].append(d.message), d.dismiss())
)
posts = []
page.on(
"request",
lambda r, posts=posts: posts.append(r.url) if r.method == "POST" else None,
)
checks = []
report["runs"].append({"interactive": interactive, "checks": checks})
def done(name, checks=checks, interactive=interactive):
checks.append(name)
print("PASS", interactive, len(checks), name, flush=True)
def ready(page=page):
expect(page.locator("[data-publication-root]")).to_have_attribute(
"aria-busy", "false"
)
def tab(name, page=page):
page.locator(f'[data-pub-tab="{name}"]').click()
def action(name, page=page):
page.locator(f'[data-pub-action="{name}"]').first.click()
def build(page=page, action=action, ready=ready):
action("candidate")
ready()
expect(page.locator("[data-pub-action=publish]")).to_be_visible()
def publish(comment, page=page, action=action, ready=ready):
action("publish")
page.locator("#release-comment").fill(comment)
action("confirm-publish")
ready()
expect(page.locator("dialog[open]")).to_have_count(0)
page.goto(admin + "/admin/login")
page.locator("[name=login]").fill("admin")
page.locator("[name=password]").fill(PASSWORD)
page.get_by_role("button", name="Войти", exact=True).click()
page.wait_for_url(admin + "/admin/")
with page.expect_response(lambda r, admin=admin: r.url == admin + "/admin/publish") as opened:
page.locator('#sidebar a[href="/admin/publish"]').click()
assert opened.value.request.headers.get("hx-boosted") == "true"
ready()
expect(page.locator(".livebar")).to_contain_text("Публичного релиза пока нет")
assert not (dist / "current").exists()
done("real_empty_first_release")
ref.goto(reference + "/publication-antirion.html")
if not interactive:
selectors = [
".heading h1",
".livebar",
".pipe",
".panel-header",
".table th",
".table td",
".button.primary",
".tabs",
]
for skin in ("light", "dark"):
page.evaluate("(skin)=>{document.body.dataset.skin=skin}", skin)
for width in (1440, 1280, 1024, 768, 390, 360):
page.set_viewport_size({"width": width, "height": 1050})
ref.set_viewport_size({"width": width, "height": 1050})
a, b = metrics(page, selectors), metrics(ref, selectors)
assert not page.evaluate(
"document.documentElement.scrollWidth>innerWidth+1"
), (skin, width)
for s in selectors:
assert a[s]["font"] == b[s]["font"], (s, width, a[s], b[s])
assert a[s]["padding"] == b[s]["padding"], (s, width, a[s], b[s])
if skin == "light":
assert a[s]["background"] == b[s]["background"], (
s,
width,
a[s],
b[s],
)
report["comparisons"].append(
{"skin": skin, "width": width, "runtime": a, "reference": b}
)
page.screenshot(
path=str(OUT / f"publication-{skin}-{width}.png"), full_page=True
)
if skin == "light":
ref.screenshot(
path=str(OUT / f"reference-{width}.png"), full_page=True
)
page.set_viewport_size({"width": 1440, "height": 1050})
page.evaluate("document.body.dataset.skin='light'")
done("original_geometry_fonts_padding_palette_responsive_12_sets")
before = len(posts)
page.locator("#pub-search").fill("no-such-document")
expect(page.locator(".table tbody")).to_contain_text("Ничего не найдено")
expect(page.locator("#pub-search")).to_be_focused()
page.locator("#pub-search").fill("pages/index.md")
page.locator('[data-pub-select="pages/index.md"]').click()
expect(page.locator(".split>.stack").last).to_contain_text("pages/index.md")
tab("checks")
tab("history")
tab("changes")
assert len(posts) == before
done("local_filters_selection_tabs_no_post")
action("compare-doc")
expect(page.locator("dialog[open]")).to_contain_text("Workspace")
page.keyboard.press("Escape")
expect(page.locator("dialog[open]")).to_have_count(0)
action("doc-history")
expect(page.locator("dialog[open]")).to_contain_text("предыдущих версий пока нет")
action("close-modal")
done("real_compare_and_empty_document_history_designer_dialog")
action("validate")
ready()
expect(page.locator(".summary")).to_contain_text("Проверено")
assert not (dist / "current").exists()
done("real_validate_does_not_publish")
gate["delay"] = 1.5
action("candidate")
tab("activity")
expect(page.locator("[data-pub-tab=activity]")).to_have_attribute(
"aria-selected", "true"
)
ready()
tab("candidate")
expect(page.locator("[data-pub-action=publish]")).to_be_enabled()
candidate = json.loads((work / "state/publication/candidate.json").read_text())
assert not (dist / "current").exists()
original_output = hash_tree(dist / candidate["id"])
done("background_candidate_does_not_freeze_tabs_or_activate")
action("candidate-diff")
expect(page.locator("dialog[open]")).to_contain_text("pages/index.md")
action("close-modal")
action("preview")
ready()
frame = page.frame_locator(".release-preview")
expect(frame.locator("body")).to_contain_text("Автоматизируем")
assert not page.frames[-1].locator("script").count()
page.screenshot(
path=str(OUT / f"candidate-preview-{interactive}.png"), full_page=True
)
action("close-modal")
done("immutable_candidate_diff_and_real_passive_preview")
action("publish")
page.locator("#release-comment").fill("Не публиковать")
action("close-modal")
assert not (dist / "current").exists()
publish("Первый проверенный релиз")
first = (dist / "current").resolve().name
assert first == candidate["id"] and hash_tree(dist / first) == original_output
expect(page.locator(".livebar")).to_contain_text(first)
done("cancel_and_explicit_publish_exact_candidate")
path = site / "pages/index.md"
source = path.read_text()
path.write_text(source + "\nИзменение для второго релиза.\n")
tab("changes")
action("refresh-workspace")
ready()
build()
candidate = json.loads((work / "state/publication/candidate.json").read_text())
action("publish")
page.locator("#release-comment").fill("Устаревший кандидат")
path.write_text(path.read_text() + "\nНовая правка после просмотра.\n")
action("confirm-publish")
ready()
expect(page.locator("#request-error")).to_contain_text("Кандидат устарел")
assert (dist / "current").resolve().name == first
action("close-modal")
page.locator("[data-close-request-error]").click()
tab("candidate")
expect(page.locator("[data-pub-action=publish]")).to_be_disabled()
done("real_stale_candidate_409_visible_and_live_unchanged")
build()
publish("Второй релиз")
second = (dist / "current").resolve().name
assert second != first
source_hash = hash_tree(site)
page.locator(f'[data-pub-action=rollback][data-release="{first}"]').click()
page.screenshot(path=str(OUT / f"rollback-{interactive}.png"), full_page=True)
action("close-modal")
assert (dist / "current").resolve().name == second
page.locator(f'[data-pub-action=rollback][data-release="{first}"]').click()
action("rollback-confirm")
ready()
assert (dist / "current").resolve().name == first and hash_tree(site) == source_hash
done("rollback_cancel_confirm_preserves_workspace")
page.goto(admin + "/admin/publish")
ready()
expect(page.locator(".livebar")).to_contain_text(first)
tab("activity")
expect(page.locator(".timeline")).to_contain_text("release_rollback")
tab("history")
page.locator(f'[data-pub-action=release-details][data-release="{second}"]').click()
expect(page.locator("dialog[open]")).to_contain_text("Второй релиз")
action("close-modal")
done("reload_real_history_comments_and_audit")
with patch(
"site_engine.core.render.Renderer.render",
side_effect=RuntimeError("QA render failure"),
):
action("candidate")
ready()
expect(page.locator("#request-error")).to_contain_text("Внутренняя ошибка сервера")
expect(page.locator("#publication-panel")).to_contain_text("Ошибка сборки")
action("build-log")
expect(page.locator("dialog[open]")).to_contain_text("ID запроса")
action("close-modal")
assert (dist / "current").resolve().name == first
page.locator("[data-close-request-error]").click()
page.route("**/admin/publication/build", lambda route: route.abort())
action("candidate")
ready()
expect(page.locator("#request-error")).to_contain_text("Нет связи с сервером")
page.unroute("**/admin/publication/build")
page.locator("[data-close-request-error]").click()
build()
done("500_network_visible_logged_and_recoverable")
page.goto(admin + "/admin/pages/index")
expect(page.locator(".builder")).to_be_visible()
page.goto(admin + "/admin/content/services/bots")
expect(page.locator(".entry-workspace")).to_be_visible()
page.goto(admin + "/admin/theme")
expect(page.locator(".theme-content")).to_be_visible()
page.goto(admin + "/admin/publish")
ready()
tab("checks")
page.locator("[data-pub-tab=checks]").focus()
page.keyboard.press("ArrowRight")
expect(page.locator("[data-pub-tab=candidate]")).to_be_focused()
page.locator("[data-action=profile]").click()
page.locator("#profile-dialog button[type=submit]").click()
expect(page.locator("input[name=login]")).to_be_visible()
done("accepted_screens_keyboard_and_logout")
browser.close()
(OUT / "report.json").write_text(json.dumps(report, ensure_ascii=False, indent=2))
assert not report["page_errors"], report["page_errors"]
assert not report["console_errors"], report["console_errors"]
assert not report["native_dialogs"], report["native_dialogs"]
print(
json.dumps(
{
"comparisons": len(report["comparisons"]),
"runs": report["runs"],
"errors": report["page_errors"],
},
ensure_ascii=False,
indent=2,
)
)
if __name__ == "__main__":
main()
+132
View File
@@ -0,0 +1,132 @@
"""Publication boot through real htmx links, history and repeated navigation."""
from __future__ import annotations
import json
import os
import shutil
import tempfile
from pathlib import Path
from unittest.mock import patch
from playwright.sync_api import expect, sync_playwright
from qa_001 import PASSWORD, ROOT, serve
from site_engine.services.auth import hash_password
from site_engine.web.app import create_app
def main():
out = Path(
os.environ.get("QA_PUBLICATION_NAV_OUT", "/tmp/site-engine-publication-navigation-001")
)
out.mkdir(parents=True, exist_ok=True)
report = {"checks": [], "page_errors": [], "console_errors": [], "native_dialogs": []}
with tempfile.TemporaryDirectory(prefix="publication-navigation-") as tmp:
work = Path(tmp)
shutil.copytree(
ROOT / "examples/site-studio", work / "site", ignore=shutil.ignore_patterns(".engine")
)
env = {
"SITE_ROOT": str(work / "site"),
"SITE_DIST": str(work / "dist"),
"SITE_STATE_DIR": str(work / "state"),
"SITE_ADMIN_LOGIN": "admin",
"SITE_ADMIN_PASSWORD_HASH": hash_password(PASSWORD, n=2**10),
"SITE_SECRET_KEY": "publication-navigation-test-" * 3,
"SITE_COOKIE_SECURE": "0",
"SITE_ADMIN_ORIGIN": "",
"SITE_PREVIEW_ORIGIN": "",
}
with patch.dict(os.environ, env), serve(create_app()) as origin, sync_playwright() as pw:
browser = pw.chromium.launch(
channel="chromium", headless=True, args=["--no-sandbox", "--no-proxy-server"]
)
context = browser.new_context(viewport={"width": 1440, "height": 960})
page = context.new_page()
page.set_default_timeout(6000)
page.on(
"pageerror",
lambda exc: report["page_errors"].append({"message": str(exc), "stack": exc.stack}),
)
page.on(
"console",
lambda msg: (
report["console_errors"].append(msg.text) if msg.type == "error" else None
),
)
page.on(
"dialog",
lambda dialog: (report["native_dialogs"].append(dialog.message), dialog.dismiss()),
)
def ready():
expect(page.locator("[data-publication-root]")).to_have_attribute(
"aria-busy", "false"
)
expect(page.locator(".livebar")).to_contain_text("Публичного релиза пока нет")
assert page.evaluate(
"htmx.config.allowScriptTags === false && htmx.config.allowEval === false"
)
def nav(path):
if page.viewport_size["width"] < 760:
page.get_by_role("button", name="Открыть меню", exact=True).click()
with page.expect_response(
lambda r: r.request.method == "GET" and r.url == origin + path
) as response:
page.locator(f'#sidebar a[href="{path}"]').click()
assert response.value.request.headers.get("hx-boosted") == "true"
page.wait_for_url(origin + path)
assert page.evaluate("window.__publicationNavigationDocument") == "preserved"
try:
page.goto(origin + "/admin/login")
page.locator("[name=login]").fill("admin")
page.locator("[name=password]").fill(PASSWORD)
page.get_by_role("button", name="Войти", exact=True).click()
page.wait_for_url(origin + "/admin/")
for width in (1440, 390):
page.set_viewport_size({"width": width, "height": 960})
for source in (
"/admin/pages",
"/admin/content/services/bots",
"/admin/pages/index",
):
page.goto(origin + source)
page.evaluate("window.__publicationNavigationDocument='preserved'")
nav("/admin/publish")
ready()
report["checks"].append(f"htmx_from_{source}_{width}")
nav("/admin/pages")
nav("/admin/publish")
ready()
page.go_back()
page.wait_for_url(origin + "/admin/pages")
page.go_forward()
page.wait_for_url(origin + "/admin/publish")
ready()
assert (
page.evaluate("window.__publicationNavigationDocument") == "preserved"
)
report["checks"].append(f"repeat_and_back_forward_{source}_{width}")
page.reload()
ready()
report["checks"].append(f"direct_reload_{width}")
page.screenshot(path=str(out / f"publication-navigation-{width}.png"))
assert not report["page_errors"], report["page_errors"]
assert not report["console_errors"], report["console_errors"]
assert not report["native_dialogs"], report["native_dialogs"]
assert not (work / "dist/current").exists()
finally:
report["last_url"] = page.url
report["boot_nodes"] = page.locator("[data-publication-boot]").count()
(out / "report.json").write_text(
json.dumps(report, ensure_ascii=False, indent=2) + "\n"
)
print(json.dumps(report, ensure_ascii=False), flush=True)
browser.close()
if __name__ == "__main__":
main()
+8 -5
View File
@@ -37,7 +37,7 @@ def main():
report = {"geometry": [], "flows": [], "errors": []}
with tempfile.TemporaryDirectory(prefix="cms-shell-") as temp:
work = Path(temp)
shutil.copytree(ROOT / "examples/studio-site", work / "site", ignore=shutil.ignore_patterns(".engine"))
shutil.copytree(ROOT / "examples/site-studio", work / "site", ignore=shutil.ignore_patterns(".engine"))
env = {
"SITE_ROOT": str(work / "site"), "SITE_DIST": str(work / "dist"),
"SITE_STATE_DIR": str(work / "state"), "SITE_ADMIN_LOGIN": "admin",
@@ -46,7 +46,7 @@ def main():
"SITE_ADMIN_ORIGIN": "", "SITE_PREVIEW_ORIGIN": "", "SITE_PUBLIC_HOST": "",
}
with patch.dict(os.environ, env), serve(create_app()) as origin, sync_playwright() as pw:
browser = pw.chromium.launch(headless=True, args=["--no-sandbox"])
browser = pw.chromium.launch(channel="chromium", headless=True, args=["--no-sandbox", "--no-proxy-server"])
page = browser.new_page(viewport={"width": 1440, "height": 960}, reduced_motion="reduce")
page.on("pageerror", lambda error: report["errors"].append(str(error)))
page.on("console", lambda message: report["errors"].append(message.text) if message.type == "error" else None)
@@ -121,7 +121,7 @@ def main():
assert page.locator("[data-command-empty]").is_visible()
page.locator("#cmd-input").fill("Контент")
page.locator("[data-command-result]:visible").click()
page.wait_for_url(origin + "/admin/content")
page.wait_for_url(origin + "/admin/content/**")
assert page.locator(".nav-item.active").inner_text() == "Контент"
report["flows"].append("Ctrl+K, real pages/sections, empty search, htmx navigation")
page.locator('[data-action="profile"]').click()
@@ -146,8 +146,11 @@ def main():
assert page.locator(".sidebar.open").count() == 0
page.set_viewport_size({"width": 1440, "height": 960})
page.goto(origin + "/admin/publish")
page.get_by_role("button", name="Опубликовать текущий черновик сайта", exact=True).click()
page.locator("#confirm-dialog button[value=confirm]").click()
page.locator('[data-pub-action=candidate]').first.click()
page.locator('[data-publication-root][aria-busy=false]').wait_for()
page.locator('[data-pub-action=publish]').click()
page.locator('#release-comment').fill('Shell QA release')
page.locator('[data-pub-action=confirm-publish]').click()
page.locator(".live-pip:not(.no-release) .mono").wait_for()
page.goto(origin + "/admin/pages")
assert page.locator(".live-pip .mono").inner_text().strip()
+48
View File
@@ -0,0 +1,48 @@
"""Transfer original Content CSS and SVGs; only isolate selectors from the shell."""
import json
import re
import sys
from pathlib import Path
from css_scope import scope_css
ROOT = Path(__file__).resolve().parents[1]
def main():
def emit(path, content):
if "--check" in sys.argv:
if not path.exists() or path.read_text() != content:
raise SystemExit(f"Content design out of date: {path}")
else:
path.write_text(content)
target = ROOT / "src/site_engine/web/admin"
css = (
(ROOT / "design/assets/builder.css").read_text()
+ "\n"
+ (ROOT / "design/assets/content-editor.css").read_text()
)
css = re.sub(r"(?<![-\w])(?:html|body)(?![-\w])", ":scope", css).replace(":root", ":scope")
css = css.replace(':scope[data-theme="antirion"]', ":scope").replace(
':scope[data-theme="rose"]', ":scope[data-unused-rose]"
)
emit(
target / "static/content-editor.css",
"/* Generated by scripts/sync_content_design.py; original declarations unchanged. */\n"
+ scope_css(css, ".entry-content-editor", ":where(.entry-content-editor)"),
)
js = (ROOT / "design/assets/content-editor.js").read_text()
data = js.split("function icon(name){const p={", 1)[1].split("}[name]||", 1)[0]
icons = dict(re.findall(r"(\w+):'([^']*)'", data))
emit(
target / "templates/_content_icons.html.j2",
"{% macro ci(name) -%}{% set paths = "
+ json.dumps(icons)
+ ' %}<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="{{ paths.get(name, paths.file) }}"/></svg>{%- endmacro %}\n',
)
if __name__ == "__main__":
main()
+41
View File
@@ -0,0 +1,41 @@
"""Reproduce the original publication CSS/SVG, scoped to the accepted runtime shell."""
import json
import re
import sys
from pathlib import Path
from css_scope import scope_css
ROOT = Path(__file__).resolve().parents[1]
def main():
target = ROOT / "src/site_engine/web/admin"
css = (ROOT / "design/assets/publication.css").read_text()
css = re.sub(r"(?<![-\w])(?:html|body)(?![-\w])", ":scope", css).replace(":root", ":scope")
css = css.replace(':scope[data-theme="antirion"]', ":scope").replace(
':scope[data-theme="rose"]', ":scope[data-unused-rose]"
)
js = (ROOT / "design/assets/publication.js").read_text()
data = js.split("const ico={", 1)[1].split("};", 1)[0]
icons = dict(re.findall(r"(\w+):'([^']*)'", data))
output = {
target
/ "static/publication.css": "/* Generated by scripts/sync_publication_design.py; original declarations unchanged. */\n"
+ scope_css(css, ".publication-content", ":where(.publication-content)"),
target / "templates/_publication_icons.html.j2": "{% macro pi(name) -%}{% set paths = "
+ json.dumps(icons)
+ ' %}<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="{{ paths.get(name, paths.file) }}"/></svg>{%- endmacro %}\n',
target / "static/publication-icons.json": json.dumps(icons, ensure_ascii=False) + "\n",
}
for path, content in output.items():
if "--check" in sys.argv:
if not path.exists() or path.read_text() != content:
raise SystemExit(f"Publication design out of date: {path}")
else:
path.write_text(content)
if __name__ == "__main__":
main()
+25 -2
View File
@@ -97,7 +97,7 @@ with TestClient(app) as client:
assert response.status_code==200
response=client.get('/admin/pages/index')
assert response.status_code==200 and 'document-editor' in response.text
for name in ('antirion-rework.css','shell.css','pages.css','pages.js','admin.css','admin.js','editor.js','preview-update.js','builder.css','builder-adapter.css','builder.js','htmx.min.js','theme-studio.css','theme-studio.js'):
for name in ('antirion-rework.css','shell.css','pages.css','pages.js','admin.css','admin.js','editor.js','preview-update.js','builder.css','builder-adapter.css','builder.js','htmx.min.js','theme-studio.css','theme-studio.js','content-editor.css','content-adapter.css','content-editor.js','favicon.svg','publication.css','publication-adapter.css','publication.js','publication-icons.json'):
assert client.get('/admin/static/'+name).status_code==200,name
assert 'pages-screen' in client.get('/admin/pages').text
cookie=client.cookies.get('se_session')
@@ -139,8 +139,31 @@ with TestClient(app) as client:
result=preview.get(result.json()['url'])
assert result.status_code==200 and 'sample-site' in result.text,result.text
assert '--color-primary: #a48bfa' in result.text
response=client.get('/admin/content/services/bots')
assert response.status_code==200 and 'entry-workspace' in response.text,response.text
from site_engine.services.entries import EntryService
entry=EntryService(Path(os.environ['SITE_ROOT']),collection='services').get('bots')
result=client.post('/admin/editor/content/services/bots/update',data={'csrf':csrf,'payload':json.dumps({'source':entry.source,'etag':entry.etag,'revision':30,'preview_view':'card'})},headers={'Origin':'http://testserver','HX-Request':'true','Accept':'application/json'})
assert result.status_code==200 and 'f-entry_card' in result.json()['preview']['html'],result.text
assert 'data-content-tab' in result.json()['projection']
assert 'data-publication-root' in client.get('/admin/publish').text
def publication(op, payload=None):
return client.post('/admin/publication/'+op,data={'csrf':csrf,'payload':json.dumps(payload or {})},headers={'Origin':'http://testserver','Accept':'application/json'})
live=(Path(os.environ['SITE_DIST'])/'current').resolve().name
candidate=publication('build')
assert candidate.status_code==200,candidate.text
identity=candidate.json()['id']
assert (Path(os.environ['SITE_DIST'])/'current').resolve().name==live
passive=publication('preview',{'id':identity,'route':'/'})
assert passive.status_code==200,passive.text
with TestClient(create_preview_app()) as preview:
result=preview.get(passive.json()['url'])
assert result.status_code==200 and '<script' not in result.text,result.text
result=publication('activate',{'id':identity,'expected_live':live,'comment':'Installed wheel release'})
assert result.status_code==200,result.text
assert (Path(os.environ['SITE_DIST'])/'current').resolve().name==identity
assert app.state.api_calls>0
print('installed wheel: all theme presets, build, widths, static, templates, Theme Manager, API, background update, bridge, separate preview OK; design/ absent')
print('installed wheel: all theme presets, build, widths, static, templates, Theme Manager, Content Editor, Publication candidates/preview/activation, API, background update, bridge, separate preview OK; design/ absent')
"""
subprocess.run([sys.executable, "-c", program], cwd=work, env=env, check=True)
@@ -0,0 +1,17 @@
# Этап 4: оригинальный Content Editor и серверный контракт
Источник композиции, размеров, CSS, SVG и сценариев: `design/content-antirion.html`, `design/assets/content-editor.{css,js}` и общие токены `design/assets/builder.css`. Сохраняется ранее принятый общий shell. Перенос не меняет файлы дизайна и контент сайта.
Необходимые доработки бэкенда:
1. Реальные коллекции и записи: enabled по feature requirements, количество и файловый статус, маршрут/display, схема, сравнение с текущим релизом. Новые manifest сохраняют `entry_sources` и `entry_routes`; старый релиз без хешей даёт неизвестный результат сравнения, а не ложное «без изменений».
2. Связи: типизированные ref/refs/link, вложенные группы и списки. Обратные зависимости: записи, композиция регионов страниц/display/Entry, fixed layout и SEO. Для запросов используется штатный Resolver с where/ids/order/limit/features и текущей редакцией записи; произвольные строки не считаются ссылками. Это зависимости структурированных данных; ссылки в Markdown, произвольном Jinja и пользовательском JS не индексируются.
3. `POST /collections/{collection}/entries/{id}/check`: проверка текущего source как кандидата к публикации; типы, обязательные поля, ссылки, assets и реальный рендер. Ничего не записывает. Проверка одной записи не заменяет проверку всего релиза. Неполный синтаксически корректный draft по-прежнему можно сохранить.
4. `POST …/duplicate` с source/etag/revision/id: CAS исходного файла и отсутствие целевого под одной SiteLock. Создаётся отдельный файл draft из текущей редакции, оригинал не меняется. `POST …/delete`: CAS, запрет удаления published до отдельного сохранения archived, история перед удалением и аудит. Ошибка аудита после записи/удаления сообщает совершённое действие и request_id.
5. Общий stateless `POST …/update` получает `preview_view: card|page`, `preview_version: workspace|live`. Workspace использует настоящий renderer и overlay; карточка — встроенный `entry_card`. Live полной страницы читает HTML и assets неизменяемого текущего релиза. Snapshot имеет прежние авторизацию/TTL/CSP и пассивный либо отдельный origin. Отдельной карточки в релизе нет: Live/Card показывает явное объяснение, а не данные workspace под видом live.
Путь запросов остаётся Browser → HTML adapter → AdminApi → JSON FastAPI → сервисы. Парсинг схем и YAML выполняет Python; mock codec и mock storage исходного прототипа не переносятся. Изменения полей остаются в памяти вкладки, обслуживаются общей очередью 003; Save пишет файл с CAS, публикация выполняется отдельно. Создание и дублирование создают настоящий draft-файл.
Slug — идентификатор файла/маршрута: показывается read-only. Переименование потребует отдельной операции с обновлением ссылок; скрытого rename при изменении поля нет. Схема коллекции доступна только для чтения и показывает серверную модель настоящего манифеста. Подписи полей берутся из `FieldDef.label`, при отсутствии — ключ.
В интерфейс не добавляются демонстрационные роли, +30 Demo, симуляция 409, mock Live, sessionStorage или localStorage с документами. Диалоги сохраняют композицию stage4-dialog из дизайна; системные alert/confirm/prompt/beforeunload запрещены.
+24 -4
View File
@@ -11,10 +11,10 @@
| 1. Общий каркас | Sidebar, группы и пункты навигации, логотип, верхняя панель, быстрый поиск, профиль, темы, сворачивание, мобильное меню | `antirion-rework.html`, `assets/antirion-rework.css`, `assets/antirion-rework.js`: sidebar/topbar/command | Принят пользователем; разрешён этап 2 |
| 2. Обзор и страницы | Композиция обзора, счётчики, поиск/фильтры, выбор строки, правый инспектор, создание страницы в модальном окне | Те же исходники: overview/pages/rows/inspector/new | Принят пользователем; разрешён этап 3 |
| 3. Редактор страниц | Заголовок с действиями, дерево слева, превью в центре, инспектор справа, Конструктор/Эксперт, каталог блоков, поля и переключения | `builder-antirion.html`, `assets/builder.css`, `assets/builder.js` | Подготовлен к проверке пользователя |
| 4. Контент и записи | Выбор коллекции, список записей, редактор по схеме, превью, вкладки и режим Эксперт | `content-antirion.html`, `assets/content-editor.css`, `assets/content-editor.js` | Ожидает этап 3 |
| 5. Публикация и завершение | Композиция публикации/истории/отката, рабочие состояния и подтверждения; итоговая сверка всех экранов, входа, ошибок и пустых состояний | `publication-antirion.html`, `assets/publication.css`, `assets/publication.js` | Ожидает этап 4 |
| 4. Контент и записи | Выбор коллекции, список записей, редактор по схеме, превью, вкладки и режим Эксперт | `content-antirion.html`, `assets/content-editor.css`, `assets/content-editor.js` | Разрешён переход к этапу 5 пользователем |
| 5. Публикация и завершение | Композиция публикации/истории/отката, рабочие состояния и подтверждения; итоговая сверка всех экранов, входа, ошибок и пустых состояний | `publication-antirion.html`, `assets/publication.css`, `assets/publication.js` | Реализован; подготовлен к проверке пользователя |
Возможности следующей очереди (candidate/diff, RBAC, медиа и прочие) требуют отдельного действующего контракта; их ограничения фиксируются при переносе соответствующего экрана.
Для этапа 5 реализован настоящий candidate/diff и защищённое переключение Live; уточнение объёма — [publication-backend.md](publication-backend.md). RBAC, медиа, durable jobs, идемпотентные операции и интеграция с агентскими changeset остаются следующей очередью.
## Этап 1 — принят пользователем
@@ -46,7 +46,7 @@ python scripts/verify_package_001.py
Дополнительная регрессия: 239 тестов OK; прежний браузерный сценарий — 8 экранов/60 проверок ширины; установленный wheel без `design/` работает. Эти результаты подтверждают совместимость, но не закрывают визуальную приёмку остальных экранов.
Статус: этапы 1–2 приняты пользователем. Этап 3 подготовлен к проверке; этапы 4–5 ожидают её результата.
Текущий статус на 2026-11-17: пользователь разрешил этап 5 после Content; Publication реализован и подготовлен к его проверке. Общая пользовательская визуальная приёмка не закрывается автоматически.
## Этап 2 — принят пользователем
@@ -142,3 +142,23 @@ Chromium открывает оригинал отдельно от настоя
### Выбор секций и подтверждения
`scripts/qa_selection_001.py` прошёл в Chromium 158 и Firefox 142; проверяет два режима превью — административный origin без scripts и bridge отдельного origin: дерево → выделение/прокрутка/инспектор, превью → дерево/инспектор, фиксированные блоки только для чтения, ноль POST при чистом выборе, неизменный iframe/снимок/source, отсутствие записи файла и публикации. Повторные правки после локального выбора передают текущий source. Проверяются отмена перехода через селектор/ссылку/выход, подтверждённый переход/выход из Entry, Escape, перезагрузка без системного диалога. Любой нативный диалог проваливает прогон. Артефакты: `/tmp/site-engine-selection-001/` и `/tmp/site-engine-selection-firefox-001/`.
## Этап 4 — Контент и записи
Перенесён оригинальный `content-antirion.html` / `assets/content-editor.{css,js}`: четыре панели, заголовок и действия, коллекции/счётчики/OFF, поиск и фильтры записей, форма по схеме, вкладки «Связи», «Где используется», «Схема», режим Expert, оба варианта preview и диалоги stage4-dialog. Сохранены исходные CSS/иконки/breakpoints, принятый shell и его тёмные токены; геометрия viewport адаптирована к фактической высоте shell. Данные/подписи полей берутся из настоящей схемы.
Обычное изменение свойства использует очередь 003: один update, локальный ввод и вкладки без ожидания ответа, сохранение поля/caret/iframe, обновление существующего preview. Отдельный Save пишет файл; duplicate создаёт draft-копию текущей редакции, delete требует сохранённого archived для published. Создание сразу создаёт draft-файл. Восстанавливаемой autosave-сессии нет.
Backend и границы: [content-backend.md](content-backend.md). Результаты и воспроизводимые команды: [verification-content.md](verification-content.md). Live/Page использует HTML/assets реального релиза; Live/Card имеет явное объяснение отсутствующего снимка карточки. Slug read-only, схема read-only; roles/+30 Demo/409 Demo/mock storage не переносятся как работающие функции.
После реализации Content пользователь разрешил переход к этапу 5; его результаты приведены ниже.
## Этап 5 — Publication (2026-11-17)
- Перенесены исходные заголовок, livebar, pipeline, таблица/инспектор и вкладки Changes/Checks/Candidate/History/Activity. CSS/SVG воспроизводятся `scripts/sync_publication_design.py --check`, HTML/JS используют реальные данные. Reset/tokens ограничены экраном; тёмная палитра соответствует принятому shell.
- Проверка и сборка не переключают Live. Кандидат фиксирует входные данные и output; preview и diff показывают этот снимок. Публикация с комментарием проверяет source/renderer/base/current и переключает готовый build без повторного рендера.
- История и журнал настоящие; перед откатом показаны реальные изменяемые публичные файлы. Отмена ничего не пишет; подтверждение не меняет workspace. Старые релизы без частных исходников показывают неизвестное сравнение.
- 409/422/500/сеть/истёкшая сессия видимы. Ошибки после фактического переключения отдельно сообщают committed_build, состояние перечитывается, автоматического повтора POST нет. Нативные alert/confirm/prompt не используются.
- Доработки и ограничения — [publication-backend.md](publication-backend.md); полные результаты — [verification-publication.md](verification-publication.md): 397 тестов полной регрессии, затем 16 целевых; 12 визуальных наборов и 25 групп Chromium на двух конфигурациях preview, общие 8 экранов/60 ширин, проверка отказов и установленного wheel.
Этап передаётся пользователю для визуальной проверки. Docker-образ требует пересборки для обновления Python/templates/static. Переход к следующей самостоятельной работе не считается разрешённым этой технической приёмкой.
File diff suppressed because it is too large Load Diff
+10 -2
View File
@@ -121,7 +121,7 @@ UI-роутеры, использующие AsyncClient, выполняются
| Релизы и текущая публикация | `GET /admin/api/v1/releases` |
| Текущие publish/rollback | `POST /admin/api/v1/publish`, `POST /admin/api/v1/rollback` |
Фигурная группа действий обозначает отдельный явный маршрут для каждого действия. Вложенные ID Page с `/` поддерживаются и проверяются по Registry; маршрут не принимает произвольный файловый путь. Списки принимают те же q/status/layout, что UI. Create возвращает 201 и DocumentSnapshot; чтение/transform/validate/save/preview — 200 с соответствующим DTO. Publish/rollback возвращают фактический результат действующих сервисов без нового candidate pipeline.
Фигурная группа действий обозначает отдельный явный маршрут для каждого действия. Вложенные ID Page с `/` поддерживаются и проверяются по Registry; маршрут не принимает произвольный файловый путь. Списки принимают те же q/status/layout, что UI. Create возвращает 201 и DocumentSnapshot; чтение/transform/validate/save/preview — 200 с соответствующим DTO. Старые Publish/rollback сохраняют прежний контракт действующих сервисов. Новый candidate workflow повторного этапа 5 описан в publication-backend.md.
DTO запросов буфера: `source`, `etag`, `revision`; transform дополнительно содержит дискриминированное типизированное `action`. `revision` — неотрицательное целое, возвращаемое без изменения, `etag` — прежний непрозрачный маркер версии. Схемы запрещают неизвестные служебные поля; пользовательские props проверяет действующая схема фрагмента/коллекции. В JSON не передаются csrf, Principal или произвольный путь записи.
@@ -265,10 +265,18 @@ HTTP/browser-проверки добавляются как воспроизво
| Номер | Направление | Доработка и результат приёмки |
|---|---|---|
| 002 | Релизы | Разделить build/publish; immutable candidate, manifest/hashes, diff, expected_live под общей блокировкой, безопасные повторы; сбой не меняет live, rollback не затирает workspace |
| — | Релизы — расширение | Надёжные фоновые jobs, реестр безопасных повторов, retention/recovery и связь с reviewed changeset. Build/publish, immutable candidate, hashes/diff и expected_live уже реализованы повторным этапом 5 в 001 |
| 003 | Медиа, структура, настройки | Безопасная загрузка, файловые metadata, where-used, changeset с recovery до rename, меню/redirect/site/data/theme; перенос каталога не теряет метаданные |
| 004 | Доступы и журнал | Пользователи, разрешения, миграции SQLite, сессии и audit UI; отказ прав проверяется сервисом, а не видимостью кнопки |
| 005 | Заявки и outbox | Версия формы, submission+outbox одной транзакцией, Telegram/retry, PII grants; сбой доставки не теряет заявку и rollback сохраняет совместимость |
| 006 | MCP | Те же сервисы и ошибки, узкие scopes, TTL/revoke, draft-only; отсутствие publish grant исключает публикацию |
Это очередность отдельных работ. Их контракты и задачи не считаются реализованными или полностью специфицированными пакетом 001.
## Уточнение плана: повторный перенос Content (2026-11-17)
Этап 4 опирается на исходный content-antirion и уже работающую очередь 003. Дополнение сервера: коллекции/зависимости, check, CAS duplicate/delete, entry manifest hashes/routes и настоящий Live/Page. Подробности и ограничения — [content-backend.md](content-backend.md), техническая приёмка — [verification-content.md](verification-content.md). После реализации требуется проверка пользователя до перехода к этапу 5. Новая схема хранения, Node frontend и серверное autosave для этого этапа не требуются.
## Уточнение плана: Publication (2026-11-17)
Пользователь разрешил этап 5. Для оригинального publication-antirion потребовалось настоящее разделение build/activate и частное происхождение релиза. Это уточнение прежнего отнесения всего candidate/diff к следующей очереди. Реализация: PublicationService под SiteLock; build_site(activate=False); отдельные API/HTML endpoints; source/render/output hash и expected_live; пассивный snapshot релиза; исходные диалоги и видимые ошибки. Старые CLI/API/обычные формы совместимы. Контракт — [publication-backend.md](publication-backend.md), приёмка — [verification-publication.md](verification-publication.md). Более широкий workflow релизов/агентских changeset не входит в этап.
@@ -0,0 +1,70 @@
# Этап 5: Publication и серверный контракт
Дата: 2026-11-17. Источники — `design/publication-antirion.html`, `design/assets/publication.css` и `publication.js`. Исходная композиция, таблица, инспектор, пять вкладок, карточки Workspace/Candidate/Live и диалоги перенесены в принятый shell. Mock-хранилище, выдуманные роли, симуляция сборок и ремонт демонстрационных данных исключены. Проверки — [verification-publication.md](verification-publication.md).
## Сценарий
1. Сохранить необходимые документы в редакторе. Несохранённые правки других вкладок не участвуют в сборке.
2. «Проверить» выполняет настоящие workspace/release-проверки. Исходники и Live не меняются; результат помечается устаревшим при изменении входных файлов или renderer.
3. «Собрать кандидата» строго проверяет и рендерит сайт в неизменяемый каталог релиза, сохраняя текущий Live. Отдельный предварительный запуск «Проверить» не обязателен: сборка сама выполняет строгую проверку.
4. Во вкладке «Кандидат» доступны настоящий снимок страницы, сравнение зафиксированных исходников с базовым Live и журнал сборок. Просмотр не пересобирает сайт.
5. «Опубликовать» открывает исходный диалог с комментарием. Подтверждение переключает `current` на выбранный снимок без повторного рендера. Комментарий обязателен, до 150 символов.
6. «История» показывает существующие каталоги релизов. Перед откатом доступны реальные изменённые публичные файлы, маршруты/формы и подтверждение. Откат переключает Live, сохраняя workspace.
Поиск, фильтры, выбор документа и вкладки работают локально. Сетевые операции выполняются через fetch в фоне; переключение вкладок остаётся доступным, повторные изменяющие действия блокируются на время запроса. Сборка на сервере синхронная: долговечной очереди заданий и отмены задачи нет.
## Один контракт FastAPI
Browser → `/admin/publication/*` (cookie, Origin, CSRF) → `AdminApi/httpx.ASGITransport` → `/admin/api/v1/publication*` → `PublicationService`. Браузер не получает внутренних credentials. Начальные данные передаются в скрытом textarea (`tojson`, чтение `.value`), который сохраняется при htmx swap с `allowScriptTags:false`; script-элементы для хранения этих данных не используются. Права и авторство берутся из проверенной сессии; отдельные API keys/scopes и RBAC пока не реализованы.
| JSON API относительно `/admin/api/v1` | Назначение |
|---|---|
| `GET /publication` | Реальное состояние, изменения, проверки, кандидат, история, сборки и журнал |
| `POST /publication/validate` | Проверить workspace/release без записи контента |
| `POST /publication/build` | Собрать кандидат без активации |
| `GET /publication/candidate-diff` | Сравнить неизменяемый кандидат с его базовым релизом |
| `GET /publication/compare?path=…` | Сравнить сохранённый файл workspace с частным снимком Live |
| `GET /publication/document-history?path=…` | Существующие версии `.engine/history`, максимум 20; восстановления здесь нет |
| `GET /publication/release?id=…` | Сравнить публичные файлы выбранного релиза и текущего Live перед откатом |
| `POST /publication/preview` | `{id, route}` → защищённый пассивный снимок настоящего релиза |
| `POST /publication/activate` | `{id, expected_live, comment}` → переключение проверенного кандидата |
| `POST /publication/rollback` | `{id, expected_live, comment}` → переключение существующего исторического релиза |
`expected_live` обязателен; до первой публикации передаётся `null`. HTML adapter читает состояние по `/admin/publication/state`; остальные названия операций совпадают. POST принимает FormData `csrf` и JSON-строку `payload`; ответ — JSON. Читающие операции — GET. Экран открыт по `/admin/publish`; без JavaScript доступна ссылка на обычную форму `/admin/publish/legacy`. Старые POST `/admin/publish`, API `/publish`, `/rollback` и CLI сохраняют прежний сценарий сборки с публикацией.
## Разделение состояния и файлов
`PublicationService` не редактирует файлы сайта. Изменения документов остаются ответственностью `ContentService` с CAS/history/audit. Проверки, сборка и переключение выполняются под общим `SiteLock`; в `build_site` добавлен параметр `activate=False`, обычное значение остаётся `True`. Внешние писатели должны соблюдать тот же lock.
Служебные данные находятся только в `SITE_STATE_DIR/publication/`:
- `candidate.json`: последний кандидат, базовый Live, хеш входных файлов и renderer, hash публичного output, время/автор/маршруты/диагностика;
- `releases/<build_id>.json`: частный снимок входных файлов и происхождение релиза, комментарий/автор и факт активации;
- `validation.json`: реальный результат последней проверки и fingerprint его входных данных;
- `builds.json`: последние 40 результатов/ошибок сборки с ID запроса и кратким журналом стадий.
Список исходников охватывает `pages`, `content`, `menus`, `assets`, `layouts`, `fragments`, `collections`, `display`, `data`, `forms`, root site/theme/redirect YAML и настроенный файл темы. Для UTF-8 текста известных расширений до 512 КиБ сохраняется исходник; для остальных файлов — hash/размер. Скрытые и служебные каталоги исключены, symlink в исходниках отклоняется. Полный hash workspace консервативно инвалидирует кандидата и при изменении иных файлов, включая README; fingerprint renderer учитывает ресурсы движка.
Частные исходники, включая draft, не копируются в публичный `dist` или manifest. В релиз рендерятся только `published`. Статус `published` в файле не означает, что сохранённая редакция уже находится в Live.
Старые/CLI-релизы без частного снимка продолжают работать: маршруты, preview и откат доступны, сравнение исходников/автор/комментарий неизвестны и обозначены явно. Ретроспективно придумывать их нельзя. После первой публикации новым workflow сравнение станет доступно для этого релиза.
Кандидат сравнивается со своей зафиксированной базой, а не с текущими изменениями workspace. Последующие правки требуют новой сборки. Откат сравнивает реальные байты публичных файлов, включая manifest/assets. Никогда не публиковавшиеся кандидаты с известным происхождением через откат выбрать нельзя.
## Конфликты, ошибки и безопасность
Перед активацией проверяются `expected_live`, актуальность ID кандидата, hash исходников/renderer/базового Live и неизменность собранных файлов. Нарушение актуальности — HTTP 409 `release_conflict`; повреждённый снимок/валидация — 422; отсутствующий релиз — 404. Отказ строгого рендера сохраняет прежние Live и кандидат.
JSON-ошибки: `error: {code, message, request_id, …}`. Непредвиденные ошибки и ошибки хранилища логируются со стеком и тем же ID. UI показывает сообщение, код и ID; 409 не закрывает подтверждение и не удаляет комментарий, автоматического повторного POST нет. Сеть и истёкшая сессия также видимы.
Если ошибка записи служебных данных/аудита произошла после сборки либо переключения, API отвечает 500 `candidate_after_build` или `release_after_commit` с `committed_build`. Сообщение различает «снимок создан, Live не переключён» и «Live уже переключён». UI перечитывает состояние перед повтором; указатель `current` остаётся источником истины. Переключение symlink атомарно, но несколько служебных JSON и audit не являются общей crash-atomic транзакцией.
Preview читает HTML/assets выбранного build ID, а не workspace, использует существующие TTL/epoch-токены и immutable snapshots. Скрипты удалены, `script-src 'none'` действует также на отдельном preview origin; iframe sandbox запрещает выполнение кода, формы и навигацию верхнего окна. Настроенный preview origin разрешён в frame-src всех страниц shell: CSP исходного документа сохраняется при htmx swap. Браузерные сценарии проверены с обеими конфигурациями origin.
Журнал показывает настоящие release-события из хвоста аудита: до 80 записей в последних 256 КиБ. Старый аудит не удаляется. Пароли, токены и тела запросов в журнал не добавляются.
## Границы этапа
Новый workflow не удаляет кандидаты/релизы автоматически. Прежняя CLI-сборка сохраняет своё `keep=5`; если каталог уже удалён, API сообщает отсутствие, кандидат становится неактуальным. Политика retention и очистка частных снимков требуют отдельной работы.
Не добавлены durable jobs, реестр идемпотентных операций, changeset/recovery нескольких документов, согласование агентских изменений, RBAC, приём заявок или MCP. Публичные формы по-прежнему отвечают HTTP 501. Исторический релиз без provenance нельзя проверить по исходным входным файлам; UI не выдаёт это за подтверждённое сравнение.
+16 -2
View File
@@ -2,7 +2,7 @@
## Редактор и файлы
Начальный режим — Конструктор. «Применить к буферу» меняет исходник в памяти открытой вкладки; «Сохранить документ» записывает его целиком. Проверка и превью не создают историю контента и не меняют `current`. Публикация отдельно собирает и переключает релиз. В Entry редактируются поля коллекции и Markdown; layout/display доступны для чтения.
Начальный режим — Конструктор. «Применить к буферу» меняет исходник в памяти открытой вкладки; «Сохранить документ» записывает его целиком. Проверка и превью не создают историю контента и не меняют `current`. Новый экран публикации отдельно собирает кандидат, затем переключает его в Live; старые формы/CLI сохраняют build+publish. В Entry редактируются поля коллекции и Markdown; layout/display доступны для чтения.
«Эксперт» хранит точный исходник. Переход между режимами без правок не пересобирает YAML; сохранение без изменений сохраняет в том числе CRLF и комментарии. Конструктор предупреждает о пересборке YAML перед первой операцией. До неё можно скачать исходник. Неприменимый YAML остаётся в «Эксперте», последнее корректное дерево доступно для просмотра. В localStorage попадают только тема и ширина навигации; HTML-кеш htmx отключён.
@@ -131,10 +131,24 @@ python scripts/verify_package_001.py
HTML-проекция содержит серверные шаблоны инспектора для всех блоков. Чистый выбор секции локально обновляет дерево/инспектор/выделение и прокрутку превью: без POST, изменения source/revision, нового снимка или замены iframe. Клик по секции превью выбирает её без дополнительной прокрутки. HTML `/select` остаётся для форм без JS и совместимости; он валидирует переданный исходник и строит инспектор, без записи файла.
Инспектор применяет поля к текущему source после паузы 650 мс; Save/выбор блока/смена режима сначала применяют ожидающую форму. Такой POST transform проверяет и преобразует переданный source, затем обновляет HTML-проекцию; это не сохранение черновика. До явного Save контент не записывается. «Текущая редакция» — память открытой вкладки, без серверного autosave/recovery; `status: draft` — статус файла, исключающий его из релиза. Ошибка формы сохраняет ввод и блокирует последующую запись до исправления. Переходы режимов сохраняют исходные байты. Структурные правки пересобирают YAML без отдельного подтверждения. Для исходника доступны сравнение/отмена, поиск, скачивание и явное форматирование через существующий metadata transform без записи.
После 003 инспектор отправляет один stateless POST update после паузы 200 мс; запрос объединяет изменения, проверку и preview. Save и смена режима дожидаются очереди. Чистый выбор секции остаётся локальным. Запрос не сохраняет черновик; контракт и очередь описаны в ../003-background-editor/runtime.md. До явного Save контент не записывается. «Текущая редакция» — память открытой вкладки, без серверного autosave/recovery; `status: draft` — статус файла, исключающий его из релиза. Ошибка формы сохраняет ввод и блокирует последующую запись до исправления. Переходы режимов сохраняют исходные байты. Структурные правки пересобирают YAML без отдельного подтверждения. Для исходника доступны сравнение/отмена, поиск, скачивание и явное форматирование через существующий metadata transform без записи.
Нативные `alert`/`confirm`/`prompt` и `beforeunload`-диалоги не вызываются. Удаление/отмена и внутренний переход с несохранёнными правками подтверждаются в окнах интерфейса; Escape отменяет действие, фокус возвращается к инициатору. При перезагрузке или закрытии вкладки системного подтверждения нет; несохранённая редакция теряется.
API `Add` принимает `props`, `BlockAction` — `type: duplicate`. Дублирование копирует поддерево, генерирует новые ID и снимает anchors копий. Ограничения регионов/слотов/циклов/типов остаются серверными. Schema передаёт manifest preview/defaults, choices и названия страниц; клиент не выдумывает значения. HTML-действия проходят прежний серверный API-клиент, credentials остаются на сервере.
Переключатель Live в редакторе пока отключён с объяснением. Рабочее превью остаётся настоящим временным снимком, а успешная проверка структуры не заменяет проверку релиза. Сохранение не выполняет publish. Компонентная и сквозная проверка: `PYTHONPATH=src python scripts/qa_builder_001.py` и `PYTHONPATH=src python scripts/qa_editor_001.py`.
## Content Editor после этапа 4
UI `/admin/content/{collection}/{id}` использует оригинальные Content templates/CSS и общую очередь 003. Состав backend-доработок и точные границы: [content-backend.md](content-backend.md); машиночитаемый контракт — [openapi.json](openapi.json). Начальный preview — настоящая карточка `entry_card`, переключатель Page рендерит display/layout. Live/Page читает immutable release; Live/Card показывает отсутствие такого артефакта. Старый manifest без Entry hashes/routes не выдаёт неизвестное сравнение за отсутствие изменений.
Дополнительная приёмка: `PYTHONPATH=src python -m unittest discover -s tests -p test_content_editor.py -v`, `PYTHONPATH=src python scripts/qa_content_001.py`, `python scripts/sync_content_design.py --check`, `python scripts/verify_package_001.py --site examples/site-studio`. Браузерный сценарий использует временный Site Studio и два режима preview; исходный дизайн открывается отдельно. Отчёт — [verification-content.md](verification-content.md).
## Publication — повторный этап 5
`GET /admin/publish` — оригинальный экран с реальными изменениями, проверками, кандидатом, историей и журналом. Проверить → собрать → preview/diff → опубликовать с комментарием; сборка и отмена подтверждения не переключают Live. При правке входных файлов/renderer/базового Live кандидат устаревает. Публикация требует `{id, expected_live, comment}`, откат — выбранный release и expected_live. Workspace при откате не меняется.
Browser fetch → `/admin/publication/*` → серверный AdminApi → `/admin/api/v1/publication*` → PublicationService. Локальные вкладки/поиск/выбор не делают POST. Несохранённые данные других вкладок не участвуют в сборке; состояние релизов в localStorage не хранится. История/сравнение берутся из настоящих файлов и частного `SITE_STATE_DIR/publication/`, старые релизы без provenance имеют неизвестное сравнение.
Все маршруты/ошибки/ограничения — [publication-backend.md](publication-backend.md), результаты — [verification-publication.md](verification-publication.md). На сервере нужен новый wheel/пересборка образа; `design/` для runtime не требуется. Дополнительных env или миграции БД нет, SITE_STATE_DIR должен оставаться приватным постоянным каталогом.
+3 -3
View File
@@ -81,7 +81,7 @@ JS прототипов описывает UX; его seed-данные, localSt
Вход/выход, обзор, список и создание страниц, формы страницы и блока, операции с блоками, коллекции, список/создание/редактирование записей, существующее превью, публикация, история релизов, откат, ошибки и пустые состояния.
Рабочие маршруты и обычные формы сохраняются. Пока новые редакторы не готовы, пользователь сохраняет изменения существующими кнопками форм. На этом этапе оформление публикации соответствует текущей операции «собрать и опубликовать».
Рабочие маршруты и обычные формы сохраняются. Пока новые редакторы не готовы, пользователь сохраняет изменения существующими кнопками форм. При первом переносе оформление публикации соответствовало операции «собрать и опубликовать». Повторный этап 5 уточняет этот контракт: проверка → сборка неизменяемого кандидата → просмотр/diff → отдельное переключение Live с CAS; см. [publication-backend.md](publication-backend.md).
### Этап B — редакторы
@@ -91,7 +91,7 @@ JS прототипов описывает UX; его seed-данные, localSt
### Следующая очередь
Отдельные кандидаты релиза, diff с live, медиабиблиотека и загрузки, changeset/rename, редактирование меню/настроек, пользователи/RBAC, заявки/outbox и MCP описываются следующими спецификациями. В 001 не добавляются Node-сборка, новая структура всего Python-пакета или миграция канонического контента в БД.
На повторном этапе 5 по разрешению пользователя в 001 включены реальные кандидаты релиза, diff с Live и проверка expected_live. Расширенный release workflow (durable jobs, безопасные повторы/реестр операций, retention и reviewed changeset), медиабиблиотека и загрузки, changeset/rename, редактирование меню/настроек, пользователи/RBAC, заявки/outbox и MCP остаются следующей очередью. В 001 не добавляются Node-сборка, новая структура всего Python-пакета или миграция канонического контента в БД.
### Контракт интерфейса
@@ -185,7 +185,7 @@ API задаёт единый контракт операций и данных.
| AC-05 | Две вкладки читают один ETag; первая сохраняет, вторая получает 409 с сохранённым вводом и текущей версией; после ручного объединения сохраняет с новым ETag. |
| AC-06 | Превью выбирает нужный вложенный/fixed-блок, соблюдает правила прокрутки и отображает последнюю версию буфера, включая ассеты workspace. |
| AC-07 | Неверный/истёкший/отозванный токен, чужой снимок, поддельные origin/source/сообщения и traversal отклоняются; приложение превью не открывает admin/login. |
| AC-08 | Успешная публикация переключает current; неудачная сохраняет live; откат сохраняет workspace. В UI отсутствует имитация ещё не реализованного кандидата. |
| AC-08 | Успешная публикация переключает current; неудачная сохраняет live; откат сохраняет workspace. Сборка кандидата не переключает Live; публикация проверяет его актуальность и expected_live без повторного рендера. |
| AC-09 | Основные экраны, ошибки, диалоги и редакторы проходят адаптивную и клавиатурную проверку на заданных размерах. |
| AC-10 | Wheel содержит runtime-ресурсы; обычная сборка сайта проходит и не содержит служебной разметки/скриптов preview-режима. |
| AC-11 | Реальный FastAPI проверяет запросы и ответы JSON API, единый формат ошибок и OpenAPI. HTML- и API-маршруты не смешивают форматы; UI вызывает API через ASGITransport с проверенным автором. Ошибки/отказ API отражаются в UI без обхода через прямую запись. |
+25 -4
View File
@@ -43,8 +43,8 @@
- Проверены q/status/layout, вложенные ID, пустая выдача, выбранный объект и неизвестный ID; представлены реальные file/layout/count/current.
- [ ] **T009** Перенести формы Page, Block и Entry и существующие операции блоков.
- Сохранены имена полей и URL, создание draft, слоты/привязки, добавление/порядок/видимость/удаление и семантика формы без изменений.
- [ ] **T010** Перенести существующие публикацию, историю и откат с подтверждениями.
- В UI отражены реальные build+publish и rollback; кандидат/diff не имитируются; ошибки сборки и отсутствие релизов отображаются.
- [x] **T010** Перенести существующие публикацию, историю и откат с подтверждениями.
- Исходный Publication, реальные build candidate/activate и rollback; настоящий diff/preview; CAS Live, видимые ошибки и пустые состояния. Техническая приёмка — verification-publication.md; визуальная проверка пользователя отдельно P006.
- [x] **T011** Исправить CSP iframe и защищённые ассеты workspace.
- Браузер загружает пассивное превью; изображения и зависимые ресурсы берутся из workspace; traversal/выход по symlink отклоняется; binary MIME корректен.
- [x] **T012** Сохранить пользовательские значения при 409/422 на существующих формах.
@@ -147,10 +147,31 @@
| NFR-03–NFR-04 | T004–T006, T021–T023, T029, T033 | AC-09 |
| NFR-05–NFR-06 | T011–T015, T020, T026, T031, T034–T036 | AC-03, AC-05, AC-08, AC-10 |
Релизы, медиа/настройки, доступы, заявки и MCP следующей очереди не входят в список выполнения 001. Их порядок и зависимости перечислены в конце `plan.md`.
Расширенный workflow релизов, медиа/настройки, доступы, заявки и MCP следующей очереди не входят в список выполнения 001; реальный candidate/diff включён уточнением этапа 5. Их порядок и зависимости перечислены в конце `plan.md`.
## Прежняя функциональная проверка (визуальная приёмка открыта повторно)
2026-11-12: 239 тестов; настоящий FastAPI/ASGITransport; 25 сценариев Chromium на двух origin; 8 экранов и 60 проверок ширины, обе темы, клавиатура и reduced motion; validate/build примеров stage7 — 0 ошибок/0 предупреждений, 7 страниц; wheel установлен вне checkout без design/. Подробная матрица требований, команды и ограничения — [verification.md](verification.md); машиночитаемые результаты — [qa-results.json](qa-results.json).
Этапы 1–2 приняты пользователем. Этап 3 (Конструктор/Эксперт Page) подготовлен к проверке: исходные компоненты builder-antirion, реальные дерево/инспектор/каталог/источники, автоматическое применение полей и явное сохранение, дублирование поддерева, перетаскивание, 422 без потери ввода, сравнение/отмена/форматирование исходника. 247 тестов; Chromium — 12 сравнений Конструктора и 6 «Эксперта», 11 групп сценариев; регрессия editor/shell/pages, CLI и установленного wheel — OK. Подробности — [design-transfer.md](design-transfer.md). Этапы 4–5 и общая визуальная приёмка T033/T036 остаются открытыми; переход — после проверки пользователя.
Этапы 1–2 приняты пользователем. Этап 3 (Конструктор/Эксперт Page) подготовлен к проверке: исходные компоненты builder-antirion, реальные дерево/инспектор/каталог/источники, автоматическое применение полей и явное сохранение, дублирование поддерева, перетаскивание, 422 без потери ввода, сравнение/отмена/форматирование исходника. 247 тестов; Chromium — 12 сравнений Конструктора и 6 «Эксперта», 11 групп сценариев; регрессия editor/shell/pages, CLI и установленного wheel — OK. Подробности — [design-transfer.md](design-transfer.md). На момент этой проверки этапы 4–5 оставались открытыми. Их текущий статус приведён ниже; общая пользовательская визуальная приёмка T033/T036 остаётся отдельной.
## Повторный перенос: этап 4 / Content (2026-11-17)
- [x] **C001** Перенести исходные четыре панели, формы, Expert, диалоги, CSS/SVG и responsive без самостоятельного дизайна.
- [x] **C002** Подключить настоящие коллекции, поля, связи, использования, схему и поиск/фильтры.
- [x] **C003** Дополнить API проверкой готовности, CAS-дублированием/удалением, сравнением и настоящим Workspace/Card/Page и Live/Page.
- [x] **C004** Подключить общую фоновую очередь 003, явное сохранение, видимые 409/422/500/сеть и исходные подтверждения.
- [x] **C005** Пользователь разрешил переход от Content к этапу 5.
Технические проверки и ограничения: [verification-content.md](verification-content.md); доработки: [content-backend.md](content-backend.md). Публикация/история/откат реализованы этапом 5 ниже; общая пользовательская визуальная приёмка остаётся отдельной.
## Повторный перенос: этап 5 / Publication (2026-11-17)
- [x] **P001** Перенести исходную композицию, CSS/SVG, пять вкладок, таблицу/инспектор и диалоги в принятый shell.
- [x] **P002** Реализовать private provenance, реальные изменения/историю, build без активации и неизменяемое сравнение кандидата.
- [x] **P003** Подключить preview готового релиза, подтверждение с комментарием, source/render/output hashes и expected_live под SiteLock.
- [x] **P004** Подключить действительные историю релизов/аудит, последствия отката и переключение без изменения workspace; видимые ошибки/сеть/конфликты, committed_build и traceback.
- [x] **P005** Проверить контракт, браузер/ширины/две темы/два preview origin, общий UI и установленный wheel; обновить OpenAPI и документацию.
- [ ] **P006** Пользовательская визуальная приёмка Publication и итоговых экранов.
Границы — [publication-backend.md](publication-backend.md); результаты и команды — [verification-publication.md](verification-publication.md). Общие T004–T009/T013/T033/T036 не закрываются автоматически технической проверкой этого экрана.
@@ -0,0 +1,59 @@
# Проверка этапа 4 — Content Editor
Дата: 2026-11-17. Реализация подготовлена к проверке пользователя. Источники — оригинальные `content-antirion.html`, `assets/content-editor.{css,js}` и общий `builder.css`. Декларации CSS и SVG переносятся воспроизводимым скриптом; принятый shell сохранён. Доработки и границы бэкенда — [content-backend.md](content-backend.md).
## Сервер и данные
`tests/test_content_editor.py`: 13 тестовых методов проверяют настоящий FastAPI/HTML adapter на временной копии текущего `examples/site-studio`:
- исходную композицию, статические ресурсы, пустую выключенную коллекцию;
- один Registry и внутренний API call на update, настоящий рендер карточки и отсутствие записи/history/publish;
- строгую проверку кандидата с required/link/asset и сохранение неполного draft отдельно;
- диагностику невалидного YAML без потери исходника;
- типизированные вложенные ref/link, обратные связи и query membership текущего кандидата;
- typed link/list/refs/boolean через общий парсер полей;
- копирование текущей редакции в draft, неизменность оригинала, CAS источника/цели и запрет traversal;
- запрет удаления published, необходимость сохранённого archive, CAS и историю;
- traceback/request_id и committed/deleted при отказе аудита после фактической операции;
- Live из HTML/assets релиза, отдельный защищённый snapshot/CSP, отсутствие смешивания с workspace;
- сравнение несохранённого source, неизвестное сравнение старого manifest и отсутствие Live/Card;
- пустой новый draft: slug как подпись только в представлении, без выдуманного title в файле;
- JSON-ошибки авторизации/CSRF/DTO.
13 тестов проходят. Вместе с 12 тестами общей очереди 003 — **25 тестов OK** после последних уточнений.
Полная регрессия — **384 unittest-теста OK**. Как и в 003, старые тесты требуют удалённый `examples/studio-site`: использовалась временная фикстура из коммита `231490b` с миграцией inline theme в файл schema 1 minimal@1; `tests/helpers.EXAMPLE` указывает на временную копию перед discovery. Примеры не возвращались в репозиторий. Ограничение и схема фикстуры описаны в [003 verification](../003-background-editor/verification.md). Старый тест заполнения `.env.example` исправлен: замена всей строки вместо конкатенации нового хеша с уже записанным пользователем. Сам `.env.example` и настройки входа не менялись.
## Chromium и оригинал
`scripts/qa_content_001.py` поднимает настоящий uvicorn на временном Site Studio и отдельно открывает дизайнерский оригинал. Сверяются **12 наборов**: 1440/1280/1024/768/390/360 px × light/dark. Проверяются шрифты/padding устойчивых компонентов, ширины колонок desktop и исходные светлые фоны; dark использует ранее принятую палитру Antirion. Снимки desktop/mobile/dark и реальный конфликт просмотрены визуально. Разные данные и настоящий рендер публичной карточки не сравниваются как попиксельно одинаковые изображения mock.
Проверяются поиск/фильтры/вкладки без POST, фокус, один update и сохранённые input/iframe, ввод и вкладки при задержанном POST, реальные asset/ref picker и boolean, добавление/удаление/перенумерация списка, Workspace/Card/Page и immutable Live/Page, явное пустое состояние Live/Card, review/Expert/diff/поиск/невалидный YAML/исправление, переход с несохранёнными правками, явный Save без publish, настоящий CAS/409, duplicate из текущей редакции, отмена и подтверждение удаления, guard published, пустая/OFF коллекция, создание draft, видимые HTTP500/сеть и восстановление.
Полный сценарий прошёл в обоих режимах preview: **13 групп** на пассивном административном origin и **12 групп** на bridge отдельного origin (сравнение геометрии общее). Все **12 визуальных наборов** проверены. Неожиданных JS/console/CSP-ошибок и native dialogs — **0**. В отчёте намеренные 409/422/500/сеть отделены от неожиданных ошибок; native dialogs запрещены. Артефакты: `/tmp/site-engine-content-001/report.json`, `content-{light,dark}-{width}.png`, `reference-{width}.png`, `review-{False,True}.png`, `conflict-{False,True}.png`.
Дополнительно `scripts/qa_editor_updates.py` прошёл **26 групп** в двух режимах preview: прежние сценарии конструктора, очереди, фокуса/caret, списков, сохранения/конфликта, JS-изоляции и Entry. **0 JS-ошибок, 0 native dialogs**. Подтверждён максимум один update одновременно. В Entry-сценарии явно выбирается Page: начальный вариант Content теперь Card, как в оригинале. Артефакты — `/tmp/site-engine-editor-updates/browser.json`.
## Сборка и упаковка
- CLI validate `examples/site-studio`: **0 ошибок, 0 предупреждений**.
- CLI build: **13 страниц**, релиз в `/tmp/site-studio-content-dist/current/`.
- `scripts/verify_package_001.py --site examples/site-studio`: wheel установлен вне checkout без `design/`; проверены Content templates/CSS/JS, настоящее чтение и карточка через HTML adapter/API, прежние Theme Manager/пресеты/сборка/preview/queue.
- `scripts/sync_content_design.py --check`: совпадают исходные декларации CSS и SVG.
- Ruff изменённых Python, `node --check` изменённых JS, `git diff --check`: проходят.
Основные команды:
```bash
PYTHONPATH=src python -m unittest discover -s tests -p test_content_editor.py -v
PYTHONPATH=src python scripts/qa_content_001.py
PYTHONPATH=src python scripts/qa_editor_updates.py
python scripts/sync_content_design.py --check
python scripts/verify_package_001.py --site examples/site-studio
PYTHONPATH=src python -m site_engine.cli validate examples/site-studio
PYTHONPATH=src python -m site_engine.cli build examples/site-studio --out /tmp/site-studio-content-dist
```
Коммит и развёртывание не выполнялись. Для пользовательской проверки требуется пересборка образа: ресурсы и код находятся в runtime-пакете. Следующий этап публикации UI ожидает проверки Content. Slug rename, редактор схем, RBAC, полноценный индекс ссылок в Markdown/Jinja/JS и отдельный сохранённый Live/Card не добавлены.
Повторная расширенная проверка перед коммитами — [verification-regression.md](verification-regression.md).
@@ -0,0 +1,76 @@
# Проверка этапа 5 — Publication
Дата: 2026-11-17. Этап реализован и подготовлен к проверке пользователя. Источник — оригинальный `publication-antirion.html` / `assets/publication.{css,js}`; адаптация сохраняет принятый Antirion shell. Контракт, данные и ограничения — [publication-backend.md](publication-backend.md).
## Проверки сервера
Полная регрессия: **397 unittest-тестов OK** (384 прежних и 13 Publication на момент запуска). После добавления проверок истории/реального output diff, отказа аудита после сборки и JSON 401 повторно выполнены все **16 Publication-тестов — OK**. На тот момент это соответствовало 400 методам; единый запуск всех 400 не заявлялся.
Новые тесты используют временный текущий `examples/site-studio`, настоящий FastAPI и HTML adapter. Проверены build без активации, публикация точных байтов без рендера, private/public разделение, source/renderer freshness, подмена output, CAS Live, замена кандидата, запрет отката неопубликованного кандидата, CLI без provenance, immutable diff, реальные версии документов и изменённые файлы релиза, неуспешный strict render, оба preview origin, CSRF/auth/session-expired/traversal/symlink, ошибки после совершённой операции и request_id/traceback.
Старым тестам нужен удалённый `examples/studio-site`. Для полной регрессии использована временная фикстура из `231490b` с уже мигрированными файловыми настройками темы; `tests/helpers.EXAMPLE` заменялся только в процессе до discovery. Файлы удалённых примеров в checkout не восстанавливались. Схема окружения — [003 verification](../003-background-editor/verification.md); подробный лог запуска — `/tmp/publication-regression.log`.
## Настоящий Chromium
`qa_publication_001.py` запускает uvicorn на временной копии Site Studio и оригинальный макет отдельно. Выполнены **12 наборов визуальной сверки**: 1440/1280/1024/768/390/360 px, светлая и тёмная тема. Измеряются шрифты/padding/цвета исходного экрана; runtime использует размеры принятого shell и его тёмную палитру. Это не побайтовое сравнение скриншотов: данные, число файлов и shell оригинала отличаются. Проверены отсутствие горизонтального переполнения и ручная сверка screenshot композиции, preview и отката.
**25 групп браузерных проверок** на двух конфигурациях preview (13 + 12):
- первый релиз и пустые состояния, реальные локальные фильтры/выбор/вкладки без POST;
- сравнение документа и существующая/пустая история в исходных диалогах;
- проверка без публикации, фоновая сборка без блокировки вкладок и без переключения Live;
- настоящий immutable diff/preview со стилями и без скриптов;
- отмена и подтверждённая публикация ровно выбранного кандидата;
- устаревший кандидат: видимый 409 и прежний Live;
- отмена/подтверждение отката, сохранение workspace, перечитывание истории/комментариев/аудита;
- намеренные 500/обрыв сети, видимая ошибка и восстановление;
- переходы на ранее перенесённые экраны, клавиатурные вкладки и выход.
Непредвиденных JS/console/CSP-ошибок и нативных alert/confirm/prompt — **0**. Намеренно вызванные HTTP 409/500 и сетевой отказ перечислены отдельно в отчёте.
Артефакты: `/tmp/site-engine-publication-001/report.json`, парные `publication-{light,dark}-*.png` / `reference-*.png`, `candidate-preview-{False,True}.png`, `rollback-{False,True}.png`. Они временные и не входят в репозиторий; сценарий воспроизводит их.
## Общая совместимость
- `qa_001.py`: **8 экранов / 60 проверок ширины — OK**, `/tmp/site-engine-publication-general/`.
- `qa_shell_001.py`: **12 наборов геометрии / 6 групп сценариев — OK**, включая Ctrl+K, htmx-переходы, мобильный фокус, профиль/выход и Live после настоящей публикации; `/tmp/site-engine-shell-001/report.json`.
- `qa_errors_001.py`: **6 групп — OK**, включая 500 публикации со стеком/ID, desktop/mobile уведомления, 500/сеть сохранения без потери ввода и последующее сохранение/публикацию; `/tmp/cms-errors-qa/report.json`.
- Установленный wheel вне checkout без `design/`: настоящие кандидат/preview/активация, API, шаблоны и новые статические ресурсы — OK; `/tmp/publication-package.log`.
Проверки генератора CSS/SVG, `node --check`, Ruff и `git diff --check` прошли. CLI: validate — 0 ошибок/0 предупреждений; build — 13 страниц в `/tmp/site-studio-publication-final`. OpenAPI экспортирован заново из приложения.
## Воспроизводимые команды
```bash
PYTHONPATH=src python -m unittest discover -s tests -p test_publication.py -v
PYTHONPATH=src python scripts/qa_publication_001.py
PYTHONPATH=src python scripts/qa_001.py --out /tmp/site-engine-publication-general
PYTHONPATH=src python scripts/qa_errors_001.py
PYTHONPATH=src python scripts/qa_shell_001.py
python scripts/verify_package_001.py
python scripts/sync_publication_design.py --check
node --check src/site_engine/web/admin/static/publication.js
PYTHONPATH=src python -m site_engine.cli export-openapi --out specs/001-antirion-admin/openapi.json
PYTHONPATH=src python -m site_engine.cli validate examples/site-studio
PYTHONPATH=src python -m site_engine.cli build examples/site-studio --out /tmp/site-studio-publication-final
```
В рабочем окружении использован Python `/tmp/flexly-cms-htmx-check/bin/python`, системный Chromium Playwright с `--no-proxy-server`. Проверки выполнялись на временных сайтах; live `data/`, `.env` и Docker не изменялись. Развёртывание контейнера, долгие нагрузочные испытания, отказ процесса во время нескольких служебных записей и пользовательская визуальная приёмка этим отчётом не подтверждаются.
## Исправление загрузки через меню (2026-11-17)
Пользователь обнаружил падение `null.textContent` при первом переходе в Publication. Первоначальный Publication QA открывал экран через `page.goto`, поэтому не покрывал этот сценарий. Утверждение об отсутствии ошибок относилось к фактически выполненным сценариям, а проверка загрузки через htmx была пропущена.
Причина воспроизведена в Chromium на временном сайте: при `allowScriptTags:false` htmx удаляет также `<script type="application/json">` с начальными данными. `initialize()` читал отсутствующий элемент. При полной загрузке браузер сохранял JSON-элемент, поэтому обновление страницы работало. Кэш браузера к этому отказу отношения не имеет.
Начальные данные перенесены в скрытый textarea с JSON, экранированным `tojson`, чтение выполняется через `.value`; политика `allowScriptTags:false` / `allowEval:false` сохранена. Ошибка разбора начальных данных отображается через общее уведомление. Основной `qa_publication_001.py` теперь входит в экран настоящим htmx-кликом и проверяет `HX-Boosted`, затем выполняет workflow публикации.
Добавлен `scripts/qa_publication_navigation_001.py`. До исправления он воспроизвёл точное исключение, отсутствие bootstrap и зависшую загрузку; после исправления прошли **14 групп проверок**: вход через меню из Pages, Entry и Page Editor; повторный вход; Back/Forward; полная перезагрузка на 1440/390 px. Проверка удостоверяется, что htmx-переходы сохраняют JS-контекст документа и запрет скриптов. Непредвиденных JS/console-ошибок и системных диалогов — 0. Публикация не запускалась.
Команда: `PYTHONPATH=src python scripts/qa_publication_navigation_001.py`. Артефакты — `/tmp/site-engine-publication-navigation-001/report.json` и `publication-navigation-{1440,390}.png`; журналы воспроизведения — `/tmp/publication-navigation-before.log` и `/tmp/publication-navigation-after.log`.
Настоящий вход через меню выявил и вторую проблему в конфигурации отдельного preview origin: после htmx swap браузер сохраняет CSP исходного документа. Разрешение iframe только в ответе `/admin/publish` не действовало при входе из Overview/Pages. Общая HTML-фабрика теперь добавляет ровно настроенный preview origin к frame-src для всех страниц shell; скриптовые разрешения и sandbox снимка сохранены. Отдельный тест проверяет исходные страницы и отсутствие лишних origin/скриптовых разрешений.
После обоих исправлений повторно прошли **17 целевых тестов**, **14 групп навигации** и полный `qa_publication_001.py`: **25 групп workflow / 12 визуальных наборов**, включая действительные htmx-переходы в обеих конфигурациях preview. Непредвиденных JS/console/CSP-ошибок — 0. Логи: `/tmp/publication-htmx-tests.log`, `/tmp/publication-navigation-after.log`, `/tmp/publication-htmx-workflow.log`. Ruff, `node --check`, проверка генератора дизайна и `git diff --check` — OK. Проверки выполнены в Chromium на временных сайтах; серверный контейнер не пересобирался.
Повторная расширенная проверка перед коммитами — [verification-regression.md](verification-regression.md).
+9 -3
View File
@@ -159,7 +159,7 @@ def prune_releases(dist: Path, keep: int) -> list[str]:
return removed
def build_site(root: Path, out: Path, *, keep: int = 5, now: dt.datetime | None = None) -> BuildResult:
def build_site(root: Path, out: Path, *, keep: int = 5, now: dt.datetime | None = None, activate: bool = True) -> BuildResult:
root, out = Path(root), Path(out)
now = now or dt.datetime.now(dt.UTC)
reg = load_site(root)
@@ -242,6 +242,11 @@ def build_site(root: Path, out: Path, *, keep: int = 5, now: dt.datetime | None
"theme": reg.theme.snapshot(),
"routes": sorted(rendered), "fragments": sorted(used),
"page_sources": page_sources,
"entry_sources": {e.file: hashlib.sha256((root / e.file).read_bytes()).hexdigest()
for cid, items in reg.entries.items() if reg.collection_enabled(cid)
for e in items if e.status == "published"},
"entry_routes": {f"{r.collection.id}/{r.entry.slug}": r.route for r in table.values()
if r.collection and r.entry and r.published},
}, ensure_ascii=False, indent=2), encoding="utf-8")
final = out / build_id
if final.exists():
@@ -254,8 +259,9 @@ def build_site(root: Path, out: Path, *, keep: int = 5, now: dt.datetime | None
except BaseException:
shutil.rmtree(staging, ignore_errors=True)
raise
switch_current(out, build_id)
prune_releases(out, keep)
if activate:
switch_current(out, build_id)
prune_releases(out, keep)
return BuildResult(build_id, out / build_id, len(rendered), source_hash, report)
+3 -1
View File
@@ -328,7 +328,7 @@ class Renderer:
return Markup("\n".join(parts))
# ── страница ──────────────────────────────────────────────────────────
def render(self, view: PageView) -> tuple[str, set[str]]:
def render(self, view: PageView, *, fragment: Block | None = None) -> tuple[str, set[str]]:
layout = self.reg.layouts.get(view.layout_id)
if layout is None:
self._issue("E_LAYOUT_MISSING", f"layout «{view.layout_id}» не найден", view.source)
@@ -347,6 +347,8 @@ class Renderer:
"build": {"id": self.build_id, "year": self.now.year},
}
st = _State(view, ctx)
if fragment is not None:
return str(self._block(fragment, st, view.source, "entry", view.id)), st.used
def region(name: str) -> Markup:
rdef = layout.regions.get(name)
+1
View File
@@ -90,6 +90,7 @@ class Resolver:
ref = self.entry_refs.get((entry.collection, entry.slug))
view = dict(entry.data)
view.update(
title=entry.data.get("title", entry.slug),
slug=entry.slug, collection=entry.collection, body=entry.body,
url=ref.route if ref else None,
)
+25
View File
@@ -126,3 +126,28 @@ class ContentService:
atomic_write(paths[rel], previous[rel])
raise
return {rel: etag_of(text.encode("utf-8")) for rel, text in texts.items()}
def copy(self, rel: str, destination: str, if_match: str, prepare: Callable[[str], str]) -> str:
"""CAS the source and absent target under one lock; write only the new file."""
with SiteLock(self.root):
source, target = self._resolve(rel), self._resolve(destination)
current = file_etag(source) or ABSENT
if current != if_match:
raise ConflictError(f'{rel}: файл изменился', current)
if target.exists():
raise ConflictError(f'{destination}: файл уже существует', file_etag(target))
text = prepare(source.read_text(encoding='utf-8'))
self._check_syntax(destination, text)
atomic_write(target, text)
return etag_of(text.encode('utf-8'))
def delete(self, rel: str, if_match: str, validate: Callable[[str], None]) -> None:
"""Validate current content, save recoverable history, then unlink atomically."""
with SiteLock(self.root):
path = self._resolve(rel)
current = file_etag(path) or ABSENT
if current != if_match:
raise ConflictError(f'{rel}: файл изменился', current)
validate(path.read_text(encoding='utf-8'))
save_previous(self.root, rel)
path.unlink()
+10 -3
View File
@@ -59,8 +59,9 @@ class AuditCommitError(EngineError):
class DocumentService:
kind = "page"
def __init__(self, root: Path, audit: AuditLog | None = None, collection: str = ""):
def __init__(self, root: Path, audit: AuditLog | None = None, collection: str = "", *, dist: Path | None = None):
self.root, self.audit, self.collection = Path(root), audit, collection
self.dist = dist
self.content = ContentService(self.root, allowed_prefixes=("pages/", "content/"))
def registry(self) -> Registry:
@@ -88,7 +89,7 @@ class DocumentService:
raise DocumentMissing("Документ не найден")
return rel
def _schema(self, reg: Registry, model: dict | None, identity: str) -> dict:
def _schema(self, reg: Registry, model: dict | None, identity: str, source: str | None = None) -> dict:
layout = None
if self.kind == "page" and model:
page = parse_page(
@@ -122,7 +123,12 @@ class DocumentService:
p.is_symlink() for p in [path, *path.parents] if p != self.root
):
asset_choices.append(path.relative_to(self.root).as_posix())
content = {}
if self.kind == "entry":
from .entry_context import entry_context
content = entry_context(reg, self.collection, identity, (model or {}).get("meta", {}), self.dist, source)
return {
"content": content,
"owner": identity if self.kind == "page" else f"{self.collection}/{identity}",
"display_owner": (reg.collections[self.collection].display or self.collection)
if self.kind == "entry"
@@ -153,6 +159,7 @@ class DocumentService:
"pages": sorted(reg.pages),
"page_titles": {pid: page.title for pid, page in reg.pages.items()},
"collections": sorted(reg.collections),
"entry_titles": {f"{cid}/{e.slug}": str(e.data.get("title", e.slug)) for cid, items in reg.entries.items() for e in items},
"entries": {
cid: sorted(e.slug for e in items) for cid, items in reg.entries.items()
},
@@ -192,7 +199,7 @@ class DocumentService:
etag,
model,
report,
self._schema(reg, model, identity),
self._schema(reg, model, identity, source),
revision,
)
+88 -1
View File
@@ -1,7 +1,94 @@
"""Collection Entry operations share validation and persistence with PageService."""
"""Collection Entries share validation, CAS, history and persistence with Pages."""
from ..build.pipeline import make_views
from ..core.render import Renderer
from ..core.routes import build_route_table
from ..core.validate import validate_release, validate_workspace
from ..errors import EngineError, Report
from ..parsing import frontmatter
from .documents import DocumentService
class EntryDeleteCommitError(EngineError):
"""The file was deleted, but the audit could not be written."""
class EntryService(DocumentService):
kind = "entry"
def check(self, identity, source, etag, revision=0):
reg, result = self.update_buffer(identity, source, etag, [], revision)
if result.model:
# Readiness is checked as if this draft were published, without a write.
candidate = next(e for e in reg.entries[self.collection] if e.slug == identity)
candidate.status = "published"
report = Report()
table = build_route_table(reg, report)
report.extend(validate_workspace(reg, table))
report.extend(validate_release(reg, table))
renderer = Renderer(reg, table, report, strict=True, build_id="validation")
for view in make_views(reg, table, report, published_only=False):
if view.id == f"{self.collection}/{identity}":
renderer.render(view)
for issue in report.issues:
if issue.path == result.path or issue.path.startswith(
(result.path + ":", result.path + ".")
):
result.report.issues.append(issue)
issues = {tuple(i.to_dict().items()): i.to_dict() for i in result.report.issues}
return {"revision": revision, "issues": list(issues.values())}
def duplicate(self, identity, destination, source, etag, context):
reg = self.registry()
rel = self._path(reg, identity)
target = self._path(reg, destination, create=True)
result = None
def prepare(_current):
nonlocal result
current_reg = self.registry()
candidate = self.snapshot(current_reg, identity, rel, source, etag)
if candidate.report.errors:
raise EngineError("Исправьте запись перед дублированием", candidate.report)
meta, body = frontmatter.parse(source)
meta["status"] = "draft"
if "title" in meta:
meta["title"] += " (копия)"
if "slug" in meta:
meta["slug"] = destination
text = frontmatter.dumps(meta, body)
result = self.snapshot(current_reg, destination, target, text, "absent")
if result.report.errors:
raise EngineError("Копия не создана", result.report)
return text
result_etag = self.content.copy(rel, target, etag, prepare)
result.etag = result_etag
self._saved(context, result, "entry_duplicate")
return result
def delete(self, identity, etag, context):
rel = self._path(self.registry(), identity)
def validate(source):
meta, _body = frontmatter.parse(source)
if meta.get("status", "draft") == "published":
raise EngineError(
"Сначала архивируйте запись и сохраните её; затем можно удалить файл."
)
self.content.delete(rel, etag, validate)
if self.audit:
try:
self.audit.write(
"entry_delete",
actor=context.principal.login,
object=rel,
ip=context.ip,
source=context.source,
)
except OSError as exc:
raise EntryDeleteCommitError(
"Запись удалена, но аудит недоступен. Не повторяйте удаление."
) from exc
return {"deleted": True, "id": identity, "collection": self.collection}
+236
View File
@@ -0,0 +1,236 @@
"""Real collection metadata and schema-typed dependencies for the Content workspace."""
import copy
import hashlib
from dataclasses import asdict
from pathlib import Path
from urllib.parse import quote
from ..build.pipeline import make_views
from ..core.models import parse_entry
from ..core.resolve import MISSING, Resolver, get_path
from ..core.routes import build_route_table
from ..core.values import Binding, LinkRef, Query, ValueShapeError, classify
from ..errors import Report
from ..parsing.yamlio import dump_yaml
from .workspace import release_info
def collection_rows(reg):
return [
{
"id": c.id,
"name": c.name,
"total": len(reg.entries.get(c.id, [])),
"published": sum(e.status == "published" for e in reg.entries.get(c.id, [])),
"enabled": reg.collection_enabled(c.id),
}
for c in reg.collections.values()
]
def collection_context(reg, collection, dist=None, sources=None):
c = reg.collections[collection]
release = release_info(Path(dist)) if dist else {"current": None, "entry_sources": None}
hashes, rows = release.get("entry_sources"), []
for e in reg.entries.get(collection, []):
raw = (sources or {}).get(e.file)
if raw is None:
path = reg.root / e.file
raw = path.read_bytes() if path.is_file() else b""
changed = (
hashes.get(e.file) != hashlib.sha256(raw).hexdigest()
if isinstance(hashes, dict)
else (True if not release["current"] else None)
)
rows.append(
{
"slug": e.slug,
"title": str(e.data.get("title", e.slug)),
"status": e.status,
"file": e.file,
"route": c.route.replace("{slug}", e.slug),
"changed": changed,
"url": f"/admin/content/{collection}/{quote(e.slug, safe='')}",
}
)
collections = collection_rows(reg)
return {
"collection": next(x for x in collections if x["id"] == collection),
"collections": collections,
"entries": rows,
"schema_text": dump_yaml(asdict(c)),
"display": f"display/{c.display or c.id}.yaml" if c.kind != "taxonomy" else "",
"kind": c.kind,
"live_build": release["current"],
"comparison_available": not release["current"] or isinstance(hashes, dict),
}
def reference_fields(fields, data, path=""):
"""Yield real field paths, including nested group/list reference controls."""
for f in fields:
name, value = f"{path}.{f.key}" if path else f.key, data.get(f.key)
if f.type in {"ref", "refs", "link"}:
yield name, f, value
elif f.type == "group" and isinstance(value, dict):
yield from reference_fields(f.fields, value, name)
elif f.type == "list" and isinstance(value, list):
for i, item in enumerate(value):
if isinstance(item, dict):
yield from reference_fields(f.fields, item, f"{name}.{i}")
def references(fields, data, path="", *, include_links=True):
"""Strings that happen to look like IDs are never treated as dependencies."""
for name, field, value in reference_fields(fields, data, path):
if field.type == "link":
if include_links and isinstance(value, dict) and isinstance(value.get("entry"), str):
yield name, value["entry"]
continue
for raw in value if isinstance(value, list) else [value]:
if isinstance(raw, str) and raw:
target = raw if field.to == "*" else f"{field.to}/{raw}"
if "/" in target:
yield name, target
def entry_context(reg, collection, identity, meta, dist=None, source=None):
# Queries must see this request's candidate. Never mutate the caller's registry.
reg = copy.copy(reg)
reg.entries = {cid: list(items) for cid, items in reg.entries.items()}
previous = next((e for e in reg.entries.get(collection, []) if e.slug == identity), None)
file = previous.file if previous else f"content/{collection}/{identity}.md"
candidate = parse_entry(
meta, previous.body if previous else "", collection, identity, file, Report()
)
if candidate:
reg.entries[collection] = [
candidate if e.slug == identity else e for e in reg.entries.get(collection, [])
]
if not previous:
reg.entries.setdefault(collection, []).append(candidate)
c, target = reg.collections[collection], f"{collection}/{identity}"
result = collection_context(
reg, collection, dist, {file: source.encode()} if source is not None else None
)
by_id = {f"{cid}/{e.slug}": e for cid, items in reg.entries.items() for e in items}
relations, usages = [], []
for field, ref in references(c.fields, meta):
e = by_id.get(ref)
relations.append(
{
"field": field,
"target": ref,
"title": str(e.data.get("title", e.slug)) if e else ref,
"status": e.status if e else "missing",
"url": f"/admin/content/{ref}" if e else "",
"file": e.file if e else f"content/{ref}.md",
}
)
for ref, e in by_id.items():
if ref != target:
for field, value in references(reg.collections[e.collection].fields, e.data):
if value == target:
usages.append(
{
"kind": "entry",
"title": str(e.data.get("title", e.slug)),
"field": field,
"file": e.file,
"url": f"/admin/content/{ref}",
}
)
table = build_route_table(reg, Report())
resolver = Resolver(reg, table, Report(), strict=False)
def walk(value, context, add, path):
if isinstance(value, dict):
expected = "query" if set(value) == {"query"} else "link" if "entry" in value else None
try:
typed = classify(value, expected)
except ValueShapeError:
typed = None
if isinstance(typed, Binding):
resolved = get_path(context, typed.path)
# Bound data is walked once; recursive bindings are not followed.
if resolved is not MISSING and resolved != value:
walk(resolved, {}, add, path)
return
if isinstance(typed, LinkRef) and typed.kind == "entry" and typed.target == target:
add(path)
if (
isinstance(typed, Query)
and typed.collection == collection
and any(x["slug"] == identity for x in resolver.query(typed, path))
):
add(path)
for key, item in value.items():
walk(item, context, add, f"{path}.{key}")
elif isinstance(value, list):
for i, item in enumerate(value):
walk(item, context, add, f"{path}.{i}")
def blocks(items, context, add, path):
for block in items:
if block.hidden or any(
not reg.site.features.get(req[8:], False) for req in block.requires
):
continue
where = f"{path}[{block.id}]"
fragment = reg.fragments.get(block.fragment)
values = dict(block.props)
if fragment:
for field in fragment.fields:
value = block.props.get(field.key, field.default)
if isinstance(value, dict) and set(value) == {"bind"}:
resolved = get_path(context, value["bind"])
value = None if resolved is MISSING else resolved
values[field.key] = value
for name, ref in references(fragment.fields, values, where, include_links=False):
if ref == target:
add(name)
walk(values, context, add, where + ".props")
for slot, children in block.slots.items():
blocks(children, context, add, where + ".slots." + slot)
# The same composed regions used by Renderer include display/Entry overrides
# and inherited layouts. Query membership honours features, order and limit.
for view in make_views(reg, table, Report(), published_only=False):
url = f"/admin/content/{view.id}" if view.entry else f"/admin/pages/{view.id}"
context = {
"entry": resolver.entry_view(view.entry) if view.entry else None,
"page": {"title": view.title, "body": view.body, "id": view.id},
"data": reg.data,
}
def add(path, view=view, url=url):
usages.append(
{
"kind": "entry" if view.entry else "page",
"title": view.title,
"field": path,
"file": view.source,
"url": url,
}
)
for name, items in view.regions.items():
blocks(items, context, add, f"regions.{name}")
layout = reg.layouts.get(view.layout_id)
if layout:
for name, region in layout.regions.items():
blocks(region.fixed, context, add, f"layouts.{layout.id}.regions.{name}.fixed")
walk(view.seo, context, add, "seo")
result.update(
relations=relations,
usages=list({(x["file"], x["field"]): x for x in usages}.values()),
route=c.route.replace("{slug}", identity),
enabled=reg.collection_enabled(collection),
ref_fields=[
{"key": name, "label": f.label or name, "to": f.to}
for name, f, value in reference_fields(c.fields, meta)
if f.type in {"ref", "refs"} or isinstance(value, dict) and "entry" in value
],
)
return result
+35 -4
View File
@@ -210,7 +210,9 @@ class PreviewStore:
reg, _result = service.overlay(identity, source, etag)
return self.render_document(reg, service, identity, revision, principal)
def render_document(self, reg, service, identity, revision, principal, *, include_html=False):
def render_document(self, reg, service, identity, revision, principal, *, include_html=False, target="page", version="workspace", dist=None):
if version == "live":
return self.render_live(reg, service, identity, revision, principal, dist, target, include_html)
report = Report()
report.extend(reg.report)
if report.errors:
@@ -223,7 +225,13 @@ class PreviewStore:
if view is None:
raise EngineError("У этого документа нет страницы превью", report)
renderer = Renderer(reg, table, report, strict=False, build_id="preview", preview_mode=True)
html, used = renderer.render(view)
if target == "card" and service.kind == "entry":
from ..core.models import Block
block = Block(id="entry_preview", fragment="entry_card", props={"entry": f"{service.collection}/{identity}"})
fragment, used = renderer.render(view, fragment=block)
html = "<!doctype html><html><head><meta name='viewport' content='width=device-width,initial-scale=1'>" + ASSETS_HEAD + "</head><body>" + fragment + "</body></html>"
else:
html, used = renderer.render(view)
css, _ = _bundle(reg, used, report)
from ..web.admin.render import read_static
@@ -234,6 +242,26 @@ class PreviewStore:
include_html=include_html,
)
def render_live(self, reg, service, identity, revision, principal, dist, target, include_html):
from types import SimpleNamespace
from ..build.pipeline import BUILD_ID_RE
if not dist or target == "card":
return {"revision": revision, "interactive": False, "expires_at": 0, "message": "Live доступен для полной страницы; отдельная карточка в релизе не хранится."}
dist = Path(dist).resolve()
release = (dist / "current").resolve()
if release.parent != dist or not BUILD_ID_RE.fullmatch(release.name):
return {"revision": revision, "interactive": False, "expires_at": 0, "message": "Публичного релиза пока нет."}
manifest = json.loads((release / "manifest.json").read_text())
route = manifest.get("entry_routes", {}).get(f"{service.collection}/{identity}")
if not route:
return {"revision": revision, "interactive": False, "expires_at": 0, "message": "Запись отсутствует в live или релиз создан до поддержки Entry snapshots."}
rel = route.lstrip('/')
rel = rel + 'index.html' if route.endswith('/') else rel
html = asset_path(release, rel).read_text()
return self.store(SimpleNamespace(root=release), html, revision, principal,
f'live:{release.name}:{service.collection}:{identity}', include_html=include_html)
def render_theme(
self,
service,
@@ -295,7 +323,7 @@ class PreviewStore:
copy_assets=target != "sample",
)
def store(self, reg, html, revision, principal, document, *, copy_assets=True, include_html=False):
def store(self, reg, html, revision, principal, document, *, copy_assets=True, include_html=False, passive=False):
from ..web.admin.render import read_static
with self.lock:
@@ -315,6 +343,9 @@ class PreviewStore:
"created": now,
"nonce": nonce,
}
if passive:
data["passive"] = True
html = re.sub(r"<script\b[^>]*>[\s\S]*?</script\s*>", "", html, flags=re.IGNORECASE)
payload = (
base64.urlsafe_b64encode(json.dumps(data, separators=(",", ":")).encode())
.rstrip(b"=")
@@ -340,7 +371,7 @@ class PreviewStore:
atomic_write(folder / "assets" / rel, raw)
html = rewrite_assets(html, prefix, token)
live_html = html
if self.config:
if self.config and not passive:
bridge = read_static("preview-update.js") + "\n" + read_static("preview.js").replace(
"__CONFIG__",
json.dumps(
+522
View File
@@ -0,0 +1,522 @@
"""Real release workflow: private provenance, immutable candidates and guarded activation.
Workspace writes still belong to ContentService. This service never edits source files.
All cooperating builds/writes/activation use SiteLock; external filesystem writers must
honour that lock. Private source snapshots are never copied to public dist.
"""
from __future__ import annotations
import datetime as dt
import hashlib
import json
import logging
from pathlib import Path
from types import SimpleNamespace
from ..build.pipeline import (
_SKIP_DIRS,
BUILD_ID_RE,
build_site,
hash_tree,
render_fingerprint,
switch_current,
)
from ..core.registry import load_site
from ..core.routes import build_route_table, route_to_output
from ..core.validate import validate_release, validate_workspace
from ..errors import ConflictError, EngineError, Report, UnsafePathError
from ..parsing.frontmatter import parse
from ..services.preview import asset_path
from ..storage.fs import atomic_write, safe_join
from ..storage.locks import SiteLock
log = logging.getLogger("uvicorn.error")
ROOT_FILES = {"site.yaml", "theme.yaml", "redirects.yaml"}
TYPES = {
"pages": "Page",
"content": "Entry",
"menus": "Menu",
"assets": "Asset",
"layouts": "Layout",
"fragments": "Fragment",
"collections": "Schema",
"display": "Display",
"data": "Data",
"forms": "Form",
}
class ReleaseMissing(EngineError):
pass
class CandidateCommitError(EngineError):
def __init__(self, build_id):
self.build_id = build_id
super().__init__(
"Кандидат собран, но запись служебных данных не завершена. Live не переключён. Обновите состояние перед повтором."
)
class ReleaseCommitError(EngineError):
def __init__(self, build_id):
self.build_id = build_id
super().__init__(
"Live переключён, но запись служебных данных не завершена. Обновите состояние перед повтором."
)
class PublicationService:
def __init__(self, root, dist, state, audit):
self.root, self.dist = Path(root), Path(dist)
self.directory, self.audit = Path(state) / "publication", audit
def current(self):
path = self.dist / "current"
if not path.exists():
return None
resolved = path.resolve()
if resolved.parent != self.dist.resolve() or not BUILD_ID_RE.fullmatch(resolved.name):
raise UnsafePathError("Некорректный указатель текущего релиза")
return resolved.name
def folder(self, identity):
if not BUILD_ID_RE.fullmatch(identity):
raise ReleaseMissing("Недопустимый ID релиза")
path = self.dist / identity
if path.is_symlink() or not path.is_dir():
raise ReleaseMissing("Релиз отсутствует или уже удалён")
return path
def manifest(self, identity):
return json.loads((self.folder(identity) / "manifest.json").read_text())
def read(self, name, default=None):
path = self.directory / name
return json.loads(path.read_text()) if path.is_file() else default
def write(self, name, data):
self.directory.mkdir(parents=True, exist_ok=True, mode=0o700)
atomic_write(self.directory / name, json.dumps(data, ensure_ascii=False, indent=2))
def provenance(self, identity):
return self.read(f"releases/{identity}.json") if identity else None
def sources(self):
result = {}
theme_file = load_site(self.root).site.theme_file
root_files = ROOT_FILES | ({theme_file} if theme_file else set())
for path in sorted(self.root.rglob("*")):
rel = path.relative_to(self.root)
if _SKIP_DIRS & set(rel.parts) or any(x.startswith(".") for x in rel.parts):
continue
if path.is_symlink():
raise UnsafePathError(f"Symlink не допускается в исходниках релиза: {rel}")
if not path.is_file() or (
rel.parts[0] not in TYPES and rel.as_posix() not in root_files
):
continue
raw = path.read_bytes()
kind = TYPES.get(rel.parts[0], "Config")
title, status, text = rel.name, "configuration", None
if kind in {"Page", "Entry"} and path.suffix == ".md":
try:
meta, _ = parse(raw.decode())
title, status = (
str(meta.get("title") or path.stem),
str(meta.get("status", "draft")),
)
except (ValueError, UnicodeError):
status = "invalid"
if len(raw) <= 524288 and path.suffix in {
".md",
".yaml",
".yml",
".css",
".js",
".j2",
".txt",
}:
try:
text = raw.decode()
except UnicodeError:
pass
result[rel.as_posix()] = {
"hash": hashlib.sha256(raw).hexdigest(),
"size": len(raw),
"title": title,
"status": status,
"type": kind,
"source": text,
}
return result
@staticmethod
def delta(now, before, unknown=False):
rows = []
for path in sorted(set(now) | set(before)):
a, b = now.get(path), before.get(path)
if a and b and a["hash"] == b["hash"]:
continue
row = a or b
rows.append(
{
"path": path,
"title": row["title"],
"type": row["type"],
"status": a["status"] if a else "deleted",
"kind": "unknown"
if unknown
else "new"
if not b
else "deleted"
if not a
else "modified",
"before": b,
"after": a,
}
)
return rows
def event(self, event, ctx, **fields):
self.audit.write(
"release_" + event, actor=ctx.principal.login, ip=ctx.ip, source=ctx.source, **fields
)
def activity(self):
path = self.audit.path
if not path.is_file():
return []
result = []
# Bounded tail; old events remain in the actual audit log.
with path.open("rb") as stream:
stream.seek(0, 2)
length = stream.tell()
stream.seek(max(0, length - 262144))
if length > 262144:
stream.readline()
for line in stream:
try:
item = json.loads(line)
except (ValueError, UnicodeError):
continue
if item.get("event", "").startswith("release_") or item.get("event") in {
"publish",
"rollback",
}:
result.append(
{
k: item[k]
for k in (
"ts",
"event",
"actor",
"object",
"errors",
"warnings",
"request_id",
)
if k in item
}
)
return result[-80:][::-1]
def state(self):
with SiteLock(self.root):
return self._state()
def _state(self):
live, current_sources = self.current(), self.sources()
baseline = self.provenance(live)
comparison = not live or baseline is not None
changes = self.delta(current_sources, (baseline or {}).get("sources", {}), not comparison)
candidate = self.read("candidate.json")
fingerprint = hash_tree(self.root)
renderer = render_fingerprint(load_site(self.root))
if candidate:
candidate = dict(candidate)
candidate["fresh"] = (
candidate["source_hash"] == fingerprint
and candidate["render_hash"] == renderer
and candidate["base"] == live
)
if not (self.dist / candidate["id"]).is_dir():
candidate["fresh"] = False
validation = self.read("validation.json")
if validation:
validation["fresh"] = (
validation["source_hash"] == fingerprint and validation["render_hash"] == renderer
)
history = []
if self.dist.is_dir():
for p in sorted(self.dist.iterdir(), reverse=True):
if BUILD_ID_RE.fullmatch(p.name) and p.is_dir() and not p.is_symlink():
m, provenance = self.manifest(p.name), self.provenance(p.name)
history.append(
{
"id": p.name,
"current": p.name == live,
"built_at": m.get("built_at"),
"pages": len(m.get("routes", [])),
"routes": m.get("routes", []),
"forms": self.forms(p.name),
"author": (provenance or {}).get("author"),
"comment": (provenance or {}).get("comment", ""),
"candidate": provenance is not None
and not provenance.get("published_at")
and p.name != live,
"comparison_available": provenance is not None,
}
)
return {
"current": live,
"changes": changes,
"comparison_available": comparison,
"source_hash": fingerprint,
"candidate": candidate,
"validation": validation,
"history": history,
"builds": self.read("builds.json", []),
"activity": self.activity(),
}
def forms(self, identity):
folder = self.folder(identity) / "_forms"
return sorted(p.stem for p in folder.glob("*.json"))
def validate(self, ctx):
with SiteLock(self.root):
reg, report = load_site(self.root), Report()
table = build_route_table(reg, report)
report.extend(validate_workspace(reg, table))
report.extend(validate_release(reg, table))
data = {
"source_hash": hash_tree(self.root),
"render_hash": render_fingerprint(reg),
"at": dt.datetime.now(dt.UTC).isoformat(),
"issues": [i.to_dict() for i in report.issues],
"errors": len(report.errors),
"warnings": len(report.warnings),
}
self.write("validation.json", data)
self.event("validate", ctx, errors=data["errors"], warnings=data["warnings"])
return data
def build(self, ctx, request_id=""):
with SiteLock(self.root):
started, base = dt.datetime.now(dt.UTC).isoformat(), self.current()
builds = self.read("builds.json", [])
completed = None
try:
sources = self.sources()
result = build_site(self.root, self.dist, activate=False)
completed = result.build_id
manifest = self.manifest(result.build_id)
candidate = {
"id": result.build_id,
"base": base,
"source_hash": result.source_hash,
"render_hash": manifest["render_hash"],
"at": started,
"author": ctx.principal.login,
"pages": result.pages,
"output_hash": hash_tree(result.output_dir),
"routes": manifest["routes"],
"issues": [i.to_dict() for i in result.report.issues],
}
prior = self.provenance(base)
changes = self.delta(
sources, (prior or {}).get("sources", {}), bool(base and prior is None)
)
candidate["changes"] = len(changes)
provenance = self.provenance(result.build_id)
# Identical build within one second can reuse an existing immutable release.
if provenance is None:
self.write(
f"releases/{result.build_id}.json", {"sources": sources, **candidate}
)
self.write("candidate.json", candidate)
builds.insert(
0,
{
"id": result.build_id,
"at": started,
"base": base,
"status": "ready",
"pages": result.pages,
"request_id": request_id,
"log": f"validate: OK\nrender: {result.pages} страниц\nsnapshot: {result.build_id}\nlive: не переключён",
},
)
self.write("builds.json", builds[:40])
self.event("build", ctx, object=result.build_id, request_id=request_id)
return candidate
except Exception as exc:
if completed is not None:
raise CandidateCommitError(completed) from exc
# Keep previous candidate and live intact; diagnostics are real, no simulated progress.
issues = (
[i.to_dict() for i in exc.report.issues] if isinstance(exc, EngineError) else []
)
builds.insert(
0,
{
"id": "",
"at": started,
"base": base,
"status": "failed",
"request_id": request_id,
"issues": issues,
"log": "Сборка не завершена. Live не переключён.\n"
+ (str(exc) if issues else "См. серверный traceback по ID запроса."),
},
)
try:
self.write("builds.json", builds[:40])
self.event("failure", ctx, request_id=request_id)
except OSError:
log.exception("release_failure_record_failed request_id=%s", request_id)
raise
def activate(self, identity, expected_live, comment, ctx, *, rollback=False):
with SiteLock(self.root):
actual = self.current()
if actual != expected_live:
raise ConflictError(
"Live изменился в другой вкладке. Обновите данные перед подтверждением.",
actual or "absent",
)
manifest = self.manifest(identity)
provenance = self.provenance(identity)
if (
rollback
and provenance
and not provenance.get("published_at")
and identity != actual
):
raise EngineError("Неопубликованный кандидат нельзя выбрать через откат")
if not rollback:
candidate = self.read("candidate.json")
if not candidate or candidate["id"] != identity:
raise ConflictError("Кандидат заменён. Проверьте актуальную сборку.", identity)
if (
candidate["base"] != actual
or candidate["source_hash"] != hash_tree(self.root)
or candidate["render_hash"] != render_fingerprint(load_site(self.root))
):
raise ConflictError(
"Кандидат устарел. Проверьте и пересоберите workspace.", identity
)
if not comment.strip():
raise ValueError("Добавьте комментарий к релизу")
if manifest.get("build_id") != identity:
raise EngineError("Manifest не соответствует выбранному релизу")
if provenance and provenance.get("output_hash") != hash_tree(self.folder(identity)):
raise EngineError("Файлы снимка изменились после сборки. Создайте новый кандидат.")
switch_current(self.dist, identity)
try:
if provenance:
provenance.update(published_at=dt.datetime.now(dt.UTC).isoformat())
if not rollback:
provenance.update(comment=comment.strip(), author=ctx.principal.login)
self.write(f"releases/{identity}.json", provenance)
if (self.read("candidate.json") or {}).get("id") == identity:
self.write("candidate.json", None)
self.event("rollback" if rollback else "publish", ctx, object=identity)
except OSError as exc:
raise ReleaseCommitError(identity) from exc
return {"current": identity, "committed": True}
def release_details(self, identity):
with SiteLock(self.root):
live = self.current()
target = self.folder(identity)
base = self.folder(live) if live else None
def outputs(folder):
if folder is None:
return {}
result = {}
for p in folder.rglob("*"):
if p.is_file():
rel = p.relative_to(folder).as_posix()
result[rel] = hashlib.sha256(
asset_path(folder, rel).read_bytes()
).hexdigest()
return result
before, after = outputs(base), outputs(target)
changes = [
{
"path": p,
"kind": "new"
if p not in before
else "deleted"
if p not in after
else "modified",
}
for p in sorted(before.keys() | after.keys())
if before.get(p) != after.get(p)
]
return {"id": identity, "base": live, "changes": changes}
def candidate_diff(self):
with SiteLock(self.root):
candidate = self.read("candidate.json")
if not candidate:
raise ReleaseMissing("Кандидат пока не создан")
snapshot = self.provenance(candidate["id"])
base = self.provenance(candidate["base"])
available = not candidate["base"] or base is not None
return {
"id": candidate["id"],
"base": candidate["base"],
"comparison_available": available,
"changes": self.delta(
(snapshot or {}).get("sources", {}),
(base or {}).get("sources", {}),
not available,
),
}
def compare(self, path):
safe_join(self.root, path)
with SiteLock(self.root):
live = self.current()
baseline = self.provenance(live)
now = self.sources().get(path)
before = (baseline or {}).get("sources", {}).get(path)
return {
"path": path,
"current": live,
"comparison_available": not live or baseline is not None,
"before": before,
"after": now,
}
def document_history(self, path):
safe_join(self.root, path)
if path.split("/", 1)[0] not in TYPES or any(p.startswith(".") for p in Path(path).parts):
raise UnsafePathError("История недоступна для этого пути")
folder = safe_join(self.root, ".engine/history/" + path)
versions = []
for p in sorted(folder.iterdir(), reverse=True) if folder.is_dir() else []:
if p.is_file() and not p.is_symlink():
versions.append({"id": p.name, "size": p.stat().st_size})
return {"path": path, "versions": versions[:20]}
def preview(self, identity, route, previews, principal):
with SiteLock(self.root):
manifest, folder = self.manifest(identity), self.folder(identity)
if route not in manifest.get("routes", []):
raise ReleaseMissing("Маршрут отсутствует в этом снимке")
html = asset_path(folder, route_to_output(route)).read_text()
return previews.store(
SimpleNamespace(root=folder),
html,
0,
principal,
f"release:{identity}:{route}",
passive=True,
)
+8 -33
View File
@@ -29,6 +29,7 @@ def release_info(dist: Path) -> dict:
"built_at": manifest.get("built_at"),
"routes": manifest.get("routes", []),
"page_sources": manifest.get("page_sources"),
"entry_sources": manifest.get("entry_sources"),
}
@@ -45,6 +46,8 @@ def filter_pages(pages, *, q="", status="", layout="", changed=False):
def workspace(root: Path, dist: Path, state: Path) -> dict:
from .entry_context import collection_rows
reg = load_site(root)
report = Report()
table = build_route_table(reg, report)
@@ -92,15 +95,7 @@ def workspace(root: Path, dist: Path, state: Path) -> dict:
return {
"site_name": reg.site.name,
"pages": sorted(pages, key=lambda p: p["route"]),
"collections": [
{
"id": c.id,
"name": c.name,
"total": len(reg.entries.get(c.id, [])),
"published": sum(e.status == "published" for e in reg.entries.get(c.id, [])),
}
for c in reg.collections.values()
],
"collections": collection_rows(reg),
"layouts": sorted(reg.layouts),
"issues": [i.to_dict() for i in report.issues],
"release": {k: release[k] for k in ("current", "built_at", "routes")},
@@ -113,36 +108,16 @@ def workspace(root: Path, dist: Path, state: Path) -> dict:
}
def entries(root: Path, collection: str) -> dict:
def entries(root: Path, collection: str, dist: Path | None = None) -> dict:
from .documents import DocumentMissing
reg = load_site(root)
c = reg.collections.get(collection)
if c is None:
raise DocumentMissing("Нет коллекции")
table = build_route_table(reg, Report())
routes = {
(r.collection.id, r.entry.slug): r.route for r in table.values() if r.collection and r.entry
}
items = reg.entries.get(c.id, [])
return {
"collection": {
"id": c.id,
"name": c.name,
"total": len(items),
"published": sum(e.status == "published" for e in items),
},
"entries": [
{
"slug": e.slug,
"title": str(e.data.get("title", e.slug)),
"status": e.status,
"file": e.file,
"route": routes.get((c.id, e.slug), "—"),
}
for e in items
],
}
from .entry_context import collection_context
return collection_context(reg, collection, dist)
def releases(dist: Path) -> dict:
+57 -45
View File
@@ -2,6 +2,7 @@
import json
import re
import secrets
from contextvars import ContextVar
from urllib.parse import quote
@@ -37,7 +38,13 @@ class AdminApplication:
)
def page(self, template, principal, section, status=200, **extra):
return page_result(render(template, **self.ctx(principal, section, **extra)), status)
result = page_result(render(template, **self.ctx(principal, section, **extra)), status)
# A boosted swap retains the starting document's CSP, including frame-src.
if self.previews.config:
result.headers["Content-Security-Policy"] = result.headers[
"Content-Security-Policy"
].replace("frame-src 'self'", "frame-src 'self' " + self.previews.config.preview)
return result
def message(self, principal, text, status, error=None):
return self.page(
@@ -89,10 +96,6 @@ class AdminApplication:
result.headers["Content-Security-Policy"] = result.headers[
"Content-Security-Policy"
].replace("style-src 'self'", "style-src 'self'; style-src-attr 'unsafe-inline'")
if self.previews.config:
result.headers["Content-Security-Policy"] = result.headers[
"Content-Security-Policy"
].replace("frame-src 'self'", "frame-src 'self' " + self.previews.config.preview)
return result
try:
if path in {"/setup/theme/skip", "/setup/theme/restart"}:
@@ -278,21 +281,20 @@ class AdminApplication:
if partial
else "page_builder.html.j2"
if snap["kind"] == "page"
else "document.html.j2"
else "content.html.j2"
)
result = self.page(
template, principal, "pages" if snap["kind"] == "page" else "content", status, **ctx
)
result.headers["X-Editor-Revision"] = str(snap["revision"])
if self.previews.config:
result.headers["Content-Security-Policy"] = result.headers[
"Content-Security-Policy"
].replace("frame-src 'self'", "frame-src 'self' " + self.previews.config.preview)
return result
async def dispatch(self, request):
json_post = request.method == "POST" and (
publication_json = request.url.path.startswith("/admin/publication/") and "application/json" in request.headers.get("accept", "")
json_post = publication_json or request.method == "POST" and (
request.url.path.startswith(("/admin/theme/", "/admin/setup/theme/"))
or (request.url.path.startswith("/admin/publication/")
and "application/json" in request.headers.get("accept", ""))
or (request.url.path.startswith("/admin/editor/")
and "application/json" in request.headers.get("accept", ""))
)
@@ -301,7 +303,7 @@ class AdminApplication:
if principal is None:
if json_post:
return self.json_failure(
401, "session_expired", "Сессия истекла. Скачайте YAML и войдите снова."
401, "session_expired", ("Сессия истекла. Войдите снова и обновите состояние публикации." if publication_json else "Сессия истекла. Скачайте YAML и войдите снова.")
)
if request.headers.get("hx-request"):
return page_result(
@@ -329,7 +331,7 @@ class AdminApplication:
token = _navigation.set(None)
try:
lightweight = request.url.path.startswith(
("/admin/editor/", "/admin/preview/")
("/admin/editor/", "/admin/preview/", "/admin/publication/")
) or (
request.method == "POST"
and request.url.path.startswith(("/admin/theme/", "/admin/setup/theme/"))
@@ -424,9 +426,10 @@ class AdminApplication:
**{k: data[k] for k in ("site_name", "pages", "collections", "paths")},
)
if path == "/content":
return self.page(
"content_index.html.j2", principal, "content", collections=data["collections"]
)
if data["collections"]:
return redirect_result("/admin/content/" + data["collections"][0]["id"])
return self.page("content.html.j2", principal, "content", snap=None,
empty_data={"collection": None, "collections": [], "entries": [], "display": "", "comparison_available": False, "live_build": None})
if (
query.get("status")
and query["status"] not in STATUSES
@@ -481,28 +484,15 @@ class AdminApplication:
match = re.fullmatch(r"/content/([a-z][a-z0-9_]*)", path)
if match and not post:
data = await api.call("GET", f"/collections/{match[1]}/entries")
if query.get("status") and query["status"] not in STATUSES:
return self.message(principal, "Проверьте status", 422)
data["entries"] = [
e
for e in data["entries"]
if (not query.get("status") or e["status"] == query["status"])
and query.get("q", "").casefold() in " ".join(str(v) for v in e.values()).casefold()
]
return self.page(
"entries_list.html.j2",
principal,
"content",
**data,
errors=[],
slug="",
filters=query,
)
if data["entries"]:
selected = next((e for e in data["entries"] if e["slug"] == query.get("selected")), data["entries"][0])
return redirect_result(f"/admin/content/{match[1]}/{selected['slug']}")
return self.page("content.html.j2", principal, "content", snap=None, empty_data=data)
match = re.fullmatch(r"/content/([a-z][a-z0-9_]*)/new", path)
if match and post:
try:
snap = await api.call(
"POST", f"/collections/{match[1]}/entries", {"id": form.first("slug").strip()}
"POST", f"/collections/{match[1]}/entries", {"id": form.first("slug").strip() or "entry-" + secrets.token_hex(3)}
)
except ApiError as exc:
if exc.status >= 500:
@@ -512,18 +502,38 @@ class AdminApplication:
data = await api.call("GET", f"/collections/{match[1]}/entries")
return exc.annotate(
self.page(
"entries_list.html.j2",
principal,
"content",
exc.status,
**data,
errors=[str(exc)],
slug=form.first("slug"),
filters={},
"content.html.j2", principal, "content", exc.status,
snap=None, empty_data=data, content_error=str(exc),
)
)
return redirect_result(f"/admin/content/{match[1]}/{snap['id']}")
if path == "/publish" or path.startswith("/publish/rollback/"):
if path.startswith("/publication/"):
operation = path.removeprefix("/publication/")
if operation not in {"state", "validate", "build", "activate", "rollback", "compare", "candidate-diff", "release", "document-history", "preview"}:
return self.json_failure(404, "not_found", "Операция публикации не найдена")
try:
if post:
if operation not in {"validate", "build", "activate", "rollback", "preview"}:
return self.json_failure(405, "method_not_allowed", "Операция доступна только для чтения")
submitted = json.loads(form.first("payload") or "{}")
result = await api.call("POST", "/publication/" + operation, submitted)
else:
if operation not in {"state", "compare", "candidate-diff", "release", "document-history"}:
return self.json_failure(405, "method_not_allowed", "Для операции требуется POST")
endpoint = "/publication" if operation == "state" else "/publication/" + operation + ("?path=" + quote(query.get("path", ""), safe="") if operation in {"compare", "document-history"} else "")
if operation == "release":
endpoint += "?id=" + quote(query.get("id", ""), safe="")
result = await api.call("GET", endpoint)
return self.json_result(result)
except (ValueError, TypeError):
return self.json_failure(422, "request_validation", "Некорректный запрос публикации")
except ApiError as exc:
return exc.annotate(self.json_result(exc.data, exc.status))
if path == "/publish" and not post:
data = await api.call("GET", "/publication")
result = self.page("publication.html.j2", principal, "publish", boot={"state": data, "csrf": self.auth.csrf_token(principal), "tab": query.get("tab", "changes")})
return result
if path in {"/publish", "/publish/legacy"} or path.startswith("/publish/rollback/"):
endpoint = (
"/releases"
if not post
@@ -588,11 +598,13 @@ class AdminApplication:
submitted = json.loads(form.first("payload"))
except (ValueError, TypeError):
return self.json_failure(422, "request_validation", "Некорректный запрос редактора")
if op not in {"update", "save"}:
if op not in {"update", "save", "duplicate", "delete", "check"}:
return self.json_failure(422, "invalid_operation", "Неизвестная операция редактора")
try:
payload = await api.call("POST", endpoint + "/" + op, submitted)
if op == "save":
if op in {"delete", "check"}:
return self.json_result(payload)
if op in {"save", "duplicate"}:
payload = {"snapshot": payload, "preview": None, "preview_error": None}
payload["projection"] = self.editor_projection(principal, payload["snapshot"], docpath, form)
return self.json_result(payload)
+1 -1
View File
@@ -35,7 +35,7 @@ def build_view(fd: FieldDef, raw: Any, name: str, ctx: Mapping[str, Any]) -> dic
view: dict[str, Any] = {
"name": name, "key": fd.key, "label": label_of(fd), "type": t, "required": fd.required,
"hint": fd.extra.get("hint"), "bind": "", "value": "", "options": [], "children": [],
"rows": [], "kind": "input", "datalist": [],
"rows": [], "kind": "input", "datalist": [], "to": fd.to,
}
if _is_bind(raw):
view["bind"] = str(raw["bind"])
+1 -1
View File
@@ -125,7 +125,7 @@ class AdminHandlers:
ctx["site_error"] = str(exc)
return _page(render("dashboard.html.j2", **ctx))
_STATIC: ClassVar[dict[str, str]] = {"theme-studio.css": "text/css; charset=utf-8",
_STATIC: ClassVar[dict[str, str]] = {"publication.css": "text/css; charset=utf-8", "publication-adapter.css": "text/css; charset=utf-8", "publication.js": "text/javascript; charset=utf-8", "publication-icons.json": "application/json","favicon.svg": "image/svg+xml","content-editor.css": "text/css; charset=utf-8", "content-adapter.css": "text/css; charset=utf-8", "content-editor.js": "text/javascript; charset=utf-8", "theme-studio.css": "text/css; charset=utf-8",
"theme-studio.js": "text/javascript; charset=utf-8","admin.css": "text/css; charset=utf-8",
"builder.css": "text/css; charset=utf-8", "builder-adapter.css": "text/css; charset=utf-8",
"builder.js": "text/javascript; charset=utf-8",
@@ -26,3 +26,25 @@ SVG в `templates/_builder_icons.html.j2` извлечены тем же скр
Адаптации находятся в `builder-adapter.css`/`builder.js`; исходный `builder.css` вручную не редактируется. Тёмные токены сопоставлены с утверждённым Antirion Rework. Проверка воспроизводимости без записи: `python scripts/sync_builder_design.py --check`. Отдельная frontend-сборка/Node/CDN не требуются.
`preview.css` переносит оформление выделения/hover и бейдж SELECTED из `previewCss` в `design/assets/builder.js` на служебные `data-preview-*` маркеры настоящих блоков. Этот CSS добавляется только в снимки предпросмотра; публичная сборка его не получает.
## Content Editor (этап 4)
`content-editor.css` генерируется `scripts/sync_content_design.py` из исходных `design/assets/builder.css` и `design/assets/content-editor.css`. Декларации, breakpoints и специфичность сохраняются; обычные селекторы ограничены `.entry-content-editor`, без CSS `@scope`. SVG paths извлечены из `icon()` оригинального content-editor.js; stroke-width 1.7 сохранён. Подсветка Expert перенесена из `highlightSource()`, с обязательным экранированием текста.
- `design/assets/builder.css`: SHA-256 `77b5864a5e9c1c0475515f8b0d305514f032c4690f1a06da809395ebe5e399c4`.
- `design/assets/content-editor.css`: SHA-256 `95cd9520f278dd86a4411653e0384ef87a9b7b96508d2bd41d18a57f7e33296f`.
- `design/assets/content-editor.js`: SHA-256 `fd4fe384c33d99da39806b226277aeda953bf2c44b445eaa59d2c1a7f37b79dd`.
- `src/site_engine/web/admin/static/content-editor.css`: SHA-256 `c160a5f94388d60f71c58e9df7ad8f90ea85f648287fdefda8525f75e0921a26`.
Адаптации семантических ссылок/форм, native dialog, CSP/iframe и высоты под принятый shell — отдельные `content-adapter.css` и `content-editor.js`. Данные, YAML, CAS, зависимости и preview поступают из FastAPI через существующий HTML adapter; mock codec/storage не переносятся. Проверка воспроизводимости: `python scripts/sync_content_design.py --check`.
## Publication (этап 5)
Источник композиции/диалогов/поведения — `design/publication-antirion.html` и `design/assets/publication.js`. `scripts/sync_publication_design.py` переносит декларации/breakpoints исходного publication.css, ограничивая селекторы `.publication-content`, и извлекает оригинальные SVG paths/stroke-width 1.7 в `_publication_icons.html.j2` и локальный `publication-icons.json`. Runtime не требует design/.
- `design/assets/publication.css`: SHA-256 `93534dbc55f29c1f3600631433bdff2cb81f896dd3849817e0feb8f57616b645`.
- `design/assets/publication.js`: SHA-256 `3d40fe2fe037b5b5713adf0be2b4403ef9542c4fc4910d0f36198f828cf13dbc`.
- `src/site_engine/web/admin/static/publication.css`: SHA-256 `45a07f20e19b07939982d9cc6cf166bf9a9b64fa52434c7861b2a11b65eec74e`.
- `src/site_engine/web/admin/static/publication-icons.json`: SHA-256 `68ee8f4b7f11b8381365569551f2a0ddb401aab5fab8c461fe3ca01e3e6edd5a`.
Адаптация к существующим FastAPI/HTML endpoints, реальным данным, CSP/native dialog, async busy/error и принятой тёмной палитре находится отдельно в `publication.js` и `publication-adapter.css`. Исходники дизайна не редактируются. Воспроизводимая проверка: `python scripts/sync_publication_design.py --check`. Node/CDN/frontend-сборка не требуются.
@@ -0,0 +1,32 @@
/* HTML/CSP/iframe adapters only. Geometry and component styles are generated from design/. */
.content.content-screen{padding:0}
.entry-content-editor [hidden]{display:none!important}
.entry-content-editor #editor-result{display:contents}
.entry-content-editor form{margin:0}
.entry-content-editor[data-ready='1'][data-mode='constructor'] #expert-pane,
.entry-content-editor[data-ready='1'][data-mode='expert'] [data-constructor]{display:none}
.entry-content-editor #preview-result iframe{display:block;width:100%;height:600px;border:0;background:#fff}
.entry-content-editor #preview-result[data-view='card'] iframe{height:340px}
.entry-content-editor .field-label{display:flex}
.entry-content-editor .list-edit-row>.entry-field{flex:1;min-width:0}
.entry-content-editor .file-picker input{min-width:0;flex:1}
.entry-content-editor .ref-pills input{width:100%}
.entry-content-editor .status:before{display:none}
.entry-content-editor dialog.stage4-dialog{padding:0;position:fixed;margin:auto}
.entry-content-editor dialog.stage4-dialog::backdrop{background:#0009}
.entry-content-editor .dialog-mask{position:static;background:transparent;padding:0}
.entry-content-editor .conflict-panel textarea{width:100%;min-height:220px}
@media(prefers-reduced-motion:reduce){.entry-content-editor *{transition:none!important;scroll-behavior:auto!important}}
body[data-skin='dark'] .entry-content-editor{color-scheme:dark;--bg:var(--paper);--surface:var(--paper);--surface2:var(--paper2);--surface3:var(--paper3);--text:var(--ink);--muted:var(--secondary);--border:var(--stroke);--border2:var(--stroke2);--accent:#aba2ff;--focus:#b9b2ff;--dim:#777a7d;--accentSoft:var(--accent2);--accentText:var(--paper);--positive:var(--good);--positiveBg:var(--goodbg);--warning:var(--warn);--warningBg:var(--warnbg);--danger:var(--error);--dangerBg:var(--errorbg);--previewOuter:var(--paper2);--shadow:0 10px 30px #0003}
/* Native typed-link controls retain the source mini-field input geometry. */
.entry-content-editor .mini-field select{background:var(--surface2);color:var(--text);border:1px solid var(--border);padding:9px 10px;width:100%;min-width:0;border-radius:var(--radius);font-size:11px;outline:none}
.entry-content-editor .mini-field select:focus{border-color:var(--accent)}
.entry-content-editor .diff-row span{overflow-wrap:anywhere;white-space:pre-wrap}
.entry-content-editor .conflict-grid pre{white-space:pre-wrap;overflow-wrap:anywhere}
/* The accepted shell's header is measured instead of the prototype's fixed 60px. */
@media(min-width:1261px){.entry-content-editor .entry-workspace{height:var(--content-workspace-height,calc(100dvh - 211px))}}
.entry-content-editor .workspace-footer>span{min-width:0;overflow-wrap:anywhere}
File diff suppressed because one or more lines are too long
@@ -0,0 +1,118 @@
/* Content UI from design/assets/content-editor.js; persistence and parsing belong to FastAPI. */
(() => {
'use strict';
const $=(s,r=document)=>r?.querySelector(s), $$=(s,r=document)=>Array.from(r?.querySelectorAll(s)||[]);
const root=()=>$('.entry-content-editor');
const esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
let filter='all',tab='fields';
function size(){const workspace=$('.entry-workspace',root()),footer=$('.workspace-footer',root());if(workspace&&footer&&innerWidth>1260){const height=Math.max(0,innerHeight-workspace.getBoundingClientRect().top-scrollY-footer.getBoundingClientRect().height);root().style.setProperty('--content-workspace-height',height+'px');}}
const sizes=new ResizeObserver(size);
function layout(){sizes.disconnect();if(root()){$$('.entry-head,.workspace-footer',root()).forEach(e=>sizes.observe(e));size();}}
addEventListener('resize',size);
function data(){try{return JSON.parse($('[data-content-navigation]')?.content.textContent||'{}');}catch{return {};}}
function error(e){window.siteAdminError?.(e,e.status);window.siteDocument?.notice(e.message||'Не удалось выполнить запрос.');}
function modal(title,html,actions=[],wide=false){
const previous=document.activeElement,dialog=document.createElement('dialog');
dialog.className='stage4-dialog'+(wide?' wide-dialog':'');
dialog.innerHTML=`<div class="dialog-header"><div><div class="eyebrow">SITE ENGINE / CONTENT</div><h2 id="content-dialog-title">${esc(title)}</h2></div><button type="button" class="button small" data-content-close aria-label="Закрыть">×</button></div><div class="dialog-body">${html}</div><div class="dialog-actions"></div>`;
dialog.setAttribute('aria-labelledby','content-dialog-title');
dialog.addEventListener('click',e=>{const r=dialog.getBoundingClientRect();if(e.target===dialog&&(e.clientX<r.left||e.clientX>r.right||e.clientY<r.top||e.clientY>r.bottom))dialog.close();});
for(const action of actions.length?actions:[{label:'Закрыть'}]){
const button=document.createElement('button');button.type='button';button.className='button '+(action.style||'');button.textContent=action.label;
button.addEventListener('click',async()=>{try{if(action.run){button.disabled=true;try{await action.run(dialog);}finally{if(button.isConnected)button.disabled=false;}}else dialog.close();}catch(e){error(e);}});$('.dialog-actions',dialog).append(button);
}
$('[data-content-close]',dialog).onclick=()=>dialog.close();
dialog.addEventListener('close',()=>{dialog.remove();if(previous?.isConnected)previous.focus({preventScroll:true});},{once:true});
$('#content-overlay',root()).append(dialog);dialog.showModal();return dialog;
}
window.siteContentConfirm=(title,message,label)=>new Promise(resolve=>{
const d=modal(title,`<p>${esc(message)}</p>`,[{label:'Остаться'},{label,style:'danger',run:d=>{resolve(true);d.close();}}]);
d.addEventListener('close',()=>resolve(false),{once:true});
});
window.siteContentConflict=(e,source,accept)=>{
modal('409 · Conflict',`<div class="issue-callout">Файл изменён на сервере. Ваш исходник остаётся в редакторе.</div><div class="conflict-grid"><div><b>Моя версия / workspace</b><pre>${esc(source)}</pre></div><div><b>Версия на сервере</b><pre>${esc(e.current.source)}</pre></div></div><label class="switch-line"><input type="checkbox" data-accept-base-check> Принимаю серверную версию как новую основу</label>`,[{label:'Закрыть'},{label:'Принять серверную версию как основу',style:'primary',run:d=>{const check=$('[data-accept-base-check]',d);if(!check.checked){check.focus();return;}accept();d.close();}}],true);
};
function setTab(next){tab=next;$$('[data-content-tab]',root()).forEach(e=>{e.classList.toggle('active',e.dataset.contentTab===tab);e.setAttribute('aria-selected',String(e.dataset.contentTab===tab));});$$('[data-content-panel]',root()).forEach(e=>e.hidden=e.dataset.contentPanel!==tab);}
function list(){const query=($('#entry-query')?.value||'').toLocaleLowerCase();let shown=0;const rows=$$('[data-entry]',root());for(const row of rows){row.hidden=!(row.dataset.entrySearch.includes(query)&&(filter==='all'||(filter==='changed'?row.dataset.entryChanged==='1':row.dataset.entryStatus===filter)));if(!row.hidden)shown++;}const empty=$('[data-content-list-empty]');if(empty)empty.hidden=!!shown;const count=$('[data-content-list-count]');if(count)count.textContent=`${shown} из ${rows.length}`;}
function highlightSource(source){let fences=0;return source.split('\n').map(line=>{
if(line==='---'){fences++;return '<span class="hl-fence">---</span>';}
const raw=esc(line);if(fences<2){if(/^\s*#/.test(line))return '<span class="hl-comment">'+raw+'</span>';const m=line.match(/^(\s*-?\s*[\w.-]+)(:)(.*)$/);if(m)return '<span class="hl-key">'+esc(m[1])+'</span><span class="hl-punc">:</span><span class="hl-value">'+esc(m[3])+'</span>';return raw;}
return /^#{1,6} /.test(line)?'<span class="hl-heading">'+raw+'</span>':raw;
}).join('\n');}
function source(){const input=$('#document-source',root());if(!input)return;$('#code-lines').innerHTML=input.value.split('\n').map((_,i)=>i+1).join('<br>');$('#entry-highlight').innerHTML=highlightSource(input.value)+'\n';const status=$('[data-content-source-status]');if(status)status.textContent=window.siteDocument?.state?.busy?'Проверка…':'Синхронизирован';}
function change(input){
const label=$$('[data-content-picked]').find(e=>e.dataset.contentPicked===input.name);if(label)label.textContent=input.value||'Файл не выбран';
const tokens=$$('[data-content-tokens]').find(e=>e.dataset.contentTokens===input.name);if(tokens)tokens.innerHTML=input.value.split(/[,\s]+/).filter(Boolean).map(value=>{const ref=tokens.dataset.refTarget==='*'?value:tokens.dataset.refTarget+'/'+value;return `<a class="ref-token" href="/admin/content/${ref.split('/').map(encodeURIComponent).join('/')}">${esc(value)} ${$('[data-content-ref-arrow]').innerHTML}</a>`;}).join('');
window.siteDocument.change(input);
}
function picker(button){
const input=$$('[name]',root()).find(e=>e.name===button.dataset.contentPicker),options=JSON.parse(button.dataset.pickerOptions||'[]'),type=button.dataset.pickerType;
if(!input)return;
const selected=new Set(type==='refs'?input.value.split(',').map(s=>s.trim()):[input.value]);
const optionValue=o=>typeof o==='string'?o:o.value;
const titles=window.siteDocument.state?.schema?.choices?.entry_titles||{};
const label=o=>typeof o==='string'?(titles[button.dataset.pickerTarget==='*'?o:button.dataset.pickerTarget+'/'+o]||o):(o.label||o.value);
let d;
if(type==='asset'){
d=modal('Выбор медиафайла',`<p>Связь Entry → Asset · ${esc(input.name)}</p><div class="asset-options">${options.map((o,i)=>`<button type="button" class="asset-option ${selected.has(optionValue(o))?'selected':''}" data-option="${i}"><span><b>${esc(label(o))}</b><small class="mono">${esc(optionValue(o))}</small></span></button>`).join('')||'<p>В assets пока нет файлов.</p>'}</div>`,[{label:'Очистить',run:d=>{input.value='';change(input);d.close();}},{label:'Отмена'}]);
$$('[data-option]',d).forEach(b=>b.onclick=()=>{input.value=optionValue(options[Number(b.dataset.option)]);change(input);d.close();});
}else{
d=modal('Выбор связанных записей',`<p>${esc(input.name)}</p><div class="ref-choices">${options.map((o,i)=>`<label class="ref-choice"><input type="${type==='refs'?'checkbox':'radio'}" name="content-reference-choice" value="${i}" ${selected.has(optionValue(o))?'checked':''}><span><b>${esc(label(o))}</b><small class="mono">${esc(optionValue(o))}</small></span></label>`).join('')||'<p>Нет подходящих записей.</p>'}</div>`,[{label:'Отмена'},{label:'Применить',style:'primary',run:d=>{input.value=$$('input:checked',d).map(e=>optionValue(options[Number(e.value)])).join(', ');change(input);d.close();}}]);
}
}
async function request(operation,extra={}){
const s=window.siteDocument.state,form=$('#buffer-form'),body=new FormData();body.set('csrf',form.elements.csrf.value);body.set('payload',JSON.stringify({source:s.source,etag:s.etag,revision:s.revision,...extra}));
let response;try{response=await fetch('/admin/editor'+s.base+'/'+operation,{method:'POST',credentials:'same-origin',headers:{'Accept':'application/json','HX-Request':'true'},body});}catch{throw {code:'network_error',message:'Нет связи с сервером. Правки остаются в редакторе.'};}
let result;try{result=await response.json();}catch{throw {code:'invalid_response',message:'Сервер вернул некорректный ответ.',status:response.status};}if(!response.ok)throw {...result.error,status:response.status};return result;
}
async function validate(){
// Flush syntax/queued field edits first; malformed Expert text still gets diagnostics.
await window.siteDocument.flush();const result=await request('check'),issues=result.issues,errors=issues.filter(i=>i.severity==='error').length;
const d=modal('Проверка записи',`<div class="review-summary"><div class="review-count"><b>${errors}</b><span>ошибок · блокируют публикацию</span></div><div class="review-count"><b>${issues.length-errors}</b><span>предупреждений</span></div><div class="review-count"><b>1</b><span>запись проверена</span></div></div><div class="review-list">${issues.map((i,n)=>`<button type="button" class="review-item ${esc(i.severity)}" data-issue="${n}"><span class="issue-label">${i.severity==='error'?'ERROR':'WARN'}</span><span><b>${esc(i.message)}</b><small>${esc(i.code)} · ${esc(i.path)}</small></span></button>`).join('')||'<div class="clean-state">✓ Ошибок и предупреждений нет</div>'}</div><div class="note-inline">Неполный черновик можно сохранить. Строгая проверка выполняется перед публикацией.</div>`);
$$('[data-issue]',d).forEach(b=>b.onclick=()=>{const issue=issues[Number(b.dataset.issue)];d.close();setTab('fields');const field=issue.path.split(/[:.]/).at(-1),input=$$('[name]',root()).find(e=>e.name==='p.'+field||e.name===field);if(input&&window.siteDocument.state.mode==='constructor'){input.focus();input.scrollIntoView({block:'center'});}else{$('[data-editor-mode=expert]').click();$('#document-source').focus();}});
}
async function duplicate(){if(!await window.siteDocument.flush())return;const revision=window.siteDocument.state.revision,navigation=data(),id=root().dataset.contentSource;let name=id+'-copy';while(navigation.entries.some(e=>e.slug===name))name+='-2';try{const result=await request('duplicate',{id:name});const go=()=>location.assign('/admin/content/'+navigation.collection.id+'/'+result.snapshot.id);if(window.siteDocument.state.revision===revision)go();else await window.siteDocument.leave(go);}catch(e){if(e.committed)window.siteDocument.notice('Копия создана, но аудит недоступен: '+e.committed.id);throw e;}}
async function remove(){
if(!await window.siteDocument.flush())return;
if(window.siteDocument.state.model?.meta.status==='published')throw {code:'published_entry',message:'Сначала архивируйте запись и сохраните её; затем можно удалить файл.'};
const d=modal('Удалить запись?',`<div class="issue-callout">Удаление файла ${esc(window.siteDocument.state.path)}. Запись будет удалена из workspace; опубликованный релиз сохранится.</div>`,[{label:'Отмена'},{label:'Удалить из workspace',style:'danger',run:async d=>{try{await request('delete');location.assign('/admin/content/'+data().collection.id);}catch(e){d.close();if(e.deleted){window.siteDocument.notice(e.message);$$('[data-content-delete],[data-save-document]').forEach(b=>b.disabled=true);}throw e;}}}]);return d;
}
function diff(){const s=window.siteDocument.state,a=s.saved.split('\n'),b=s.source.split('\n');modal('Сравнение исходника',`<p>Последний сохранённый черновик ↔ текущее рабочее состояние</p><div class="diff-table"><div class="diff-head"><b>Saved draft</b><b>Workspace</b></div>${Array.from({length:Math.max(a.length,b.length)},(_,i)=>`<div class="diff-row ${(a[i]||'')!==(b[i]||'')?'changed':''}"><span>${esc(a[i])}</span><span>${esc(b[i])}</span></div>`).join('')}</div>`,[],true);}
function find(){const d=modal('Поиск в исходнике','<label class="entry-field">Строка поиска<input type="search" data-source-query autocomplete="off"></label>',[{label:'Отмена'},{label:'Найти',style:'primary',run:d=>{const q=$('[data-source-query]',d).value;if(!q)return;const input=$('#document-source'),i=input.value.toLowerCase().indexOf(q.toLowerCase());if(i<0){window.siteDocument.notice('Строка не найдена.');return;}d.close();input.focus();input.setSelectionRange(i,i+q.length);}}]);$('[data-source-query]',d).focus();}
document.addEventListener('click',e=>{
if(!root()?.contains(e.target))return;const b=e.target.closest('button');if(!b)return;
const work=async()=>{
if(b.dataset.contentTab)setTab(b.dataset.contentTab);
if(b.dataset.contentFilter){filter=b.dataset.contentFilter;$$('[data-content-filter]').forEach(el=>el.classList.toggle('active',el===b));list();}
if(b.dataset.contentPicker)picker(b);
if(b.dataset.contentConfigure){setTab('fields');const button=$$('[data-content-picker]').find(el=>el.dataset.contentPicker===b.dataset.contentConfigure);if(button)picker(button);else{const input=$$('[name]').find(el=>el.name===b.dataset.contentConfigure+'.target');input?.focus();input?.scrollIntoView({block:'center'});}}
if(b.dataset.contentAdd){const list=$$('[data-list-name]').find(el=>el.dataset.listName===b.dataset.contentAdd),blank=$(':scope > .blank[hidden]',list);if(blank){blank.hidden=false;$('input:not([type=hidden]):not([type=checkbox]),textarea,select',blank)?.focus();}}
if(b.dataset.contentRemove){const row=b.closest('[data-list-row]'),input=$(':scope > [data-list-delete] input',row);input.checked=true;row.hidden=true;change(input);}
if(b.hasAttribute('data-content-validate'))await validate();
if(b.hasAttribute('data-content-duplicate'))await duplicate();
if(b.hasAttribute('data-content-delete'))await remove();
if(b.hasAttribute('data-content-apply'))await window.siteDocument.flush(true);
if(b.hasAttribute('data-content-diff')){await window.siteDocument.flush();diff();}
if(b.hasAttribute('data-content-find'))find();
if(b.dataset.contentPreview||b.dataset.contentVersion){await window.siteDocument.preview(b.dataset.contentPreview,b.dataset.contentVersion);}
};work().catch(error);
});
document.addEventListener('input',e=>{if(!root()?.contains(e.target))return;if(e.target.id==='entry-query')list();if(e.target.id==='document-source')source();if(e.target.dataset.contentBool){const input=$$('input[name]',e.target.closest('.entry-field')).find(el=>el.name===e.target.dataset.contentBool);input.value=String(e.target.checked);e.target.nextElementSibling.textContent=e.target.checked?'Включено':'Выключено';}},true);
document.addEventListener('scroll',e=>{if(root()?.contains(e.target)&&e.target.id==='document-source'){const h=$('#entry-highlight'),l=$('#code-lines');h.scrollTop=e.target.scrollTop;h.scrollLeft=e.target.scrollLeft;l.scrollTop=e.target.scrollTop;}},true);
document.addEventListener('document:projection',e=>{
if(!root()?.contains(e.target))return;const doc=e.detail?.html&&new DOMParser().parseFromString(e.detail.html,'text/html');
if(doc){for(const selector of ['[data-content-navigation]','[data-content-diagnostics]','[data-content-panel=relations]','[data-content-panel=usage]','[data-content-panel=schema]']){const old=$(selector,root()),fresh=$(selector,doc);if(old&&fresh)old.replaceWith(fresh);}}
$$('[data-list-row]').forEach(row=>{const b=$(':scope > [data-content-remove]',row);if(b)b.dataset.contentRemove=row.dataset.listRow;});setTab(tab);source();
});
document.addEventListener('document:state',()=>{
if(!root())return;const s=window.siteDocument?.state;if(!s)return;source();const title=$('[data-inspector] [name="p.title"]')?.value||s.model?.meta.title||root().dataset.contentSource;const heading=$('[data-entry-title]');if(heading)heading.textContent=title;
const row=$$('[data-entry]').find(e=>e.dataset.entry===root().dataset.contentSource),entry=data().entries?.find(e=>e.slug===root().dataset.contentSource);
if(row&&s.model){$('.entry-row-copy>b',row).textContent=title;row.dataset.entrySearch=(title+' '+row.dataset.entry).toLocaleLowerCase();row.dataset.entryStatus=s.model.meta.status||'draft';row.dataset.entryChanged=String(Number(s.dirty||entry?.changed));const badge=$('.status',row);badge.textContent=({published:'В каталоге',draft:'Черновик',archived:'Архив'})[row.dataset.entryStatus];badge.classList.toggle('good',row.dataset.entryStatus==='published');badge.classList.toggle('warn',row.dataset.entryStatus!=='published');}list();
const box=$('#preview-result');box.dataset.view=root().dataset.previewView||'card';box.classList.toggle('site-card-preview',box.dataset.view==='card');box.classList.toggle('site-page-preview',box.dataset.view==='page');
for(const [attr,key,fallback] of [['preview','previewView','card'],['version','previewVersion','workspace']])$$('[data-content-'+attr+']').forEach(b=>{const active=b.dataset['content'+attr[0].toUpperCase()+attr.slice(1)]===(root().dataset[key]||fallback);b.classList.toggle('active',active);b.setAttribute('aria-pressed',String(active));});
$('[data-content-preview-state]').textContent=(root().dataset.previewVersion||'workspace')+' / '+(s.model?.meta.status||'draft');
const issues=s.issues||[];const messages=$('[data-content-source-errors]');if(messages)messages.textContent=issues.map(i=>i.code+' · '+i.message).join('\n');
});
document.addEventListener('keydown',e=>{if(!root()||!window.siteDocument.state)return;if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='s'){e.preventDefault();$('[data-save-document]').click();}if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='f'&&e.target.id==='document-source'){e.preventDefault();find();}if((e.ctrlKey||e.metaKey)&&e.key==='Enter'&&e.target.id==='document-source'){e.preventDefault();window.siteDocument.flush(true).catch(error);}});
document.addEventListener('htmx:load',()=>{layout();if(root()){list();source();}});if(root()){list();source();layout();}
})();
+19 -16
View File
@@ -106,7 +106,7 @@
if(parent.moveBefore)parent.moveBefore(node,one('#expert-pane',s.root));else{window.siteDocument.previewReloading();parent.insertBefore(node,one('#expert-pane',s.root));}
}
function choose(block,scroll=true,bindings=false){
const s=current;if(!s?.valid)return;
const s=current;if(!s?.valid||s.root.classList.contains('entry-content-editor'))return;
if(s.page){
const t=Array.from(s.root.querySelectorAll('[data-section-inspector]')).find(e=>e.dataset.blockId===block.id&&e.dataset.blockScope===block.scope&&e.dataset.blockOwner===block.owner);if(!t)return;
const pane=t.content.querySelector('#inspectpane').cloneNode(true);hydrate(pane);movePreviewOut();one('#inspectpane',s.root).replaceWith(pane);
@@ -144,10 +144,10 @@
const form=Array.from(s.root.querySelectorAll('[data-inspector]')).find(e=>keyOf(fields(e))===key);if(!form)continue;
const active=document.activeElement,wasInside=form.contains(active);
form.querySelectorAll('[data-list-row]').forEach(row=>{if(rename(row.dataset.listRow)===null)row.remove();});
form.querySelectorAll('[name],[data-list-name],[data-list-row],[id^="dl-"],[list^="dl-"]').forEach(node=>{
for(const attr of ['name','data-list-name','data-list-row','id','list']){
const value=node.getAttribute(attr);if(!value||(['id','list'].includes(attr)&&!value.startsWith('dl-')))continue;
const prefix=['id','list'].includes(attr)?'dl-':'',next=rename(value.slice(prefix.length));if(next!==null)node.setAttribute(attr,prefix+next);
form.querySelectorAll('[name],[data-list-name],[data-list-row],[id],[for],[data-field-container],[data-content-picker],[data-content-picked],[data-content-tokens],[data-content-bool],[data-content-add],[data-content-remove]').forEach(node=>{
for(const attr of ['name','data-list-name','data-list-row','id','list','for','data-field-container','data-content-picker','data-content-picked','data-content-tokens','data-content-bool','data-content-add','data-content-remove']){
const value=node.getAttribute(attr);if(!value||(['id','list','for'].includes(attr)&&!value.startsWith('dl-')&&!value.startsWith('content-')))continue;
const prefix=['id','list','for'].includes(attr)?(value.startsWith('dl-')?'dl-':'content-'):'',next=rename(value.slice(prefix.length));if(next!==null)node.setAttribute(attr,prefix+next);
}
});
if(wasInside&&!active.isConnected)one('input:not([type=hidden]),textarea,select',form)?.focus({preventScroll:true});
@@ -223,7 +223,7 @@
if(replaceInspector&&!s.readonlySelection&&s.entryInspector){const pane=s.entryInspector.cloneNode(true);hydrate(pane);one('.doc-inspector')?.replaceWith(pane);}
}
if(!replaceInspector)reconcileInspector();
syncSelection();s.root.dispatchEvent(new CustomEvent('document:projection',{bubbles:true}));
syncSelection();s.root.dispatchEvent(new CustomEvent('document:projection',{bubbles:true,detail:{html}}));
}
function passive(frame){
const s=current,p=s?.preview;if(!p||p.interactive||p.document)return;
@@ -240,6 +240,7 @@
function displayPreview(value){
const s=current;if(value.revision!==s.rev)return;
const box=one('#preview-result'),frame=one('iframe',box),p=s.preview;
if(!value.url){const text=document.createElement('p');text.className='preview-empty';text.textContent=value.message||'Превью недоступно.';box.replaceChildren(text);s.preview={...value,ready:true};box.dataset.revision=String(value.revision);status();return;}
if(frame&&p?.ready&&value.html){
if(p.document&&p.document===frame.contentDocument){
window.sitePreviewDocument(p.document,value.html);Object.assign(p,value,{ready:true,document:p.document});
@@ -277,16 +278,17 @@
s.requestSelection=s.selection;
s.running=(async()=>{
try{
const result=await post(s,'update',{source,etag:s.etag,revision:rev,operations});
const result=await post(s,'update',{source,etag:s.etag,revision:rev,operations,preview_view:s.root.dataset.previewView||'page',preview_version:s.root.dataset.previewVersion||'workspace'});
if(!alive(s))return false;
if(result.snapshot.revision!==rev)throw {code:'revision_mismatch',message:'Ответ редактора относится к другой версии.'};
s.model=result.snapshot.model;s.schema=result.snapshot.schema;s.issues=result.snapshot.issues;
acknowledgeDeletes(batch);
for(const [key,edit]of batch)if(s.edits.get(key)===edit)s.edits.delete(key);
if(s.sourceEpoch===sourceEpoch){s.buffer=result.snapshot.source;s.validated=s.buffer;s.validationPending=false;s.source.value=s.buffer;}
const structural=sourceChanged||operations.some(op=>['add','delete','duplicate','move','toggle','format'].includes(op.fields.operation?.[0]))||(s.layout&&s.layout!==result.snapshot.schema.layout);
s.layout=result.snapshot.schema.layout;
const metadata=one('[data-inspector] [name=title]',s.root);
const title=s.edits.has('metadata:')&&metadata?metadata.value:result.snapshot.model?.meta.title||result.snapshot.id;
const metadata=one('[data-inspector] [name=title]',s.root),entryTitle=one('[data-inspector] [name="p.title"]',s.root);
const title=s.edits.has('entry_fields:')&&entryTitle?entryTitle.value:s.edits.has('metadata:')&&metadata?metadata.value:result.snapshot.model?.meta.title||result.snapshot.id;
const heading=one('.doc-toolbar h1');if(heading)heading.textContent=title;
const badge=one('[data-page-status]');if(badge)badge.textContent=result.snapshot.model?.meta.status||'draft';
const operation=operations.at(-1)?.fields.operation?.[0];
@@ -299,7 +301,7 @@
}catch(e){
if(!alive(s)||e.name==='AbortError')return false;
s.failedRev=rev;
if(e.buffer&&s.sourceEpoch===sourceEpoch&&!batch.length){s.valid=false;projection(e.projection);}
if(e.buffer&&s.sourceEpoch===sourceEpoch&&!batch.length){s.valid=false;s.issues=e.issues||[];projection(e.projection);}
failure(e,e.status);return false;
}finally{if(alive(s)){s.running=null;status();}}
})();
@@ -321,7 +323,7 @@
s.saving=(async()=>{
try{
const result=await post(s,'save',{source,etag:s.etag,revision:rev});if(!alive(s))return;
s.etag=result.snapshot.etag;s.saved=source;
s.etag=result.snapshot.etag;s.saved=source;if(s.rev===rev){s.model=result.snapshot.model;s.schema=result.snapshot.schema;s.issues=result.snapshot.issues;projection(result.projection);}
notice(s.rev===rev?'Документ сохранён. Публикация не выполнялась.':'Документ сохранён; новые правки ещё не сохранены.');
}catch(e){
if(!alive(s)||e.name==='AbortError')return;
@@ -332,7 +334,7 @@
})();status();await s.saving;
}
function conflict(error,source){
const s=current;one('[data-conflict-dialog]',s.root)?.remove();
const s=current;if(s.root.classList.contains('entry-content-editor')){window.siteContentConflict(error,source,()=>{s.etag=error.current.etag;status();notice('Новая основа принята. Проверьте исходник и сохраните отдельной кнопкой.');});return;}one('[data-conflict-dialog]',s.root)?.remove();
const dialog=document.createElement('dialog');dialog.className='modal builder-dialog expert-conflict-dialog conflict-panel';dialog.dataset.conflictDialog='';
dialog.innerHTML='<div class="modal-head"><h2>Документ изменён на сервере</h2><p>Ваши правки остаются в редакторе. Сравните версии и выполните слияние в «Эксперте».</p></div><div class="modal-body"><div class="conflict-columns"><label>Отправленный исходник<textarea rows="14" readonly></textarea></label><label>Серверный исходник<textarea rows="14" readonly></textarea></label></div><label class="checkrow"><input type="checkbox"> Принимаю серверную версию как новую основу</label></div><div class="modal-foot"><button type="button" class="button" data-close-dialog>Закрыть</button><button type="button" class="button primary" data-accept-base>Принять эту серверную версию как основу</button></div>';
const texts=dialog.querySelectorAll('textarea');texts[0].value=source;texts[1].value=error.current.source;
@@ -340,7 +342,7 @@
s.root.append(dialog);dialog.addEventListener('close',()=>dialog.remove(),{once:true});dialog.showModal();
}
async function leave(action){
const s=current,confirm=s.page?window.siteBuilderConfirm:window.siteAdminConfirm;
const s=current,confirm=s.page?window.siteBuilderConfirm:(s.root.classList.contains('entry-content-editor')?window.siteContentConfirm:window.siteAdminConfirm);
if(dirty()&&!await confirm('Есть несохранённые изменения','При переходе правки этой вкладки будут потеряны. Сохраните документ, если хотите оставить изменения.','Уйти без сохранения'))return false;
if(!alive(s))return false;clearTimeout(s.timer);s.controller.abort();action();return true;
}
@@ -354,13 +356,14 @@
if(!root){current=null;return;}
const form=one('#buffer-form',root),raw=JSON.parse(root.dataset.rawSource);
current={root,form,source:one('#document-source',root),buffer:raw,saved:JSON.parse(root.dataset.canonicalSource),validated:raw,rev:Number(root.dataset.revision),etag:form.elements.etag.value,
page:root.classList.contains('page-builder'),mode:form.elements.mode.value||'constructor',selection:form.elements.selection.value,readonlySelection:one('#editor-result').dataset.readonly||'',valid:one('#editor-result').dataset.valid==='1',
model:null,schema:null,issues:[],page:root.classList.contains('page-builder'),mode:form.elements.mode.value||'constructor',selection:form.elements.selection.value,readonlySelection:one('#editor-result').dataset.readonly||'',valid:one('#editor-result').dataset.valid==='1',
edits:new Map(),fieldValues:new Map(),validationPending:false,sourceEpoch:0,failedRev:-1,timer:null,running:null,saving:null,controller:new AbortController(),preview:null,viewport:{x:0,y:0},device:'desktop'};
hydrate(root);root.dataset.ready='1';showMode(current.valid?current.mode:'expert');flush(true);
}
window.siteDocument={
get state(){const s=current;return s?{source:s.buffer,saved:s.saved,dirty:dirty(),mode:s.mode,busy:!!(s.running||s.saving),base:s.root.dataset.base}:null;},
get state(){const s=current;return s?{source:s.buffer,saved:s.saved,dirty:dirty(),mode:s.mode,busy:!!(s.running||s.saving),base:s.root.dataset.base,etag:s.etag,revision:s.rev,model:s.model,schema:s.schema,issues:s.issues,path:one('.doc-toolbar code',s.root)?.textContent}:null;},
notice,leave,flush,
preview:(view,version)=>{const s=current;if(view)s.root.dataset.previewView=view;if(version)s.root.dataset.previewVersion=version;s.rev++;s.failedRev=-1;status();return enqueue(()=>flush(true));},
previewReloading:()=>{const s=current;if(s?.preview){s.preview.ready=false;s.preview.document=null;setTimeout(()=>{if(alive(s)&&!s.preview.ready)displayPreview({...s.preview,html:''});},0);}},
change:element=>remember(element,true),
transform:values=>enqueue(()=>transform(values)),
@@ -389,7 +392,7 @@
document.addEventListener('change',event=>{if(current?.root.contains(event.target)&&event.target.closest('[data-inspector]'))remember(event.target,true);});
document.addEventListener('submit',event=>{
const s=current;if(!s)return;const form=event.target;
if(form.closest('#document-editor')){
if(form.closest('#document-editor')&&!form.hasAttribute('data-content-create')){
if(form.method==='dialog')return;
event.preventDefault();event.stopImmediatePropagation();
const submitter=event.submitter,data=fields(form,submitter),action=new URL(submitter?.hasAttribute('formaction')?submitter.formAction:form.action).pathname.split('/').pop();
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 1"/>

After

Width:  |  Height:  |  Size: 60 B

@@ -0,0 +1,24 @@
/* Runtime/CSP/native-dialog adapters; composition and declarations are in publication.css. */
.content.publication-content { padding:0; max-width:none; }
.publication-content { min-width:0; }
.publication-content [hidden] { display:none!important; }
.publication-content .wrap { font-size:13px; }
.publication-content .publication-footer { display:flex;justify-content:space-between;gap:10px;flex-wrap:wrap;margin-top:20px;color:var(--muted2);font-size:10px; }
.publication-content .note-spaced { margin-top:16px; }
.publication-content .note-separated { margin:16px 0; }
.publication-content .inline-actions { display:flex;gap:8px;flex-wrap:wrap;margin-top:15px; }
.publication-content .pipe strong,.publication-content .build-row small,.publication-content .live-identity strong,.publication-content .sum strong { overflow-wrap:anywhere; }
.publication-content .live-symbol { flex:none; }
.publication-content .dialog { padding:0; margin:auto; }
.publication-content .dialog:not([open]) { display:none; }
.publication-content .dialog[open] { display:flex; }
.publication-content .dialog::backdrop { background:rgba(0,0,0,.65); }
.publication-content .dialog-head h2 { color:var(--fg); }
.publication-content .dialog-actions { flex-wrap:wrap; }
.publication-content #publication-notice { position:fixed;bottom:18px;right:18px;max-width:min(430px,calc(100vw - 32px));pointer-events:none;z-index:80; }
.publication-content #publication-notice:not(:empty) { background:var(--fg);color:var(--bg);padding:12px 16px;border-radius:7px;box-shadow:0 12px 28px #0005;font-size:11px; }
.publication-content .release-preview { width:100%;height:420px;border:1px solid var(--border);background:var(--panel); }
.publication-content .publication-error { overflow-wrap:anywhere; }
/* Use the accepted Antirion dark palette; the design's Rose palette is a separate theme. */
body[data-skin=dark] .publication-content { color-scheme:dark;--bg:var(--paper);--fg:var(--ink);--muted:var(--secondary);--muted2:var(--dim);--panel:var(--paper);--panel-soft:var(--paper2);--panel-hover:var(--paper3);--border:var(--stroke);--border2:var(--stroke2);--accent:var(--focus);--accent-bg:var(--paper3);--accent-on:#fff;--positive:var(--good);--positive-bg:var(--goodbg);--warning:var(--warn);--warning-bg:var(--warnbg);--negative:var(--error);--negative-bg:var(--errorbg);--shadow:none; }
@media(max-width:760px) { .publication-content .check{flex-wrap:wrap}.publication-content .heading-actions{width:100%}.publication-content .heading-actions .button{flex:1}.publication-content .dialog { max-width:calc(100% - 28px) }.publication-content .dialog-head,.publication-content .dialog-content,.publication-content .dialog-actions{padding-left:14px;padding-right:14px} }
@@ -0,0 +1 @@
{"home": "M3 3h7v7H3zM14 3h7v7h-7zM3 14h7v7H3zM14 14h7v7h-7z", "pages": "M7 3h10l4 4v14H7z M17 3v5h4 M11 13h6 M11 17h6", "content": "M12 2 3 7l9 5 9-5-9-5z M3 12l9 5 9-5 M3 17l9 5 9-5", "publish": "M12 3v13m-5-5 5 5 5-5 M4 17v4h16v-4", "media": "M3 3h18v18H3z M7 16l4-4 3 3 3-3 4 4", "settings": "M4 6h16 M4 12h16 M4 18h16", "history": "M4 3h16v18H4z M8 9h8 M8 13h8 M8 17h5", "search": "M11 3a8 8 0 1 0 0 16a8 8 0 0 0 0-16z M17 17l4 4", "check": "M4 12l5 5 11-11", "alert": "M12 2 2 21h20L12 2z M12 9v5 M12 17v1", "plus": "M12 4v16 M4 12h16", "file": "M6 2h10l4 4v16H6z M16 2v5h4 M9 12h8 M9 16h8", "arrow": "M4 12h16m-6-6 6 6-6 6", "eye": "M2 12s4-7 10-7 10 7 10 7-4 7-10 7-10-7-10-7z M12 9a3 3 0 1 0 0 6 3 3 0 0 0 0-6", "refresh": "M3 11a9 9 0 1 1 3 7 M3 5v6h6", "shield": "M12 2l8 4v6c0 6-4 9-8 10-4-1-8-4-8-10V6z", "code": "M8 7l-5 5 5 5 M16 7l5 5-5 5", "menu": "M3 6h18 M3 12h18 M3 18h18", "close": "M5 5l14 14 M19 5 5 19", "clock": "M12 2a10 10 0 1 0 0 20a10 10 0 0 0 0-20z M12 7v6l4 2", "layers": "M3 7l9-4 9 4-9 5-9-5 M3 13l9 5 9-5", "copy": "M8 8h13v13H8z M3 3h13v4 M3 3v13h4"}
@@ -0,0 +1,24 @@
/* Generated by scripts/sync_publication_design.py; original declarations unchanged. */
/* Stage 5 / Publication Design Prototype — responsive, static, no CDN */
:where(.publication-content){font-family:Inter,ui-sans-serif,system-ui,-apple-system,"Segoe UI",Arial,sans-serif;font-synthesis:none;font-size:13px}
:where(.publication-content) *{box-sizing:border-box}:where(.publication-content){margin:0;min-width:320px;min-height:100vh;background:var(--bg);color:var(--fg)}:where(.publication-content) button,:where(.publication-content) input,:where(.publication-content) select,:where(.publication-content) textarea{font:inherit}:where(.publication-content) button{cursor:pointer}:where(.publication-content) button:disabled{cursor:not-allowed;opacity:.42}:where(.publication-content) button:focus-visible,:where(.publication-content) input:focus-visible,:where(.publication-content) select:focus-visible,:where(.publication-content) a:focus-visible{outline:2px solid var(--accent);outline-offset:2px}:where(.publication-content) a{color:inherit;text-decoration:none}:where(.publication-content) svg{width:16px;height:16px;vertical-align:middle;flex:none}:where(.publication-content) .mono,:where(.publication-content) code{font-family:ui-monospace,SFMono-Regular,Consolas,"Liberation Mono",monospace}:where(.publication-content) code{overflow-wrap:anywhere}:where(.publication-content) .muted{color:var(--muted)}:where(.publication-content) .sr-only{position:absolute;clip:rect(0,0,0,0);width:1px;height:1px;overflow:hidden}
:where(.publication-content){color-scheme:light;--nav:#151719;--nav-border:#343639;--nav-text:#aeb3b7;--nav-active:#2a2c31;--bg:#f7f7f5;--fg:#22252a;--muted:#74777e;--muted2:#9fa2a8;--panel:#fff;--panel-soft:#f1f1ef;--panel-hover:#f7f6fc;--border:#dedfdd;--border2:#ecece9;--accent:#7564da;--accent-bg:#f0edff;--accent-on:#fff;--positive:#27745b;--positive-bg:#e6f5eb;--warning:#98601d;--warning-bg:#fff0d7;--negative:#a13c52;--negative-bg:#fcebef;--radius:5px;--shadow:0 4px 16px rgba(20,19,33,.035)}
:where(.publication-content)[data-unused-rose]{color-scheme:dark;--nav:#07080a;--nav-border:#27272a;--nav-text:#929299;--nav-active:#1e1e20;--bg:#0c0c0f;--fg:#f5f3f5;--muted:#a0a0a9;--muted2:#71727a;--panel:#131316;--panel-soft:#1c1c20;--panel-hover:#20151d;--border:#303035;--border2:#27272b;--accent:#f3559b;--accent-bg:#341625;--accent-on:#fff;--positive:#32d19b;--positive-bg:#103429;--warning:#e7bd71;--warning-bg:#392a1e;--negative:#f4909f;--negative-bg:#381b25;--radius:12px;--shadow:none}
:where(.publication-content) .layout{display:grid;grid-template-columns:218px minmax(0,1fr);min-height:100vh}:where(.publication-content) .side{position:sticky;top:0;height:100vh;display:flex;flex-direction:column;background:var(--nav);border-right:1px solid var(--nav-border);color:var(--nav-text);z-index:15;min-width:0}:where(.publication-content) .brand{display:flex;align-items:center;gap:10px;height:76px;padding:15px 16px;border-bottom:1px solid var(--nav-border)}:where(.publication-content) .brand-logo{width:36px;height:36px;display:grid;place-items:center;background:linear-gradient(145deg,#ed9ecd,#d85197);color:#fff;font-size:20px;border-radius:10px;font-weight:900}:where(.publication-content) .brand-name{font-size:13px;color:#fff;font-weight:730}:where(.publication-content) .brand-tag{font-size:9px;letter-spacing:.12em;color:#898990;margin-top:3px;font-weight:700}:where(.publication-content) .side-nav{padding:16px 9px;flex:1;overflow:auto}:where(.publication-content) .navlabel{font-size:9px;letter-spacing:.12em;color:#666a73;padding:10px 12px 9px;font-weight:800}:where(.publication-content) .side-link{display:flex;align-items:center;gap:12px;min-height:39px;padding:8px 12px;color:#a4a6ab;border-radius:6px;margin-bottom:2px;position:relative;font-size:12px}:where(.publication-content) .side-link:hover{color:#fff;background:#232428}:where(.publication-content) .side-link.active{color:#fff;background:var(--nav-active);font-weight:660}:where(.publication-content) .side-link.active:before{position:absolute;left:0;top:7px;bottom:7px;width:3px;background:var(--accent);border-radius:4px;content:""}:where(.publication-content) .side-link em{font-style:normal;font-size:10px;opacity:.8;margin-left:auto}:where(.publication-content) .bottom{padding:14px 12px 18px;border-top:1px solid var(--nav-border)}:where(.publication-content) .site-picker{border:1px solid #323239;border-radius:8px;padding:11px;color:#fff;display:flex;gap:8px;align-items:center;background:#17181b}:where(.publication-content) .site-picker small{display:block;color:#94959e;font-size:10px;margin-top:4px}:where(.publication-content) .tiny{font-size:10px}:where(.publication-content) .side-note{display:flex;align-items:center;gap:8px;margin-top:14px;color:#9a9ba3;font-size:10px}:where(.publication-content) .side-note .dot{width:7px;height:7px;background:#30c98d;border-radius:50%;flex:none}
:where(.publication-content) .main{min-width:0;display:flex;flex-direction:column}:where(.publication-content) .top{height:60px;border-bottom:1px solid var(--border);display:flex;align-items:center;gap:13px;padding:0 28px;background:var(--panel);flex:none;position:sticky;top:0;z-index:12}:where(.publication-content) .crumb{display:flex;align-items:center;gap:10px;font-size:11px;color:var(--muted);min-width:0}:where(.publication-content) .crumb strong{color:var(--fg);font-weight:680}:where(.publication-content) .push{flex:1}:where(.publication-content) .live-indicator{white-space:nowrap;display:flex;align-items:center;gap:7px;font-size:10px;font-weight:750}:where(.publication-content) .live-indicator .dot{background:var(--positive);border-radius:50%;width:7px;height:7px}:where(.publication-content) .avatar{border:1px solid var(--border);background:var(--panel-soft);color:var(--fg);display:grid;place-items:center;width:30px;height:30px;border-radius:6px;font-size:10px;font-weight:750}:where(.publication-content) .mobile-menu{display:none}:where(.publication-content) .icon-btn{width:32px;height:32px;border:1px solid transparent;background:transparent;color:var(--muted);display:grid;place-items:center;border-radius:6px}:where(.publication-content) .icon-btn:hover{border-color:var(--border);color:var(--fg)}
:where(.publication-content) .wrap{padding:32px 28px 45px;max-width:1800px;width:100%;margin:0 auto}:where(.publication-content) .overline{text-transform:uppercase;font:700 10px/1.5 ui-monospace,monospace;letter-spacing:.11em;color:var(--accent)}:where(.publication-content) .heading{display:flex;align-items:flex-end;justify-content:space-between;gap:20px;padding-bottom:20px}:where(.publication-content) .heading h1{margin:8px 0 8px;font-size:clamp(26px,3.2vw,38px);letter-spacing:-.045em;font-weight:690}:where(.publication-content) .heading p{color:var(--muted);font-size:12px;line-height:1.55;margin:0;max-width:650px}:where(.publication-content) .heading-actions{display:flex;gap:7px;align-items:center;flex-wrap:wrap}:where(.publication-content) .button{border:1px solid var(--border);padding:0 13px;min-height:34px;border-radius:6px;background:var(--panel);color:var(--fg);display:inline-flex;align-items:center;justify-content:center;gap:7px;font-weight:660;font-size:11px;white-space:nowrap}:where(.publication-content) .button:hover:not(:disabled){background:var(--panel-soft);border-color:var(--accent)}:where(.publication-content) .button.primary{background:var(--accent);border-color:var(--accent);color:var(--accent-on)}:where(.publication-content) .button.primary:hover:not(:disabled){filter:brightness(1.07)}:where(.publication-content) .button.subtle{background:transparent}:where(.publication-content) .button.danger{color:var(--negative);border-color:var(--negative)}:where(.publication-content) .button.tiny{min-height:28px;padding:0 9px;font-size:10px}:where(.publication-content) .button svg{width:14px;height:14px}:where(.publication-content) .chip{display:inline-flex;align-items:center;gap:6px;padding:4px 8px;font-size:10px;line-height:1.2;font-weight:670;border-radius:5px;white-space:nowrap;background:var(--panel-soft);color:var(--muted)}:where(.publication-content) .chip:before{content:"";width:5px;height:5px;border-radius:50%;background:currentColor}:where(.publication-content) .chip.good{background:var(--positive-bg);color:var(--positive)}:where(.publication-content) .chip.warn{background:var(--warning-bg);color:var(--warning)}:where(.publication-content) .chip.bad{background:var(--negative-bg);color:var(--negative)}:where(.publication-content) .chip.purple{background:var(--accent-bg);color:var(--accent)}
:where(.publication-content) .livebar{border:1px solid var(--border);border-radius:var(--radius);background:var(--panel);padding:17px 20px;display:flex;align-items:center;gap:20px;margin-bottom:20px}:where(.publication-content) .live-identity{display:flex;align-items:center;gap:12px;min-width:0}:where(.publication-content) .live-symbol{width:38px;height:38px;background:var(--positive-bg);color:var(--positive);display:grid;place-items:center;border-radius:9px}:where(.publication-content) .live-identity strong{display:block;font-size:14px}:where(.publication-content) .live-identity small{display:block;font-size:10px;color:var(--muted);margin-top:5px}:where(.publication-content) .live-actions{margin-left:auto;display:flex;gap:8px;align-items:center}:where(.publication-content) .pipeline{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px;margin-bottom:22px}:where(.publication-content) .pipe{border:1px solid var(--border);border-radius:var(--radius);background:var(--panel);padding:16px 18px;min-width:0;position:relative}:where(.publication-content) .pipe:before{content:"";position:absolute;top:-1px;left:16px;right:16px;height:2px;background:var(--border)}:where(.publication-content) .pipe:nth-child(1):before{background:var(--accent)}:where(.publication-content) .pipe:nth-child(2):before{background:var(--warning)}:where(.publication-content) .pipe:nth-child(3):before{background:var(--positive)}:where(.publication-content) .pipe .step{display:flex;justify-content:space-between;align-items:center;gap:8px;color:var(--muted);font-size:10px;text-transform:uppercase;letter-spacing:.08em;font-weight:700}:where(.publication-content) .pipe strong{font-size:20px;letter-spacing:-.035em;display:block;margin:12px 0 7px}:where(.publication-content) .pipe p{margin:0;font-size:11px;line-height:1.5;color:var(--muted)}
:where(.publication-content) .tabs{display:flex;gap:20px;border-bottom:1px solid var(--border);margin:8px 0 22px;min-width:0;overflow-x:auto;scrollbar-width:thin}:where(.publication-content) .tab{background:none;border:0;border-bottom:2px solid transparent;color:var(--muted);padding:12px 2px;font-size:12px;white-space:nowrap;font-weight:620}:where(.publication-content) .tab.active{color:var(--fg);border-color:var(--accent)}:where(.publication-content) .tab .num{font-size:10px;padding:2px 5px;background:var(--panel-soft);border-radius:4px;margin-left:5px;color:var(--muted)}:where(.publication-content) .split{display:grid;grid-template-columns:minmax(0,1.65fr) minmax(270px,.85fr);gap:17px}:where(.publication-content) .stack{display:flex;flex-direction:column;gap:17px;min-width:0}:where(.publication-content) .panel{background:var(--panel);border:1px solid var(--border);border-radius:var(--radius);min-width:0;overflow:hidden;box-shadow:var(--shadow)}:where(.publication-content) .panel-header{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:16px 18px;border-bottom:1px solid var(--border2)}:where(.publication-content) .panel-header h2,:where(.publication-content) .panel-header h3{margin:0;font-size:13px;font-weight:730}:where(.publication-content) .panel-header p{margin:5px 0 0;color:var(--muted);font-size:10px}:where(.publication-content) .panel-body{padding:18px}:where(.publication-content) .panel-tools{display:flex;align-items:center;gap:8px;flex-wrap:wrap;padding:12px 16px;border-bottom:1px solid var(--border2)}:where(.publication-content) .search{min-height:33px;display:flex;gap:9px;align-items:center;padding:0 10px;border:1px solid var(--border);border-radius:6px;background:var(--bg);flex:1;min-width:140px}:where(.publication-content) .search input{border:0;outline:0;background:transparent;color:var(--fg);width:100%;min-width:0;font-size:11px}:where(.publication-content) .search svg{color:var(--muted)}:where(.publication-content) select,:where(.publication-content) textarea,:where(.publication-content) input[type=text]{border:1px solid var(--border);background:var(--panel);color:var(--fg);border-radius:6px;min-height:34px;padding:7px 10px;min-width:0}:where(.publication-content) .panel-tools select{min-width:116px}:where(.publication-content) .table-scroll{overflow-x:auto;max-width:100%}:where(.publication-content) .table{width:100%;border-collapse:collapse;min-width:610px;text-align:left;font-size:11px}:where(.publication-content) .table th{background:var(--panel-soft);color:var(--muted);font-size:9px;text-transform:uppercase;letter-spacing:.07em;font-weight:720;padding:12px 13px}:where(.publication-content) .table td{padding:11px 13px;border-bottom:1px solid var(--border2);vertical-align:middle}:where(.publication-content) .table tr:last-child td{border-bottom:0}:where(.publication-content) .table tbody tr:hover{background:var(--panel-hover)}:where(.publication-content) .table tbody tr.selected{background:var(--accent-bg)}:where(.publication-content) .table .file-name{font-weight:690;overflow-wrap:anywhere}:where(.publication-content) .file-sub{display:block;font-size:10px;color:var(--muted);margin-top:4px;overflow-wrap:anywhere}:where(.publication-content) .table a{text-decoration:underline;text-decoration-color:var(--border)}:where(.publication-content) .file-button{border:0;background:transparent;color:var(--fg);font-weight:700;padding:0;text-align:left;font-size:11px}:where(.publication-content) .file-button:hover{color:var(--accent)}:where(.publication-content) .table-footer{display:flex;justify-content:space-between;gap:12px;color:var(--muted);font-size:10px;padding:12px 16px;border-top:1px solid var(--border2)}
:where(.publication-content) .kv{display:grid;grid-template-columns:100px minmax(0,1fr);gap:10px;border-bottom:1px solid var(--border2);padding:10px 0;font-size:11px}:where(.publication-content) .kv:last-child{border-bottom:0}:where(.publication-content) .kv b{font-weight:620;overflow-wrap:anywhere}:where(.publication-content) .kv span{color:var(--muted)}:where(.publication-content) .note{font-size:11px;line-height:1.55;padding:12px 13px;border-left:2px solid var(--accent);background:var(--accent-bg);color:var(--fg)}:where(.publication-content) .empty{padding:29px;text-align:center;color:var(--muted);font-size:11px;line-height:1.6}:where(.publication-content) .empty strong{display:block;color:var(--fg);font-size:13px;margin-bottom:4px}:where(.publication-content) .check{display:flex;align-items:flex-start;gap:12px;padding:13px 16px;border-bottom:1px solid var(--border2)}:where(.publication-content) .check svg{width:17px;height:17px;color:var(--muted)}:where(.publication-content) .check.bad svg{color:var(--negative)}:where(.publication-content) .check.warn svg{color:var(--warning)}:where(.publication-content) .check.good svg{color:var(--positive)}:where(.publication-content) .check-info{min-width:0;flex:1}:where(.publication-content) .check-info b{display:block;font-size:11px}:where(.publication-content) .check-info small{display:block;color:var(--muted);margin-top:5px;overflow-wrap:anywhere;line-height:1.5}:where(.publication-content) .check-actions{display:flex;gap:6px;align-items:center;flex-wrap:wrap}:where(.publication-content) .inline-info{display:flex;align-items:center;gap:8px;color:var(--muted);font-size:10px;line-height:1.5;padding:10px 16px;background:var(--panel-soft)}:where(.publication-content) .summary{display:grid;grid-template-columns:repeat(3,1fr);gap:10px;padding:14px 16px;border-bottom:1px solid var(--border2)}:where(.publication-content) .sum{padding:10px;border-radius:6px;background:var(--panel-soft);min-width:0}:where(.publication-content) .sum strong{font-size:20px;display:block}:where(.publication-content) .sum span{font-size:10px;color:var(--muted)}:where(.publication-content) .log{margin:0;white-space:pre-wrap;overflow-wrap:anywhere;background:var(--panel-soft);border-radius:6px;padding:14px;font:11px/1.75 ui-monospace,monospace}:where(.publication-content) .source-compare{display:grid;grid-template-columns:1fr 1fr;gap:10px}:where(.publication-content) .compare-col{padding:12px;border:1px solid var(--border);border-radius:7px;min-width:0}:where(.publication-content) .compare-col h4{font-size:10px;text-transform:uppercase;letter-spacing:.08em;margin:0 0 8px;color:var(--muted)}:where(.publication-content) .compare-col pre{font:11px/1.65 ui-monospace,monospace;white-space:pre-wrap;overflow-wrap:anywhere;margin:0;color:var(--fg)}:where(.publication-content) .compare-col .preview-mini{border:1px solid var(--border);background:var(--panel-soft);padding:13px;border-radius:6px;margin-top:8px}:where(.publication-content) .mini-head{height:10px;border-radius:4px;background:var(--border);width:70%;margin-bottom:14px}:where(.publication-content) .mini-line{height:6px;border-radius:3px;background:var(--border);margin-bottom:8px;width:90%}:where(.publication-content) .mini-line:nth-child(odd){width:65%}:where(.publication-content) .mini-pill{height:17px;background:var(--accent);width:75px;border-radius:4px;margin-top:12px}
:where(.publication-content) .builds{display:flex;flex-direction:column}:where(.publication-content) .build-row{display:grid;grid-template-columns:105px minmax(0,1fr) 140px auto;align-items:center;gap:15px;padding:14px 16px;border-bottom:1px solid var(--border2);font-size:11px}:where(.publication-content) .build-row:last-child{border-bottom:0}:where(.publication-content) .build-row strong{display:block;font-size:11px}:where(.publication-content) .build-row small{display:block;color:var(--muted);font-size:10px;margin-top:5px}:where(.publication-content) .build-row .code-id{font:700 11px ui-monospace,monospace;overflow-wrap:anywhere}:where(.publication-content) .build-row .actions{display:flex;gap:6px;flex-wrap:wrap;justify-content:flex-end}:where(.publication-content) .bullet{width:6px;height:6px;border-radius:50%;display:inline-block;background:var(--accent);margin-right:7px}
:where(.publication-content) .timeline{display:flex;flex-direction:column;gap:13px;padding:16px 18px}:where(.publication-content) .event{border-left:2px solid var(--border);padding-left:14px;font-size:11px;line-height:1.5}:where(.publication-content) .event b{display:block}:where(.publication-content) .event small{display:block;color:var(--muted);margin-top:3px}:where(.publication-content) .event.publish{border-color:var(--positive)}:where(.publication-content) .event.rollback{border-color:var(--warning)}:where(.publication-content) .event.failure{border-color:var(--negative)}
:where(.publication-content) #modal-root:empty{display:none}:where(.publication-content) .modal-backdrop{position:fixed;inset:0;background:rgba(0,0,0,.65);display:grid;place-items:center;z-index:50;padding:20px}:where(.publication-content) .dialog{background:var(--panel);border:1px solid var(--border);color:var(--fg);width:min(630px,100%);max-height:min(88vh,850px);display:flex;flex-direction:column;border-radius:var(--radius);box-shadow:0 20px 80px #0005}:where(.publication-content) .dialog.wide{width:min(950px,100%)}:where(.publication-content) .dialog-head{display:flex;justify-content:space-between;gap:14px;padding:19px 22px 15px;border-bottom:1px solid var(--border)}:where(.publication-content) .dialog-head h2{font-size:17px;margin:0 0 4px}:where(.publication-content) .dialog-head p{font-size:11px;color:var(--muted);margin:0}:where(.publication-content) .dialog-content{overflow:auto;padding:20px 22px}:where(.publication-content) .dialog-actions{display:flex;gap:8px;justify-content:flex-end;padding:14px 22px;border-top:1px solid var(--border)}:where(.publication-content) .field{display:block;margin:0 0 14px;font-size:11px;font-weight:670}:where(.publication-content) .field input,:where(.publication-content) .field textarea,:where(.publication-content) .field select{display:block;margin-top:7px;width:100%;min-height:35px}:where(.publication-content) .field textarea{resize:vertical;min-height:75px}:where(.publication-content) .warning-box{border:1px solid var(--negative);padding:13px;border-radius:8px;background:var(--negative-bg);font-size:11px;line-height:1.6;margin:12px 0}:where(.publication-content) .dialog pre{max-height:320px;overflow:auto}:where(.publication-content) #notice{position:fixed;bottom:18px;right:18px;max-width:min(430px,calc(100vw - 32px));pointer-events:none;z-index:80}:where(.publication-content) #notice:not(:empty){background:var(--fg);color:var(--bg);padding:12px 16px;border-radius:7px;box-shadow:0 12px 28px #0005;font-size:11px}:where(.publication-content) .mobile-cover{display:none}:where(.publication-content) .responsive-only{display:none}
:where(.publication-content) .brand-logo{background:#f4f4f1;color:#1b1d21;clip-path:polygon(0 0,100% 0,100% 76%,78% 100%,0 100%);border-radius:0}:where(.publication-content) .side-link.active:before{background:#c4b9ff}:where(.publication-content)[data-unused-rose] .brand-logo{background:linear-gradient(135deg,#fa823a,#ff3f8d);border-radius:10px}:where(.publication-content)[data-unused-rose] .side-link.active{border-radius:12px}:where(.publication-content)[data-unused-rose] .pipe,:where(.publication-content)[data-unused-rose] .panel{box-shadow:none}:where(.publication-content)[data-unused-rose] .table tbody tr.selected{background:#261723}:where(.publication-content)[data-unused-rose] .button.primary{background:linear-gradient(110deg,#f07655,#ed438c)}
@media(max-width:1200px){:where(.publication-content) .wrap{padding:28px 20px}:where(.publication-content) .top{padding:0 20px}:where(.publication-content) .layout{grid-template-columns:196px minmax(0,1fr)}:where(.publication-content) .split{grid-template-columns:minmax(0,1.3fr) minmax(235px,.8fr)}}
@media(max-width:990px){:where(.publication-content) .split{grid-template-columns:1fr}:where(.publication-content) .pipeline{gap:9px}:where(.publication-content) .pipe{padding:13px}:where(.publication-content) .pipe strong{font-size:17px}:where(.publication-content) .build-row{grid-template-columns:95px 1fr auto}:where(.publication-content) .build-row .meta-date{display:none}}
@media(max-width:760px){:where(.publication-content) .layout{grid-template-columns:minmax(0,1fr)}:where(.publication-content) .side{position:fixed;left:0;top:0;width:248px;height:100dvh;transform:translateX(-104%);transition:transform .18s ease;box-shadow:0 10px 40px #0006}:where(.publication-content) .layout.menu-open .side{transform:translateX(0)}:where(.publication-content) .mobile-cover{display:block;position:fixed;inset:0;background:#0009;z-index:14;opacity:0;pointer-events:none}:where(.publication-content) .layout.menu-open .mobile-cover{opacity:1;pointer-events:auto}:where(.publication-content) .mobile-menu{display:grid}:where(.publication-content) .top{padding:0 15px}:where(.publication-content) .top .crumb{overflow:hidden}:where(.publication-content) .crumb .hide-small{display:none}:where(.publication-content) .live-indicator{font-size:9px}:where(.publication-content) .heading{align-items:flex-start;flex-direction:column}:where(.publication-content) .wrap{padding:23px 14px 35px}:where(.publication-content) .livebar{flex-wrap:wrap;padding:14px}:where(.publication-content) .live-actions{width:100%;justify-content:space-between;margin:0}:where(.publication-content) .pipeline{grid-template-columns:1fr}:where(.publication-content) .pipe{padding:12px 14px}:where(.publication-content) .pipe strong{margin:7px 0 3px}:where(.publication-content) .tabs{margin-bottom:15px}:where(.publication-content) .build-row{grid-template-columns:90px minmax(0,1fr);gap:9px}:where(.publication-content) .build-row .actions{grid-column:2;justify-content:flex-start}:where(.publication-content) .source-compare{grid-template-columns:1fr}:where(.publication-content) .summary{gap:6px}:where(.publication-content) .sum{padding:8px}:where(.publication-content) .panel-header,:where(.publication-content) .panel-body{padding:14px}:where(.publication-content) .heading-actions .button{flex:1}}
@media(max-width:420px){:where(.publication-content) .top .live-indicator .mono{display:none}:where(.publication-content) .button{font-size:10px;padding:0 10px}:where(.publication-content) .panel-tools{padding:11px;gap:7px}:where(.publication-content) .panel-tools select{flex:1;min-width:0}:where(.publication-content) .search{flex-basis:100%}:where(.publication-content) .table{min-width:560px}:where(.publication-content) .heading h1{font-size:27px}:where(.publication-content) .livebar .chip{font-size:9px}}
@media(prefers-reduced-motion:reduce){:where(.publication-content) *{transition:none!important;scroll-behavior:auto!important}}
/* Header mobile trigger should remain hidden at desktop widths (icon-btn displays grid). */
:where(.publication-content) .top .mobile-menu{display:none}
@media(max-width:760px){:where(.publication-content) .top .mobile-menu{display:grid}}
@@ -0,0 +1,225 @@
/* Publication: original design composition and interactions, real FastAPI operations.
* Browser storage is never a source of release/workspace state. */
(() => {
'use strict';
if (window.sitePublication) return;
window.sitePublication = true;
const $ = (q, root = document) => root?.querySelector(q);
const esc = x => String(x ?? '').replace(/[&<>"']/g, ch => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[ch]));
const tabs = ['changes', 'checks', 'candidate', 'history', 'activity'];
let root, data, csrf, icons = {}, busy = false, generation = 0, invoker;
let state = {tab:'changes', filter:'all', query:'', type:'all', selected:''};
const icon = n => `<svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="${icons[n] || icons.file || ''}"/></svg>`;
const btn = (text, action, cls = '', extra = '') => `<button type="button" class="button ${cls}" data-pub-action="${action}" ${extra}>${text}</button>`;
const chip = (text, style = '') => `<span class="chip ${style}">${esc(text)}</span>`;
const date = value => value ? new Date(value).toLocaleString('ru-RU') : '—';
const chosen = () => data.changes.find(x => x.path === state.selected) || data.changes[0] || null;
const issues = () => data.validation?.issues || [];
const editUrl = c => !c || !c.after ? '' : c.type === 'Page' ? '/admin/pages/' + c.path.slice(6, -3).split('/').map(encodeURIComponent).join('/') : c.type === 'Entry' ? '/admin/content/' + c.path.slice(8, -3).split('/').map(encodeURIComponent).join('/') : c.path === 'theme.yaml' ? '/admin/theme' : '';
function notify(message) {
const el = $('#publication-notice', root);
if (el) el.textContent = message;
}
function error(detail, status) {
window.siteAdminError?.(detail, status);
notify([detail.message, detail.code, detail.request_id && 'ID запроса: ' + detail.request_id].filter(Boolean).join(' · '));
}
async function call(operation, payload, query = '') {
const originRoot=root,originGeneration=generation;
const options = {headers:{Accept:'application/json'}};
if (payload !== undefined) {
const form = new FormData();
form.set('csrf', csrf); form.set('payload', JSON.stringify(payload));
options.method = 'POST'; options.body = form;
}
let response;
try { response = await fetch('/admin/publication/' + operation + query, options); }
catch (_) { throw {status:0, detail:{code:'network_error', message:'Нет связи с сервером. Обновите состояние перед повтором операции.'}}; }
let result;
try { result = await response.json(); }
catch (_) { throw {status:response.status, detail:{code:'invalid_response', message:'Сервер вернул некорректный ответ. Обновите состояние перед повтором.', request_id:response.headers.get('X-Request-ID')}}; }
if(originGeneration!==generation||!originRoot?.isConnected)throw {cancelled:true};
if (!response.ok) throw {status:response.status, detail:result.error || {code:'http_error', message:'Не удалось выполнить запрос'}};
return result;
}
function heading() {
return `<div class="heading"><div><div class="overline">05 / RELEASE WORKFLOW · ATOMIC SITE RELEASES</div><h1>Публикация сайта</h1><p>Проверьте изменённые документы, соберите снимок-кандидат и переключите live. Редактируемые файлы workspace остаются отдельно от неизменяемого релиза.</p></div><div class="heading-actions">${btn(icon('check')+' Проверить','validate')}${btn(icon('plus')+' Собрать кандидата','candidate','primary')}</div></div>`;
}
function liveBar() {
const r = data.history.find(x => x.current);
return `<section class="livebar"><div class="live-identity"><div class="live-symbol">${icon(r ? 'check' : 'clock')}</div><div><strong>${r ? 'Активный релиз <code>'+esc(data.current)+'</code>' : 'Публичного релиза пока нет'}</strong><small>${r ? `Собран ${date(r.built_at)}${r.author ? ' · '+esc(r.author) : ''} · ${r.pages} страниц` : 'Соберите и проверьте первый снимок сайта'}</small></div></div><div class="live-actions">${chip(r ? 'LIVE' : 'Нет публикаций', r ? 'good' : 'warn')}${btn('История','history-tab','subtle tiny')}</div></section>`;
}
function pipeline() {
const candidate = data.candidate, errors = data.validation?.errors;
return `<div class="pipeline"><div class="pipe"><div class="step"><span>01 / Workspace</span>${chip(!data.comparison_available ? 'Нет сравнения' : data.changes.length ? 'Есть изменения' : 'Без изменений', data.changes.length ? 'purple' : 'good')}</div><strong>${data.changes.length} файлов</strong><p>Сохранённые документы и настройки. ${errors === undefined ? 'Строгая проверка выполняется при сборке.' : 'Ошибок последней проверки: '+errors+'.'}</p></div><div class="pipe"><div class="step"><span>02 / Candidate</span>${chip(candidate?.fresh ? 'Ready' : candidate ? 'Устарел' : 'Не собран', candidate?.fresh ? 'good' : 'warn')}</div><strong>${candidate ? esc(candidate.id) : 'Ожидает проверки'}</strong><p>${candidate ? `Зафиксирован ${date(candidate.at)} · ${candidate.changes} изменений` : 'Снимок создаётся только после строгой валидации workspace.'}</p></div><div class="pipe"><div class="step"><span>03 / Live</span>${chip(data.current ? 'Active' : 'Ожидает', data.current ? 'good' : 'warn')}</div><strong class="mono">${esc(data.current || 'Нет публикаций')}</strong><p>Неизменяемый build_id. Ошибочная сборка не меняет публичную версию.</p></div></div>`;
}
function tabBar() {
const counts = [data.changes.length, issues().length, data.candidate ? 1 : 0, data.history.length, data.activity.length];
return `<div class="tabs" role="tablist" aria-label="Публикация">${['Изменения','Проверки','Кандидат','История','Журнал'].map((title,i) => `<button id="pub-tab-${tabs[i]}" class="tab ${state.tab===tabs[i] ? 'active' : ''}" data-pub-tab="${tabs[i]}" role="tab" aria-selected="${state.tab===tabs[i]}" aria-controls="publication-panel" tabindex="${state.tab===tabs[i] ? 0 : -1}">${title}<span class="num">${counts[i]}</span></button>`).join('')}</div>`;
}
function filteredChanges() {
return data.changes.filter(x => (state.filter==='all'||state.filter===x.kind) && (state.type==='all'||state.type===x.type) && [x.title,x.path].some(s => s.toLocaleLowerCase().includes(state.query.toLocaleLowerCase())));
}
function changeTable() {
const rows=filteredChanges();
const options = (choices, value) => choices.map(([k,l])=>`<option value="${k}" ${value===k?'selected':''}>${l}</option>`).join('');
return `<section class="panel" data-pub-table><div class="panel-header"><div><h2>Изменения после live</h2><p>Сравнение рабочего дерева файлов с текущим опубликованным снимком</p></div>${chip(`${data.changes.length} documents`,'purple')}</div><div class="panel-tools"><label class="search">${icon('search')}<input id="pub-search" placeholder="Путь или название файла" value="${esc(state.query)}" aria-label="Поиск изменений"></label><select id="pub-change-kind" aria-label="Тип изменения">${options([['all','Все изменения'],['modified','Изменены'],['new','Добавлены'],['deleted','Удалены'],['unknown','Без сравнения']],state.filter)}</select><select id="pub-change-type" aria-label="Тип документа">${options([['all','Все типы'],...Array.from(new Set(data.changes.map(x=>x.type))).sort().map(x=>[x,x])],state.type)}</select></div>${!data.comparison_available ? '<div class="inline-info">У активного релиза нет частного снимка исходников. Показан текущий workspace; изменения относительно live неизвестны.</div>' : ''}<div class="table-scroll"><table class="table"><thead><tr><th>Файл / Название</th><th>Тип</th><th>Изменение</th><th>Статус</th><th></th></tr></thead><tbody>${rows.map(x=>`<tr class="${chosen()?.path===x.path?'selected':''}"><td><button class="file-button" data-pub-select="${esc(x.path)}">${esc(x.title)}</button><small class="file-sub mono">${esc(x.path)}</small></td><td>${esc(x.type)}</td><td>${chip(({new:'Добавлен',deleted:'Удалён',modified:'Изменён',unknown:'Неизвестно'})[x.kind],x.kind==='deleted'?'bad':x.kind==='new'?'good':'purple')}</td><td>${chip(({published:'В каталоге',draft:'Черновик',archived:'Архив',deleted:'Удалён',configuration:'Настройки',invalid:'Ошибка'})[x.status]||x.status,x.status==='published'?'good':'warn')}</td><td>${editUrl(x)?`<a class="button tiny" href="${editUrl(x)}" title="Открыть документ">${icon('arrow')} Открыть</a>`:''}</td></tr>`).join('')||'<tr><td colspan="5"><div class="empty"><strong>Ничего не найдено</strong>Измените фильтры или обновите документы в редакторах.</div></td></tr>'}</tbody></table></div><div class="table-footer"><span>${rows.length} из ${data.changes.length} изменений</span>${btn('Обновить данные из редакторов','refresh-workspace','tiny')}</div></section>`;
}
function selectedPanel() {
const c=chosen();
if(!c) return '<section class="panel"><div class="panel-header"><h3>Инспектор документа</h3></div><div class="empty">Изменений не найдено.</div></section>';
return `<section class="panel"><div class="panel-header"><div><h3>Инспектор · ${esc(c.title)}</h3><p class="mono">${esc(c.path)}</p></div>${btn(icon('eye'),'compare-doc','tiny','aria-label="Сравнить документ"')}</div><div class="panel-body"><div class="kv"><span>Сущность</span><b>${esc(c.type)}</b></div><div class="kv"><span>Изменение</span><b>${esc(c.kind)}</b></div><div class="kv"><span>Workspace</span><b>${c.after?'Сохранённая версия':'Удалён'}</b></div><div class="kv"><span>Live</span><b>${!data.comparison_available?'Нет исходного снимка':c.before?'В снимке '+esc(data.current):'Нет в live'}</b></div><div class="kv"><span>Размер</span><b>${c.after?.size??c.before?.size??0} байт</b></div><div class="note note-spaced">Флаг <b>status: published</b> в файле не означает, что последние изменения уже видны посетителям.</div><div class="inline-actions">${btn(icon('code')+' Diff','compare-doc','tiny')}${btn('История документа','doc-history','tiny')}${editUrl(c)?`<a class="button tiny" href="${editUrl(c)}">Редактор ${icon('arrow')}</a>`:''}</div></div></section>`;
}
function modelPanel() {
return '<section class="panel"><div class="panel-header"><div><h3>Модель публикации</h3><p>Не путайте три состояния</p></div></div><div class="panel-body"><div class="kv"><span>Workspace</span><b>Текущие редактируемые файлы</b></div><div class="kv"><span>Candidate</span><b>Проверенный immutable snapshot</b></div><div class="kv"><span>Live</span><b>Указатель на конкретный build ID</b></div><div class="note note-spaced">В публикацию входят сохранённые файлы. Несохранённые правки в открытых редакторах остаются в этих вкладках.</div></div></section>';
}
function changesTab() {
return `<div class="split"><div class="stack">${changeTable()}<section class="panel"><div class="panel-header"><div><h3>Как подготовить релиз</h3><p>Изменения могут затрагивать ссылки, меню и обработчики форм</p></div></div><div class="panel-body"><div class="check good">${icon('check')}<div class="check-info"><b>Workspace не равен Live</b><small>Открытие редактора не публикует файл. Обновлённые документы подхватываются после обновления списка.</small></div></div><div class="check warn">${icon('alert')}<div class="check-info"><b>Связанные файлы должны проходить проверку вместе</b><small>Публикация записи создаёт согласованный релиз сайта.</small></div></div></div></section></div><div class="stack">${selectedPanel()}${modelPanel()}</div></div>`;
}
function checksTab() {
const v=data.validation;
return `<div class="split"><div class="stack"><section class="panel"><div class="panel-header"><div><h2>Проверка перед публикацией</h2><p>Ошибки блокируют кандидата · предупреждения требуют внимания, но не блокируют</p></div>${btn(icon('check')+' Запустить validate','validate','primary')}</div><div class="summary"><div class="sum"><strong>${v?.errors??'—'}</strong><span>Ошибок</span></div><div class="sum"><strong>${v?.warnings??'—'}</strong><span>Предупреждений</span></div><div class="sum"><strong>${v?.fresh?'Проверено':v?'Устарело':'—'}</strong><span>${date(v?.at)}</span></div></div>${!v?.fresh?'<div class="inline-info">Запустите проверку текущего workspace. Сборка дополнительно проверит реальный рендер.</div>':''}${issues().map(x=>`<div class="check ${x.severity==='error'?'bad':'warn'}">${icon('alert')}<div class="check-info"><b>${esc(x.message)}</b><small><code>${esc(x.code)} · ${esc(x.path)}</code> · ${esc(x.hint)}</small></div><div class="check-actions">${chip(x.severity==='error'?'ERROR':'WARNING',x.severity==='error'?'bad':'warn')}${btn('К файлу','issue','tiny',`data-path="${esc(x.path)}"`)}</div></div>`).join('')||(v?`<div class="check good">${icon('check')}<div class="check-info"><b>Проблем не найдено</b><small>Серверная проверка структуры, схем и ссылок пройдена.</small></div>${chip('OK','good')}</div>`:'<div class="empty">Проверка ещё не запускалась.</div>')}</section></div><div class="stack"><section class="panel"><div class="panel-header"><h3>Результат валидации</h3></div><div class="panel-body"><div class="kv"><span>Текущая версия</span><b class="mono">${esc(data.current||'Нет публикаций')}</b></div><div class="kv"><span>Ошибки</span><b>${v?.errors??'—'}</b></div><div class="kv"><span>Предупреждения</span><b>${v?.warnings??'—'}</b></div><div class="note note-spaced">Сохранение неполного draft допускается. Полнота опубликованных документов и строгий рендер проверяются перед созданием релиза.</div></div></section>${selectedPanel()}</div></div>`;
}
function candidateTab() {
const c=data.candidate;
return `<div class="split"><div class="stack"><section class="panel"><div class="panel-header"><div><h2>Release candidate</h2><p>Фиксированный снимок состояния рабочего дерева</p></div>${btn(icon('plus')+' Сформировать кандидата','candidate','primary')}</div>${!c?`<div class="empty"><strong>Кандидат пока не создан</strong>Исправьте ошибки и соберите проверенный снимок.<div class="inline-actions">${btn('Перейти к проверкам','checks-tab')}</div></div>`:`<div class="panel-body"><div class="kv"><span>Build ID</span><b class="mono">${esc(c.id)}</b></div><div class="kv"><span>Состояние</span>${chip(c.fresh?'READY':'STALE — изменился workspace или live',c.fresh?'good':'bad')}</div><div class="kv"><span>Основа</span><b class="mono">${esc(c.base||'Первая публикация')}</b></div><div class="kv"><span>Создан</span><b>${date(c.at)}</b></div><div class="kv"><span>Автор</span><b>${esc(c.author)}</b></div><div class="kv"><span>Снимок</span><b>${c.pages} страниц · ${c.changes} изменений</b></div><div class="note note-separated">Кандидат фиксирует данные на момент сборки. Правки после его создания требуют повторной сборки.</div><div class="inline-actions">${btn('Просмотр сборки','preview')}${btn('Сравнить с live','candidate-diff')}${btn('Опубликовать','publish','primary',c.fresh?'':'disabled')}</div></div>`}</section><section class="panel"><div class="panel-header"><h3>Журнал сборок</h3></div>${data.builds.map((b,i)=>`<div class="build-row"><span class="code-id">${esc(b.id||'Не завершена')}</span><div><strong>${b.status==='ready'?'Кандидат собран':'Ошибка сборки'}</strong><small>${date(b.at)} · ${esc(b.base||'Первый релиз')}</small></div>${chip(b.status==='ready'?'Успешно':'Ошибка',b.status==='ready'?'good':'bad')}${btn('Лог','build-log','tiny',`data-index="${i}"`)}</div>`).join('')||'<div class="empty">Сборок пока нет.</div>'}</section></div><div class="stack">${modelPanel()}${selectedPanel()}</div></div>`;
}
function historyTab() {
return `<div class="split"><div class="stack"><section class="panel"><div class="panel-header"><div><h2>История релизов</h2><p>Каждый build ID представляет конкретный снимок сайта. Откат не трогает workspace.</p></div>${chip(`${data.history.length} builds`,'purple')}</div>${data.history.map(r=>`<div class="build-row"><div class="code-id">${esc(r.id)}</div><div><strong>${esc(r.comment||(r.candidate?'Неопубликованный кандидат':'Снимок сайта'))}</strong><small>${date(r.built_at)}${r.author?' · '+esc(r.author):''} · ${r.pages} страниц</small></div><div class="meta-date">${chip(r.current?'LIVE':r.candidate?'Candidate':'История',r.current?'good':'')}</div><div class="actions">${btn('Детали','release-details','tiny',`data-release="${r.id}"`)}${!r.current&&!r.candidate?btn('Откат','rollback','tiny',`data-release="${r.id}"`):''}</div></div>`).join('')||'<div class="empty">Релизов пока нет.</div>'}</section></div><div class="stack"><section class="panel"><div class="panel-header"><h3>Правила отката</h3></div><div class="panel-body"><div class="kv"><span>Live</span><b class="mono">${esc(data.current||'Нет публикаций')}</b></div><div class="kv"><span>Workspace</span><b>Не меняется при rollback</b></div><div class="kv"><span>Формы</span><b>Приём заявок пока недоступен (HTTP 501)</b></div><div class="note note-spaced">Откат выбирает ранее созданный снимок. Перед подтверждением проверьте страницы и конфигурации форм релиза.</div></div></section></div></div>`;
}
function activityTab() {
return `<div class="split"><div class="stack"><section class="panel"><div class="panel-header"><div><h2>Аудит действий</h2><p>Серверные события validate / build / publish / rollback</p></div>${btn('Обновить','refresh-workspace','subtle tiny')}</div>${data.activity.length?`<div class="timeline">${data.activity.map(e=>`<div class="event ${esc(e.event.replace('release_',''))}"><b>${esc(e.event)} ${esc(e.object||'')}</b><small>${date(e.ts)} · ${esc(e.actor||'—')}${e.request_id?' · ID '+esc(e.request_id):''}</small></div>`).join('')}</div>`:'<div class="empty">Пока событий нет. Запустите проверку или сборку.</div>'}</section></div><div class="stack"><section class="panel"><div class="panel-header"><h3>Источники аудита</h3></div><div class="panel-body"><div class="kv"><span>Источник</span><b>Серверный audit.jsonl</b></div><div class="kv"><span>Доступ</span><b>Действующая сессия администратора</b></div><div class="note note-spaced">Показаны последние события публикации. Полный журнал хранится на сервере.</div></div></section></div></div>`;
}
function render() {
if(!root?.isConnected) return;
$('[data-publication-view]',root).innerHTML=heading()+liveBar()+pipeline()+tabBar()+`<div id="publication-panel" role="tabpanel" aria-labelledby="pub-tab-${state.tab}">${({changes:changesTab,checks:checksTab,candidate:candidateTab,history:historyTab,activity:activityTab})[state.tab]()}</div><footer class="publication-footer"><span>Workspace ≠ Candidate ≠ Live</span><span>Site Engine · Stage 5</span></footer>`;
root.setAttribute('aria-busy',String(busy));
root.querySelectorAll('[data-pub-action]').forEach(b=>{if(!b.hasAttribute('data-pub-disabled'))b.dataset.pubDisabled=String(b.disabled);b.disabled=busy||b.dataset.pubDisabled==='true';});
}
function closeModal() { $('dialog[open]',root)?.close(); }
function modal(title,description,body,actions='',wide=false) {
closeModal(); invoker=document.activeElement;
$('#publication-modal-root',root).innerHTML=`<dialog class="dialog ${wide?'wide':''}" aria-labelledby="publication-dialog-title"><div class="dialog-head"><div><h2 id="publication-dialog-title">${esc(title)}</h2><p>${esc(description)}</p></div><button type="button" class="icon-btn" data-pub-action="close-modal" aria-label="Закрыть">${icon('close')}</button></div><div class="dialog-content">${body}</div><div class="dialog-actions">${actions||btn('Закрыть','close-modal')}</div></dialog>`;
const dialog=$('dialog',root);
dialog.addEventListener('close',()=>{if(invoker?.isConnected) invoker.focus();else $(`[data-pub-tab="${state.tab}"]`,root)?.focus();});
dialog.addEventListener('click',e=>{if(e.target!==dialog)return;const r=dialog.getBoundingClientRect();if(e.clientX<r.left||e.clientX>r.right||e.clientY<r.top||e.clientY>r.bottom)dialog.close();});
dialog.showModal();
$('input,button',dialog)?.focus();
}
async function refresh() {
const mine=generation, next=await call('state');
if(mine!==generation||!root?.isConnected) return;
data=next;render();
const pip=$('.live-pip');
if(pip){pip.classList.toggle('no-release',!data.current);pip.title=data.current?'Активный публичный релиз: '+data.current:'Публичного релиза пока нет';pip.innerHTML=data.current?'LIVE <span class="mono">'+esc(data.current)+'</span>':'НЕТ РЕЛИЗА';}
}
async function run(action,button) {
if(busy) return;
if(action==='close-modal'){closeModal();return;}
if(action.endsWith('-tab')){state.tab=action.split('-')[0];render();return;}
if(action==='publish') {
const c=data.candidate;if(!c?.fresh)return;
modal('Подтвердить публикацию','Атомарное переключение LIVE',`<div class="kv"><span>Текущий live</span><b class="mono">${esc(data.current||'Нет публикаций')}</b></div><div class="kv"><span>Кандидат</span><b class="mono">${esc(c.id)}</b></div><div class="kv"><span>Снимок</span><b>${c.pages} страниц · ${c.changes} изменений</b></div><label class="field">Комментарий к релизу<input type="text" id="release-comment" maxlength="150" placeholder="Кратко опишите изменения"></label><div class="warning-box">Будет опубликован проверенный снимок. Рабочие файлы останутся прежними.</div>`,btn('Отмена','close-modal')+btn('Опубликовать','confirm-publish','primary',`data-release="${c.id}" data-base="${esc(data.current||'')}"`));
$('#release-comment',root)?.focus();return;
}
if(action==='build-log') {
const b=data.builds[Number(button.dataset.index)];if(!b)return;
modal('Лог сборки '+(b.id||''),`${date(b.at)} · ${b.status}`,`<pre class="log">${esc(b.log)}${b.request_id?'\nID запроса: '+esc(b.request_id):''}</pre>${(b.issues||[]).map(x=>`<p>${esc(x.code)} · ${esc(x.path)} · ${esc(x.message)}</p>`).join('')}`);return;
}
if(action==='issue') {
const path=button.dataset.path;
state.selected=data.changes.find(x=>path===x.path||path.startsWith(x.path+'.'))?.path||'';
state.tab='changes';state.query='';state.filter='all';state.type='all';render();return;
}
if(action==='confirm-publish'&&!$('#release-comment',root)?.value.trim()) {$('#release-comment',root)?.focus();notify('Добавьте комментарий к релизу');return;}
busy=true;render();notify(({validate:'Проверяем сохранённые файлы…',candidate:'Собираем снимок…', 'confirm-publish':'Переключаем live…','rollback-confirm':'Выполняем откат…'})[action]||'Загружаем данные…');
const mine=generation;
try {
if(action==='refresh-workspace') await refresh();
else if(action==='validate') {await call('validate',{});state.tab='checks';await refresh();}
else if(action==='candidate') {await call('build',{});state.tab='candidate';await refresh();}
else if(action==='confirm-publish'||action==='rollback-confirm') {
const payload={id:button.dataset.release,expected_live:button.dataset.base||null,comment:$('#release-comment',root)?.value||''};
await call(action==='confirm-publish'?'activate':'rollback',payload);closeModal();state.tab='history';await refresh();
} else if(action==='release-details'||action==='rollback') {
const r=data.history.find(x=>x.id===button.dataset.release);if(!r)return;
const detail=await call('release',undefined,'?id='+encodeURIComponent(r.id));
if(action==='rollback') {
modal('Проверить откат','Просмотр последствий до подтверждения',`<div class="kv"><span>Сейчас live</span><b class="mono">${esc(detail.base||'Нет публикаций')}</b></div><div class="kv"><span>Выбран</span><b class="mono">${esc(r.id)}</b></div><div class="kv"><span>Изменится</span><b>${detail.changes.length} файлов в публичном снимке</b></div><div class="kv"><span>Страниц</span><b>${r.pages}</b></div><div class="kv"><span>Формы</span><b>${esc(r.forms.join(', ')||'Нет конфигураций')}</b></div><div class="warning-box">Live будет указывать на выбранный релиз. Файлы workspace не изменятся. Приём публичных форм пока возвращает HTTP 501.</div><pre class="log">${esc(detail.changes.map(c=>c.kind+' · '+c.path).join('\n')||'Нет отличающихся файлов')}</pre>`,btn('Отмена','close-modal')+btn('Подтвердить откат','rollback-confirm','danger',`data-release="${r.id}" data-base="${esc(detail.base||'')}"`));
} else modal('Релиз '+r.id,`${date(r.built_at)}${r.author?' · '+r.author:''}`,`<div class="kv"><span>Комментарий</span><b>${esc(r.comment||'—')}</b></div><div class="kv"><span>Статус</span>${chip(r.current?'LIVE':r.candidate?'Кандидат':'Исторический',r.current?'good':'')}</div><div class="kv"><span>Страниц</span><b>${r.pages}</b></div><div class="kv"><span>Формы</span><b>${esc(r.forms.join(', ')||'Нет конфигураций')}</b></div><pre class="log">${esc(r.routes.join('\n'))}</pre>`,btn('Просмотр снимка','preview','',`data-release="${r.id}"`)+(r.current||r.candidate?'':btn('Подготовить откат','rollback','danger',`data-release="${r.id}"`))+btn('Закрыть','close-modal'));
} else if(action==='candidate-diff') {
const x=await call('candidate-diff');
modal('Кандидат ↔ Live',`${x.id} ↔ ${x.base||'Первая публикация'}`,`<pre class="log">${esc(x.changes.map(c=>c.kind+' · '+c.path).join('\n')||'Изменений нет')}</pre><div class="note note-spaced">${x.comparison_available?'Сравнение зафиксированных исходников кандидата с его базовым релизом.':'У базового релиза нет частного снимка исходников; сравнение неизвестно.'}</div>`, '', true);
} else if(action==='compare-doc') {
const c=chosen();if(!c)return;
const x=await call('compare',undefined,'?path='+encodeURIComponent(c.path));
const serial=d=>d ? d.source??`SHA-256: ${d.hash}\nРазмер: ${d.size} байт\nИсходник недоступен для двоичного или большого файла.` : '(файл отсутствует)';
modal('Сравнение изменений',`${x.path} · Workspace ↔ Live`,`<div class="source-compare"><div class="compare-col"><h4>LIVE / ${esc(x.current||'Нет публикаций')}</h4><pre>${esc(x.comparison_available?serial(x.before):'У релиза нет частного снимка исходников.')}</pre></div><div class="compare-col"><h4>Workspace / сохранённая версия</h4><pre>${esc(serial(x.after))}</pre></div></div>`,btn('Закрыть','close-modal'),true);
} else if(action==='doc-history') {
const c=chosen();if(!c)return;
const x=await call('document-history',undefined,'?path='+encodeURIComponent(c.path));
modal('История документа',`Файл: ${x.path}`,x.versions.length?`<div class="timeline">${x.versions.map(v=>`<div class="event"><b>${esc(v.id)}</b><small>${v.size} байт</small></div>`).join('')}</div>`:'<div class="empty">Сохранённых предыдущих версий пока нет.</div>');
} else if(action==='preview') {
const id=button.dataset.release||data.candidate?.id,r=data.history.find(x=>x.id===id);if(!r)return;
const route=r.routes.includes('/')?'/':r.routes[0];if(!route)return;
const preview=await call('preview',{id,route});
// Release snapshots remain passive even when the editor bridge is configured.
modal('Просмотр сборки',`${id} · ${route}`,'<iframe class="release-preview" title="Предпросмотр снимка релиза" sandbox="allow-same-origin"></iframe>',btn('Закрыть','close-modal'),true);
$('.release-preview',root).src=preview.url;
}
if(mine===generation)notify(({validate:'Проверка завершена.',candidate:'Кандидат собран. Live не изменён.','confirm-publish':'Релиз опубликован.','rollback-confirm':'Live переключён. Workspace не изменён.'})[action]||'Данные загружены.');
} catch(exc) {
if(mine!==generation||exc.cancelled)return;
if(['candidate','confirm-publish','rollback-confirm'].includes(action)) {
if(action==='candidate')state.tab='candidate';
try{await refresh();}catch(_){}
}
error(exc.detail||{code:'client_error',message:'Не удалось выполнить операцию.'},exc.status);
} finally {if(mine===generation){busy=false;render();}}
}
async function initialize() {
const next=$('[data-publication-root]');if(!next||next===root)return;
const bootstrap=$('[data-publication-boot]',next);
let boot;
try {boot=JSON.parse(bootstrap.value);}
catch(_) {window.siteAdminError?.({code:'invalid_bootstrap',message:'Не удалось прочитать данные публикации. Обновите страницу.'},0);return;}
root=next;generation++;busy=false;
csrf=boot.csrf;data=boot.state;state={tab:tabs.includes(boot.tab)?boot.tab:'changes',filter:'all',type:'all',query:'',selected:''};
const mine=generation;
try {
const response=await fetch('/admin/static/publication-icons.json');
if(!response.ok)throw new Error('icons');
const loaded=await response.json();
if(mine!==generation||!next.isConnected)return;
icons=loaded;
} catch(_) {
if(mine!==generation||!next.isConnected)return;
error({code:'resource_error',message:'Не удалось загрузить иконки публикации. Обновите страницу.'},0);
}
render();
}
document.addEventListener('click',event=>{
if(!root?.contains(event.target))return;
const tab=event.target.closest('[data-pub-tab]');if(tab){state.tab=tab.dataset.pubTab;render();$(`[data-pub-tab="${state.tab}"]`,root)?.focus();return;}
const selected=event.target.closest('[data-pub-select]');if(selected){state.selected=selected.dataset.pubSelect;render();root.querySelectorAll('[data-pub-select]').forEach(x=>{if(x.dataset.pubSelect===state.selected)x.focus();});return;}
const button=event.target.closest('[data-pub-action]');if(button)run(button.dataset.pubAction,button);
});
document.addEventListener('input',event=>{
if(event.target.id!=='pub-search'||!root?.contains(event.target))return;
state.query=event.target.value;const start=event.target.selectionStart,end=event.target.selectionEnd;
$('[data-pub-table]',root).outerHTML=changeTable();const input=$('#pub-search',root);input.focus();input.setSelectionRange(start,end);
});
document.addEventListener('change',event=>{
if(!root?.contains(event.target))return;
if(event.target.id==='pub-change-kind'){state.filter=event.target.value;render();$('#pub-change-kind',root)?.focus();}
if(event.target.id==='pub-change-type'){state.type=event.target.value;render();$('#pub-change-type',root)?.focus();}
});
document.addEventListener('keydown',event=>{
const tab=event.target.closest?.('[data-pub-tab]');if(!tab||!root?.contains(tab))return;
let i=tabs.indexOf(tab.dataset.pubTab);
if(event.key==='ArrowRight')i=(i+1)%tabs.length;else if(event.key==='ArrowLeft')i=(i+tabs.length-1)%tabs.length;else if(event.key==='Home')i=0;else if(event.key==='End')i=tabs.length-1;else return;
event.preventDefault();state.tab=tabs[i];render();$(`[data-pub-tab="${state.tab}"]`,root)?.focus();
});
document.addEventListener('htmx:load',initialize);
initialize();
})();
@@ -0,0 +1,30 @@
{% from '_content_icons.html.j2' import ci %}
{% from '_fields.html.j2' import field as fallback %}
{% macro cf(f, compact=false) %}
<div class='entry-field{% if compact %} mini-field{% endif %}' data-field-container='{{ f.name }}'>
<label class='field-label' for='content-{{ f.name }}'>{{ f.label }}{% if f.required %}<i>*</i>{% endif %}<small class='mono'>{{ f.key }}</small></label>
{% if f.type == 'asset' %}
<div class='file-picker'><span class='mono' data-content-picked='{{ f.name }}'>{{ f.value or 'Файл не выбран' }}</span><input type='hidden' id='content-{{ f.name }}' name='{{ f.name }}' value='{{ f.value }}'><button type='button' class='button small' data-content-picker='{{ f.name }}' data-picker-type='asset' data-picker-options='{{ f.datalist|tojson }}'>{{ ci('image') }} Выбрать</button></div>
{% elif f.type in ['ref','refs'] %}
<div class='ref-pills' data-content-tokens='{{ f.name }}' data-ref-target='{{ f.to }}'>{% for value in f.value.replace(',', ' ').split() %}{% if value in f.datalist %}<a class='ref-token' href='/admin/content/{{ value if f.to == "*" else f.to ~ "/" ~ value }}'>{{ value }} {{ ci('arrow') }}</a>{% else %}<span class='ref-token'>{{ value }} {{ ci('alert') }}</span>{% endif %}{% endfor %}</div><input type='hidden' id='content-{{ f.name }}' name='{{ f.name }}' value='{{ f.value }}'><button type='button' class='button small' data-content-picker='{{ f.name }}' data-picker-type='{{ f.type }}' data-picker-target='{{ f.to|default("") }}' data-picker-options='{{ f.datalist|tojson }}'>{{ ci('link') }} Выбрать записи</button>
{% elif f.type == 'boolean' %}
<label class='switch-line'><input type='checkbox' data-content-bool='{{ f.name }}'{% if f.options[1].selected %} checked{% endif %}><span>{{ 'Включено' if f.options[1].selected else 'Выключено' }}</span></label><input type='hidden' name='{{ f.name }}' value='{{ "true" if f.options[1].selected else "false" if f.options[2].selected else "" }}'>
{% elif f.kind == 'list' %}
<div class='list-edit' data-list-name='{{ f.name }}'>
{% for row in f.rows %}<div class='list-edit-row{% if row.blank %} blank{% endif %}' data-list-row='{{ row.name }}'{% if row.blank %} hidden{% endif %}>
{% if row.bind %}<input type='hidden' name='{{ row.name }}._bind' value='{{ row.bind }}'><small>Источник: {{ row.bind }}</small>{% endif %}
{% if row.item %}{{ cf(row.item, true) }}{% else %}<div class='group-edit'>{% for child in row.children %}{{ cf(child, true) }}{% endfor %}</div>{% endif %}
<label data-list-delete hidden><input type='checkbox' name='{{ row.name }}._del' value='1'></label>
<button type='button' class='button small' data-content-remove='{{ row.name }}' aria-label='Удалить строку'>×</button></div>{% endfor %}
</div><button type='button' class='button small' data-content-add='{{ f.name }}'>{{ ci('plus') }} Добавить строку</button>
{% elif f.kind == 'group' %}<div class='group-edit'>{% for child in f.children %}{{ cf(child, true) }}{% endfor %}</div>
{% elif f.kind == 'link' %}<div class='group-edit'><label class='mini-field'><span>Тип ссылки</span><select name='{{ f.name }}.kind'>{% for kind,label in [('page','Страница'),('entry','Запись'),('url','Адрес')] %}<option value='{{ kind }}'{% if kind == f.link_kind %} selected{% endif %}>{{ label }}</option>{% endfor %}</select></label><label class='mini-field'><span>Цель</span><input name='{{ f.name }}.target' value='{{ f.target }}'></label><label class='mini-field'><span>Подпись</span><input name='{{ f.name }}.label' value='{{ f.link_label }}'></label><label class='switch-line'><input type='checkbox' name='{{ f.name }}.new_tab' value='1'{% if f.new_tab %} checked{% endif %}>В новой вкладке</label></div>
{% elif f.kind == 'textarea' %}<textarea id='content-{{ f.name }}' name='{{ f.name }}' rows='{{ 8 if f.type == "markdown" else 3 }}' spellcheck='false'>{{ f.value }}</textarea>
{% elif f.kind == 'select' %}<select id='content-{{ f.name }}' name='{{ f.name }}'>{% for o in f.options %}<option value='{{ o.value }}'{% if o.selected %} selected{% endif %}>{{ o.label }}</option>{% endfor %}</select>
{% elif f.kind in ['query','multiselect'] %}{{ fallback(f) }}
{% else %}<input id='content-{{ f.name }}' name='{{ f.name }}' type='{{ "date" if f.kind == "date" else "text" }}'{% if f.kind == 'number' %} inputmode='decimal'{% endif %} value='{{ f.value }}'>
{% endif %}
{% if f.hint %}<small>{{ f.hint }}</small>{% endif %}
{% if f.bind %}<small>Источник: {{ f.bind }}</small>{% endif %}<input type='hidden' name='{{ f.name }}._bind' value='{{ f.bind }}'>
</div>
{% endmacro %}
@@ -0,0 +1 @@
{% macro ci(name) -%}{% set paths = {"grid": "M3 3h8v8H3zM13 3h8v8h-8zM3 13h8v8H3zM13 13h8v8h-8z", "file": "M5 2h10l4 4v16H5z M14 2v5h5 M9 13h6 M9 17h6", "layers": "M12 2 3 7l9 5 9-5-9-5z M3 12l9 5 9-5 M3 17l9 5 9-5", "globe": "M12 2a10 10 0 1 0 0 20a10 10 0 0 0 0-20z M2 12h20", "edit": "M12 20h9 M3 17l11-11 4 4-11 11H3z M14 6l3-3 4 4-3 3", "search": "M11 3a8 8 0 1 0 0 16a8 8 0 0 0 0-16z M17 17l4 4", "plus": "M12 4v16 M4 12h16", "save": "M4 3h14l3 3v15H3V3z M7 3v7h10V3 M7 21v-8h10v8", "check": "M4 12l5 5 11-11", "code": "M8 7l-5 5 5 5 M16 7l5 5-5 5", "eye": "M2 12s4-7 10-7 10 7 10 7-4 7-10 7-10-7-10-7z M12 9a3 3 0 1 0 0 6a3 3 0 0 0 0-6", "link": "M10 14a4 4 0 0 0 6 0l3-3a4 4 0 0 0-6-6l-1 1 M14 10a4 4 0 0 0-6 0l-3 3a4 4 0 0 0 6 6l1-1", "alert": "M12 2 2 21h20L12 2z M12 9v5 M12 17v1", "trash": "M4 7h16 M8 7V4h8v3 M6 7l1 14h10l1-14", "copy": "M8 8h13v13H8z M3 3h13v4 M3 3v13h4", "arrow": "M4 12h16m-6-6 6 6-6 6", "menu": "M3 6h18 M3 12h18 M3 18h18", "close": "M5 5l14 14 M19 5 5 19", "date": "M4 5h16v16H4z M8 2v6 M16 2v6 M4 10h16", "image": "M3 3h18v18H3z M8 8h2 M3 19l7-7 4 4 3-3 4 4", "refresh": "M3 11a9 9 0 1 1 3 7 M3 5v6h6", "chevron": "M9 5l7 7-7 7", "lock": "M5 10h14v12H5z M8 10V7a4 4 0 0 1 8 0v3"} %}<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="{{ paths.get(name, paths.file) }}"/></svg>{%- endmacro %}
@@ -0,0 +1 @@
{% macro pi(name) -%}{% set paths = {"home": "M3 3h7v7H3zM14 3h7v7h-7zM3 14h7v7H3zM14 14h7v7h-7z", "pages": "M7 3h10l4 4v14H7z M17 3v5h4 M11 13h6 M11 17h6", "content": "M12 2 3 7l9 5 9-5-9-5z M3 12l9 5 9-5 M3 17l9 5 9-5", "publish": "M12 3v13m-5-5 5 5 5-5 M4 17v4h16v-4", "media": "M3 3h18v18H3z M7 16l4-4 3 3 3-3 4 4", "settings": "M4 6h16 M4 12h16 M4 18h16", "history": "M4 3h16v18H4z M8 9h8 M8 13h8 M8 17h5", "search": "M11 3a8 8 0 1 0 0 16a8 8 0 0 0 0-16z M17 17l4 4", "check": "M4 12l5 5 11-11", "alert": "M12 2 2 21h20L12 2z M12 9v5 M12 17v1", "plus": "M12 4v16 M4 12h16", "file": "M6 2h10l4 4v16H6z M16 2v5h4 M9 12h8 M9 16h8", "arrow": "M4 12h16m-6-6 6 6-6 6", "eye": "M2 12s4-7 10-7 10 7 10 7-4 7-10 7-10-7-10-7z M12 9a3 3 0 1 0 0 6 3 3 0 0 0 0-6", "refresh": "M3 11a9 9 0 1 1 3 7 M3 5v6h6", "shield": "M12 2l8 4v6c0 6-4 9-8 10-4-1-8-4-8-10V6z", "code": "M8 7l-5 5 5 5 M16 7l5 5-5 5", "menu": "M3 6h18 M3 12h18 M3 18h18", "close": "M5 5l14 14 M19 5 5 19", "clock": "M12 2a10 10 0 1 0 0 20a10 10 0 0 0 0-20z M12 7v6l4 2", "layers": "M3 7l9-4 9 4-9 5-9-5 M3 13l9 5 9-5", "copy": "M8 8h13v13H8z M3 3h13v4 M3 3v13h4"} %}<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="{{ paths.get(name, paths.file) }}"/></svg>{%- endmacro %}
@@ -2,6 +2,7 @@
<html lang='ru'>
<head>
<meta charset='utf-8'>
<link rel='icon' type='image/svg+xml' href='{{ static_url("favicon.svg") }}'>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<meta name='robots' content='noindex, nofollow'>
<meta name='htmx-config' content='{"allowEval":false,"allowScriptTags":false,"selfRequestsOnly":true,"includeIndicatorStyles":false,"attributesToSettle":["class","width","height"],"historyCacheSize":0,"responseHandling":[{"code":"204","swap":false},{"code":"[23]..","swap":true},{"code":"4..","swap":true,"error":false},{"code":"5..","swap":false,"error":true}]}'>
@@ -12,6 +13,10 @@
<link rel='stylesheet' href='{{ static_url("pages.css") }}'>
<link rel='stylesheet' href='{{ static_url("builder.css") }}'>
<link rel='stylesheet' href='{{ static_url("builder-adapter.css") }}'>
<link rel='stylesheet' href='{{ static_url("content-editor.css") }}'>
<link rel='stylesheet' href='{{ static_url("content-adapter.css") }}'>
<link rel="stylesheet" href="{{ static_url("publication.css") }}">
<link rel="stylesheet" href="{{ static_url("publication-adapter.css") }}">
{% block styles %}{% endblock %}
</head>
<body data-skin='light'{% block bodyattrs %}{% endblock %}>
@@ -24,5 +29,7 @@
<script src='{{ static_url("editor.js") }}' defer></script>
<script src='{{ static_url("builder.js") }}' defer></script>
<script src='{{ static_url("theme-studio.js") }}' defer></script>
<script src='{{ static_url("content-editor.js") }}' defer></script>
<script src="{{ static_url("publication.js") }}" defer></script>
</body>
</html>
@@ -0,0 +1,33 @@
{% extends 'shell.html.j2' %}
{% from '_content_icons.html.j2' import ci %}
{% set data = snap.schema.content if snap else empty_data %}
{% block contentclass %}design-content content-screen{% endblock %}
{% block title %}{{ meta.get('title', snap.id) if snap else 'Контент и коллекции' }} — Site Engine{% endblock %}
{% block content %}
<div class='entry-content-editor'{% if snap %} id='document-editor' data-base='{{ base }}' data-preview-origin='{{ preview_origin }}' data-revision='{{ snap.revision }}' data-raw-source='{{ snap.source|tojson }}' data-canonical-source='{{ canonical_source|tojson }}'{% else %} id='content-workspace'{% endif %} data-preview-view='card' data-preview-version='workspace' data-collection='{{ data.collection.id if data.collection else "" }}' data-content-source='{{ snap.id if snap else "" }}' hx-boost='false'>
<div class='head entry-head doc-toolbar'><div class='head-main'><div class='eyebrow'>04 / CONTENT OPERATIONS · ENTRY EDITOR</div><h1>{{ meta.get('title', snap.id) if snap else 'Управление контентом' }}</h1><div class='head-meta'><span class='status good' id='buffer-status' role='status'>Нет несохранённых изменений</span>{% if snap %}<code>{{ snap.path }}</code>{% endif %}<span>Pages ≠ Entries</span></div></div><div class='head-actions'>{% if snap %}<div class='toggle' aria-label='Режим редактора'><button type='button' data-editor-mode='constructor' aria-pressed='true' class='active'>Конструктор</button><button type='button' data-editor-mode='expert' aria-pressed='false'>Эксперт</button></div><button class='button' type='button' data-content-validate>{{ ci('check') }} Проверить</button><button class='button primary' type='submit' form='buffer-form' data-save-document>{{ ci('save') }} Сохранить черновик</button>{% endif %}</div></div>
{% if content_error|default('') %}<div class='issue-callout' role='alert'>{{ content_error }}</div>{% endif %}
<div class='entry-workspace'>
<div id='collection-host'><section class='collection-pane'><div class='pane-title'><div><b>Коллекции</b><small>collections/*.yaml</small></div><span class='mini-pill'>{{ data.collections|length }}</span></div><div class='collection-chips'>
{% for c in data.collections %}<a class='collection-choice{% if data.collection and c.id == data.collection.id %} active{% endif %}' href='/admin/content/{{ c.id }}'><span><b>{{ c.name }}</b><small class='mono'>{{ c.id }}</small></span><span class='collection-right'><strong>{{ c.total }}</strong>{% if not c.enabled %}<em>OFF</em>{% endif %}</span></a>{% else %}<div class='empty-pane'>Коллекций нет</div>{% endfor %}</div><div class='pane-help'><b>File-first CMS</b><p>Контент хранится в Markdown + YAML. SQLite не является источником публичных записей.</p></div></section></div>
<div id='entry-list-host'><section class='entry-pane'><div class='pane-title'><div><b>Записи / {{ data.collection.id if data.collection else '—' }}</b><small>{{ data.entries|length }} записей · {{ 'активна' if data.collection and data.collection.enabled else 'коллекция выключена' }}</small></div>{% if data.collection %}<form data-content-create method='post' action='/admin/content/{{ data.collection.id }}/new'><input type='hidden' name='csrf' value='{{ csrf }}'><button class='button small' type='submit' title='Создать запись' aria-label='Создать запись'{% if not data.collection.enabled %} disabled{% endif %}>{{ ci('plus') }}</button></form>{% endif %}</div>
<div class='search-wrap'>{{ ci('search') }}<input id='entry-query' placeholder='Поиск записей / slug' aria-label='Поиск записей'></div><div class='entry-filters'>{% for value,label in [('all','Все'),('published','В каталоге'),('draft','Черновики'),('changed','Изменены')] %}<button type='button' data-content-filter='{{ value }}'{% if value == 'all' %} class='active'{% endif %}{% if value == 'changed' and not data.comparison_available %} disabled title='В этом релизе нет хешей записей для сравнения'{% endif %}>{{ label }}</button>{% endfor %}</div>
<div class='entry-list' id='entry-list'>{% for e in data.entries %}<a class='entry-row{% if snap and e.slug == snap.id %} active{% endif %}' href='{{ e.url }}' data-entry='{{ e.slug }}' data-entry-status='{{ e.status }}' data-entry-changed='{{ 1 if e.changed else 0 }}' data-entry-search='{{ (e.title ~ " " ~ e.slug)|lower }}'><span class='entry-row-icon'>{{ ci('file') }}</span><span class='entry-row-copy'><b>{{ e.title }}</b><small class='mono'>{{ e.slug }}</small><span class='entry-status-row'><span class='status {{ "good" if e.status == "published" else "warn" }}'>{{ {'published':'В каталоге','draft':'Черновик','archived':'Архив'}.get(e.status,e.status) }}</span>{% if e.changed %}<em class='mini-pill'>● Правки</em>{% endif %}</span></span>{{ ci('chevron') }}</a>{% endfor %}
<div class='empty-pane' data-content-list-empty{% if data.entries %} hidden{% endif %}>{{ ci('search') }}<b>{{ 'Ничего не найдено' if data.entries else 'Записей пока нет' }}</b><p>{{ 'Измените фильтры или создайте запись.' if not data.collection or data.collection.enabled else 'Коллекция выключена: записи не участвуют в публичной сборке.' }}</p></div></div><div class='list-foot'><span data-content-list-count>{{ data.entries|length }} из {{ data.entries|length }}</span></div></section></div>
<div class='content-editor'><div id='entry-editor'>
{% if snap %}
{% include 'entry_editor_result.html.j2' %}
<form id='buffer-form' method='post' action='/admin/editor{{ base }}/save'>
<input type='hidden' name='csrf' value='{{ csrf }}'><input type='hidden' name='etag' value='{{ snap.etag }}'><input type='hidden' name='revision' value='{{ snap.revision }}'><input type='hidden' name='mode' value='{{ mode }}'><input type='hidden' name='selection' value=''>
<div class='expert-wrap' id='expert-pane'><div class='expert-header'><div><div class='eyebrow'>SOURCE / ENTRY</div><h2>{{ snap.path }}</h2><p>YAML front matter + Markdown body · schema: {{ data.collection.id }}</p></div><div class='expert-actions'><button class='button small' type='button' data-content-find>{{ ci('search') }} Найти</button><button class='button small' type='button' data-content-validate>{{ ci('check') }} Проверить</button><button class='button small primary' type='button' data-content-apply>{{ ci('code') }} Применить</button><button class='button small' type='button' data-content-diff>Diff</button><button class='button small' type='button' data-download>Скачать</button></div></div><div class='source-toolbar'><span>YAML + MARKDOWN</span><span data-content-source-status>Синхронизирован</span></div><div class='source-code'><div class='code-lines' id='code-lines'></div><div class='source-edit-wrap'><pre id='entry-highlight' aria-hidden='true'></pre><textarea id='document-source' name='source' spellcheck='false' aria-label='Исходник записи YAML и Markdown'>{{ snap.source }}</textarea></div></div><div class='source-errorbox' data-content-source-errors>{% for issue in snap.issues %}<p>{{ issue.code }} · {{ issue.message }}</p>{% endfor %}</div></div>
</form>{% else %}<div class='empty-editor'>Выберите запись или активную коллекцию.</div>{% endif %}
</div></div>
<div id='preview-host'><aside class='preview-pane'><div class='pane-title'><div><b>Предпросмотр</b><small>{{ data.display or 'Выберите запись' }}</small></div></div><div class='preview-pane-content'>
<div class='toggle w-full' aria-label='Вариант отображения'><button type='button' data-content-preview='card' aria-pressed='false'>Карточка</button><button type='button' data-content-preview='page' class='active' aria-pressed='true'>Полная страница</button></div><div class='toggle w-full preview-version' aria-label='Снимок'><button type='button' data-content-version='workspace' class='active' aria-pressed='true'>Workspace</button><button type='button' data-content-version='live' aria-pressed='false'{% if not data.live_build %} disabled title='Публичного релиза пока нет'{% endif %}>Live</button></div>
<div class='preview-route'><span>PUBLIC ROUTE</span><code>{{ data.route|default('—') }}</code></div><div id='preview-result' aria-live='polite' class='site-page-preview'><p class='preview-empty'>{{ 'Подготовка предпросмотра…' if snap else 'Выберите запись для предпросмотра.' }}</p></div>
<div class='preview-info'><div><span>Display template</span><code>{{ data.display or '—' }}</code></div><div><span>Источник</span><code>{{ snap.path if snap else '—' }}</code></div><div><span>Состояние</span><b data-content-preview-state>workspace / черновик</b></div></div>
</div></aside></div></div>
<div class='workspace-footer'><span id='editor-notice' role='status' aria-live='polite'>Сохранение документа не публикует сайт.</span><span>Workspace ≠ Live Release{% if data.live_build %} · {{ data.live_build }}{% endif %}</span></div>
<div id='content-overlay'></div><template data-content-ref-arrow>{{ ci('arrow') }}</template>
</div>
{% endblock %}
@@ -1,46 +1,35 @@
{% from '_fields.html.j2' import field %}
{% macro buffer_fields() %}<input type='hidden' name='csrf' value='{{ csrf }}'><input type='hidden' name='etag' value='{{ snap.etag }}'><input type='hidden' name='revision' value='{{ snap.revision }}'><input type='hidden' name='selection' value='{{ selection }}'>{% if not compact_update|default(false) %}<textarea name='source' hidden>{{ snap.source }}</textarea>{% endif %}{% endmacro %}
<div id='editor-result' data-revision='{{ snap.revision }}' data-valid='{{ 1 if snap.model else 0 }}' data-saved='{{ 1 if saved else 0 }}' data-etag='{{ snap.etag }}' {% if not compact_update|default(false) %}data-raw-source='{{ snap.source|tojson }}'{% endif %} data-title='{{ meta.get("title", snap.id) }}' data-readonly='{{ readonly_key }}'>
{% if not compact_update|default(false) %}<textarea data-next-source hidden>{{ snap.source }}</textarea>{% endif %}
{% if saved %}<p class='success' role='status'>Документ сохранён. Публикация не выполнялась.</p>{% endif %}
{% if errors %}<ul class='issues' role='alert'>{% for e in errors %}<li class='error'>{{ e }}</li>{% endfor %}</ul>{% endif %}
{% if submitted_fields %}<details class='submitted-fields'><summary>Отправленные значения формы</summary>{% for key, values in submitted_fields %}{% if key not in ['csrf','source'] %}<p><code>{{ key }}</code>: {{ values|join(', ') }}</p>{% endif %}{% endfor %}</details>{% endif %}
{% if snap.issues %}<ul class='issues'>{% for i in snap.issues %}<li class='{{ i.severity }}'><code>{{ i.code }}</code> {{ i.path }}: {{ i.message }}</li>{% endfor %}</ul>{% endif %}
{% if conflict %}<section class='conflict-panel' role='alert'><h2>Документ изменён на сервере</h2><p>Ваш буфер сохранён. Сравните версии, внесите слияние в «Эксперте», затем явно примите новую основу и нажмите Save.</p><div class='conflict-columns'><label>Отправленный исходник<textarea rows='16' readonly>{{ snap.source }}</textarea></label><label>Серверный исходник<textarea rows='16' readonly>{{ conflict.source }}</textarea></label></div><form method='post' action='/admin/editor{{ base }}/rebase'>{{ buffer_fields() }}<input type='hidden' name='new_etag' value='{{ conflict.etag }}'><label class='inline'><input type='checkbox' name='confirm_rebase' value='1' required> Принимаю указанную серверную версию как новую основу</label><button type='submit' data-rebase='{{ conflict.etag }}'>Принять эту серверную версию как основу</button></form><p class='hint'>Кнопка меняет только ETag основы; исходник остаётся вашим. Повторное сохранение — отдельное действие.</p></section>{% endif %}
<div class='constructor-grid' data-constructor>
{% if snap.model %}
<section class='doc-tree' aria-label='Структура документа'><h2>Структура</h2>
<form method='post' action='/admin/editor{{ base }}/select' hx-post='/admin/editor{{ base }}/select' hx-target='#editor-result' hx-swap='outerHTML'>{{ buffer_fields() }}<button name='choose' value='' type='submit'>Свойства документа</button></form>
{% for b in fixed + display %}<div class='readonly-block{% if readonly_selected and readonly_selected.scope == b.scope and readonly_selected.owner == b.owner and readonly_selected.id == b.id %} selected{% endif %}' data-tree-scope='{{ b.scope }}' data-tree-owner='{{ b.owner }}' data-tree-id='{{ b.id }}'><small>{{ b.scope }} / {{ b.region }}</small><form method='post' action='/admin/editor{{ base }}/select' hx-post='/admin/editor{{ base }}/select' hx-target='#editor-result' hx-swap='outerHTML'>{{ buffer_fields() }}<button name='choose_readonly' value='{{ {"scope":b.scope,"owner":b.owner,"id":b.id}|tojson }}'>{{ b.fragment }} · {{ b.id }}</button></form><span class='hint'>Только чтение · определяется шаблоном</span></div>{% endfor %}
{% for b in blocks %}
<div class='tree-node{% if selected and selected.id == b.id %} selected{% endif %}' data-tree-scope='{{ b.scope }}' data-tree-owner='{{ b.owner }}' data-tree-id='{{ b.id }}' data-depth='{{ b.depth }}'>
<small>{{ b.region }}</small><form method='post' action='/admin/editor{{ base }}/select' hx-post='/admin/editor{{ base }}/select' hx-target='#editor-result' hx-swap='outerHTML'>{{ buffer_fields() }}<button name='choose' value='{{ b.id }}' type='submit'>{{ b.fragment }} <code>{{ b.id }}</code></button></form>
{% if b.hidden %}<span class='hint'>Скрыт: отсутствует в превью</span>{% endif %}{% if b.requires %}<span class='hint'>Условие: {{ b.requires|join(', ') }}</span>{% endif %}
</div>
{% else %}<p class='muted'>Блоков документа нет.</p>{% endfor %}
{% if snap.kind == 'page' %}<details><summary>Добавить блок</summary><form method='post' action='/admin/editor{{ base }}/transform' hx-post='/admin/editor{{ base }}/transform' hx-target='#editor-result' hx-swap='outerHTML'>{{ buffer_fields() }}<input type='hidden' name='operation' value='add'><label>Фрагмент<select name='fragment'>{% for id, f in snap.schema.fragments.items() %}<option value='{{ id }}'>{{ f.name }} / {{ id }}</option>{% endfor %}</select></label><label>Регион<select name='region'>{% for name, r in snap.schema.regions.items() %}{% if r.allow is not none or not r.fixed %}<option>{{ name }}</option>{% endif %}{% endfor %}</select></label><label>ID родителя (для слота)<input name='parent'></label><label>Слот<input name='slot'></label><button type='submit'>Добавить в буфер</button></form></details>{% endif %}
</section>
<section class='doc-inspector' aria-label='Инспектор'><h2>{{ readonly_selected.fragment if readonly_selected else selected.fragment if selected else 'Свойства документа' }}</h2>
{% if readonly_selected %}<div data-readonly-inspector><p>Только чтение · {{ readonly_selected.scope }} / {{ readonly_selected.owner }}</p><p><code>{{ readonly_selected.id }}</code> · {{ readonly_selected.region }}</p><h3>Props</h3><pre>{{ readonly_selected.get('props', {})|tojson(indent=2) }}</pre><p class='hint'>Этот блок определяется шаблоном. Изменение layout/display из редактора документа недоступно.</p></div>
{% else %}
<form method='post' action='/admin/editor{{ base }}/transform' hx-post='/admin/editor{{ base }}/transform' hx-target='#editor-result' hx-swap='outerHTML' data-inspector>{{ buffer_fields() }}
<input type='hidden' name='operation' value='{{ "block" if selected else "metadata" if snap.kind == "page" else "entry_fields" }}'>
{% if selected %}<input type='hidden' name='block_id' value='{{ selected.id }}'><p><code>{{ selected.id }}</code></p>
{% for f in fields %}{{ field(f) }}{% endfor %}
<label class='inline'><input type='checkbox' name='hidden' value='1'{% if selected.hidden %} checked{% endif %}> Скрыть блок</label>
<label>Якорь<input name='anchor' value='{{ selected.anchor|default("", true) }}'></label><label>Заметка<input name='note' value='{{ selected.note|default("", true) }}'></label>
{% for key, enabled in snap.schema.features.items() %}<label class='inline'><input type='checkbox' name='requires' value='feature.{{ key }}'{% if 'feature.' + key in selected.get('requires', []) %} checked{% endif %}> feature.{{ key }} ({{ enabled }})</label>{% endfor %}
{% else %}
{% if snap.kind == 'page' %}<label>Заголовок<input name='title' value='{{ meta.get("title", "") }}'></label><label>Layout<select name='layout'><option value=''>Наследовать ({{ snap.schema.layout }})</option>{% for l in snap.schema.layouts %}<option{% if meta.get('layout') == l %} selected{% endif %}>{{ l }}</option>{% endfor %}</select></label><label>Маршрут<input name='route' value='{{ meta.get("route", "") }}'></label><label>SEO description<textarea name='seo_description'>{{ meta.get('seo', {}).get('description', '') }}</textarea></label>
{% else %}{% for f in fields %}{{ field(f) }}{% endfor %}{% endif %}
<label>Статус<select name='status'>{% for s in statuses %}<option{% if meta.get('status', 'draft') == s %} selected{% endif %}>{{ s }}</option>{% endfor %}</select></label>
{% if snap.schema.has_body %}<label>Markdown<textarea name='body' rows='8'>{{ body }}</textarea></label>{% endif %}
{% endif %}
<button type='submit'>Применить к буферу</button></form>
{% if selected %}<form method='post' action='/admin/editor{{ base }}/transform' hx-post='/admin/editor{{ base }}/transform' hx-target='#editor-result' hx-swap='outerHTML'>{{ buffer_fields() }}<input type='hidden' name='block_id' value='{{ selected.id }}'><input type='hidden' name='operation' value='move'><button name='direction' value='up'>↑ Выше</button><button name='direction' value='down'>↓ Ниже</button><label>Перед ID<input name='before'></label><button type='submit'>Переместить к ID</button></form><form method='post' action='/admin/editor{{ base }}/transform' hx-post='/admin/editor{{ base }}/transform' hx-target='#editor-result' hx-swap='outerHTML' data-confirm='Удалить блок из буфера вместе с вложенными блоками?'>{{ buffer_fields() }}<input type='hidden' name='block_id' value='{{ selected.id }}'><button name='operation' value='toggle'>Скрыть / показать</button><button name='operation' value='delete' class='danger'>Удалить блок</button></form>{% endif %}
<p class='hint'>Конструктор пересобирает YAML: комментарии и форматирование могут измениться. Перед первой правкой скачайте исходник.</p>
{% endif %}
</section>
{% else %}<p class='error'>Конструктор недоступен: исправьте исходник в режиме «Эксперт». Последнее корректное дерево сохраняется в открытом редакторе.</p>{% endif %}
</div>
{% from '_content_icons.html.j2' import ci %}
{% from '_content_fields.html.j2' import cf %}
{% set data = snap.schema.content %}
{% macro slug_field() %}<div class='entry-field'><label class='field-label' for='entry-slug'>Slug / маршрут<small class='mono'>slug</small></label><input id='entry-slug' value='{{ snap.id }}' readonly title='Идентификатор файла. Переименование требует отдельной операции с обновлением ссылок.'></div>{% endmacro %}
<div id='editor-result' data-revision='{{ snap.revision }}' data-valid='{{ 1 if snap.model else 0 }}' data-saved='{{ 1 if saved else 0 }}' data-etag='{{ snap.etag }}' data-title='{{ meta.get("title", snap.id) }}' data-readonly=''>
{% if not compact_update|default(false) %}<textarea data-next-source hidden>{{ snap.source }}</textarea>{% endif %}
<div class='editor-content doc-inspector' data-constructor>
<div class='editor-title'><div><div class='eyebrow'>ENTRY / {{ data.collection.id }}</div><h2 data-entry-title>{{ meta.get('title', snap.id) }}</h2><p class='mono'>{{ snap.path }}</p></div><div class='editor-quick'><button type='button' class='button small' data-content-duplicate>{{ ci('copy') }} Дублировать</button><button type='button' class='button small danger' data-content-delete>{{ ci('trash') }} Удалить</button></div></div>
<div class='entry-tabs'>{% for tab,label in [('fields','Поля'),('relations','Связи'),('usage','Где используется'),('schema','Схема')] %}<button type='button' data-content-tab='{{ tab }}'{% if tab == 'fields' %} class='active'{% endif %}>{{ label }}</button>{% endfor %}</div>
<div class='entry-tab-body'>
<div data-content-panel='fields'>
{% if errors %}<div class='issue-callout' role='alert'>{% for error in errors %}<p>{{ error }}</p>{% endfor %}</div>{% endif %}
{% if not snap.model %}<div class='issue-callout'>Исправьте исходник в режиме «Эксперт». Ваш текст остаётся в редакторе.</div>{% else %}
<form class='editor-form' method='post' action='/admin/editor{{ base }}/transform' data-inspector>
<input type='hidden' name='csrf' value='{{ csrf }}'><input type='hidden' name='etag' value='{{ snap.etag }}'><input type='hidden' name='operation' value='entry_fields'>
{% if not compact_update|default(false) %}<textarea name='source' hidden>{{ snap.source }}</textarea>{% endif %}
<div class='field-section'><h3>Поля коллекции <small>генерируются по collections/{{ data.collection.id }}.yaml</small></h3><div class='field-grid'>
{% if not fields|selectattr('key','equalto','title')|list %}{{ slug_field() }}{% endif %}
{% for f in fields %}{{ cf(f) }}{% if f.key == 'title' %}{{ slug_field() }}{% endif %}{% endfor %}
</div></div>
{% if snap.schema.has_body %}<div class='field-section'><h3>Markdown body</h3><div class='entry-field' data-field-container='body'><label class='field-label' for='content-body'>Основной текст<small class='mono'>body</small></label><textarea id='content-body' name='body' rows='8' spellcheck='false'>{{ body }}</textarea><small>Markdown body хранится отдельно от front matter</small></div></div>{% endif %}
<div class='field-section'><h3>Файловый статус</h3><label class='entry-field'><span class='field-label'>Статус документа</span><select id='entry-status' name='status'>{% for value,label in [('draft','Черновик · draft'),('published','В каталоге · published'),('archived','Архив · archived')] %}<option value='{{ value }}'{% if meta.get('status','draft') == value %} selected{% endif %}>{{ label }}</option>{% endfor %}</select><small>published в файле ≠ текущий live build</small></label></div>
<button class='button small' type='submit'>Применить изменения</button>
</form>{% endif %}</div>
<div class='tab-panel' data-content-panel='relations' hidden><div class='panel-heading'><h3>Связи записи</h3><p>Entry → refs → Entry · редактируются в форме или напрямую здесь</p></div>
{% for f in data.ref_fields %}<div class='relation-group'><div class='relation-group-head'><strong>{{ f.label }}</strong><button class='button small' type='button' data-content-configure='p.{{ f.key }}'>Настроить</button></div>{% for r in data.relations if r.field == f.key %}<a class='relation-row{% if not r.url %} bad{% endif %}'{% if r.url %} href='{{ r.url }}'{% endif %}><span>{{ ci('link' if r.url else 'alert') }}</span><div><b>{{ r.title }}</b><small class='mono'>{{ r.file }}</small></div><span class='status{% if r.status == "published" %} good{% endif %}'>{{ r.status }}</span></a>{% else %}<p class='muted'>Нет связей</p>{% endfor %}</div>{% else %}<div class='muted'>В схеме этой коллекции нет полей refs.</div>{% endfor %}
<div class='note-inline'>При удалении записи связь не исправляется автоматически: серверная валидация находит битые ссылки.</div></div>
<div class='tab-panel' data-content-panel='usage' hidden><div class='panel-heading'><h3>Где используется?</h3><p>Обратные зависимости Entry → refs, Collection query → rendered output</p></div><div class='usage-count'>{{ data.usages|length }} использований <span class='mono'>{{ data.collection.id }}/{{ snap.id }}</span></div>
{% for u in data.usages %}<a class='usage-row' href='{{ u.url }}'><span class='usage-glyph'>{{ ci('file' if u.kind == 'page' else 'layers') }}</span><span><b>{{ u.title }}</b><small>{{ u.file }} → {{ u.field }}</small></span>{{ ci('arrow') }}</a>{% else %}<div class='empty-pane'>Привязок к этой записи пока нет.</div>{% endfor %}</div>
<div class='tab-panel' data-content-panel='schema' hidden><div class='panel-heading'><h3>Схема коллекции</h3><p>Только чтение · определения типов коллекции</p></div><div class='schema-contract'><span class='status warn'>READ ONLY</span><span class='mono'>collections/{{ data.collection.id }}.yaml</span></div><pre class='schema-code'>{{ data.schema_text }}</pre><div class='note-inline'>Редактор записей и редактор YAML документа используют одну схему. Эксперт не меняет определения типов.</div></div>
</div>
<template data-content-diagnostics>{{ snap.issues|tojson }}</template>
<template data-content-navigation>{{ data|tojson }}</template>
</div></div>
@@ -0,0 +1,11 @@
{% extends 'shell.html.j2' %}
{% block title %}Публикация — админка{% endblock %}
{% block contentclass %}design-content publication-content{% endblock %}
{% block content %}
<div id='publication-editor' class='wrap' data-publication-root hx-boost='false'>
<div data-publication-view><div class='heading'><div><div class='overline'>05 / RELEASE WORKFLOW · ATOMIC SITE RELEASES</div><h1>Публикация сайта</h1></div></div><p role='status'>Загрузка данных публикации…</p></div>
<textarea data-publication-boot hidden>{{ boot|tojson }}</textarea>
<noscript><p>Для просмотра кандидата и сравнения включите JavaScript. Доступна <a href='/admin/publish/legacy'>обычная форма публикации</a>.</p></noscript>
<div id='publication-modal-root'></div><div id='publication-notice' role='status' aria-live='polite'></div>
</div>
{% endblock %}
+70
View File
@@ -107,9 +107,26 @@ class InspectorEdit(DTO):
class EditorUpdate(Buffer):
preview_view: Literal["page", "card"] = "page"
preview_version: Literal["workspace", "live"] = "workspace"
operations: list[Action | InspectorEdit] = Field(default_factory=list, max_length=100)
class EntryDeleted(DTO):
deleted: Literal[True]
id: str
collection: str
class EntryCheck(DTO):
revision: int
issues: list[IssueDTO]
class EntryCopy(Buffer):
id: str = Field(pattern=r"^[a-z0-9][a-z0-9_-]*$", max_length=200)
class Create(DTO):
id: str = Field(min_length=1, max_length=200)
title: str = ""
@@ -172,6 +189,8 @@ class ErrorBody(DTO):
current: Snapshot | ThemeSnapshot | None = None
committed: Snapshot | ThemeSnapshot | None = None
buffer: Snapshot | None = None
deleted: bool | None = None
committed_build: str | None = None
class ErrorEnvelope(DTO):
@@ -194,6 +213,8 @@ class PageRow(DTO):
class EntryRow(DTO):
changed: bool | None = None
url: str = ""
slug: str
title: str
status: str
@@ -202,6 +223,7 @@ class EntryRow(DTO):
class CollectionRow(DTO):
enabled: bool = True
id: str
name: str
total: int
@@ -226,6 +248,12 @@ class Workspace(DTO):
class Entries(DTO):
collections: list[CollectionRow] = Field(default_factory=list)
schema_text: str = ""
display: str = ""
kind: str = "content"
live_build: str | None = None
comparison_available: bool = False
collection: CollectionRow
entries: list[EntryRow]
@@ -272,3 +300,45 @@ def snapshot_dto(value):
schema=value.schema,
revision=value.revision,
)
class PublicationDocument(DTO):
hash: str
size: int
title: str
status: str
type: str
source: str | None = None
class PublicationChange(DTO):
path: str
title: str
type: str
status: str
kind: Literal["new", "modified", "deleted", "unknown"]
before: PublicationDocument | None = None
after: PublicationDocument | None = None
class PublicationState(DTO):
current: str | None
source_hash: str
comparison_available: bool
changes: list[PublicationChange]
candidate: dict[str, Any] | None = None
validation: dict[str, Any] | None = None
history: list[dict[str, Any]]
builds: list[dict[str, Any]]
activity: list[dict[str, Any]]
class ReleaseActivate(DTO):
id: str = Field(pattern=r"^\d{8}T\d{6}-[0-9a-f]{8}$")
expected_live: str | None
comment: str = Field(default="", max_length=150)
class ReleasePreview(DTO):
id: str = Field(pattern=r"^\d{8}T\d{6}-[0-9a-f]{8}$")
route: str = Field(default="/", max_length=2000)
+100 -6
View File
@@ -12,9 +12,15 @@ from starlette.exceptions import HTTPException as StarletteHTTPException
from ...core.models import STATUSES
from ...errors import ConflictError, EngineError, UnsafePathError
from ...services.documents import AuditCommitError, DocumentMissing, EditorContext
from ...services.entries import EntryService
from ...services.entries import EntryDeleteCommitError, EntryService
from ...services.pages import PageService
from ...services.preview import asset_path
from ...services.publication import (
CandidateCommitError,
PublicationService,
ReleaseCommitError,
ReleaseMissing,
)
from ...services.publish import publish, rollback
from ...services.theme import OnboardingService, ThemeCommitError, ThemeService
from ...services.workspace import entries, filter_pages, releases, workspace
@@ -27,10 +33,16 @@ from .models import (
EditorUpdate,
EditorUpdateResult,
Entries,
EntryCheck,
EntryCopy,
EntryDeleted,
ErrorEnvelope,
OnboardingState,
PageRow,
Preview,
PublicationState,
ReleaseActivate,
ReleasePreview,
Releases,
Rollback,
Snapshot,
@@ -81,7 +93,7 @@ def install_api(app, auth, root, dist, previews):
return (
PageService(root, auth.audit)
if kind == "page"
else EntryService(root, auth.audit, collection)
else EntryService(root, auth.audit, collection, dist=dist)
)
def themes():
@@ -110,7 +122,7 @@ def install_api(app, auth, root, dist, previews):
409,
"conflict",
exc,
submitted=buf.model_dump(exclude={"action", "operations"}) if buf else None,
submitted=buf.model_dump(include={"source", "etag", "revision"}) if buf else None,
current=current,
)
except AuditCommitError as exc:
@@ -121,6 +133,9 @@ def install_api(app, auth, root, dist, previews):
exc,
committed=snapshot_dto(exc.snapshot).model_dump(by_alias=True, mode="json"),
)
except EntryDeleteCommitError as exc:
log.exception("entry_delete_after_commit request_id=%s", request_id())
return error(500, "entry_deleted_audit_failed", exc, deleted=True)
except DocumentMissing as exc:
return error(404, "not_found", exc)
except UnsafePathError as exc:
@@ -131,7 +146,7 @@ def install_api(app, auth, root, dist, previews):
"validation",
exc,
issues=[i.to_dict() for i in exc.report.issues],
submitted=buf.model_dump(exclude={"action", "operations"}) if buf else None,
submitted=buf.model_dump(include={"source", "etag", "revision"}) if buf else None,
)
except (ValueError, KeyError) as exc:
return error(422, "invalid_operation", exc)
@@ -235,7 +250,7 @@ def install_api(app, auth, root, dist, previews):
def read():
if status and status not in STATUSES:
raise EngineError("Некорректный status")
data = entries(root, collection)
data = entries(root, collection, dist)
data["entries"] = [
e
for e in data["entries"]
@@ -246,6 +261,69 @@ def install_api(app, auth, root, dist, previews):
return invoke(read)
def publication():
return PublicationService(root, dist, auth.state_dir, auth.audit)
def publication_invoke(fn):
try:
return fn()
except ReleaseMissing as exc:
return error(404, "release_not_found", exc)
except CandidateCommitError as exc:
log.exception("candidate_after_build request_id=%s", request_id())
return error(500, "candidate_after_build", exc, committed_build=exc.build_id)
except ReleaseCommitError as exc:
log.exception("release_after_commit request_id=%s", request_id())
return error(500, "release_after_commit", exc, committed_build=exc.build_id)
except ConflictError as exc:
return error(409, "release_conflict", exc)
except UnsafePathError as exc:
return error(403, "forbidden", exc)
except EngineError as exc:
return error(422, "release_validation", exc, issues=[i.to_dict() for i in exc.report.issues])
except ValueError as exc:
return error(422, "invalid_operation", exc)
@router.get("/publication", response_model=PublicationState)
def publication_state():
return publication_invoke(lambda: publication().state())
@router.post("/publication/validate")
def publication_validate(ctx: Ctx):
return publication_invoke(lambda: publication().validate(ctx))
@router.post("/publication/build")
def publication_build(ctx: Ctx):
return publication_invoke(lambda: publication().build(ctx, request_id()))
@router.post("/publication/activate")
def publication_activate(body: ReleaseActivate, ctx: Ctx):
return publication_invoke(lambda: publication().activate(body.id, body.expected_live, body.comment, ctx))
@router.post("/publication/rollback")
def publication_rollback(body: ReleaseActivate, ctx: Ctx):
return publication_invoke(lambda: publication().activate(body.id, body.expected_live, body.comment, ctx, rollback=True))
@router.get("/publication/release")
def publication_release(id: str):
return publication_invoke(lambda: publication().release_details(id))
@router.get("/publication/candidate-diff")
def publication_candidate_diff():
return publication_invoke(lambda: publication().candidate_diff())
@router.get("/publication/compare")
def publication_compare(path: str):
return publication_invoke(lambda: publication().compare(path))
@router.get("/publication/document-history")
def publication_document_history(path: str):
return publication_invoke(lambda: publication().document_history(path))
@router.post("/publication/preview", response_model=Preview)
def publication_preview(body: ReleasePreview, ctx: Ctx):
return publication_invoke(lambda: publication().preview(body.id, body.route, previews, ctx.principal))
@router.get("/releases", response_model=Releases)
def release_list():
return releases(dist)
@@ -386,7 +464,8 @@ def install_api(app, auth, root, dist, previews):
preview, preview_error = None, None
try:
preview = previews.render_document(
reg, svc, identity, body.revision, ctx.principal, include_html=True
reg, svc, identity, body.revision, ctx.principal, include_html=True,
target=body.preview_view, version=body.preview_version, dist=dist
)
except Exception as exc: # noqa: BLE001 - preview failure is an independent result
# A failed preview must never roll back accepted in-memory edits.
@@ -410,6 +489,21 @@ def install_api(app, auth, root, dist, previews):
def entry_update(collection: str, identity: str, body: EditorUpdate, ctx: Ctx):
return update("entry", identity, body, ctx, collection)
@router.post("/collections/{collection}/entries/{identity}/check", response_model=EntryCheck)
def entry_check(collection: str, identity: str, body: Buffer, ctx: Ctx):
svc = service("entry", collection)
return invoke(lambda: svc.check(identity, body.source, body.etag, body.revision), svc, identity, body)
@router.post("/collections/{collection}/entries/{identity}/duplicate", response_model=Snapshot, status_code=201)
def entry_duplicate(collection: str, identity: str, body: EntryCopy, ctx: Ctx):
svc = service("entry", collection)
return invoke(lambda: snapshot_dto(svc.duplicate(identity, body.id, body.source, body.etag, ctx)), svc, identity, body)
@router.post("/collections/{collection}/entries/{identity}/delete", response_model=EntryDeleted)
def entry_delete(collection: str, identity: str, body: Buffer, ctx: Ctx):
svc = service("entry", collection)
return invoke(lambda: svc.delete(identity, body.etag, ctx), svc, identity, body)
@router.post("/editor/pages/{identity:path}/validate", response_model=Snapshot)
@router.post("/pages/{identity:path}/validate", response_model=Snapshot)
def page_validate(identity: str, body: Buffer, ctx: Ctx):
+1 -1
View File
@@ -17,7 +17,7 @@ def snapshot_response(store, snapshot, token, asset=None):
except (PermissionError, OSError, ValueError, UnsafePathError):
return Response("Превью недоступно", status_code=403, headers={"Cache-Control": "no-store"})
config = store.config
script = f"'nonce-{data['nonce']}'" if config else "'none'"
script = f"'nonce-{data['nonce']}'" if config and not data.get("passive") else "'none'"
ancestors = config.admin if config else "'self'"
headers = {
"Cache-Control": "no-store",
+359
View File
@@ -0,0 +1,359 @@
"""Content editor contract: real metadata, stateless readiness, CAS and immutable Live."""
import json
import os
import shutil
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
from fastapi.testclient import TestClient
from site_engine.build.pipeline import build_site
from site_engine.core.registry import load_site
from site_engine.parsing.frontmatter import dumps, parse
from site_engine.parsing.yamlio import dump_yaml, load_yaml
from site_engine.services.auth import hash_password
from site_engine.services.documents import EditorContext
from site_engine.services.entries import EntryService
from site_engine.web.app import create_app
ROOT = Path(__file__).resolve().parents[1]
class ContentEditorTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.password = "content editor test password"
cls.password_hash = hash_password(cls.password, n=2**10)
def setUp(self):
tmp = tempfile.TemporaryDirectory(prefix="content-editor-test-")
self.addCleanup(tmp.cleanup)
self.work = Path(tmp.name)
self.site = self.work / "site"
self.dist = self.work / "dist"
shutil.copytree(
ROOT / "examples/site-studio", self.site, ignore=shutil.ignore_patterns(".engine")
)
env = patch.dict(
os.environ,
{
"SITE_ROOT": str(self.site),
"SITE_DIST": str(self.dist),
"SITE_STATE_DIR": str(self.work / "state"),
"SITE_ADMIN_LOGIN": "admin",
"SITE_ADMIN_PASSWORD_HASH": self.password_hash,
"SITE_SECRET_KEY": "content-editor-test-secret-" * 3,
"SITE_COOKIE_SECURE": "0",
"SITE_ADMIN_ORIGIN": "",
"SITE_PREVIEW_ORIGIN": "",
},
)
env.start()
self.addCleanup(env.stop)
self.app = create_app()
self.client = TestClient(self.app)
self.addCleanup(self.client.close)
cookie = self.app.state.auth.login("admin", self.password, "testclient")
self.client.cookies.set("se_session", cookie)
self.app.state.api_credentials["test"] = (cookie, "testclient")
self.principal = self.app.state.auth.authenticate(cookie)
self.ctx = EditorContext(self.principal, "testclient")
self.csrf = self.app.state.auth.csrf_token(self.principal)
self.svc = EntryService(self.site, collection="services", dist=self.dist)
self.snap = self.svc.get("bots")
def payload(self, **extra):
return {"source": self.snap.source, "etag": self.snap.etag, "revision": 7, **extra}
def api(self, op, payload=None, identity="bots"):
return self.client.post(
f"/admin/api/v1/collections/services/entries/{identity}/{op}",
json=self.payload() if payload is None else payload,
headers={"Authorization": "Bearer test"},
)
def ui(self, op, payload=None, csrf=None):
return self.client.post(
"/admin/editor/content/services/bots/" + op,
data={
"csrf": self.csrf if csrf is None else csrf,
"payload": json.dumps(self.payload() if payload is None else payload),
},
headers={
"Origin": "http://testserver",
"HX-Request": "true",
"Accept": "application/json",
},
)
def test_original_workspace_markup_static_and_empty_disabled_collection(self):
response = self.client.get("/admin/content/services/bots")
self.assertEqual(response.status_code, 200)
for marker in (
"entry-workspace",
"collection-pane",
"entry-pane",
"editor-content",
"preview-pane",
"entry-tabs",
"source-edit-wrap",
"data-content-picker",
):
self.assertIn(marker, response.text)
self.assertNotIn("409 Demo", response.text)
for name in ("content-editor.css", "content-adapter.css", "content-editor.js"):
self.assertEqual(self.client.get("/admin/static/" + name).status_code, 200)
empty = self.client.get("/admin/content/posts")
self.assertEqual(empty.status_code, 200)
self.assertIn("Записей пока нет", empty.text)
self.assertIn("OFF", empty.text)
self.assertIn("disabled", empty.text)
def test_update_has_one_registry_and_api_call_and_no_write(self):
before = (self.site / self.snap.path).read_bytes()
calls = self.app.state.api_calls
payload = self.payload(
preview_view="card",
operations=[{"type": "entry_fields", "values": {"title": "Current candidate"}}],
)
with patch("site_engine.services.documents.load_site", wraps=load_site) as load:
response = self.ui("update", payload)
self.assertEqual(response.status_code, 200, response.text)
self.assertEqual(load.call_count, 1)
self.assertEqual(self.app.state.api_calls - calls, 1)
result = response.json()
self.assertIn("Current candidate", result["preview"]["html"])
self.assertIn("f-entry_card", result["preview"]["html"])
self.assertIn("data-content-panel", result["projection"])
self.assertNotIn("name='source'", result["projection"])
self.assertEqual((self.site / self.snap.path).read_bytes(), before)
self.assertFalse((self.site / ".engine/history").exists())
self.assertFalse((self.dist / "current").exists())
def test_readiness_missing_required_and_render_errors_does_not_block_draft_save(self):
meta, body = parse(self.snap.source)
meta.update(
status="draft", hero_asset="assets/missing.webp", cta={"href": {"page": "missing-page"}}
)
meta.pop("title")
source = dumps(meta, body)
response = self.ui("check", self.payload(source=source))
self.assertEqual(response.status_code, 200, response.text)
codes = {i["code"] for i in response.json()["issues"]}
self.assertIn("E_ENTRY_REQUIRED", codes)
self.assertTrue({"E_ASSET_MISSING", "E_LINK_BROKEN"} & codes, codes)
self.assertEqual((self.site / self.snap.path).read_text(), self.snap.source)
self.assertEqual(self.ui("save", self.payload(source=source)).status_code, 200)
self.assertFalse((self.dist / "current").exists())
def test_readiness_reports_invalid_yaml_without_rewriting_source(self):
source = "---\ntitle: [\n---\nCurrent text"
response = self.api("check", self.payload(source=source))
self.assertEqual(response.status_code, 200)
self.assertTrue(response.json()["issues"])
self.assertEqual((self.site / self.snap.path).read_text(), self.snap.source)
def test_dependencies_use_candidate_query_membership_and_nested_typed_refs(self):
schema_file = self.site / "collections/cases.yaml"
schema = load_yaml(schema_file.read_text())
schema["fields"].append(
{
"key": "nested",
"type": "list",
"fields": [
{"key": "related", "type": "ref", "to": "*"},
{"key": "link", "type": "link"},
],
}
)
schema_file.write_text(dump_yaml(schema))
target = self.site / "content/cases/booking.md"
meta, body = parse(target.read_text())
meta["nested"] = [{"related": "services/bots", "link": {"entry": "services/bots"}}]
target.write_text(dumps(meta, body))
meta, body = parse(self.snap.source)
result = self.svc.validate_source("bots", self.snap.source, self.snap.etag).schema[
"content"
]
self.assertTrue(any(u["field"] == "nested.0.related" for u in result["usages"]))
self.assertTrue(any(u["field"] == "nested.0.link" for u in result["usages"]))
# Home's featured query uses the candidate, not the saved file.
home_before = [u for u in result["usages"] if u["file"] == "pages/index.md"]
self.assertTrue(home_before)
meta["status"] = "draft"
result = self.svc.validate_source("bots", dumps(meta, body), self.snap.etag).schema[
"content"
]
self.assertFalse(any(u["file"] == "pages/index.md" for u in result["usages"]))
self.assertTrue(any(r["target"] == "scenarios/legal" for r in result["relations"]))
self.assertFalse(next(c for c in result["collections"] if c["id"] == "posts")["enabled"])
def test_typed_form_preserves_link_list_refs_and_optional_boolean(self):
response = self.api(
"update",
self.payload(
operations=[
{
"type": "inspector",
"fields": {
"operation": ["entry_fields"],
"p.title": ["Typed fields"],
"p.featured": ["false"],
"p.cta.href.kind": ["entry"],
"p.cta.href.target": ["services/ai"],
"p.benefits.0": ["First"],
"p.benefits.1": ["Second"],
"p.benefits.0._del": ["1"],
"p.related_scenarios": ["legal, services"],
"status": ["draft"],
},
}
]
),
)
self.assertEqual(response.status_code, 200, response.text)
meta = response.json()["snapshot"]["model"]["meta"]
self.assertEqual(meta["benefits"], ["Second"])
self.assertEqual(meta["cta"]["href"], {"entry": "services/ai"})
self.assertEqual(meta["related_scenarios"], ["legal", "services"])
self.assertFalse(meta["featured"])
def test_duplicate_uses_current_editor_and_cas_both_files(self):
source = self.snap.source.replace("Telegram-боты", "My candidate", 1)
response = self.ui("duplicate", self.payload(source=source, id="bots-copy"))
self.assertEqual(response.status_code, 200, response.text)
copy = response.json()["snapshot"]
self.assertEqual(copy["model"]["meta"]["status"], "draft")
self.assertEqual(copy["model"]["meta"]["title"], "My candidate (копия)")
self.assertEqual(copy["model"]["meta"]["slug"], "bots-copy")
self.assertEqual((self.site / self.snap.path).read_text(), self.snap.source)
self.assertEqual(self.api("duplicate", self.payload(id="bots-copy")).status_code, 409)
(self.site / self.snap.path).write_text(self.snap.source + "\nchanged")
self.assertEqual(self.api("duplicate", self.payload(id="bots-another")).status_code, 409)
self.assertFalse((self.site / "content/services/bots-another.md").exists())
self.assertEqual(self.api("duplicate", self.payload(id="../outside")).status_code, 422)
def test_delete_requires_saved_archive_cas_and_history(self):
self.assertEqual(self.api("delete").status_code, 422)
# Unsaved status does not authorize deleting a published file.
self.assertEqual(
self.api(
"delete", self.payload(source=self.snap.source.replace("published", "archived"))
).status_code,
422,
)
snapshot = self.svc.save_source(
"bots", self.snap.source.replace("published", "archived"), self.snap.etag, self.ctx
)
self.assertEqual(self.api("delete").status_code, 409)
response = self.api("delete", {"source": snapshot.source, "etag": snapshot.etag})
self.assertEqual(response.status_code, 200, response.text)
self.assertTrue(response.json()["deleted"])
self.assertFalse((self.site / self.snap.path).exists())
history = list((self.site / ".engine/history").rglob("*"))
self.assertTrue(any(p.is_file() for p in history))
def test_after_commit_audit_failure_reports_committed_copy_or_deleted_flag(self):
with patch.object(
self.app.state.auth.audit, "write", side_effect=OSError("audit unavailable")
):
with self.assertLogs("uvicorn.error", level="ERROR") as logs:
response = self.api("duplicate", self.payload(id="bots-copy"))
self.assertEqual(response.status_code, 500)
self.assertEqual(response.json()["error"]["committed"]["id"], "bots-copy")
self.assertTrue(any("Traceback" in item for item in logs.output))
copy_svc = EntryService(self.site, collection="services")
snapshot = copy_svc.get("bots-copy")
with patch.object(
self.app.state.auth.audit, "write", side_effect=OSError("audit unavailable")
):
response = self.api(
"delete", {"source": snapshot.source, "etag": snapshot.etag}, identity="bots-copy"
)
self.assertEqual(response.status_code, 500)
self.assertTrue(response.json()["error"]["deleted"])
self.assertFalse((self.site / snapshot.path).exists())
def test_live_is_release_html_and_assets_not_current_workspace(self):
build_site(self.site, self.dist)
manifest = json.loads((self.dist / "current/manifest.json").read_text())
self.assertEqual(manifest["entry_routes"]["services/bots"], "/services/bots/")
self.assertIn(self.snap.path, manifest["entry_sources"])
response = self.api(
"update",
self.payload(
preview_version="live",
preview_view="page",
source=self.snap.source.replace("Telegram-боты", "Only workspace", 1),
),
)
self.assertEqual(response.status_code, 200, response.text)
preview = response.json()["preview"]
self.assertIn("Telegram-боты", preview["html"])
self.assertNotIn("Only workspace", preview["html"])
result = self.client.get(preview["url"])
self.assertEqual(result.status_code, 200)
self.assertIn("script-src 'none'", result.headers["content-security-policy"])
from urllib.parse import parse_qs, urlsplit
token = parse_qs(urlsplit(preview["url"]).query)["token"][0]
folder, _meta = self.app.state.previews.authorize(preview["snapshot"], token)
self.assertTrue(list((folder / "assets").glob("site.*.css")))
self.assertEqual(self.client.get(preview["url"].split("?")[0]).status_code, 403)
card = self.api("update", self.payload(preview_version="live", preview_view="card")).json()[
"preview"
]
self.assertFalse(card["url"])
self.assertIn("карточка", card["message"])
def test_comparison_uses_unsaved_candidate_and_old_release_is_unknown(self):
build_site(self.site, self.dist)
self.assertFalse(
next(
e for e in self.svc.get("bots").schema["content"]["entries"] if e["slug"] == "bots"
)["changed"]
)
candidate = self.svc.validate_source("bots", self.snap.source + "\nunsaved", self.snap.etag)
self.assertTrue(
next(e for e in candidate.schema["content"]["entries"] if e["slug"] == "bots")[
"changed"
]
)
manifest_file = self.dist / "current/manifest.json"
manifest = json.loads(manifest_file.read_text())
del manifest["entry_sources"]
del manifest["entry_routes"]
manifest_file.write_text(json.dumps(manifest))
result = self.svc.get("bots").schema["content"]
self.assertFalse(result["comparison_available"])
self.assertIsNone(result["entries"][0]["changed"])
live = self.api("update", self.payload(preview_version="live")).json()["preview"]
self.assertFalse(live["url"])
self.assertIn("snapshots", live["message"])
def test_empty_new_draft_has_real_card_without_inventing_saved_title(self):
snap = self.svc.create("empty-draft", "", None, self.ctx)
response = self.api(
"update",
{"source": snap.source, "etag": snap.etag, "preview_view": "card"},
identity="empty-draft",
)
self.assertEqual(response.status_code, 200, response.text)
self.assertIsNone(response.json()["preview_error"])
self.assertIn("empty-draft", response.json()["preview"]["html"])
self.assertNotIn("title", parse((self.site / snap.path).read_text())[0])
def test_auth_csrf_and_validation_failures_have_visible_json_contract(self):
response = self.ui("check", csrf="bad")
self.assertEqual(response.status_code, 403)
self.assertTrue(response.json()["error"]["request_id"])
self.assertEqual(self.api("update", self.payload(preview_view="fake")).status_code, 422)
self.client.cookies.clear()
self.assertEqual(self.ui("delete").status_code, 401)
if __name__ == "__main__":
unittest.main()
+397
View File
@@ -0,0 +1,397 @@
"""Publication contract: real candidates, private provenance, CAS and immutable live."""
import json
import os
import shutil
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
from fastapi.testclient import TestClient
from site_engine.build.pipeline import build_site, hash_tree
from site_engine.services.auth import hash_password
from site_engine.services.documents import EditorContext
from site_engine.services.publication import PublicationService
from site_engine.web.app import create_app
ROOT = Path(__file__).resolve().parents[1]
class PublicationTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.password = "publication test password"
cls.password_hash = hash_password(cls.password, n=2**10)
def setUp(self):
tmp = tempfile.TemporaryDirectory(prefix="publication-test-")
self.addCleanup(tmp.cleanup)
self.work = Path(tmp.name)
self.site, self.dist, self.state = (self.work / n for n in ("site", "dist", "state"))
shutil.copytree(
ROOT / "examples/site-studio", self.site, ignore=shutil.ignore_patterns(".engine")
)
env = patch.dict(
os.environ,
{
"SITE_ROOT": str(self.site),
"SITE_DIST": str(self.dist),
"SITE_STATE_DIR": str(self.state),
"SITE_ADMIN_LOGIN": "admin",
"SITE_ADMIN_PASSWORD_HASH": self.password_hash,
"SITE_SECRET_KEY": "publication-test-secret-" * 4,
"SITE_COOKIE_SECURE": "0",
"SITE_ADMIN_ORIGIN": "",
"SITE_PREVIEW_ORIGIN": "",
},
)
env.start()
self.addCleanup(env.stop)
self.app = create_app()
self.client = TestClient(self.app)
self.addCleanup(self.client.close)
cookie = self.app.state.auth.login("admin", self.password, "testclient")
self.client.cookies.set("se_session", cookie)
self.app.state.api_credentials["test"] = (cookie, "testclient")
self.principal = self.app.state.auth.authenticate(cookie)
self.ctx = EditorContext(self.principal, "testclient")
self.csrf = self.app.state.auth.csrf_token(self.principal)
self.svc = PublicationService(self.site, self.dist, self.state, self.app.state.auth.audit)
def api(self, method="GET", path="", payload=None):
return self.client.request(
method,
"/admin/api/v1/publication" + path,
json=payload,
headers={"Authorization": "Bearer test"},
)
def ui(self, operation, payload=None, csrf=None):
return self.client.post(
"/admin/publication/" + operation,
data={
"csrf": self.csrf if csrf is None else csrf,
"payload": json.dumps(payload or {}),
},
headers={"Origin": "http://testserver", "Accept": "application/json"},
)
def build(self):
r = self.api("POST", "/build")
self.assertEqual(r.status_code, 200, r.text)
return r.json()
def activate(self, candidate, base=None, comment="Проверенный релиз"):
return self.api(
"POST", "/activate", {"id": candidate["id"], "expected_live": base, "comment": comment}
)
def edit(self, rel="pages/index.md", old="Студия автоматизации", new="Новая студия"):
path = self.site / rel
source = path.read_text()
if old not in source:
source += "\n" + new
else:
source = source.replace(old, new)
path.write_text(source)
def test_original_screen_and_api_only_adapter_static_and_csrf(self):
r = self.client.get("/admin/publish")
self.assertEqual(r.status_code, 200, r.text)
self.assertIn("data-publication-root", r.text)
for name in (
"publication.css",
"publication-adapter.css",
"publication.js",
"publication-icons.json",
):
self.assertEqual(self.client.get("/admin/static/" + name).status_code, 200, name)
before = self.app.state.api_calls
self.assertEqual(self.ui("validate").status_code, 200)
self.assertEqual(self.app.state.api_calls - before, 1)
self.assertEqual(self.ui("build", csrf="bad").status_code, 403)
self.assertEqual(self.client.get("/admin/publication/build").status_code, 405)
self.assertEqual(self.client.get("/admin/publication/unknown").status_code, 404)
def test_build_never_activates_and_private_snapshots_never_in_dist(self):
initial = hash_tree(self.site)
c = self.build()
self.assertIsNone(self.svc.current())
self.assertEqual(hash_tree(self.site), initial)
self.assertTrue((self.dist / c["id"] / "index.html").is_file())
self.assertFalse((self.dist / c["id"] / "pages").exists())
self.assertFalse((self.dist / c["id"] / "content").exists())
self.assertNotIn("sources", self.svc.manifest(c["id"]))
self.assertIn("content/services/automation.md", self.svc.provenance(c["id"])["sources"])
state = self.api().json()
self.assertTrue(state["candidate"]["fresh"])
self.assertTrue(state["history"][0]["candidate"])
self.assertEqual(state["builds"][0]["status"], "ready")
def test_activate_exact_existing_output_and_no_rebuild(self):
c = self.build()
output = hash_tree(self.dist / c["id"])
with patch(
"site_engine.services.publication.build_site",
side_effect=AssertionError("must not rebuild"),
):
r = self.activate(c)
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(self.svc.current(), c["id"])
self.assertEqual(hash_tree(self.dist / c["id"]), output)
state = self.api().json()
self.assertIsNone(state["candidate"])
self.assertFalse(state["changes"])
self.assertEqual(state["history"][0]["comment"], "Проверенный релиз")
def test_stale_source_and_replaced_candidate_cannot_activate_or_rollback(self):
c = self.build()
self.edit()
self.assertFalse(self.api().json()["candidate"]["fresh"])
self.assertEqual(self.activate(c).status_code, 409)
self.assertEqual(
self.api("POST", "/rollback", {"id": c["id"], "expected_live": None}).status_code, 422
)
newer = self.build()
self.assertNotEqual(c["id"], newer["id"])
self.assertEqual(self.activate(c).status_code, 409)
self.assertIsNone(self.svc.current())
def test_engine_resources_and_output_tampering_invalidate_candidate(self):
c = self.build()
with patch(
"site_engine.services.publication.render_fingerprint", return_value="changed-engine"
):
self.assertFalse(self.api().json()["candidate"]["fresh"])
self.assertEqual(self.activate(c).status_code, 409)
(self.dist / c["id"] / "index.html").write_text("tampered")
self.assertEqual(self.activate(c).status_code, 422)
self.assertIsNone(self.svc.current())
def test_live_cas_and_rollback_do_not_touch_workspace(self):
a = self.build()
self.assertEqual(self.activate(a).status_code, 200)
self.edit()
b = self.build()
self.assertEqual(self.activate(b, base="20000101T000000-12345678").status_code, 409)
self.assertEqual(self.activate(b, base=a["id"]).status_code, 200)
before = hash_tree(self.site)
r = self.api("POST", "/rollback", {"id": a["id"], "expected_live": b["id"]})
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(self.svc.current(), a["id"])
self.assertEqual(hash_tree(self.site), before)
self.assertEqual(
self.api("POST", "/rollback", {"id": b["id"], "expected_live": b["id"]}).status_code,
409,
)
self.assertTrue(self.api().json()["changes"])
def test_comparison_actual_text_added_deleted_assets_and_old_release_unknown(self):
a = self.build()
self.activate(a)
self.edit()
(self.site / "assets/new.txt").write_text("new asset")
(self.site / "assets/hero.webp").unlink()
state = self.api().json()
rows = {x["path"]: x for x in state["changes"]}
self.assertEqual(rows["pages/index.md"]["kind"], "modified")
self.assertEqual(rows["assets/new.txt"]["kind"], "new")
self.assertEqual(rows["assets/hero.webp"]["kind"], "deleted")
diff = self.api(path="/compare?path=pages/index.md").json()
self.assertNotEqual(diff["before"]["source"], diff["after"]["source"])
(self.state / "publication/releases" / f"{a['id']}.json").unlink()
state = self.api().json()
self.assertFalse(state["comparison_available"])
self.assertTrue(all(x["kind"] == "unknown" for x in state["changes"]))
self.assertIsNone(self.api(path="/compare?path=pages/index.md").json()["before"])
def test_candidate_diff_is_immutable_after_workspace_change(self):
a = self.build()
self.activate(a)
self.edit()
self.build()
before = self.api(path="/candidate-diff").json()
(self.site / "assets/not-in-candidate.txt").write_text("later")
after = self.api(path="/candidate-diff").json()
self.assertEqual(before, after)
self.assertNotIn("assets/not-in-candidate.txt", json.dumps(after))
def test_validation_and_failed_strict_render_preserve_live_and_previous_candidate(self):
a = self.build()
self.activate(a)
self.edit()
b = self.build()
with (
patch(
"site_engine.core.render.Renderer.render",
side_effect=RuntimeError("real render probe"),
),
self.assertLogs("uvicorn.error", level="ERROR") as captured,
):
r = self.api("POST", "/build")
self.assertEqual(r.status_code, 500)
self.assertIn("real render probe", "\n".join(captured.output))
self.assertTrue(r.json()["error"]["request_id"])
state = self.api().json()
self.assertEqual(state["current"], a["id"])
self.assertEqual(state["candidate"]["id"], b["id"])
self.assertEqual(state["builds"][0]["status"], "failed")
self.edit(
"pages/index.md", "status: published", "status: published\nlayout: missing-layout"
)
r = self.api("POST", "/validate")
self.assertEqual(r.status_code, 200, r.text)
self.assertGreater(r.json()["errors"], 0)
self.assertEqual(self.api("POST", "/build").status_code, 422)
self.assertEqual(self.svc.current(), a["id"])
def test_passive_snapshot_is_real_build_with_assets_and_no_site_scripts(self):
c = self.build()
self.edit()
r = self.api("POST", "/preview", {"id": c["id"], "route": "/"})
self.assertEqual(r.status_code, 200, r.text)
preview = r.json()
page = self.client.get(preview["url"])
self.assertEqual(page.status_code, 200)
self.assertNotIn("<script", page.text)
self.assertIn("script-src 'none'", page.headers["content-security-policy"])
self.assertIn("site.", page.text)
self.assertEqual(
self.api("POST", "/preview", {"id": c["id"], "route": "/missing/"}).status_code, 404
)
self.assertEqual(self.client.get(preview["url"].split("?")[0]).status_code, 403)
with patch.dict(
os.environ,
{
"SITE_ADMIN_ORIGIN": "http://127.0.0.1:9100",
"SITE_PREVIEW_ORIGIN": "http://127.0.0.1:9101",
},
):
from site_engine.services.preview import PreviewConfig, PreviewStore
from site_engine.web.preview_app import snapshot_response
store = PreviewStore(self.state, b"secret", PreviewConfig.from_env())
p = self.svc.preview(c["id"], "/", store, self.principal)
from urllib.parse import parse_qs, urlsplit
token = parse_qs(urlsplit(p["url"]).query)["token"][0]
response = snapshot_response(store, p["snapshot"], token)
self.assertNotIn(b"<script", response.body)
self.assertIn("script-src 'none'", response.headers["content-security-policy"])
def test_commit_audit_failure_reports_actual_switched_release(self):
c = self.build()
with (
patch.object(
self.app.state.auth.audit, "write", side_effect=OSError("audit unavailable")
),
self.assertLogs("uvicorn.error", level="ERROR"),
):
r = self.activate(c)
self.assertEqual(r.status_code, 500)
self.assertEqual(r.json()["error"]["committed_build"], c["id"])
self.assertEqual(self.svc.current(), c["id"])
def test_auth_path_traversal_and_symlinks_are_rejected(self):
c = self.build()
for path in ("../.env", ".env", "/etc/passwd"):
self.assertIn(self.api(path="/document-history?path=" + path).status_code, (403, 422))
self.assertEqual(
self.api("POST", "/preview", {"id": "../bad", "route": "/"}).status_code, 422
)
link = self.site / "assets/outside.txt"
link.symlink_to("/etc/passwd")
self.assertEqual(self.api("POST", "/build").status_code, 403)
link.unlink()
self.app.state.api_credentials.pop("test")
self.assertEqual(self.api().status_code, 401)
self.app.state.auth.logout(self.principal)
self.assertEqual(self.ui("build").status_code, 401)
self.assertTrue((self.dist / c["id"]).exists())
def test_cli_compatibility_without_private_provenance(self):
a = build_site(self.site, self.dist)
state = self.api().json()
self.assertEqual(state["current"], a.build_id)
self.assertFalse(state["comparison_available"])
self.assertIsNone(state["history"][0]["author"])
self.edit()
b = self.build()
self.assertEqual(self.activate(b, base=a.build_id).status_code, 200)
self.assertEqual(
self.api("POST", "/rollback", {"id": a.build_id, "expected_live": b["id"]}).status_code,
200,
)
def test_release_details_show_actual_changed_outputs_and_real_document_history(self):
from site_engine.services.pages import PageService
a = self.build()
self.activate(a)
svc = PageService(self.site, self.app.state.auth.audit)
snap = svc.get("index")
svc.save_source(
"index",
snap.source.replace("Автоматизируем бизнес", "Обновлённый бизнес"),
snap.etag,
self.ctx,
)
history = self.api(path="/document-history?path=pages/index.md").json()
self.assertEqual(len(history["versions"]), 1)
b = self.build()
self.activate(b, base=a["id"])
details = self.api(path="/release?id=" + a["id"])
self.assertEqual(details.status_code, 200, details.text)
self.assertEqual(details.json()["base"], b["id"])
self.assertIn("index.html", [x["path"] for x in details.json()["changes"]])
self.assertEqual(self.api(path="/release?id=../bad").status_code, 404)
def test_built_candidate_audit_failure_is_explicit_and_does_not_activate(self):
with (
patch.object(
self.app.state.auth.audit, "write", side_effect=OSError("audit unavailable")
),
self.assertLogs("uvicorn.error", level="ERROR"),
):
response = self.api("POST", "/build")
self.assertEqual(response.status_code, 500)
detail = response.json()["error"]
self.assertEqual(detail["code"], "candidate_after_build")
self.assertTrue((self.dist / detail["committed_build"]).is_dir())
self.assertIsNone(self.svc.current())
self.assertEqual(self.api().json()["candidate"]["id"], detail["committed_build"])
def test_expired_session_read_is_json_and_requires_new_login(self):
self.app.state.auth.logout(self.principal)
response = self.client.get(
"/admin/publication/state", headers={"Accept": "application/json"}
)
self.assertEqual(response.status_code, 401)
self.assertEqual(response.json()["error"]["code"], "session_expired")
def test_starting_shell_allows_only_configured_preview_origin(self):
from site_engine.services.preview import PreviewConfig
initial = self.client.get("/admin/pages")
self.assertIn("frame-src 'self';", initial.headers["content-security-policy"])
config = PreviewConfig("http://127.0.0.1:9100", "http://127.0.0.1:9101")
with patch.object(self.app.state.previews, "config", config):
for path in (
"/admin/",
"/admin/pages",
"/admin/pages/index",
"/admin/content/services/bots",
"/admin/theme",
"/admin/publish",
):
response = self.client.get(path)
self.assertEqual(response.status_code, 200, path)
policy = response.headers["content-security-policy"]
directives = dict(
part.strip().split(" ", 1) for part in policy.split(";") if part.strip()
)
self.assertEqual(directives["frame-src"], "'self' " + config.preview, path)
self.assertEqual(directives["script-src"], "'self'", path)
self.assertEqual(directives["frame-ancestors"], "'none'", path)