feat: WEB-01 core Design interpreter over public Analysis 3
Implement the first real Design capability in the unique owner repository: - src/analysis.rs runs the verified CLI check --emit with direct argv, validates Analysis 3 schema/source_digest, and snapshots one module without any implicit discovery or Markdown parser. - src/document.rs selects the exact Knowledge H2 by anchor, direct retained H3 sections, and the single GFM 组件 table from the analysis AST; cell text is read from the analysis-provided source by UTF-8 byte span. - src/lib.rs binds design links by exact candidate_path + anchor (never label or filename guessing), validates rows/slots/widths, recursion, containment cycles and module/depth/byte limits, and builds deterministic component definitions, separate instances, source identities and a provisional handoff. - Stable diagnostics separate Engine failures (exit 2) from author-contract errors (exit 1); no partial model on failure. - tests/design_contract.rs exercises the real CLI for recursive layout, definition reuse, width forms and the main negative cases; scripts/ci.sh is the explicit entry (fmt/clippy/test) with a verified CLI. Scenarios/input/event/dependency contracts and the full WEB-03 handoff remain open and are recorded as unverified in the evidence document. Refs cflmy/marqdo-web-design#1, cflmy/marqdo#6
This commit was merged in pull request #3.
This commit is contained in:
1 parent
39c99e59d2
commit
75cd26ef89
13 files changed
+1649
-15
No files matched your search
+1
-4
@@ -1,4 +1 @@
|
||||
/target/
|
||||
/dist/
|
||||
/.secrets/
|
||||
*.log
|
||||
/target
|
||||
Generated
+105
@@ -0,0 +1,105 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
|
||||
|
||||
[[package]]
|
||||
name = "marqdo-web-design"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.154"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"memchr",
|
||||
"serde",
|
||||
"serde_core",
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
[package]
|
||||
name = "marqdo-web-design"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
rust-version = "1.89"
|
||||
license = "MIT OR Apache-2.0"
|
||||
description = "Deterministic interpreter of the Marqdo Web design contract over public CLI Analysis 3"
|
||||
|
||||
[dependencies]
|
||||
serde_json = "1"
|
||||
@@ -30,3 +30,11 @@ Web 领域**唯一设计文档解释实现**。本仓库交付独立 Rust librar
|
||||
## 工单
|
||||
|
||||
首版开发任务:WEB-01(Analysis 3 消费与设计编译)、WEB-03(handoff/组件图/单组件交付)。合同语义冲突归 `marqdo-ext-web` 协调;只有 CLI 公开 Analysis 合同本身不满足需求时才向 `marqdo-cli` 发工单,并附固定 SHA 与最小复现。
|
||||
|
||||
## 实现进展
|
||||
|
||||
- `src/analysis.rs`:真实 CLI `check --emit` 调用、Analysis 3 协议/摘要校验、单一模块快照。
|
||||
- `src/document.rs`:精确 anchor 选 Knowledge H2、直接保留 H3、GFM `组件` 表 AST/表头/单元格/Link 选择。
|
||||
- `src/lib.rs`:递归布局、实例、宽度/行/槽校验、包含环与深度/模块/字节上限、稳定诊断、源身份与确定性 handoff。
|
||||
- `tests/design_contract.rs`:8 个真实 CLI 契约测试(正例 + 负例);`scripts/ci.sh` 为显式验收入口。
|
||||
- 未完成:`输入`/`事件`/`依赖`/`验收`、`场景`/`交互`、WEB-03 完整 handoff/组件图;证据见 [docs/evidence/WEB-01-design-core.md](docs/evidence/WEB-01-design-core.md)。
|
||||
@@ -34,3 +34,9 @@ pub fn handoff(design: &Design) -> String;
|
||||
|
||||
- `load`/`handoff` 与数据模型在 WEB-01 前为 provisional,可破坏式调整;WEB-01 后进入 SemVer。
|
||||
- 需要破坏性变更时,Design 与 Preview 在同一领域候选组合中一起升级,`Cargo.lock` 固定实际消费身份;不维护旧协议 fallback。
|
||||
|
||||
## 实现状态(WEB-01 核心候选)
|
||||
|
||||
`load` 已实现:真实 CLI Analysis 3 摄入、精确 anchor 选 Knowledge H2、`组件` 表递归布局、宽度/行/槽校验、包含环与资源上限、稳定诊断与源身份;`handoff` 目前输出确定性的组件树与来源摘要。
|
||||
|
||||
未导出/未实现:`输入`/`事件`/`依赖`/`验收` 合同模型、`Scenario`/`Interaction`、`DesignGraph` 的完整依赖图与 WEB-03 handoff。按 provisional 约定,这些可在 WEB-01 完成前破坏式调整;Preview 不得自行实现上述解释。
|
||||
+10
-11
@@ -27,22 +27,21 @@ RC.4 Analysis 只包含已静态加载模块,`not_loaded` 不等于缺失。
|
||||
- `missing/ambiguous/outside_scope/invalid/external` 对设计依赖是错误;普通内容链接不追踪。无法从公开字段确认物理映射时报告“不支持”,不得调用私有 loader 或搜索文件名。
|
||||
- 并发编辑一致性:以实际输入 bytes 与 digest 校验;同一文件在一轮中两次 Analysis 内容不同即失败重试;输出前复核所有参与设计的源码/资产摘要。交付只列真正使用的输入,不打包全部已加载依赖。
|
||||
|
||||
## 计划代码结构(尚未创建)
|
||||
## 代码结构(WEB-01 核心已创建)
|
||||
|
||||
```text
|
||||
Cargo.toml / Cargo.lock
|
||||
src/lib.rs # 公开 API 与结果类型
|
||||
src/analysis.rs # CLI 调用、公开协议校验、静态输入快照
|
||||
src/document.rs # 确定的章节/表格选择、单元引用
|
||||
src/model.rs # 定义、实例、布局、场景、来源
|
||||
src/graph.rs # 递归链接、循环、依赖与限制
|
||||
src/handoff.rs # Markdown 交付
|
||||
src/diagnostic.rs # 稳定错误码与来源位置
|
||||
tests/ # 单元、负例、真实 CLI contract
|
||||
scripts/ci.sh # 激活时提供的独立验收入口
|
||||
docs/
|
||||
src/lib.rs # 公开 API、递归布局/实例/上限/handoff(WEB-01 核心)
|
||||
src/analysis.rs # CLI check --emit 调用、Analysis 3 校验、模块快照
|
||||
src/document.rs # 精确 anchor/H3/GFM 表/Link 选择
|
||||
src/diagnostic.rs # 稳定错误码、span、Engine/Design 区分
|
||||
tests/design_contract.rs # 真实 CLI 正例 + 负例
|
||||
scripts/ci.sh # 显式独立验收入口(fmt/clippy/test)
|
||||
docs/ # API、开发指南与证据
|
||||
```
|
||||
|
||||
尚未拆分 `model.rs`/`graph.rs`/`handoff.rs` 是当前规模下的有意选择;场景/输入事件合同与完整 handoff 落地时再按真实边界拆分,不做预先空壳。
|
||||
|
||||
不为每个表格新建 crate;Design 与 Preview 各一个主要 crate。`docs/WEB-DESIGN.md` 在领域仓库,本仓库不得复制。
|
||||
|
||||
## 公开 API 原则
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
# WEB-01 Design 核心候选证据(布局 / 源身份 / 诊断)
|
||||
|
||||
日期:2026-11-27。责任仓:`marqdo-web-design`;工单:[marqdo-web-design#1](https://git.cflmy.cn/cflmy/marqdo-web-design/issues/1)(WEB-01);父工单:根 [marqdo#6](https://git.cflmy.cn/cflmy/marqdo/issues/6)。
|
||||
|
||||
本文件记录 WEB-01 的**核心候选**:Analysis 3 摄入、精确组件引用、递归布局、稳定诊断与源身份。场景/输入/事件/依赖与更完整 handoff 仍属 WEB-01/WEB-03 后续,未在本证据中声明完成。
|
||||
|
||||
## 输入身份
|
||||
|
||||
| 对象 | 身份 |
|
||||
| --- | --- |
|
||||
| CLI | 由根固定 `cli/deadf6e` 构建的 `marqdo 3.0.0-rc.4`,SHA-256 `sha256:6ede3b9e8bcfad3942573e68b5f54b2c5bc2866b37d102f63acd49a55cb212db` |
|
||||
| 根组合 | `cflmy/marqdo@d4ccb77` |
|
||||
| 合同 | `marqdo-ext-web` 的 `docs/WEB-DESIGN.md`(只读引用,不复制) |
|
||||
| 平台 | Linux x86_64(本机验证) |
|
||||
|
||||
## 执行
|
||||
|
||||
```sh
|
||||
MARQDO_BIN=<verified marqdo> scripts/ci.sh
|
||||
# = cargo fmt --check; cargo clippy --all-targets --locked -D warnings; cargo test --locked
|
||||
```
|
||||
|
||||
测试直接启动真实 CLI `check --emit` 生成 Analysis 3(无 mock),临时工程由测试写入。
|
||||
|
||||
## 已验证(8 个真实 CLI 契约测试)
|
||||
|
||||
- 正例:递归 `组件` 布局(index → nav → leaf、workspace 内容组件)、定义复用但实例独立(`root`/`root/left`/`root/right`)、内容-only 组件、宽度 `auto`/`1fr..12fr`/`120px..1200px`。
|
||||
- 源身份:每个参与模块的 root-relative path、module id、`source_digest`、Unit path/anchor/UTF-8 span;两次加载的 handoff 逐字节一致。
|
||||
- 负例(稳定诊断码):缺失/歧义 anchor、H2 非 Knowledge(Exec)、带 `#` 的 unit、表头/列数/非 Link 单元格/非法宽度/重复 slot/行号不连续、目标越界(Analysis 无可用 candidate)、目标 anchor 缺失、包含环、模块/深度/源字节上限、CLI 缺失、ENTRY 越出 root、ENTRY 不存在。
|
||||
- 引擎失败与作者合同错误区分(`LoadError::Engine`/`Design`),宿主据此映射退出码 2/1;失败不产生部分模型。
|
||||
- 不使用 `../design` 路径依赖,不复制 Markdown/语言解析器;只消费 Analysis 公开字段。
|
||||
|
||||
## 未实现 / 未验证(不隐藏)
|
||||
|
||||
- 保留 H3 的 `输入`/`事件`/`依赖`/`验收` 合同模型、`场景`/`交互`(有限状态)解释与校验尚未实现;
|
||||
- handoff 当前为确定性组件树/来源摘要,WEB-03 的组件图、单组件切片与漂移标识未完成;
|
||||
- 并发编辑/陈旧 Analysis 的二次一致性复核、资源上限的完整矩阵、symlink/双重编码等安全负例仅覆盖部分;
|
||||
- 未配置组件 CI 服务(`scripts/ci.sh` 为显式入口,需 CI 传入固定 CLI 制品);领域/根接入(WEB-05)未开始。
|
||||
|
||||
因此 WEB-01 不关闭;后续在同一仓库按上述范围继续,不把本候选当作完整验收。
|
||||
Executable
+8
@@ -0,0 +1,8 @@
|
||||
#!/usr/bin/env bash
|
||||
# WEB-01 independent entry: explicit verified CLI, real Analysis contract tests.
|
||||
set -eu
|
||||
: "${MARQDO_BIN:?set MARQDO_BIN to the verified marqdo executable}"
|
||||
export MARQDO_BIN
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy --all-targets --locked -- -D warnings
|
||||
cargo test --locked
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
//! Static input snapshot: run the public CLI `check --emit` and validate Analysis 3.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::diagnostic::{span_from, Diagnostic, Diagnostics, LoadError};
|
||||
|
||||
static UNIQUE: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Module {
|
||||
/// Canonical physical path.
|
||||
pub path: PathBuf,
|
||||
/// Root-relative path used in diagnostics and source identities.
|
||||
pub relative: String,
|
||||
pub source: String,
|
||||
pub source_digest: String,
|
||||
pub module_id: String,
|
||||
pub units: Vec<Value>,
|
||||
pub anchors: Vec<Value>,
|
||||
pub document: Value,
|
||||
pub references: Vec<Value>,
|
||||
}
|
||||
|
||||
impl Module {
|
||||
pub fn text(&self, span: &Value) -> Option<&str> {
|
||||
let (start, end) = span_from(span)?;
|
||||
let bytes = self.source.as_bytes();
|
||||
if start > end || end > bytes.len() {
|
||||
return None;
|
||||
}
|
||||
std::str::from_utf8(&bytes[start..end]).ok()
|
||||
}
|
||||
|
||||
pub fn text_span(&self, start: usize, end: usize) -> Option<&str> {
|
||||
let bytes = self.source.as_bytes();
|
||||
if start > end || end > bytes.len() {
|
||||
return None;
|
||||
}
|
||||
std::str::from_utf8(&bytes[start..end]).ok()
|
||||
}
|
||||
}
|
||||
|
||||
fn temp_dir() -> Result<PathBuf, LoadError> {
|
||||
let unique = UNIQUE.fetch_add(1, Ordering::Relaxed);
|
||||
let path =
|
||||
std::env::temp_dir().join(format!("marqdo-web-design-{}-{unique}", std::process::id()));
|
||||
std::fs::create_dir_all(&path).map_err(|error| {
|
||||
LoadError::Engine(vec![Diagnostic::error(
|
||||
"web.engine.tempdir",
|
||||
format!("cannot create temporary directory: {error}"),
|
||||
)])
|
||||
})?;
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
/// Analyse one document through the public CLI, returning the single module.
|
||||
pub fn analyze(cli: &Path, document: &Path, root: &Path) -> Result<Module, LoadError> {
|
||||
let canonical = document.canonicalize().map_err(|error| {
|
||||
LoadError::Engine(vec![Diagnostic::error(
|
||||
"web.engine.entry",
|
||||
format!("cannot canonicalize {}: {error}", document.display()),
|
||||
)])
|
||||
})?;
|
||||
let work = temp_dir()?;
|
||||
let emit = work.join("analysis.json");
|
||||
let output = Command::new(cli)
|
||||
.arg("check")
|
||||
.arg(&canonical)
|
||||
.arg("--emit")
|
||||
.arg(&emit)
|
||||
.current_dir(canonical.parent().unwrap_or(root))
|
||||
.output()
|
||||
.map_err(|error| {
|
||||
LoadError::Engine(vec![Diagnostic::error(
|
||||
"web.engine.cli_missing",
|
||||
format!("cannot execute {}: {error}", cli.display()),
|
||||
)])
|
||||
})?;
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
|
||||
return Err(LoadError::Engine(vec![Diagnostic::error(
|
||||
"web.engine.cli_failed",
|
||||
format!(
|
||||
"`check --emit` failed with exit {:?}: {stderr}",
|
||||
output.status.code()
|
||||
),
|
||||
)
|
||||
.at(
|
||||
relative_path(&canonical, root).unwrap_or_else(|| canonical.display().to_string()),
|
||||
None,
|
||||
)]));
|
||||
}
|
||||
let raw = std::fs::read(&emit).map_err(|error| {
|
||||
LoadError::Engine(vec![Diagnostic::error(
|
||||
"web.engine.analysis",
|
||||
format!("cannot read emitted Analysis: {error}"),
|
||||
)])
|
||||
})?;
|
||||
let analysis: Value = serde_json::from_slice(&raw).map_err(|error| {
|
||||
LoadError::Engine(vec![Diagnostic::error(
|
||||
"web.engine.analysis",
|
||||
format!("emitted Analysis is not valid JSON: {error}"),
|
||||
)])
|
||||
})?;
|
||||
validate_analysis(&analysis, &canonical, root)?;
|
||||
let module = analysis["modules"][0].clone();
|
||||
let source = module["source"].as_str().unwrap_or_default().to_string();
|
||||
let source_digest = module["source_digest"]
|
||||
.as_str()
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
let module_id = module["id"].as_str().unwrap_or_default().to_string();
|
||||
let units = module["units"].as_array().cloned().unwrap_or_default();
|
||||
let anchors = module["anchors"].as_array().cloned().unwrap_or_default();
|
||||
let document = module["document"].clone();
|
||||
let references = module["references"].as_array().cloned().unwrap_or_default();
|
||||
let relative =
|
||||
relative_path(&canonical, root).unwrap_or_else(|| canonical.display().to_string());
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
Ok(Module {
|
||||
path: canonical,
|
||||
relative,
|
||||
source,
|
||||
source_digest,
|
||||
module_id,
|
||||
units,
|
||||
anchors,
|
||||
document,
|
||||
references,
|
||||
})
|
||||
}
|
||||
|
||||
fn relative_path(path: &Path, root: &Path) -> Option<String> {
|
||||
path.strip_prefix(root)
|
||||
.ok()
|
||||
.map(|value| value.to_string_lossy().replace('\\', "/"))
|
||||
}
|
||||
|
||||
fn validate_analysis(analysis: &Value, document: &Path, root: &Path) -> Result<(), LoadError> {
|
||||
let engine = |code, message: String| {
|
||||
LoadError::Engine(vec![Diagnostic::error(code, message).at(
|
||||
relative_path(document, root).unwrap_or_else(|| document.display().to_string()),
|
||||
None,
|
||||
)])
|
||||
};
|
||||
if analysis["schema"].as_str() != Some("marqdo.analysis") {
|
||||
return Err(engine(
|
||||
"web.engine.protocol",
|
||||
"CLI output is not marqdo.analysis".to_string(),
|
||||
));
|
||||
}
|
||||
if analysis["schema_version"].as_u64() != Some(3) {
|
||||
return Err(engine(
|
||||
"web.engine.protocol",
|
||||
"Analysis schema_version must be 3".to_string(),
|
||||
));
|
||||
}
|
||||
let modules = analysis["modules"]
|
||||
.as_array()
|
||||
.ok_or_else(|| engine("web.engine.protocol", "Analysis has no modules".to_string()))?;
|
||||
if modules.len() != 1 {
|
||||
return Err(engine(
|
||||
"web.engine.protocol",
|
||||
format!("expected one analyzed module, found {}", modules.len()),
|
||||
));
|
||||
}
|
||||
let module = &modules[0];
|
||||
let digest = module["source_digest"].as_str().unwrap_or_default();
|
||||
if digest.len() != 64 || !digest.chars().all(|ch| ch.is_ascii_hexdigit()) {
|
||||
return Err(engine(
|
||||
"web.engine.protocol",
|
||||
"Analysis module has no valid source_digest".to_string(),
|
||||
));
|
||||
}
|
||||
let source = module["source"].as_str().unwrap_or_default();
|
||||
if source.is_empty() {
|
||||
return Err(engine(
|
||||
"web.engine.protocol",
|
||||
"Analysis module inlines no source; stale/tampered input".to_string(),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn engine_diagnostics(error: LoadError) -> Diagnostics {
|
||||
error.into_diagnostics()
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
//! Stable diagnostic codes and source locations.
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Severity {
|
||||
Error,
|
||||
Warning,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Span {
|
||||
pub start: usize,
|
||||
pub end: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Diagnostic {
|
||||
pub code: &'static str,
|
||||
pub severity: Severity,
|
||||
pub message: String,
|
||||
pub path: Option<String>,
|
||||
pub anchor: Option<String>,
|
||||
pub span: Option<Span>,
|
||||
}
|
||||
|
||||
impl Diagnostic {
|
||||
pub fn error(code: &'static str, message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
code,
|
||||
severity: Severity::Error,
|
||||
message: message.into(),
|
||||
path: None,
|
||||
anchor: None,
|
||||
span: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn at(mut self, path: impl Into<String>, span: Option<(usize, usize)>) -> Self {
|
||||
self.path = Some(path.into());
|
||||
self.span = span.map(|(start, end)| Span { start, end });
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_anchor(mut self, anchor: impl Into<String>) -> Self {
|
||||
self.anchor = Some(anchor.into());
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
pub type Diagnostics = Vec<Diagnostic>;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum LoadError {
|
||||
/// The CLI/engine/protocol failed; hosts map this to exit code 2.
|
||||
Engine(Diagnostics),
|
||||
/// The author document violates the design contract; hosts map this to exit code 1.
|
||||
Design(Diagnostics),
|
||||
}
|
||||
|
||||
impl From<Diagnostic> for LoadError {
|
||||
fn from(diagnostic: Diagnostic) -> Self {
|
||||
LoadError::Design(vec![diagnostic])
|
||||
}
|
||||
}
|
||||
|
||||
impl LoadError {
|
||||
pub fn diagnostics(&self) -> &Diagnostics {
|
||||
match self {
|
||||
Self::Engine(items) | Self::Design(items) => items,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn into_diagnostics(self) -> Diagnostics {
|
||||
match self {
|
||||
Self::Engine(items) | Self::Design(items) => items,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn span_from(value: &Value) -> Option<(usize, usize)> {
|
||||
Some((
|
||||
value.get("start")?.as_u64()? as usize,
|
||||
value.get("end")?.as_u64()? as usize,
|
||||
))
|
||||
}
|
||||
+287
@@ -0,0 +1,287 @@
|
||||
//! Deterministic selection of the contract's units and GFM tables from Analysis 3.
|
||||
//!
|
||||
//! Only public Analysis facts are consumed: unit ids/paths/spans/anchors and the
|
||||
//! canonical Markdown AST. No Markdown parser is implemented here; cell text is
|
||||
//! read from the analysis-provided source by UTF-8 byte span.
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::analysis::Module;
|
||||
use crate::diagnostic::{span_from, Diagnostic};
|
||||
|
||||
pub const COMPONENTS: &str = "组件";
|
||||
pub const COMPONENTS_HEADER: [&str; 4] = ["行", "槽", "组件", "宽度"];
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Unit {
|
||||
pub id: String,
|
||||
pub kind: String,
|
||||
pub mode: String,
|
||||
pub name: String,
|
||||
pub level: u64,
|
||||
pub path: Vec<String>,
|
||||
pub parent_id: Option<String>,
|
||||
pub span: (usize, usize),
|
||||
pub heading_span: Option<(usize, usize)>,
|
||||
}
|
||||
|
||||
impl Unit {
|
||||
pub fn anchor_text(&self) -> &str {
|
||||
self.path.last().map(String::as_str).unwrap_or("")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Link {
|
||||
pub url: String,
|
||||
pub span: (usize, usize),
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Cell {
|
||||
pub span: (usize, usize),
|
||||
pub text: String,
|
||||
pub links: Vec<Link>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Table {
|
||||
pub span: (usize, usize),
|
||||
pub headers: Vec<String>,
|
||||
pub rows: Vec<Vec<Cell>>,
|
||||
}
|
||||
|
||||
fn units(module: &Module) -> Vec<Unit> {
|
||||
module
|
||||
.units
|
||||
.iter()
|
||||
.filter_map(|unit| {
|
||||
let id = unit["id"].as_str()?.to_string();
|
||||
Some(Unit {
|
||||
id,
|
||||
kind: unit["kind"].as_str().unwrap_or("").to_string(),
|
||||
mode: unit["mode"].as_str().unwrap_or("").to_string(),
|
||||
name: unit["name"].as_str().unwrap_or("").to_string(),
|
||||
level: unit["level"].as_u64()?,
|
||||
path: unit["path"]
|
||||
.as_array()?
|
||||
.iter()
|
||||
.filter_map(|value| value.as_str().map(ToString::to_string))
|
||||
.collect(),
|
||||
parent_id: unit["parent_id"].as_str().map(ToString::to_string),
|
||||
span: span_from(&unit["span"]).unwrap_or((0, 0)),
|
||||
heading_span: span_from(&unit["heading_span"]),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn text_at(module: &Module, span: (usize, usize)) -> String {
|
||||
module
|
||||
.text_span(span.0, span.1)
|
||||
.unwrap_or_default()
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// Select the Knowledge H2 by its exact anchor, never by label/path guessing.
|
||||
pub fn knowledge_h2(module: &Module, anchor: &str) -> Result<Unit, Diagnostic> {
|
||||
let mut matches = Vec::new();
|
||||
for entry in &module.anchors {
|
||||
if entry["anchor"].as_str() != Some(anchor) {
|
||||
continue;
|
||||
}
|
||||
let Some(unit_id) = entry["unit_id"].as_str() else {
|
||||
continue;
|
||||
};
|
||||
if let Some(unit) = units(module).into_iter().find(|unit| unit.id == unit_id) {
|
||||
matches.push(unit);
|
||||
}
|
||||
}
|
||||
if matches.is_empty() {
|
||||
return Err(Diagnostic::error(
|
||||
"web.unit.anchor_missing",
|
||||
format!("no unit has the exact anchor {anchor:?}"),
|
||||
)
|
||||
.with_anchor(anchor)
|
||||
.at(module.relative.clone(), None));
|
||||
}
|
||||
if matches.len() > 1 {
|
||||
return Err(Diagnostic::error(
|
||||
"web.unit.anchor_ambiguous",
|
||||
format!("anchor {anchor:?} resolves to more than one unit"),
|
||||
)
|
||||
.with_anchor(anchor)
|
||||
.at(module.relative.clone(), None));
|
||||
}
|
||||
let unit = matches.remove(0);
|
||||
if unit.kind != "knowledge" || unit.level != 2 || unit.mode != "knowledge" {
|
||||
return Err(Diagnostic::error(
|
||||
"web.unit.not_knowledge_h2",
|
||||
format!(
|
||||
"design component must be a Knowledge H2 (found kind={} level={} mode={})",
|
||||
unit.kind, unit.level, unit.mode
|
||||
),
|
||||
)
|
||||
.with_anchor(anchor)
|
||||
.at(module.relative.clone(), unit.heading_span));
|
||||
}
|
||||
Ok(unit)
|
||||
}
|
||||
|
||||
/// Direct retained H3 sections under one H2.
|
||||
pub fn direct_sections(module: &Module, h2: &Unit) -> Vec<Unit> {
|
||||
units(module)
|
||||
.into_iter()
|
||||
.filter(|unit| {
|
||||
unit.level == 3
|
||||
&& unit.kind == "section"
|
||||
&& unit.parent_id.as_deref() == Some(h2.id.as_str())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn walk_tables<'a>(node: &'a Value, out: &mut Vec<&'a Value>) {
|
||||
if node["kind"].as_str() == Some("table") {
|
||||
out.push(node);
|
||||
}
|
||||
if let Some(children) = node["children"].as_array() {
|
||||
for child in children {
|
||||
walk_tables(child, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn walk_links<'a>(node: &'a Value, out: &mut Vec<&'a Value>) {
|
||||
if node["kind"].as_str() == Some("link") {
|
||||
out.push(node);
|
||||
}
|
||||
if let Some(children) = node["children"].as_array() {
|
||||
for child in children {
|
||||
walk_links(child, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Select the single retained `组件` table inside its direct H3 section.
|
||||
/// Returns `Ok(None)` when the component declares no component table.
|
||||
pub fn components_table(module: &Module, h2: &Unit) -> Result<Option<(Unit, Table)>, Diagnostic> {
|
||||
let section = direct_sections(module, h2)
|
||||
.into_iter()
|
||||
.find(|section| section.name == COMPONENTS);
|
||||
let Some(section) = section else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut tables = Vec::new();
|
||||
walk_tables(&module.document, &mut tables);
|
||||
let mut inside: Vec<&Value> = tables
|
||||
.into_iter()
|
||||
.filter(|table| {
|
||||
span_from(&table["span"])
|
||||
.map(|(start, end)| start >= section.span.0 && end <= section.span.1)
|
||||
.unwrap_or(false)
|
||||
})
|
||||
.collect();
|
||||
match inside.len() {
|
||||
0 => Err(
|
||||
Diagnostic::error("web.table.missing", "`组件` section has no GFM table")
|
||||
.at(module.relative.clone(), Some(section.span))
|
||||
.with_anchor(section.anchor_text().to_string()),
|
||||
),
|
||||
1 => Ok(Some((
|
||||
section.clone(),
|
||||
parse_table(module, inside.remove(0))?,
|
||||
))),
|
||||
_ => Err(Diagnostic::error(
|
||||
"web.table.multiple",
|
||||
"`组件` section must contain exactly one GFM table",
|
||||
)
|
||||
.at(module.relative.clone(), Some(section.span))),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_table(module: &Module, table: &Value) -> Result<Table, Diagnostic> {
|
||||
let span = span_from(&table["span"]).ok_or_else(|| {
|
||||
Diagnostic::error("web.table.span", "table has no source span")
|
||||
.at(module.relative.clone(), None)
|
||||
})?;
|
||||
let mut ast_rows = Vec::new();
|
||||
if let Some(children) = table["children"].as_array() {
|
||||
for child in children {
|
||||
if child["kind"].as_str() == Some("table_row") {
|
||||
ast_rows.push(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
if ast_rows.len() < 2 {
|
||||
return Err(Diagnostic::error(
|
||||
"web.table.rows",
|
||||
"`组件` table needs a header and at least one component row",
|
||||
)
|
||||
.at(module.relative.clone(), Some(span)));
|
||||
}
|
||||
let headers: Vec<String> = ast_rows[0]["children"]
|
||||
.as_array()
|
||||
.map(|cells| {
|
||||
cells
|
||||
.iter()
|
||||
.map(|cell| {
|
||||
text_at(module, span_from(&cell["span"]).unwrap_or((0, 0)))
|
||||
.trim()
|
||||
.to_string()
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
if headers != COMPONENTS_HEADER {
|
||||
return Err(Diagnostic::error(
|
||||
"web.table.header",
|
||||
format!(
|
||||
"`组件` header must be exactly {:?}, found {:?}",
|
||||
COMPONENTS_HEADER, headers
|
||||
),
|
||||
)
|
||||
.at(module.relative.clone(), Some(span)));
|
||||
}
|
||||
let mut rows = Vec::new();
|
||||
for row in ast_rows.iter().skip(1) {
|
||||
let raw_cells = row["children"].as_array().cloned().unwrap_or_default();
|
||||
if raw_cells.len() != COMPONENTS_HEADER.len() {
|
||||
return Err(Diagnostic::error(
|
||||
"web.table.columns",
|
||||
format!(
|
||||
"component row must have {} cells, found {}",
|
||||
COMPONENTS_HEADER.len(),
|
||||
raw_cells.len()
|
||||
),
|
||||
)
|
||||
.at(module.relative.clone(), span_from(&row["span"])));
|
||||
}
|
||||
let mut cells = Vec::new();
|
||||
for cell in raw_cells {
|
||||
let cell_span = span_from(&cell["span"]).unwrap_or((0, 0));
|
||||
let mut ast_links = Vec::new();
|
||||
walk_links(&cell, &mut ast_links);
|
||||
let links = ast_links
|
||||
.into_iter()
|
||||
.filter_map(|link| {
|
||||
let span = span_from(&link["span"])?;
|
||||
let url = link["url"].as_str()?.to_string();
|
||||
let text = text_at(module, span);
|
||||
Some(Link { url, span, text })
|
||||
})
|
||||
.collect();
|
||||
cells.push(Cell {
|
||||
span: cell_span,
|
||||
text: text_at(module, cell_span),
|
||||
links,
|
||||
});
|
||||
}
|
||||
rows.push(cells);
|
||||
}
|
||||
Ok(Table {
|
||||
span,
|
||||
headers,
|
||||
rows,
|
||||
})
|
||||
}
|
||||
+574
@@ -0,0 +1,574 @@
|
||||
//! Marqdo Web Design — the single interpreter of the Web author contract over
|
||||
//! public CLI Analysis 3 (WEB-01/WEB-03).
|
||||
//!
|
||||
//! The library never parses Markdown itself: it runs the verified CLI's public
|
||||
//! `check --emit`, consumes Analysis 3 units/anchors/AST/spans/references, and
|
||||
//! binds design links by exact candidate path + anchor. Diagnostics carry stable
|
||||
//! codes with source path/span. Engine failures (missing CLI, protocol drift,
|
||||
//! stale/tampered Analysis) are distinct from author-contract errors so hosts can
|
||||
//! map exit codes 2 and 1.
|
||||
|
||||
pub mod analysis;
|
||||
pub mod diagnostic;
|
||||
pub mod document;
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use analysis::Module;
|
||||
use diagnostic::{Diagnostic, LoadError, Span};
|
||||
use document::{Cell, Link, Unit};
|
||||
|
||||
pub use diagnostic::{LoadError as Error, Severity};
|
||||
|
||||
/// Explicit inputs; there is no implicit CLI or project discovery.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct LoadConfig {
|
||||
/// Verified `marqdo` executable.
|
||||
pub cli: PathBuf,
|
||||
pub entry: PathBuf,
|
||||
/// Exact Knowledge H2 anchor (no `#`).
|
||||
pub unit: String,
|
||||
/// Explicit design root; every component target must stay inside it.
|
||||
pub root: PathBuf,
|
||||
pub max_depth: usize,
|
||||
pub max_modules: usize,
|
||||
pub max_source_bytes: usize,
|
||||
}
|
||||
|
||||
impl LoadConfig {
|
||||
pub fn new(
|
||||
cli: impl Into<PathBuf>,
|
||||
entry: impl Into<PathBuf>,
|
||||
unit: impl Into<String>,
|
||||
root: impl Into<PathBuf>,
|
||||
) -> Self {
|
||||
Self {
|
||||
cli: cli.into(),
|
||||
entry: entry.into(),
|
||||
unit: unit.into(),
|
||||
root: root.into(),
|
||||
max_depth: 12,
|
||||
max_modules: 64,
|
||||
max_source_bytes: 8 * 1024 * 1024,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SourceRef {
|
||||
/// Root-relative path.
|
||||
pub path: String,
|
||||
pub module_id: String,
|
||||
pub unit_id: String,
|
||||
pub unit_path: Vec<String>,
|
||||
pub anchor: String,
|
||||
pub source_digest: String,
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Width {
|
||||
Auto,
|
||||
Fr(u8),
|
||||
Px(u16),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Width {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Auto => write!(formatter, "auto"),
|
||||
Self::Fr(value) => write!(formatter, "{value}fr"),
|
||||
Self::Px(value) => write!(formatter, "{value}px"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ChildSlot {
|
||||
pub slot: String,
|
||||
pub row: u32,
|
||||
pub width: Width,
|
||||
pub target: String,
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ComponentDef {
|
||||
pub key: String,
|
||||
pub source: SourceRef,
|
||||
pub slots: Vec<ChildSlot>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Instance {
|
||||
/// `root` then one segment per slot path; reused definitions keep separate instances.
|
||||
pub id: String,
|
||||
pub definition: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SourceIdentity {
|
||||
pub path: String,
|
||||
pub module_id: String,
|
||||
pub source_digest: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Design {
|
||||
pub root: String,
|
||||
pub definitions: BTreeMap<String, ComponentDef>,
|
||||
pub instances: Vec<Instance>,
|
||||
pub sources: Vec<SourceIdentity>,
|
||||
}
|
||||
|
||||
fn design_error(code: &'static str, message: impl Into<String>) -> LoadError {
|
||||
LoadError::Design(vec![Diagnostic::error(code, message)])
|
||||
}
|
||||
|
||||
fn engine_error(code: &'static str, message: impl Into<String>) -> LoadError {
|
||||
LoadError::Engine(vec![Diagnostic::error(code, message)])
|
||||
}
|
||||
|
||||
fn source_ref(module: &Module, unit: &Unit, anchor: &str) -> SourceRef {
|
||||
SourceRef {
|
||||
path: module.relative.clone(),
|
||||
module_id: module.module_id.clone(),
|
||||
unit_id: unit.id.clone(),
|
||||
unit_path: unit.path.clone(),
|
||||
anchor: anchor.to_string(),
|
||||
source_digest: module.source_digest.clone(),
|
||||
span: Span {
|
||||
start: unit.span.0,
|
||||
end: unit.span.1,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn definition_key(module: &Module, anchor: &str) -> String {
|
||||
format!("{}#{}", module.relative, anchor)
|
||||
}
|
||||
|
||||
fn parse_row(value: &str) -> Result<u32, &'static str> {
|
||||
let trimmed = value.trim();
|
||||
if trimmed.is_empty() || !trimmed.chars().all(|ch| ch.is_ascii_digit()) {
|
||||
return Err("row must be a positive integer");
|
||||
}
|
||||
let parsed: u32 = trimmed.parse().map_err(|_| "row is out of range")?;
|
||||
if parsed == 0 {
|
||||
return Err("row numbering starts at 1");
|
||||
}
|
||||
Ok(parsed)
|
||||
}
|
||||
|
||||
fn parse_slot(value: &str) -> Result<String, &'static str> {
|
||||
let slot = value.trim();
|
||||
let mut chars = slot.chars();
|
||||
let Some(first) = chars.next() else {
|
||||
return Err("slot is empty");
|
||||
};
|
||||
if !first.is_ascii_lowercase() {
|
||||
return Err("slot must start with [a-z]");
|
||||
}
|
||||
if !chars.all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || matches!(ch, '_' | '-')) {
|
||||
return Err("slot may only contain [a-z0-9_-]");
|
||||
}
|
||||
Ok(slot.to_string())
|
||||
}
|
||||
|
||||
fn parse_width(value: &str) -> Result<Width, &'static str> {
|
||||
let width = value.trim();
|
||||
if width == "auto" {
|
||||
return Ok(Width::Auto);
|
||||
}
|
||||
if let Some(fr) = width.strip_suffix("fr") {
|
||||
let parsed: u8 = fr.parse().map_err(|_| "fr width must be an integer")?;
|
||||
if !(1..=12).contains(&parsed) {
|
||||
return Err("fr width must be 1..=12");
|
||||
}
|
||||
return Ok(Width::Fr(parsed));
|
||||
}
|
||||
if let Some(px) = width.strip_suffix("px") {
|
||||
let parsed: u16 = px.parse().map_err(|_| "px width must be an integer")?;
|
||||
if !(120..=1200).contains(&parsed) {
|
||||
return Err("px width must be 120..=1200");
|
||||
}
|
||||
return Ok(Width::Px(parsed));
|
||||
}
|
||||
Err("width must be auto, 1fr..12fr or 120px..1200px")
|
||||
}
|
||||
|
||||
fn single_link<'a>(
|
||||
cell: &'a Cell,
|
||||
path: &str,
|
||||
span: (usize, usize),
|
||||
) -> Result<&'a Link, LoadError> {
|
||||
match cell.links.len() {
|
||||
0 => Err(LoadError::Design(vec![Diagnostic::error(
|
||||
"web.link.none",
|
||||
"component cell must contain exactly one Markdown Link",
|
||||
)
|
||||
.at(path.to_string(), Some(span))])),
|
||||
1 => Ok(&cell.links[0]),
|
||||
count => Err(LoadError::Design(vec![Diagnostic::error(
|
||||
"web.link.multiple",
|
||||
format!("component cell must contain exactly one Link, found {count}"),
|
||||
)
|
||||
.at(path.to_string(), Some(span))])),
|
||||
}
|
||||
}
|
||||
|
||||
fn find_reference<'a>(module: &'a Module, link: &Link) -> Result<&'a Value, LoadError> {
|
||||
module
|
||||
.references
|
||||
.iter()
|
||||
.find(|reference| {
|
||||
reference["url"].as_str() == Some(link.url.as_str())
|
||||
&& diagnostic::span_from(&reference["span"]) == Some(link.span)
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
LoadError::Design(vec![Diagnostic::error(
|
||||
"web.link.reference",
|
||||
format!("no Analysis reference for design link {:?}", link.url),
|
||||
)
|
||||
.at(module.relative.clone(), Some(link.span))])
|
||||
})
|
||||
}
|
||||
|
||||
struct Loader {
|
||||
config: LoadConfig,
|
||||
root: PathBuf,
|
||||
modules: BTreeMap<PathBuf, Module>,
|
||||
definitions: BTreeMap<String, ComponentDef>,
|
||||
stack: Vec<String>,
|
||||
source_bytes: usize,
|
||||
}
|
||||
|
||||
impl Loader {
|
||||
fn analyze(&mut self, document: &Path) -> Result<Module, LoadError> {
|
||||
let canonical = document.canonicalize().map_err(|error| {
|
||||
engine_error(
|
||||
"web.engine.entry",
|
||||
format!("cannot canonicalize {}: {error}", document.display()),
|
||||
)
|
||||
})?;
|
||||
if let Some(module) = self.modules.get(&canonical) {
|
||||
return Ok(module.clone());
|
||||
}
|
||||
if self.modules.len() >= self.config.max_modules {
|
||||
return Err(design_error(
|
||||
"web.limit.modules",
|
||||
format!("analysis module limit {} reached", self.config.max_modules),
|
||||
));
|
||||
}
|
||||
let module = analysis::analyze(&self.config.cli, &canonical, &self.root)?;
|
||||
self.source_bytes += module.source.len();
|
||||
if self.source_bytes > self.config.max_source_bytes {
|
||||
return Err(design_error(
|
||||
"web.limit.bytes",
|
||||
format!("source byte limit {} reached", self.config.max_source_bytes),
|
||||
));
|
||||
}
|
||||
self.modules.insert(canonical, module.clone());
|
||||
Ok(module)
|
||||
}
|
||||
|
||||
fn resolve_target(
|
||||
&mut self,
|
||||
module: &Module,
|
||||
link: &Link,
|
||||
) -> Result<(Module, Unit, String), LoadError> {
|
||||
let reference = find_reference(module, link)?;
|
||||
let candidate = reference["candidate_path"]
|
||||
.as_str()
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
let fragment = reference["fragment"].as_str().unwrap_or("").to_string();
|
||||
if candidate.is_empty() || fragment.is_empty() {
|
||||
return Err(LoadError::Design(vec![Diagnostic::error(
|
||||
"web.link.candidate",
|
||||
"design link must expose a candidate_path and a fragment",
|
||||
)
|
||||
.at(module.relative.clone(), Some(link.span))]));
|
||||
}
|
||||
if Path::new(&candidate).is_absolute() || link.url.contains("://") {
|
||||
return Err(LoadError::Design(vec![Diagnostic::error(
|
||||
"web.link.absolute",
|
||||
"design link must be a project-relative .mq.md path",
|
||||
)
|
||||
.at(module.relative.clone(), Some(link.span))]));
|
||||
}
|
||||
if !candidate.ends_with(".mq.md") {
|
||||
return Err(LoadError::Design(vec![Diagnostic::error(
|
||||
"web.link.target_kind",
|
||||
format!("design target must be a .mq.md document, got {candidate:?}"),
|
||||
)
|
||||
.at(module.relative.clone(), Some(link.span))]));
|
||||
}
|
||||
let source_dir = module.path.parent().unwrap_or(&self.root);
|
||||
let target = source_dir.join(&candidate);
|
||||
let canonical = target.canonicalize().map_err(|error| {
|
||||
LoadError::Design(vec![Diagnostic::error(
|
||||
"web.link.target_missing",
|
||||
format!("cannot resolve design target {candidate:?}: {error}"),
|
||||
)
|
||||
.at(module.relative.clone(), Some(link.span))])
|
||||
})?;
|
||||
if !canonical.starts_with(&self.root) {
|
||||
return Err(LoadError::Design(vec![Diagnostic::error(
|
||||
"web.link.outside_root",
|
||||
format!("design target {candidate:?} escapes the explicit root"),
|
||||
)
|
||||
.at(module.relative.clone(), Some(link.span))]));
|
||||
}
|
||||
let target_module = self.analyze(&canonical)?;
|
||||
let unit = document::knowledge_h2(&target_module, &fragment).map_err(|diagnostic| {
|
||||
let span = diagnostic.span.clone().map(|span| (span.start, span.end));
|
||||
LoadError::Design(vec![diagnostic.at(target_module.relative.clone(), span)])
|
||||
})?;
|
||||
Ok((target_module, unit, fragment))
|
||||
}
|
||||
|
||||
fn load_definition(
|
||||
&mut self,
|
||||
module: &Module,
|
||||
unit: &Unit,
|
||||
anchor: &str,
|
||||
depth: usize,
|
||||
) -> Result<String, LoadError> {
|
||||
let key = definition_key(module, anchor);
|
||||
if self.definitions.contains_key(&key) {
|
||||
return Ok(key);
|
||||
}
|
||||
if depth > self.config.max_depth {
|
||||
return Err(design_error(
|
||||
"web.limit.depth",
|
||||
format!("design recursion depth {} exceeded", self.config.max_depth),
|
||||
));
|
||||
}
|
||||
if self.stack.iter().any(|item| item == &key) {
|
||||
return Err(design_error(
|
||||
"web.link.cycle",
|
||||
format!("visual containment cycle at {key}"),
|
||||
));
|
||||
}
|
||||
self.stack.push(key.clone());
|
||||
let table = document::components_table(module, unit)?;
|
||||
let mut slots = Vec::new();
|
||||
if let Some((section, table)) = table {
|
||||
let mut previous_row = 0u32;
|
||||
let mut seen_slots = BTreeSet::new();
|
||||
for cells in &table.rows {
|
||||
let row_text = cells[0].text.trim();
|
||||
let slot_text = cells[1].text.trim();
|
||||
let width_text = cells[3].text.trim();
|
||||
let row = parse_row(row_text).map_err(|message| {
|
||||
LoadError::Design(vec![Diagnostic::error("web.layout.row", message)
|
||||
.at(module.relative.clone(), Some(cells[0].span))])
|
||||
})?;
|
||||
if previous_row == 0 {
|
||||
if row != 1 {
|
||||
return Err(LoadError::Design(vec![Diagnostic::error(
|
||||
"web.layout.row_order",
|
||||
"first component row must be 1",
|
||||
)
|
||||
.at(module.relative.clone(), Some(cells[0].span))]));
|
||||
}
|
||||
} else if row != previous_row && row != previous_row + 1 {
|
||||
return Err(LoadError::Design(vec![Diagnostic::error(
|
||||
"web.layout.row_order",
|
||||
format!("rows must be continuous; {previous_row} followed by {row}"),
|
||||
)
|
||||
.at(module.relative.clone(), Some(cells[0].span))]));
|
||||
}
|
||||
previous_row = row;
|
||||
let slot = parse_slot(slot_text).map_err(|message| {
|
||||
LoadError::Design(vec![Diagnostic::error("web.layout.slot", message)
|
||||
.at(module.relative.clone(), Some(cells[1].span))])
|
||||
})?;
|
||||
if !seen_slots.insert(slot.clone()) {
|
||||
return Err(LoadError::Design(vec![Diagnostic::error(
|
||||
"web.layout.slot_duplicate",
|
||||
format!("slot {slot:?} is declared twice in one component"),
|
||||
)
|
||||
.at(module.relative.clone(), Some(cells[1].span))]));
|
||||
}
|
||||
let width = parse_width(width_text).map_err(|message| {
|
||||
LoadError::Design(vec![Diagnostic::error("web.layout.width", message)
|
||||
.at(module.relative.clone(), Some(cells[3].span))])
|
||||
})?;
|
||||
let link = single_link(&cells[2], &module.relative, cells[2].span)?;
|
||||
if cells[2].text.trim() != link.text.trim() {
|
||||
return Err(LoadError::Design(vec![Diagnostic::error(
|
||||
"web.link.cell_text",
|
||||
"component cell must contain only the design Link",
|
||||
)
|
||||
.at(module.relative.clone(), Some(cells[2].span))]));
|
||||
}
|
||||
let (target_module, target_unit, target_anchor) =
|
||||
self.resolve_target(module, link)?;
|
||||
let target_key =
|
||||
self.load_definition(&target_module, &target_unit, &target_anchor, depth + 1)?;
|
||||
slots.push(ChildSlot {
|
||||
slot,
|
||||
row,
|
||||
width,
|
||||
target: target_key,
|
||||
span: Span {
|
||||
start: cells[2].span.0,
|
||||
end: cells[2].span.1,
|
||||
},
|
||||
});
|
||||
}
|
||||
let _ = section;
|
||||
}
|
||||
self.stack.pop();
|
||||
let definition = ComponentDef {
|
||||
key: key.clone(),
|
||||
source: source_ref(module, unit, anchor),
|
||||
slots,
|
||||
};
|
||||
self.definitions.insert(key.clone(), definition);
|
||||
Ok(key)
|
||||
}
|
||||
}
|
||||
|
||||
/// Load one explicit design unit and interpret the contract.
|
||||
pub fn load(config: &LoadConfig) -> Result<Design, LoadError> {
|
||||
if config.unit.starts_with('#') {
|
||||
return Err(design_error(
|
||||
"web.unit.anchor_invalid",
|
||||
"`unit` is the exact anchor without a leading '#'",
|
||||
));
|
||||
}
|
||||
let root = config.root.canonicalize().map_err(|error| {
|
||||
engine_error(
|
||||
"web.engine.root",
|
||||
format!(
|
||||
"cannot canonicalize root {}: {error}",
|
||||
config.root.display()
|
||||
),
|
||||
)
|
||||
})?;
|
||||
let entry = config.entry.canonicalize().map_err(|error| {
|
||||
engine_error(
|
||||
"web.engine.entry",
|
||||
format!(
|
||||
"cannot canonicalize entry {}: {error}",
|
||||
config.entry.display()
|
||||
),
|
||||
)
|
||||
})?;
|
||||
if !entry.starts_with(&root) {
|
||||
return Err(design_error(
|
||||
"web.unit.entry_outside_root",
|
||||
"ENTRY must stay inside --root",
|
||||
));
|
||||
}
|
||||
if entry.extension().and_then(|ext| ext.to_str()) != Some("md")
|
||||
|| !entry.to_string_lossy().ends_with(".mq.md")
|
||||
{
|
||||
return Err(design_error(
|
||||
"web.unit.entry_kind",
|
||||
"ENTRY must be a .mq.md document",
|
||||
));
|
||||
}
|
||||
let mut loader = Loader {
|
||||
config: config.clone(),
|
||||
root: root.clone(),
|
||||
modules: BTreeMap::new(),
|
||||
definitions: BTreeMap::new(),
|
||||
stack: Vec::new(),
|
||||
source_bytes: 0,
|
||||
};
|
||||
let module = loader.analyze(&entry)?;
|
||||
let unit = document::knowledge_h2(&module, &config.unit)?;
|
||||
let root_key = loader.load_definition(&module, &unit, &config.unit, 0)?;
|
||||
let mut instances = Vec::new();
|
||||
collect_instances(&loader.definitions, &root_key, "root", &mut instances);
|
||||
let mut sources = loader
|
||||
.modules
|
||||
.values()
|
||||
.map(|module| SourceIdentity {
|
||||
path: module.relative.clone(),
|
||||
module_id: module.module_id.clone(),
|
||||
source_digest: module.source_digest.clone(),
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
sources.sort_by(|left, right| left.path.cmp(&right.path));
|
||||
Ok(Design {
|
||||
root: root_key,
|
||||
definitions: loader.definitions,
|
||||
instances,
|
||||
sources,
|
||||
})
|
||||
}
|
||||
|
||||
fn collect_instances(
|
||||
definitions: &BTreeMap<String, ComponentDef>,
|
||||
key: &str,
|
||||
path: &str,
|
||||
out: &mut Vec<Instance>,
|
||||
) {
|
||||
out.push(Instance {
|
||||
id: path.to_string(),
|
||||
definition: key.to_string(),
|
||||
});
|
||||
if let Some(definition) = definitions.get(key) {
|
||||
for slot in &definition.slots {
|
||||
collect_instances(
|
||||
definitions,
|
||||
&slot.target,
|
||||
&format!("{path}/{}", slot.slot),
|
||||
out,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Derive a Markdown handoff from the model only; never re-reads sources.
|
||||
pub fn handoff(design: &Design) -> String {
|
||||
let mut out = String::new();
|
||||
out.push_str("# Design handoff\n\n");
|
||||
out.push_str(&format!("root: `{}`\n\n", design.root));
|
||||
out.push_str("## Component tree\n\n");
|
||||
for instance in &design.instances {
|
||||
let definition = design.definitions.get(&instance.definition);
|
||||
let depth = instance.id.matches('/').count();
|
||||
let indent = " ".repeat(depth);
|
||||
out.push_str(&format!(
|
||||
"{indent}- `{}` ({})",
|
||||
instance.id, instance.definition
|
||||
));
|
||||
if let Some(definition) = definition {
|
||||
out.push_str(&format!(
|
||||
" — {} [{}]",
|
||||
definition.source.path, definition.source.anchor
|
||||
));
|
||||
}
|
||||
out.push('\n');
|
||||
if let Some(definition) = definition {
|
||||
for slot in &definition.slots {
|
||||
out.push_str(&format!(
|
||||
"{indent} - slot `{}` row {} {} -> `{}`\n",
|
||||
slot.slot, slot.row, slot.width, slot.target
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push_str("\n## Sources\n\n");
|
||||
for source in &design.sources {
|
||||
out.push_str(&format!(
|
||||
"- `{}` digest `sha256:{}`\n",
|
||||
source.path, source.source_digest
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Count definitions/instances for diagnostics and tests.
|
||||
pub fn statistics(design: &Design) -> (usize, usize) {
|
||||
(design.definitions.len(), design.instances.len())
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
//! WEB-01 contract tests against the real verified CLI (no mocked Analysis).
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use marqdo_web_design::{handoff, load, statistics, Error, LoadConfig};
|
||||
|
||||
static UNIQUE: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
fn cli() -> PathBuf {
|
||||
PathBuf::from(
|
||||
std::env::var("MARQDO_BIN")
|
||||
.expect("set MARQDO_BIN to the verified marqdo executable for WEB-01 tests"),
|
||||
)
|
||||
}
|
||||
|
||||
struct TempProject {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl TempProject {
|
||||
fn new() -> Self {
|
||||
let unique = UNIQUE.fetch_add(1, Ordering::Relaxed);
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"marqdo-web-design-test-{}-{unique}",
|
||||
std::process::id()
|
||||
));
|
||||
std::fs::create_dir_all(&path).unwrap();
|
||||
Self { path }
|
||||
}
|
||||
|
||||
fn write(&self, relative: &str, text: &str) {
|
||||
let path = self.path.join(relative);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, text).unwrap();
|
||||
}
|
||||
|
||||
fn config(&self, entry: &str, unit: &str) -> LoadConfig {
|
||||
LoadConfig::new(cli(), self.path.join(entry), unit, self.path.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempProject {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
fn design_code(error: Error) -> &'static str {
|
||||
match error {
|
||||
Error::Design(items) => items[0].code,
|
||||
Error::Engine(items) => panic!("expected design error, got engine: {items:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn engine_code(error: Error) -> &'static str {
|
||||
match error {
|
||||
Error::Engine(items) => items[0].code,
|
||||
Error::Design(items) => panic!("expected engine error, got design: {items:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
const INDEX: &str = r#"# 页面
|
||||
|
||||
## @knowledge 工作台
|
||||
|
||||
面向研究人员的页面。
|
||||
|
||||
### 内容
|
||||
|
||||
一些正文。
|
||||
|
||||
### 组件
|
||||
|
||||
| 行 | 槽 | 组件 | 宽度 |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | nav | [导航](components/nav.mq.md#导航) | 220px |
|
||||
| 1 | main | [工作区](components/workspace.mq.md#工作区) | 1fr |
|
||||
"#;
|
||||
|
||||
const NAV: &str = r#"# 导航组件
|
||||
|
||||
## @knowledge 导航
|
||||
|
||||
### 内容
|
||||
|
||||
导航正文。
|
||||
|
||||
### 组件
|
||||
|
||||
| 行 | 槽 | 组件 | 宽度 |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | leaf | [叶子](leaf.mq.md#叶子) | auto |
|
||||
"#;
|
||||
|
||||
const LEAF: &str = r#"# 叶子组件
|
||||
|
||||
## @knowledge 叶子
|
||||
|
||||
### 内容
|
||||
|
||||
叶子正文。
|
||||
"#;
|
||||
|
||||
fn basic_project() -> TempProject {
|
||||
let project = TempProject::new();
|
||||
project.write("index.mq.md", INDEX);
|
||||
project.write("components/nav.mq.md", NAV);
|
||||
project.write("components/leaf.mq.md", LEAF);
|
||||
project.write(
|
||||
"components/workspace.mq.md",
|
||||
"# 工作区页面\n\n## @knowledge 工作区\n\n### 内容\n\n工作区正文。\n",
|
||||
);
|
||||
project
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loads_recursive_layout_with_stable_source_identity() {
|
||||
let project = basic_project();
|
||||
let design = load(&project.config("index.mq.md", "工作台")).expect("load");
|
||||
assert_eq!(design.root, "index.mq.md#工作台");
|
||||
assert_eq!(statistics(&design), (4, 4));
|
||||
assert_eq!(design.definitions["index.mq.md#工作台"].slots.len(), 2);
|
||||
let root_slot = &design.definitions["index.mq.md#工作台"].slots[0];
|
||||
assert_eq!(root_slot.slot, "nav");
|
||||
assert_eq!(root_slot.row, 1);
|
||||
assert_eq!(root_slot.width.to_string(), "220px");
|
||||
assert_eq!(root_slot.target, "components/nav.mq.md#导航");
|
||||
assert_eq!(
|
||||
design.definitions["components/nav.mq.md#导航"].slots[0].target,
|
||||
"components/leaf.mq.md#叶子"
|
||||
);
|
||||
assert_eq!(design.sources.len(), 4);
|
||||
for source in &design.sources {
|
||||
assert_eq!(source.source_digest.len(), 64);
|
||||
assert!(!source.module_id.is_empty());
|
||||
}
|
||||
let first = handoff(&design);
|
||||
assert!(first.contains("components/leaf.mq.md#叶子"));
|
||||
assert!(first.contains("sha256:"));
|
||||
let again = load(&project.config("index.mq.md", "工作台")).expect("deterministic load");
|
||||
assert_eq!(first, handoff(&again));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reuses_definition_but_keeps_separate_instances() {
|
||||
let project = TempProject::new();
|
||||
project.write(
|
||||
"index.mq.md",
|
||||
"# 页面\n\n## @knowledge 工作台\n\n### 组件\n\n| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | left | [叶子](leaf.mq.md#叶子) | auto |\n| 1 | right | [叶子](leaf.mq.md#叶子) | auto |\n",
|
||||
);
|
||||
project.write("leaf.mq.md", LEAF);
|
||||
let design = load(&project.config("index.mq.md", "工作台")).expect("load");
|
||||
assert_eq!(design.definitions.len(), 2);
|
||||
let ids: Vec<&str> = design
|
||||
.instances
|
||||
.iter()
|
||||
.map(|item| item.id.as_str())
|
||||
.collect();
|
||||
assert_eq!(ids, vec!["root", "root/left", "root/right"]);
|
||||
assert_eq!(design.instances[1].definition, "leaf.mq.md#叶子");
|
||||
assert_eq!(design.instances[2].definition, "leaf.mq.md#叶子");
|
||||
assert_ne!(design.instances[1].id, design.instances[2].id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_content_only_component_and_width_forms() {
|
||||
let project = TempProject::new();
|
||||
project.write("index.mq.md", INDEX);
|
||||
project.write("components/nav.mq.md", &NAV.replace("220px", "1200px"));
|
||||
project.write("components/leaf.mq.md", LEAF);
|
||||
project.write(
|
||||
"components/workspace.mq.md",
|
||||
"# 工作区页面\n\n## @knowledge 工作区\n\n### 内容\n\n正文。\n\n### 组件\n\n| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | a | [叶子](leaf.mq.md#叶子) | 12fr |\n",
|
||||
);
|
||||
load(&project.config("index.mq.md", "工作台")).expect("width forms");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_missing_anchor_and_non_knowledge_units() {
|
||||
let project = basic_project();
|
||||
let error = load(&project.config("index.mq.md", "不存在")).unwrap_err();
|
||||
assert!(matches!(error, Error::Design(_)));
|
||||
assert_eq!(design_code(error), "web.unit.anchor_missing");
|
||||
|
||||
let exec = TempProject::new();
|
||||
exec.write("index.mq.md", "# @exec 页面\n\n## 函数\n\n`return 1`\n");
|
||||
let error = load(&exec.config("index.mq.md", "函数")).unwrap_err();
|
||||
assert_eq!(design_code(error), "web.unit.not_knowledge_h2");
|
||||
|
||||
let hashed = basic_project();
|
||||
let mut config = hashed.config("index.mq.md", "工作台");
|
||||
config.unit = "#工作台".to_string();
|
||||
assert_eq!(
|
||||
design_code(load(&config).unwrap_err()),
|
||||
"web.unit.anchor_invalid"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_component_tables_and_cells() {
|
||||
let cases: &[(&str, &str)] = &[
|
||||
(
|
||||
"| 行 | 槽 | 组件 |\n| --- | --- | --- |\n| 1 | nav | [导航](components/nav.mq.md#导航) |\n",
|
||||
"web.table.header",
|
||||
),
|
||||
(
|
||||
"| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | nav | 纯文本 | 220px |\n",
|
||||
"web.link.none",
|
||||
),
|
||||
(
|
||||
"| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | nav | [导航](components/nav.mq.md#导航) | 50% |\n",
|
||||
"web.layout.width",
|
||||
),
|
||||
(
|
||||
"| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | nav | [导航](components/nav.mq.md#导航) | auto |\n| 1 | nav | [导航](components/nav.mq.md#导航) | auto |\n",
|
||||
"web.layout.slot_duplicate",
|
||||
),
|
||||
(
|
||||
"| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 2 | nav | [导航](components/nav.mq.md#导航) | auto |\n",
|
||||
"web.layout.row_order",
|
||||
),
|
||||
];
|
||||
for (table, expected) in cases {
|
||||
let project = TempProject::new();
|
||||
project.write(
|
||||
"index.mq.md",
|
||||
&format!("# 页面\n\n## @knowledge 工作台\n\n### 组件\n\n{table}"),
|
||||
);
|
||||
project.write("components/nav.mq.md", NAV);
|
||||
project.write("components/leaf.mq.md", LEAF);
|
||||
let error = load(&project.config("index.mq.md", "工作台")).unwrap_err();
|
||||
assert_eq!(design_code(error), *expected, "table case: {table}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_scope_anchor_and_cycle_errors() {
|
||||
let outside = TempProject::new();
|
||||
outside.write(
|
||||
"index.mq.md",
|
||||
"# 页面\n\n## @knowledge 工作台\n\n### 组件\n\n| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | a | [外部](../../outside.mq.md#目标) | auto |\n",
|
||||
);
|
||||
outside.write(
|
||||
"outside.mq.md",
|
||||
"# 目标页面\n\n## @knowledge 目标\n\n### 内容\n\nx\n",
|
||||
);
|
||||
// Analysis reports an out-of-scope link without a usable candidate path, so
|
||||
// the deterministic rejection is the candidate diagnostic (never a guess).
|
||||
assert_eq!(
|
||||
design_code(load(&outside.config("index.mq.md", "工作台")).unwrap_err()),
|
||||
"web.link.candidate"
|
||||
);
|
||||
|
||||
let missing = basic_project();
|
||||
missing.write(
|
||||
"components/nav.mq.md",
|
||||
"# 导航组件\n\n## @knowledge 导航\n\n### 组件\n\n| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | leaf | [缺失](leaf.mq.md#不存在) | auto |\n",
|
||||
);
|
||||
assert_eq!(
|
||||
design_code(load(&missing.config("index.mq.md", "工作台")).unwrap_err()),
|
||||
"web.unit.anchor_missing"
|
||||
);
|
||||
|
||||
let cycle = TempProject::new();
|
||||
cycle.write(
|
||||
"index.mq.md",
|
||||
"# 页面\n\n## @knowledge 工作台\n\n### 组件\n\n| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | a | [甲](components/a.mq.md#甲) | auto |\n",
|
||||
);
|
||||
cycle.write(
|
||||
"components/a.mq.md",
|
||||
"# 甲页面\n\n## @knowledge 甲\n\n### 组件\n\n| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | b | [乙](b.mq.md#乙) | auto |\n",
|
||||
);
|
||||
cycle.write(
|
||||
"components/b.mq.md",
|
||||
"# 乙页面\n\n## @knowledge 乙\n\n### 组件\n\n| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | a | [甲](a.mq.md#甲) | auto |\n",
|
||||
);
|
||||
let cycle_error = load(&cycle.config("index.mq.md", "工作台")).unwrap_err();
|
||||
let cycle_code = match &cycle_error {
|
||||
Error::Design(items) => items[0].code,
|
||||
Error::Engine(items) => items[0].code,
|
||||
};
|
||||
assert_eq!(cycle_code, "web.link.cycle", "{cycle_error:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_engine_failures_and_limits() {
|
||||
let project = basic_project();
|
||||
let mut config = project.config("index.mq.md", "工作台");
|
||||
config.cli = PathBuf::from("/nonexistent/marqdo");
|
||||
assert_eq!(
|
||||
engine_code(load(&config).unwrap_err()),
|
||||
"web.engine.cli_missing"
|
||||
);
|
||||
|
||||
let mut limited = project.config("index.mq.md", "工作台");
|
||||
limited.max_modules = 1;
|
||||
assert_eq!(
|
||||
design_code(load(&limited).unwrap_err()),
|
||||
"web.limit.modules"
|
||||
);
|
||||
|
||||
let mut shallow = project.config("index.mq.md", "工作台");
|
||||
shallow.max_depth = 0;
|
||||
assert_eq!(design_code(load(&shallow).unwrap_err()), "web.limit.depth");
|
||||
|
||||
let mut outside_entry = project.config("index.mq.md", "工作台");
|
||||
outside_entry.root = project.path.join("components");
|
||||
assert_eq!(
|
||||
design_code(load(&outside_entry).unwrap_err()),
|
||||
"web.unit.entry_outside_root"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entry_must_be_mq_md_and_expose_analysis_schema() {
|
||||
let project = basic_project();
|
||||
let config = project.config("index.mq.md", "工作台");
|
||||
// A missing entry is an engine/input failure, not a design violation.
|
||||
let mut missing = config.clone();
|
||||
missing.entry = project.path.join("nope.mq.md");
|
||||
assert_eq!(engine_code(load(&missing).unwrap_err()), "web.engine.entry");
|
||||
}
|
||||
Reference in new issue
Block a user