sync update from LAN repo (source master @ c21a2a4a)
This commit is contained in:
1 parent
ea9dcff9c0
commit
66a443e915
140 files changed
+13777
-1040
No files matched your search
+242
-23
@@ -14,6 +14,12 @@ HTML 模板需要的 ``DATA`` 结构后,本模块负责把数据**填充**进模
|
||||
行内无换行),所以用 ``^const VAR=.*;$`` (MULTILINE) 精确命中该行整体替换,绝不
|
||||
误伤模板里别处出现的同名子串。替换值用函数回调写入,避开 ``re.sub`` 把 JSON 里的
|
||||
反斜杠当反向引用的坑。
|
||||
* **结构化模板(kind="structured")**: no.1 起引入 page-generator 范式——目录含
|
||||
``template.html``(骨架,带 :data:`STRUCTURED_MARKERS` 注入标记)/``runtime.js``
|
||||
(渲染逻辑 + 页面内 JSON 编辑器)/``data.json``(默认数据,兼作转换契约)/可选
|
||||
``manifest.json``。填充走 :func:`compose_structured` 标记组合,产物仍是自包含
|
||||
单文件 HTML;``reference_data`` 读 ``data.json``,与单文件模板的契约/校验/合并
|
||||
语义完全一致。
|
||||
* **harness 层、零 app.* 依赖**:可被调度器(harness)与 Gateway 路由(app)共同 import。
|
||||
|
||||
公开入口:``list_templates`` / ``get_template`` / ``reference_data`` /
|
||||
@@ -107,6 +113,14 @@ def extract_embedded_json(text: str | None) -> Any | None:
|
||||
# 模板资源根目录(随 git 发布,与本模块同级 ``templates/`` 子目录)。
|
||||
_TEMPLATES_ROOT = Path(__file__).parent / "templates"
|
||||
|
||||
# 结构化模板骨架里的三个注入标记(compose_structured 逐个替换)。
|
||||
DATA_MARKER = "__PAGE_DATA__"
|
||||
MANIFEST_MARKER = "__PAGE_MANIFEST__"
|
||||
RUNTIME_MARKER = "__PAGE_RUNTIME__"
|
||||
STRUCTURED_MARKERS: tuple[str, ...] = (DATA_MARKER, MANIFEST_MARKER, RUNTIME_MARKER)
|
||||
# 结构化模板目录里的组成文件(manifest.json 可选,其余必备)。
|
||||
STRUCTURED_PARTS: tuple[str, ...] = ("template.html", "runtime.js", "data.json", "manifest.json")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TemplateSpec:
|
||||
@@ -115,9 +129,20 @@ class TemplateSpec:
|
||||
``file`` 相对 :data:`_TEMPLATES_ROOT`;``data_var``/``manifest_var`` 是模板里
|
||||
待替换的 JS 常量名(``manifest_var`` 为空表示该模板没有 MANIFEST 行)。
|
||||
|
||||
``kind`` 有两种:
|
||||
|
||||
* ``"single"``(默认): 单文件模板,数据以 ``const DATA={…};`` 单行内嵌,填充 =
|
||||
行级替换;
|
||||
* ``"structured"``: 结构化模板(page-generator 范式),目录含
|
||||
``template.html``(骨架,带 :data:`STRUCTURED_MARKERS` 三个注入标记)/
|
||||
``runtime.js``(渲染 + 页面内 JSON 编辑器)/``data.json``(默认数据,即转换
|
||||
契约)/可选 ``manifest.json``,填充 = 标记组合,产物仍是自包含单文件 HTML。
|
||||
``legacy_file`` 指向单文件时代的随包正文,供 template_store 自动升级时做
|
||||
「未被手改」的字节级比对。
|
||||
|
||||
``convertible=False`` 表示该模板暂只「直接展示已有数据」——执行时原样输出模板
|
||||
HTML,不做 JSON 转换/校验/填充(无 ``const DATA=`` 注入行的模板用它,后续接入
|
||||
转换后改回 True)。
|
||||
转换后再改回 True)。
|
||||
"""
|
||||
|
||||
id: str
|
||||
@@ -127,6 +152,12 @@ class TemplateSpec:
|
||||
data_var: str = "DATA"
|
||||
manifest_var: str = ""
|
||||
convertible: bool = True
|
||||
kind: str = "single"
|
||||
legacy_file: str = ""
|
||||
|
||||
@property
|
||||
def structured(self) -> bool:
|
||||
return self.kind == "structured"
|
||||
|
||||
|
||||
# 已注册模板(随包 seed 源 + 存储缺失时的兜底注册表)。新增模板时在此追加一条
|
||||
@@ -136,9 +167,14 @@ TEMPLATES: tuple[TemplateSpec, ...] = (
|
||||
id="no1",
|
||||
name="no.1",
|
||||
description="",
|
||||
file="no1/taiwan_littoral_ui_redwhite_v2.html",
|
||||
file="no1/template.html",
|
||||
data_var="DATA",
|
||||
manifest_var="MANIFEST",
|
||||
# 结构化模板(page-generator 范式):骨架 + runtime + 默认数据 + MANIFEST,
|
||||
# 填充走 compose_structured 标记组合;legacy_file 是单文件时代的随包正文,
|
||||
# 供 template_store 把「未被手改」的旧存储副本自动升级到结构化版。
|
||||
kind="structured",
|
||||
legacy_file="no1/taiwan_littoral_ui_redwhite_v2.html",
|
||||
),
|
||||
TemplateSpec(
|
||||
id="no2",
|
||||
@@ -401,6 +437,7 @@ def get_template(template_id: str) -> TemplateSpec | None:
|
||||
data_var="DATA",
|
||||
manifest_var=str(meta.get("manifest_var") or ""),
|
||||
convertible=bool(meta.get("convertible")),
|
||||
kind=str(meta.get("kind") or "single"),
|
||||
)
|
||||
return _TEMPLATES_BY_ID.get(template_id)
|
||||
|
||||
@@ -435,8 +472,122 @@ def _template_path(spec: TemplateSpec) -> Path:
|
||||
return _TEMPLATES_ROOT / spec.file
|
||||
|
||||
|
||||
# ── 结构化模板(骨架 + runtime + 数据分文件,组合成单文件产物) ────────────────
|
||||
|
||||
|
||||
def _structured_part(template_id: str, name: str) -> Path | None:
|
||||
"""结构化模板某个组成文件的路径:存储副本优先,随包文件兜底;都没有返回 None。
|
||||
|
||||
``manifest.json`` 可选;其余文件缺失属打包损坏,由 :func:`_structured_text` 报错。
|
||||
"""
|
||||
from deerflow.runtime.scheduler import template_store
|
||||
|
||||
store_file = template_store.store_root() / template_id / name
|
||||
if store_file.is_file():
|
||||
return store_file
|
||||
fallback = _TEMPLATES_ROOT / template_id / name
|
||||
return fallback if fallback.is_file() else None
|
||||
|
||||
|
||||
def _structured_text(template_id: str, name: str) -> str:
|
||||
path = _structured_part(template_id, name)
|
||||
if path is None:
|
||||
raise TemplateError(f"结构化模板文件缺失:{template_id}/{name}")
|
||||
return path.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def _read_default_manifest(template_id: str) -> dict[str, Any]:
|
||||
"""结构化模板的默认 MANIFEST;没有 manifest.json 时返回空对象。"""
|
||||
path = _structured_part(template_id, "manifest.json")
|
||||
if path is None:
|
||||
return {}
|
||||
try:
|
||||
obj = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError) as exc:
|
||||
raise TemplateError(f"解析 {template_id}/manifest.json 失败:{exc}") from exc
|
||||
return obj if isinstance(obj, dict) else {}
|
||||
|
||||
|
||||
def structured_module_labels(template_id: str) -> list[dict[str, str]]:
|
||||
"""结构化模板各数据模块(DATA 顶层键)的中文显示名,管理页「编辑数据」用。
|
||||
|
||||
标签来源按优先级:MANIFEST.页面 的「编号」精确命中 → 「数据源/架构数据」去掉
|
||||
``data/`` 前缀和 ``.json`` 后缀后命中(如 organization_charts) → 编号按 ``_``
|
||||
拆分后命中任一段(如 events/projects 命中 events_projects)。都没有则回退键名。
|
||||
"""
|
||||
ref = reference_data(template_id)
|
||||
manifest = _read_default_manifest(template_id)
|
||||
labels: dict[str, str] = {}
|
||||
split_index: dict[str, str] = {}
|
||||
pages = manifest.get("页面")
|
||||
if isinstance(pages, list):
|
||||
for page in pages:
|
||||
if not isinstance(page, dict):
|
||||
continue
|
||||
name = str(page.get("名称") or "").strip()
|
||||
if not name:
|
||||
continue
|
||||
candidates: list[str] = []
|
||||
for field in ("编号", "数据源", "架构数据"):
|
||||
raw = str(page.get(field) or "").strip()
|
||||
if not raw:
|
||||
continue
|
||||
key = raw.removeprefix("data/").removesuffix(".json")
|
||||
if key:
|
||||
candidates.append(key)
|
||||
for key in candidates:
|
||||
labels[key] = name
|
||||
first = candidates[0] if candidates else ""
|
||||
if first and "_" in first:
|
||||
for part in first.split("_"):
|
||||
if part:
|
||||
split_index[part] = name
|
||||
out: list[dict[str, str]] = []
|
||||
for key in ref:
|
||||
out.append({"key": key, "label": labels.get(key) or split_index.get(key) or key})
|
||||
return out
|
||||
|
||||
|
||||
def compose_structured(
|
||||
*,
|
||||
skeleton: str,
|
||||
runtime: str,
|
||||
data: Any,
|
||||
manifest: dict[str, Any] | None = None,
|
||||
) -> str:
|
||||
"""把数据/运行时按标记组合进骨架,产出自包含单文件 HTML。
|
||||
|
||||
与 page-generator 技能的 render 脚本同一套安全转义:数据 JSON 里的 ``</`` →
|
||||
``<\\/``(JSON 字符串里 ``\\/`` 合法),runtime 里的 ``</script`` → ``<\\/script``,
|
||||
防止内容提前闭合 script 标签。组合后断言无残留标记。
|
||||
"""
|
||||
serialized_data = json.dumps(data, ensure_ascii=False).replace("</", "<\\/")
|
||||
out = skeleton.replace(DATA_MARKER, serialized_data)
|
||||
if MANIFEST_MARKER in out:
|
||||
serialized_manifest = (
|
||||
json.dumps(manifest, ensure_ascii=False).replace("</", "<\\/")
|
||||
if manifest is not None
|
||||
else "{}"
|
||||
)
|
||||
out = out.replace(MANIFEST_MARKER, serialized_manifest)
|
||||
out = out.replace(RUNTIME_MARKER, runtime.replace("</script", "<\\/script"))
|
||||
residual = [m for m in STRUCTURED_MARKERS if m in out]
|
||||
if residual:
|
||||
raise TemplateError(f"结构化模板组合后仍残留标记:{'、'.join(residual)}")
|
||||
return out
|
||||
|
||||
|
||||
def read_template_text(template_id: str) -> str:
|
||||
spec = _require(template_id)
|
||||
if spec.structured:
|
||||
# 结构化模板对外始终呈现「组合后的完整文档」(预览/只展示/参考展示共用);
|
||||
# 骨架原文(编辑用)由 template_store.read_template_html 直接读文件。
|
||||
return compose_structured(
|
||||
skeleton=_structured_text(template_id, "template.html"),
|
||||
runtime=_structured_text(template_id, "runtime.js"),
|
||||
data=reference_data(template_id),
|
||||
manifest=_read_default_manifest(template_id),
|
||||
)
|
||||
path = _template_path(spec)
|
||||
if not path.is_file():
|
||||
raise TemplateError(f"模板文件缺失:{path}")
|
||||
@@ -464,8 +615,22 @@ def _extract_const_object(text: str, var: str) -> Any:
|
||||
|
||||
@lru_cache(maxsize=16)
|
||||
def reference_data(template_id: str) -> dict[str, Any]:
|
||||
"""模板内嵌的参考 ``DATA`` 对象(目标格式范例 + 校验基准),按模板缓存。"""
|
||||
"""模板内嵌的参考 ``DATA`` 对象(目标格式范例 + 校验基准),按模板缓存。
|
||||
|
||||
单文件模板解析 ``const DATA=`` 行;结构化模板直接读 ``data.json``(两者语义一致:
|
||||
顶层键即子页面,validate_data/merge_with_reference/骨架 prompt 全部通用)。
|
||||
"""
|
||||
spec = _require(template_id)
|
||||
if spec.structured:
|
||||
try:
|
||||
obj = json.loads(_structured_text(template_id, "data.json"))
|
||||
except OSError as exc:
|
||||
raise TemplateError(f"读取 {template_id}/data.json 失败:{exc}") from exc
|
||||
except ValueError as exc:
|
||||
raise TemplateError(f"解析 {template_id}/data.json 失败:{exc}") from exc
|
||||
if not isinstance(obj, dict):
|
||||
raise TemplateError(f"模板 {template_id} 的 data.json 不是对象")
|
||||
return obj
|
||||
text = read_template_text(template_id)
|
||||
obj = _extract_const_object(text, spec.data_var)
|
||||
if not isinstance(obj, dict):
|
||||
@@ -774,28 +939,18 @@ def pop_page_titles(obj: dict[str, Any]) -> tuple[str | None, str | None]:
|
||||
return title, subtitle
|
||||
|
||||
|
||||
def fill_template(
|
||||
template_id: str,
|
||||
data_obj: Any,
|
||||
*,
|
||||
manifest_overrides: dict[str, Any] | None = None,
|
||||
update_date: date | None = None,
|
||||
title: str | None = None,
|
||||
subtitle: str | None = None,
|
||||
) -> str:
|
||||
"""把 ``data_obj`` 填进模板的 ``const DATA=…`` 行,产出完整 HTML 文档。
|
||||
def _apply_page_titles(
|
||||
text: str,
|
||||
title: str | None,
|
||||
subtitle: str | None,
|
||||
manifest_overrides: dict[str, Any] | None,
|
||||
) -> tuple[str, dict[str, Any] | None]:
|
||||
"""替换页头静态标题/副标题;给出 title 时同步返回含 ``系统.名称`` 的 overrides。
|
||||
|
||||
可选地更新 MANIFEST 的「系统.更新时间」(``update_date``,默认不动) 以及任意
|
||||
``manifest_overrides``(深合并到解析后的 MANIFEST,如改系统名称)。
|
||||
|
||||
``title``/``subtitle`` 来自转换结果里的「页面标题/页面副标题」:模板页头
|
||||
(<title>、第一个 <h1>、其后紧跟的副标题 <p>)是写死的静态 HTML,不随 DATA
|
||||
变化——给出新标题时替换这三处,并把 MANIFEST 的 系统.名称 一并同步;
|
||||
不给则保持模板原文。
|
||||
模板页头(``<title>``、第一个 ``<h1>``、其后紧跟的副标题 ``<p>``)是写死的静态
|
||||
HTML,不随 DATA 变化——给出新标题时替换这两处,并把 MANIFEST 的 系统.名称 一并
|
||||
同步;不给则保持模板原文。单文件/结构化两条填充路径共用。
|
||||
"""
|
||||
spec = _require(template_id)
|
||||
text = read_template_text(template_id)
|
||||
|
||||
if title:
|
||||
overrides = dict(manifest_overrides or {})
|
||||
system = overrides.get("系统")
|
||||
@@ -815,6 +970,70 @@ def fill_template(
|
||||
count=1,
|
||||
flags=re.DOTALL,
|
||||
)
|
||||
return text, manifest_overrides
|
||||
|
||||
|
||||
def _fill_structured(
|
||||
template_id: str,
|
||||
data_obj: Any,
|
||||
*,
|
||||
manifest_overrides: dict[str, Any] | None,
|
||||
update_date: date | None,
|
||||
title: str | None,
|
||||
subtitle: str | None,
|
||||
) -> str:
|
||||
"""结构化模板填充:标记组合出完整单文件 HTML(数据内嵌 JSON 元素 + runtime 内联)。"""
|
||||
skeleton, manifest_overrides = _apply_page_titles(
|
||||
_structured_text(template_id, "template.html"), title, subtitle, manifest_overrides
|
||||
)
|
||||
manifest = _read_default_manifest(template_id)
|
||||
if update_date is not None:
|
||||
system = manifest.get("系统")
|
||||
if isinstance(system, dict):
|
||||
system["更新时间"] = update_date.isoformat()
|
||||
if manifest_overrides:
|
||||
_deep_merge(manifest, manifest_overrides)
|
||||
return compose_structured(
|
||||
skeleton=skeleton,
|
||||
runtime=_structured_text(template_id, "runtime.js"),
|
||||
data=data_obj,
|
||||
manifest=manifest,
|
||||
)
|
||||
|
||||
|
||||
def fill_template(
|
||||
template_id: str,
|
||||
data_obj: Any,
|
||||
*,
|
||||
manifest_overrides: dict[str, Any] | None = None,
|
||||
update_date: date | None = None,
|
||||
title: str | None = None,
|
||||
subtitle: str | None = None,
|
||||
) -> str:
|
||||
"""把 ``data_obj`` 填进模板,产出完整 HTML 文档。
|
||||
|
||||
单文件模板:行级替换 ``const DATA=…``;结构化模板::func:`_fill_structured`
|
||||
标记组合。可选地更新 MANIFEST 的「系统.更新时间」(``update_date``,默认不动)
|
||||
以及任意 ``manifest_overrides``(深合并到解析后的 MANIFEST,如改系统名称)。
|
||||
|
||||
``title``/``subtitle`` 来自转换结果里的「页面标题/页面副标题」:模板页头
|
||||
(<title>、第一个 <h1>、其后紧跟的副标题 <p>)是写死的静态 HTML,不随 DATA
|
||||
变化——给出新标题时替换这三处,并把 MANIFEST 的 系统.名称 一并同步;
|
||||
不给则保持模板原文。
|
||||
"""
|
||||
spec = _require(template_id)
|
||||
if spec.structured:
|
||||
return _fill_structured(
|
||||
template_id,
|
||||
data_obj,
|
||||
manifest_overrides=manifest_overrides,
|
||||
update_date=update_date,
|
||||
title=title,
|
||||
subtitle=subtitle,
|
||||
)
|
||||
|
||||
text = read_template_text(template_id)
|
||||
text, manifest_overrides = _apply_page_titles(text, title, subtitle, manifest_overrides)
|
||||
|
||||
data_re = _const_line_re(spec.data_var)
|
||||
if data_re.search(text) is None:
|
||||
|
||||
Reference in new issue
Block a user