Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2f18dede85 | ||
|
|
495d2e4bf7 | ||
|
|
9684e388ce |
No files matched your search
@@ -37,4 +37,4 @@ Web 领域**唯一设计文档解释实现**。本仓库交付独立 Rust librar
|
|||||||
- `src/document.rs`:精确 anchor 选 Knowledge H2、直接保留 H3、GFM `组件` 表 AST/表头/单元格/Link 选择。
|
- `src/document.rs`:精确 anchor 选 Knowledge H2、直接保留 H3、GFM `组件` 表 AST/表头/单元格/Link 选择。
|
||||||
- `src/lib.rs`:递归布局、实例、宽度/行/槽校验、包含环与深度/模块/字节上限、稳定诊断、源身份与确定性 handoff。
|
- `src/lib.rs`:递归布局、实例、宽度/行/槽校验、包含环与深度/模块/字节上限、稳定诊断、源身份与确定性 handoff。
|
||||||
- `tests/design_contract.rs`:8 个真实 CLI 契约测试(正例 + 负例);`scripts/ci.sh` 为显式验收入口。
|
- `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)。
|
- 未完成:WEB-03 完整 handoff/组件图/单组件切片、组件 CI 服务与 WEB-05;内容投影、并发一致性与主要安全负例已实现;证据见 [docs/evidence/WEB-01-design-core.md](docs/evidence/WEB-01-design-core.md)。
|
||||||
+1
-1
@@ -39,4 +39,4 @@ pub fn handoff(design: &Design) -> String;
|
|||||||
|
|
||||||
`load` 已实现:真实 CLI Analysis 3 摄入、精确 anchor 选 Knowledge H2、`组件` 表递归布局、宽度/行/槽校验、包含环与资源上限、稳定诊断与源身份;`handoff` 目前输出确定性的组件树与来源摘要。
|
`load` 已实现:真实 CLI Analysis 3 摄入、精确 anchor 选 Knowledge H2、`组件` 表递归布局、宽度/行/槽校验、包含环与资源上限、稳定诊断与源身份;`handoff` 目前输出确定性的组件树与来源摘要。
|
||||||
|
|
||||||
未导出/未实现:`输入`/`事件`/`依赖`/`验收` 合同模型、`Scenario`/`Interaction`、`DesignGraph` 的完整依赖图与 WEB-03 handoff。按 provisional 约定,这些可在 WEB-01 完成前破坏式调整;Preview 不得自行实现上述解释。
|
`InputDecl`/`EventDecl`/`Scenario`/`Interaction`/`Dependency`/`Acceptance` 已导出;`ContentBlock`/`ContentLink` 已导出(安全结构投影,raw HTML 为占位)。未导出/未实现:`DesignGraph` 的完整组合图与 WEB-03 的组件切片/漂移标识。按 provisional 约定,这些可在 WEB-01 完成前破坏式调整;Preview 不得自行实现上述解释。
|
||||||
@@ -30,11 +30,39 @@ MARQDO_BIN=<verified marqdo> scripts/ci.sh
|
|||||||
- 引擎失败与作者合同错误区分(`LoadError::Engine`/`Design`),宿主据此映射退出码 2/1;失败不产生部分模型。
|
- 引擎失败与作者合同错误区分(`LoadError::Engine`/`Design`),宿主据此映射退出码 2/1;失败不产生部分模型。
|
||||||
- 不使用 `../design` 路径依赖,不复制 Markdown/语言解析器;只消费 Analysis 公开字段。
|
- 不使用 `../design` 路径依赖,不复制 Markdown/语言解析器;只消费 Analysis 公开字段。
|
||||||
|
|
||||||
|
## 补充候选:保留合同表格(输入/事件/场景/交互/依赖/验收)
|
||||||
|
|
||||||
|
同一候选后续提交实现了 WEB-DESIGN §3.2/§5 的保留 H3 合同:
|
||||||
|
|
||||||
|
- `输入`(名称/类型/说明)、`事件`(名称/数据/说明):纯文本单元格、名称非空且组件内唯一;链接被拒绝。
|
||||||
|
- `场景`(状态/内容/初始):ASCII slug 状态、组件内唯一、恰好一个 initial;内容单元格必须且只能含一个 Link,指向 Knowledge 单元(拒绝 Exec/设计组件声明);只允许叶子组件;数量上限 32。
|
||||||
|
- `交互`(当前/事件/下一状态):状态必须存在、事件标签非空且同一当前状态唯一、每个状态从初始状态可达;多状态必须有交互;无场景不得有交互;转移上限 128。
|
||||||
|
- `依赖`(组件/原因):必须指向已加载设计组件、原因非空;跨组件设计依赖环确定性报错(报告协调需求,不宣称可并行)。
|
||||||
|
- `验收`:直接 H3 内容必须非空,作为交付文本保留,不自动解释为测试。
|
||||||
|
- 资源上限与合同建议对齐:文档 100 / 定义 200 / 实例 1000 / 深度 12 / 每行槽 12 / 场景 32 / 转移 128 / 单文件 1 MiB / 总输入 16 MiB;handoff 增加 inputs/events/scenarios/transitions/dependencies/acceptance。
|
||||||
|
- 测试增至 14 个真实 CLI 契约用例,覆盖上述正例与主要负例(重复 input/event、非法状态、非叶子场景、场景内容指向组件、不可达状态、缺交互、依赖未知/环、空验收、每行槽上限、单文件上限)。
|
||||||
|
|
||||||
|
## 补充候选 3:显式 --root 内的 outside_scope 链接
|
||||||
|
|
||||||
|
WEB-00 探测发现一个真实边界:CLI 的最近项目根由 entry 父目录决定,组件引用 `../shared/x.mq.md` 时 Analysis 会标 `outside_scope` 且不提供 `candidate_path`,即使目标在设计命令的显式 `--root` 内。Design 的处理(不调用私有 loader、不搜索文件):
|
||||||
|
|
||||||
|
- 仅当 reference `state == outside_scope` 且 URL 是不含 scheme、不以 `/` 开头的相对路径时,用公开 URL 的路径部分相对**来源模块目录**解析;
|
||||||
|
- 解析结果必须 canonicalize 到显式 `--root` 内,否则 `web.link.outside_root`;
|
||||||
|
- 精确 anchor 仍由目标模块 Analysis 的 anchors 验证;
|
||||||
|
- 该规则支撑合同 §2 的 `--root` 设计范围;未发现 CLI 私有字段需求,记录为 Design 解释规则(后续若 CLI Analysis 提供显式 root-relative candidate 可简化)。
|
||||||
|
|
||||||
|
## 补充候选 2:内容投影、并发一致性与安全边界
|
||||||
|
|
||||||
|
- **内容投影**:`ContentBlock`/`ContentLink` 只从 Analysis AST 的结构节点与源码 byte span 投影;raw HTML 一律成为 `[raw HTML as inert text]` 占位,绝不当活动 HTML;组件 `内容` 场景内容均带 block/link span,Preview 不需要自行解析 Markdown。
|
||||||
|
- **并发/陈旧一致性**:一次 `load` 完成所有模块构建后,对参与的每个模块重新 `check --emit` 并比较 `source_digest`;中途变化返回 Engine `web.engine.stale`(退出码 2),不产生部分成功模型。
|
||||||
|
- **安全负例**:symlink 指向 root 外 → `web.link.outside_root`;绝对路径 `/tmp/...` 链接被拒(candidate/absolute);`%2e%2e` 编码穿越不会解码为父目录,按不可解析 candidate 拒绝;raw HTML 负例以占位处理。
|
||||||
|
- 测试增至 18 个真实 CLI 契约用例(新增内容投影、raw HTML 占位、symlink/绝对/双重编码、伪造 CLI 输出导致过期检测)。
|
||||||
|
|
||||||
## 未实现 / 未验证(不隐藏)
|
## 未实现 / 未验证(不隐藏)
|
||||||
|
|
||||||
- 保留 H3 的 `输入`/`事件`/`依赖`/`验收` 合同模型、`场景`/`交互`(有限状态)解释与校验尚未实现;
|
- 场景内容目标的 Exec 子树负例(非组件声明)尚未单独覆盖;资源/输出/HTML 大小与完整 CSP 由 WEB-02 Preview 承担;
|
||||||
- handoff 当前为确定性组件树/来源摘要,WEB-03 的组件图、单组件切片与漂移标识未完成;
|
- handoff 当前为确定性组件树/来源摘要,WEB-03 的组件图、单组件切片与漂移标识未完成;
|
||||||
- 并发编辑/陈旧 Analysis 的二次一致性复核、资源上限的完整矩阵、symlink/双重编码等安全负例仅覆盖部分;
|
- 并发编辑一致性已做二次摘要复核;资源上限覆盖主要项,完整矩阵随 WEB-02 输出预算补齐;
|
||||||
- 未配置组件 CI 服务(`scripts/ci.sh` 为显式入口,需 CI 传入固定 CLI 制品);领域/根接入(WEB-05)未开始。
|
- 未配置组件 CI 服务(`scripts/ci.sh` 为显式入口,需 CI 传入固定 CLI 制品);领域/根接入(WEB-05)未开始。
|
||||||
|
|
||||||
因此 WEB-01 不关闭;后续在同一仓库按上述范围继续,不把本候选当作完整验收。
|
因此 WEB-01 不关闭;后续在同一仓库按上述范围继续,不把本候选当作完整验收。
|
||||||
+155
-8
@@ -84,6 +84,106 @@ fn text_at(module: &Module, span: (usize, usize)) -> String {
|
|||||||
.to_string()
|
.to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct ContentBlock {
|
||||||
|
pub kind: String,
|
||||||
|
pub text: String,
|
||||||
|
pub span: (usize, usize),
|
||||||
|
pub links: Vec<ContentLink>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct ContentLink {
|
||||||
|
pub text: String,
|
||||||
|
pub url: String,
|
||||||
|
pub span: (usize, usize),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Safe projection of the analysis AST inside one source span.
|
||||||
|
///
|
||||||
|
/// Only structural kinds are exposed; raw HTML becomes an inert placeholder and
|
||||||
|
/// link targets remain data for the Preview's protocol allowlist. No Markdown is
|
||||||
|
/// re-parsed: block text is read from the analysis-provided source by span.
|
||||||
|
pub fn content_blocks(module: &Module, span: (usize, usize)) -> Vec<ContentBlock> {
|
||||||
|
let mut blocks = Vec::new();
|
||||||
|
let Some(children) = module.document["children"].as_array() else {
|
||||||
|
return blocks;
|
||||||
|
};
|
||||||
|
for child in children {
|
||||||
|
let Some((start, end)) = span_from(&child["span"]) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if start < span.0 || end > span.1 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let kind = match child["kind"].as_str().unwrap_or("") {
|
||||||
|
"paragraph" => "paragraph",
|
||||||
|
"list" => "list",
|
||||||
|
"table" => "table",
|
||||||
|
"code_block" => "code",
|
||||||
|
"html" | "html_block" => "placeholder",
|
||||||
|
"heading" => "heading",
|
||||||
|
"block_quote" => "quote",
|
||||||
|
other => other,
|
||||||
|
};
|
||||||
|
let mut links = Vec::new();
|
||||||
|
walk_links(child, &mut links);
|
||||||
|
let links = links
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|link| {
|
||||||
|
let span = span_from(&link["span"])?;
|
||||||
|
Some(ContentLink {
|
||||||
|
text: text_at(module, span),
|
||||||
|
url: link["url"].as_str()?.to_string(),
|
||||||
|
span,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let mut text = text_at(module, (start, end));
|
||||||
|
if kind == "placeholder" {
|
||||||
|
text = format!("[raw HTML as inert text] {text}");
|
||||||
|
}
|
||||||
|
blocks.push(ContentBlock {
|
||||||
|
kind: kind.to_string(),
|
||||||
|
text,
|
||||||
|
span: (start, end),
|
||||||
|
links,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
blocks
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolve one exact anchor to its unit without imposing the design-component kind.
|
||||||
|
pub fn any_unit_by_anchor(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;
|
||||||
|
}
|
||||||
|
if let Some(unit) = entry["unit_id"]
|
||||||
|
.as_str()
|
||||||
|
.and_then(|unit_id| units(module).into_iter().find(|unit| unit.id == unit_id))
|
||||||
|
{
|
||||||
|
matches.push(unit);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
match matches.len() {
|
||||||
|
0 => Err(Diagnostic::error(
|
||||||
|
"web.unit.anchor_missing",
|
||||||
|
format!("no unit has the exact anchor {anchor:?}"),
|
||||||
|
)
|
||||||
|
.with_anchor(anchor)
|
||||||
|
.at(module.relative.clone(), None)),
|
||||||
|
1 => Ok(matches.remove(0)),
|
||||||
|
_ => Err(Diagnostic::error(
|
||||||
|
"web.unit.anchor_ambiguous",
|
||||||
|
format!("anchor {anchor:?} resolves to more than one unit"),
|
||||||
|
)
|
||||||
|
.with_anchor(anchor)
|
||||||
|
.at(module.relative.clone(), None)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Select the Knowledge H2 by its exact anchor, never by label/path guessing.
|
/// Select the Knowledge H2 by its exact anchor, never by label/path guessing.
|
||||||
pub fn knowledge_h2(module: &Module, anchor: &str) -> Result<Unit, Diagnostic> {
|
pub fn knowledge_h2(module: &Module, anchor: &str) -> Result<Unit, Diagnostic> {
|
||||||
let mut matches = Vec::new();
|
let mut matches = Vec::new();
|
||||||
@@ -163,6 +263,48 @@ fn walk_links<'a>(node: &'a Value, out: &mut Vec<&'a Value>) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Select the single table with one exact header inside a direct retained H3.
|
||||||
|
/// `Ok(None)` means the section is absent.
|
||||||
|
pub fn section_table(
|
||||||
|
module: &Module,
|
||||||
|
h2: &Unit,
|
||||||
|
name: &str,
|
||||||
|
header: &[&str],
|
||||||
|
) -> Result<Option<(Unit, Table)>, Diagnostic> {
|
||||||
|
let Some(section) = direct_sections(module, h2)
|
||||||
|
.into_iter()
|
||||||
|
.find(|section| section.name == name)
|
||||||
|
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",
|
||||||
|
format!("`{name}` section has no GFM table"),
|
||||||
|
)
|
||||||
|
.at(module.relative.clone(), Some(section.span))),
|
||||||
|
1 => {
|
||||||
|
let table = parse_table_with_header(module, inside.remove(0), header, name)?;
|
||||||
|
Ok(Some((section, table)))
|
||||||
|
}
|
||||||
|
_ => Err(Diagnostic::error(
|
||||||
|
"web.table.multiple",
|
||||||
|
format!("`{name}` section must contain exactly one GFM table"),
|
||||||
|
)
|
||||||
|
.at(module.relative.clone(), Some(section.span))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Select the single retained `组件` table inside its direct H3 section.
|
/// Select the single retained `组件` table inside its direct H3 section.
|
||||||
/// Returns `Ok(None)` when the component declares no component table.
|
/// Returns `Ok(None)` when the component declares no component table.
|
||||||
pub fn components_table(module: &Module, h2: &Unit) -> Result<Option<(Unit, Table)>, Diagnostic> {
|
pub fn components_table(module: &Module, h2: &Unit) -> Result<Option<(Unit, Table)>, Diagnostic> {
|
||||||
@@ -190,7 +332,7 @@ pub fn components_table(module: &Module, h2: &Unit) -> Result<Option<(Unit, Tabl
|
|||||||
),
|
),
|
||||||
1 => Ok(Some((
|
1 => Ok(Some((
|
||||||
section.clone(),
|
section.clone(),
|
||||||
parse_table(module, inside.remove(0))?,
|
parse_table_with_header(module, inside.remove(0), &COMPONENTS_HEADER, COMPONENTS)?,
|
||||||
))),
|
))),
|
||||||
_ => Err(Diagnostic::error(
|
_ => Err(Diagnostic::error(
|
||||||
"web.table.multiple",
|
"web.table.multiple",
|
||||||
@@ -200,7 +342,12 @@ pub fn components_table(module: &Module, h2: &Unit) -> Result<Option<(Unit, Tabl
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn parse_table(module: &Module, table: &Value) -> Result<Table, Diagnostic> {
|
fn parse_table_with_header(
|
||||||
|
module: &Module,
|
||||||
|
table: &Value,
|
||||||
|
expected_header: &[&str],
|
||||||
|
name: &str,
|
||||||
|
) -> Result<Table, Diagnostic> {
|
||||||
let span = span_from(&table["span"]).ok_or_else(|| {
|
let span = span_from(&table["span"]).ok_or_else(|| {
|
||||||
Diagnostic::error("web.table.span", "table has no source span")
|
Diagnostic::error("web.table.span", "table has no source span")
|
||||||
.at(module.relative.clone(), None)
|
.at(module.relative.clone(), None)
|
||||||
@@ -233,12 +380,12 @@ fn parse_table(module: &Module, table: &Value) -> Result<Table, Diagnostic> {
|
|||||||
.collect()
|
.collect()
|
||||||
})
|
})
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
if headers != COMPONENTS_HEADER {
|
if headers != expected_header {
|
||||||
return Err(Diagnostic::error(
|
return Err(Diagnostic::error(
|
||||||
"web.table.header",
|
"web.table.header",
|
||||||
format!(
|
format!(
|
||||||
"`组件` header must be exactly {:?}, found {:?}",
|
"`{name}` header must be exactly {:?}, found {:?}",
|
||||||
COMPONENTS_HEADER, headers
|
expected_header, headers
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
.at(module.relative.clone(), Some(span)));
|
.at(module.relative.clone(), Some(span)));
|
||||||
@@ -246,12 +393,12 @@ fn parse_table(module: &Module, table: &Value) -> Result<Table, Diagnostic> {
|
|||||||
let mut rows = Vec::new();
|
let mut rows = Vec::new();
|
||||||
for row in ast_rows.iter().skip(1) {
|
for row in ast_rows.iter().skip(1) {
|
||||||
let raw_cells = row["children"].as_array().cloned().unwrap_or_default();
|
let raw_cells = row["children"].as_array().cloned().unwrap_or_default();
|
||||||
if raw_cells.len() != COMPONENTS_HEADER.len() {
|
if raw_cells.len() != expected_header.len() {
|
||||||
return Err(Diagnostic::error(
|
return Err(Diagnostic::error(
|
||||||
"web.table.columns",
|
"web.table.columns",
|
||||||
format!(
|
format!(
|
||||||
"component row must have {} cells, found {}",
|
"`{name}` row must have {} cells, found {}",
|
||||||
COMPONENTS_HEADER.len(),
|
expected_header.len(),
|
||||||
raw_cells.len()
|
raw_cells.len()
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|||||||
+725
-9
@@ -22,6 +22,7 @@ use diagnostic::{Diagnostic, LoadError, Span};
|
|||||||
use document::{Cell, Link, Unit};
|
use document::{Cell, Link, Unit};
|
||||||
|
|
||||||
pub use diagnostic::{LoadError as Error, Severity};
|
pub use diagnostic::{LoadError as Error, Severity};
|
||||||
|
pub use document::{ContentBlock, ContentLink};
|
||||||
|
|
||||||
/// Explicit inputs; there is no implicit CLI or project discovery.
|
/// Explicit inputs; there is no implicit CLI or project discovery.
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
@@ -35,6 +36,11 @@ pub struct LoadConfig {
|
|||||||
pub root: PathBuf,
|
pub root: PathBuf,
|
||||||
pub max_depth: usize,
|
pub max_depth: usize,
|
||||||
pub max_modules: usize,
|
pub max_modules: usize,
|
||||||
|
pub max_definitions: usize,
|
||||||
|
pub max_instances: usize,
|
||||||
|
pub max_scenes: usize,
|
||||||
|
pub max_transitions: usize,
|
||||||
|
pub max_file_bytes: usize,
|
||||||
pub max_source_bytes: usize,
|
pub max_source_bytes: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -51,8 +57,13 @@ impl LoadConfig {
|
|||||||
unit: unit.into(),
|
unit: unit.into(),
|
||||||
root: root.into(),
|
root: root.into(),
|
||||||
max_depth: 12,
|
max_depth: 12,
|
||||||
max_modules: 64,
|
max_modules: 100,
|
||||||
max_source_bytes: 8 * 1024 * 1024,
|
max_definitions: 200,
|
||||||
|
max_instances: 1000,
|
||||||
|
max_scenes: 32,
|
||||||
|
max_transitions: 128,
|
||||||
|
max_file_bytes: 1024 * 1024,
|
||||||
|
max_source_bytes: 16 * 1024 * 1024,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -95,11 +106,67 @@ pub struct ChildSlot {
|
|||||||
pub span: Span,
|
pub span: Span,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct InputDecl {
|
||||||
|
pub name: String,
|
||||||
|
pub entry_type: String,
|
||||||
|
pub description: String,
|
||||||
|
pub span: Span,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct EventDecl {
|
||||||
|
pub name: String,
|
||||||
|
pub data: String,
|
||||||
|
pub description: String,
|
||||||
|
pub span: Span,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct Scenario {
|
||||||
|
pub state: String,
|
||||||
|
/// Content unit (Knowledge H2/H3), never a design-component declaration.
|
||||||
|
pub content: SourceRef,
|
||||||
|
/// Safe structural projection of the content unit.
|
||||||
|
pub content_blocks: Vec<ContentBlock>,
|
||||||
|
pub initial: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct Interaction {
|
||||||
|
pub current: String,
|
||||||
|
pub event: String,
|
||||||
|
pub next: String,
|
||||||
|
pub span: Span,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct Dependency {
|
||||||
|
/// Component definition key (`root-relative path#anchor`).
|
||||||
|
pub target: String,
|
||||||
|
pub reason: String,
|
||||||
|
pub span: Span,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct Acceptance {
|
||||||
|
pub text: String,
|
||||||
|
pub span: Span,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct ComponentDef {
|
pub struct ComponentDef {
|
||||||
pub key: String,
|
pub key: String,
|
||||||
pub source: SourceRef,
|
pub source: SourceRef,
|
||||||
pub slots: Vec<ChildSlot>,
|
pub slots: Vec<ChildSlot>,
|
||||||
|
/// Safe structural projection of the direct `内容` section, if present.
|
||||||
|
pub content: Vec<ContentBlock>,
|
||||||
|
pub inputs: Vec<InputDecl>,
|
||||||
|
pub events: Vec<EventDecl>,
|
||||||
|
pub scenarios: Vec<Scenario>,
|
||||||
|
pub interactions: Vec<Interaction>,
|
||||||
|
pub dependencies: Vec<Dependency>,
|
||||||
|
pub acceptance: Option<Acceptance>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
@@ -237,6 +304,72 @@ fn find_reference<'a>(module: &'a Module, link: &Link) -> Result<&'a Value, Load
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn plain_text(
|
||||||
|
cells: &[Cell],
|
||||||
|
module: &Module,
|
||||||
|
code: &'static str,
|
||||||
|
) -> Result<Vec<String>, LoadError> {
|
||||||
|
let mut values = Vec::new();
|
||||||
|
for cell in cells {
|
||||||
|
if !cell.links.is_empty() {
|
||||||
|
return Err(LoadError::Design(vec![Diagnostic::error(
|
||||||
|
code,
|
||||||
|
"this contract table accepts plain text only, not links",
|
||||||
|
)
|
||||||
|
.at(module.relative.clone(), Some(cell.span))]));
|
||||||
|
}
|
||||||
|
values.push(cell.text.trim().to_string());
|
||||||
|
}
|
||||||
|
Ok(values)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn normalized_key(module: &Module, anchor: &str) -> String {
|
||||||
|
format!("{}#{}", module.relative, anchor)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_initial(value: &str) -> Result<bool, &'static str> {
|
||||||
|
match value.trim() {
|
||||||
|
"true" => Ok(true),
|
||||||
|
"false" => Ok(false),
|
||||||
|
_ => Err("初始 must be exactly `true` or `false`"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn design_candidate(
|
||||||
|
reference: &serde_json::Value,
|
||||||
|
link: &Link,
|
||||||
|
module: &Module,
|
||||||
|
) -> Result<String, LoadError> {
|
||||||
|
if let Some(candidate) = reference["candidate_path"].as_str() {
|
||||||
|
if !candidate.is_empty() {
|
||||||
|
return Ok(candidate.to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// A link inside the explicit design --root can lie outside the CLI's nearest
|
||||||
|
// project root (for example a component referencing `../shared/x.mq.md`).
|
||||||
|
// Analysis then reports `outside_scope` without candidate_path; the public
|
||||||
|
// reference URL plus the explicit design root still determine the physical
|
||||||
|
// target, so derive it and require the root check afterwards.
|
||||||
|
if reference["state"].as_str() == Some("outside_scope") {
|
||||||
|
let raw = link.url.split('#').next().unwrap_or("");
|
||||||
|
if !raw.is_empty() && !raw.starts_with('/') && !raw.contains("://") && !raw.contains('\\') {
|
||||||
|
return Ok(raw.to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(LoadError::Design(vec![Diagnostic::error(
|
||||||
|
"web.link.candidate",
|
||||||
|
"design link must expose a project-relative candidate path",
|
||||||
|
)
|
||||||
|
.at(module.relative.clone(), Some(link.span))]))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn json_span(span: (usize, usize)) -> Span {
|
||||||
|
Span {
|
||||||
|
start: span.0,
|
||||||
|
end: span.1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
struct Loader {
|
struct Loader {
|
||||||
config: LoadConfig,
|
config: LoadConfig,
|
||||||
root: PathBuf,
|
root: PathBuf,
|
||||||
@@ -264,6 +397,15 @@ impl Loader {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
let module = analysis::analyze(&self.config.cli, &canonical, &self.root)?;
|
let module = analysis::analyze(&self.config.cli, &canonical, &self.root)?;
|
||||||
|
if module.source.len() > self.config.max_file_bytes {
|
||||||
|
return Err(design_error(
|
||||||
|
"web.limit.source",
|
||||||
|
format!(
|
||||||
|
"source file {} exceeds the {} byte limit",
|
||||||
|
module.relative, self.config.max_file_bytes
|
||||||
|
),
|
||||||
|
));
|
||||||
|
}
|
||||||
self.source_bytes += module.source.len();
|
self.source_bytes += module.source.len();
|
||||||
if self.source_bytes > self.config.max_source_bytes {
|
if self.source_bytes > self.config.max_source_bytes {
|
||||||
return Err(design_error(
|
return Err(design_error(
|
||||||
@@ -281,18 +423,15 @@ impl Loader {
|
|||||||
link: &Link,
|
link: &Link,
|
||||||
) -> Result<(Module, Unit, String), LoadError> {
|
) -> Result<(Module, Unit, String), LoadError> {
|
||||||
let reference = find_reference(module, link)?;
|
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();
|
let fragment = reference["fragment"].as_str().unwrap_or("").to_string();
|
||||||
if candidate.is_empty() || fragment.is_empty() {
|
if fragment.is_empty() {
|
||||||
return Err(LoadError::Design(vec![Diagnostic::error(
|
return Err(LoadError::Design(vec![Diagnostic::error(
|
||||||
"web.link.candidate",
|
"web.link.candidate",
|
||||||
"design link must expose a candidate_path and a fragment",
|
"design link must expose an exact anchor fragment",
|
||||||
)
|
)
|
||||||
.at(module.relative.clone(), Some(link.span))]));
|
.at(module.relative.clone(), Some(link.span))]));
|
||||||
}
|
}
|
||||||
|
let candidate = design_candidate(reference, link, module)?;
|
||||||
if Path::new(&candidate).is_absolute() || link.url.contains("://") {
|
if Path::new(&candidate).is_absolute() || link.url.contains("://") {
|
||||||
return Err(LoadError::Design(vec![Diagnostic::error(
|
return Err(LoadError::Design(vec![Diagnostic::error(
|
||||||
"web.link.absolute",
|
"web.link.absolute",
|
||||||
@@ -331,6 +470,121 @@ impl Loader {
|
|||||||
Ok((target_module, unit, fragment))
|
Ok((target_module, unit, fragment))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn resolve_content_unit(
|
||||||
|
&mut self,
|
||||||
|
module: &Module,
|
||||||
|
link: &Link,
|
||||||
|
) -> Result<(Module, Unit), LoadError> {
|
||||||
|
let reference = find_reference(module, link)?;
|
||||||
|
let fragment = reference["fragment"].as_str().unwrap_or("").to_string();
|
||||||
|
if fragment.is_empty() {
|
||||||
|
return Err(LoadError::Design(vec![Diagnostic::error(
|
||||||
|
"web.scene.content",
|
||||||
|
"场景 content link must name an exact anchor",
|
||||||
|
)
|
||||||
|
.at(module.relative.clone(), Some(link.span))]));
|
||||||
|
}
|
||||||
|
let candidate = match design_candidate(reference, link, module) {
|
||||||
|
Ok(candidate) => candidate,
|
||||||
|
Err(_) if reference["fragment"].as_str().is_some() => String::new(),
|
||||||
|
Err(error) => return Err(error),
|
||||||
|
};
|
||||||
|
let target_module = if candidate.is_empty() {
|
||||||
|
module.clone()
|
||||||
|
} else {
|
||||||
|
if Path::new(&candidate).is_absolute() || link.url.contains("://") {
|
||||||
|
return Err(LoadError::Design(vec![Diagnostic::error(
|
||||||
|
"web.scene.content",
|
||||||
|
"场景 content target must be project-relative",
|
||||||
|
)
|
||||||
|
.at(module.relative.clone(), Some(link.span))]));
|
||||||
|
}
|
||||||
|
let target = module.path.parent().unwrap_or(&self.root).join(&candidate);
|
||||||
|
let canonical = target.canonicalize().map_err(|error| {
|
||||||
|
LoadError::Design(vec![Diagnostic::error(
|
||||||
|
"web.scene.content",
|
||||||
|
format!("cannot resolve 场景 content target {candidate:?}: {error}"),
|
||||||
|
)
|
||||||
|
.at(module.relative.clone(), Some(link.span))])
|
||||||
|
})?;
|
||||||
|
if !canonical.starts_with(&self.root) {
|
||||||
|
return Err(LoadError::Design(vec![Diagnostic::error(
|
||||||
|
"web.scene.content",
|
||||||
|
"场景 content target escapes the explicit root",
|
||||||
|
)
|
||||||
|
.at(module.relative.clone(), Some(link.span))]));
|
||||||
|
}
|
||||||
|
self.analyze(&canonical)?
|
||||||
|
};
|
||||||
|
let scene_unit =
|
||||||
|
document::any_unit_by_anchor(&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)])
|
||||||
|
})?;
|
||||||
|
if scene_unit.mode != "knowledge" || matches!(scene_unit.kind.as_str(), "exec" | "function")
|
||||||
|
{
|
||||||
|
return Err(LoadError::Design(vec![Diagnostic::error(
|
||||||
|
"web.scene.content",
|
||||||
|
format!(
|
||||||
|
"场景 content must be a Knowledge unit (kind={} mode={})",
|
||||||
|
scene_unit.kind, scene_unit.mode
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.with_anchor(fragment)
|
||||||
|
.at(module.relative.clone(), Some(link.span))]));
|
||||||
|
}
|
||||||
|
Ok((target_module, scene_unit))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resolve_dependency_component(
|
||||||
|
&mut self,
|
||||||
|
module: &Module,
|
||||||
|
link: &Link,
|
||||||
|
) -> Result<(Module, Unit), 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.dependency.target",
|
||||||
|
"依赖 component cell must link to a design component anchor",
|
||||||
|
)
|
||||||
|
.at(module.relative.clone(), Some(link.span))]));
|
||||||
|
}
|
||||||
|
if Path::new(&candidate).is_absolute() || link.url.contains("://") {
|
||||||
|
return Err(LoadError::Design(vec![Diagnostic::error(
|
||||||
|
"web.dependency.target",
|
||||||
|
"依赖 target must be project-relative",
|
||||||
|
)
|
||||||
|
.at(module.relative.clone(), Some(link.span))]));
|
||||||
|
}
|
||||||
|
let target = module.path.parent().unwrap_or(&self.root).join(&candidate);
|
||||||
|
let canonical = target.canonicalize().map_err(|error| {
|
||||||
|
LoadError::Design(vec![Diagnostic::error(
|
||||||
|
"web.dependency.target",
|
||||||
|
format!("cannot resolve 依赖 target {candidate:?}: {error}"),
|
||||||
|
)
|
||||||
|
.at(module.relative.clone(), Some(link.span))])
|
||||||
|
})?;
|
||||||
|
if !canonical.starts_with(&self.root) {
|
||||||
|
return Err(LoadError::Design(vec![Diagnostic::error(
|
||||||
|
"web.dependency.target",
|
||||||
|
"依赖 target escapes the explicit root",
|
||||||
|
)
|
||||||
|
.at(module.relative.clone(), Some(link.span))]));
|
||||||
|
}
|
||||||
|
let target_module = self.analyze(&canonical)?;
|
||||||
|
let target_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, target_unit))
|
||||||
|
}
|
||||||
|
|
||||||
fn load_definition(
|
fn load_definition(
|
||||||
&mut self,
|
&mut self,
|
||||||
module: &Module,
|
module: &Module,
|
||||||
@@ -356,7 +610,7 @@ impl Loader {
|
|||||||
}
|
}
|
||||||
self.stack.push(key.clone());
|
self.stack.push(key.clone());
|
||||||
let table = document::components_table(module, unit)?;
|
let table = document::components_table(module, unit)?;
|
||||||
let mut slots = Vec::new();
|
let mut slots: Vec<ChildSlot> = Vec::new();
|
||||||
if let Some((section, table)) = table {
|
if let Some((section, table)) = table {
|
||||||
let mut previous_row = 0u32;
|
let mut previous_row = 0u32;
|
||||||
let mut seen_slots = BTreeSet::new();
|
let mut seen_slots = BTreeSet::new();
|
||||||
@@ -411,6 +665,13 @@ impl Loader {
|
|||||||
self.resolve_target(module, link)?;
|
self.resolve_target(module, link)?;
|
||||||
let target_key =
|
let target_key =
|
||||||
self.load_definition(&target_module, &target_unit, &target_anchor, depth + 1)?;
|
self.load_definition(&target_module, &target_unit, &target_anchor, depth + 1)?;
|
||||||
|
let row_slots = slots.iter().filter(|existing| existing.row == row).count() + 1;
|
||||||
|
if row_slots > 12 {
|
||||||
|
return Err(design_error(
|
||||||
|
"web.layout.slots_per_row",
|
||||||
|
format!("row {row} exceeds the 12 slots per row limit"),
|
||||||
|
));
|
||||||
|
}
|
||||||
slots.push(ChildSlot {
|
slots.push(ChildSlot {
|
||||||
slot,
|
slot,
|
||||||
row,
|
row,
|
||||||
@@ -424,17 +685,425 @@ impl Loader {
|
|||||||
}
|
}
|
||||||
let _ = section;
|
let _ = section;
|
||||||
}
|
}
|
||||||
|
let mut inputs = Vec::new();
|
||||||
|
if let Some((_, table)) =
|
||||||
|
document::section_table(module, unit, "输入", &["名称", "类型", "说明"])?
|
||||||
|
{
|
||||||
|
let mut seen = BTreeSet::new();
|
||||||
|
for cells in &table.rows {
|
||||||
|
let values = plain_text(cells, module, "web.input.text")?;
|
||||||
|
if values[0].is_empty() {
|
||||||
|
return Err(LoadError::Design(vec![Diagnostic::error(
|
||||||
|
"web.input.name",
|
||||||
|
"输入 name must not be empty",
|
||||||
|
)
|
||||||
|
.at(module.relative.clone(), Some(cells[0].span))]));
|
||||||
|
}
|
||||||
|
if !seen.insert(values[0].clone()) {
|
||||||
|
return Err(LoadError::Design(vec![Diagnostic::error(
|
||||||
|
"web.input.name",
|
||||||
|
format!("输入 name {:?} is declared twice", values[0]),
|
||||||
|
)
|
||||||
|
.at(module.relative.clone(), Some(cells[0].span))]));
|
||||||
|
}
|
||||||
|
inputs.push(InputDecl {
|
||||||
|
name: values[0].clone(),
|
||||||
|
entry_type: values[1].clone(),
|
||||||
|
description: values[2].clone(),
|
||||||
|
span: json_span(cells[0].span),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut events = Vec::new();
|
||||||
|
if let Some((_, table)) =
|
||||||
|
document::section_table(module, unit, "事件", &["名称", "数据", "说明"])?
|
||||||
|
{
|
||||||
|
let mut seen = BTreeSet::new();
|
||||||
|
for cells in &table.rows {
|
||||||
|
let values = plain_text(cells, module, "web.event.text")?;
|
||||||
|
if values[0].is_empty() {
|
||||||
|
return Err(LoadError::Design(vec![Diagnostic::error(
|
||||||
|
"web.event.name",
|
||||||
|
"事件 name must not be empty",
|
||||||
|
)
|
||||||
|
.at(module.relative.clone(), Some(cells[0].span))]));
|
||||||
|
}
|
||||||
|
if !seen.insert(values[0].clone()) {
|
||||||
|
return Err(LoadError::Design(vec![Diagnostic::error(
|
||||||
|
"web.event.name",
|
||||||
|
format!("事件 name {:?} is declared twice", values[0]),
|
||||||
|
)
|
||||||
|
.at(module.relative.clone(), Some(cells[0].span))]));
|
||||||
|
}
|
||||||
|
events.push(EventDecl {
|
||||||
|
name: values[0].clone(),
|
||||||
|
data: values[1].clone(),
|
||||||
|
description: values[2].clone(),
|
||||||
|
span: json_span(cells[0].span),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut scenarios = Vec::new();
|
||||||
|
if let Some((_, table)) =
|
||||||
|
document::section_table(module, unit, "场景", &["状态", "内容", "初始"])?
|
||||||
|
{
|
||||||
|
if !slots.is_empty() {
|
||||||
|
return Err(design_error(
|
||||||
|
"web.scene.not_leaf",
|
||||||
|
"`场景` is only allowed on a leaf component (no child slots)",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if table.rows.len() > self.config.max_scenes {
|
||||||
|
return Err(design_error(
|
||||||
|
"web.limit.scenes",
|
||||||
|
format!("scene limit {} exceeded", self.config.max_scenes),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let mut seen = BTreeSet::new();
|
||||||
|
let mut initial = 0;
|
||||||
|
for cells in &table.rows {
|
||||||
|
let state = cells[0].text.trim().to_string();
|
||||||
|
if !valid_state(&state) {
|
||||||
|
return Err(LoadError::Design(vec![Diagnostic::error(
|
||||||
|
"web.scene.state",
|
||||||
|
format!("state {state:?} must be a lowercase ASCII slug"),
|
||||||
|
)
|
||||||
|
.at(module.relative.clone(), Some(cells[0].span))]));
|
||||||
|
}
|
||||||
|
if !seen.insert(state.clone()) {
|
||||||
|
return Err(LoadError::Design(vec![Diagnostic::error(
|
||||||
|
"web.scene.state_duplicate",
|
||||||
|
format!("state {state:?} is declared twice"),
|
||||||
|
)
|
||||||
|
.at(module.relative.clone(), Some(cells[0].span))]));
|
||||||
|
}
|
||||||
|
let link = single_link(&cells[1], &module.relative, cells[1].span)?;
|
||||||
|
let (target_module, target_unit) = self.resolve_content_unit(module, link)?;
|
||||||
|
if cells[1].text.trim() != link.text.trim() {
|
||||||
|
return Err(LoadError::Design(vec![Diagnostic::error(
|
||||||
|
"web.scene.content",
|
||||||
|
"场景 content cell must contain only the content Link",
|
||||||
|
)
|
||||||
|
.at(module.relative.clone(), Some(cells[1].span))]));
|
||||||
|
}
|
||||||
|
let is_initial = parse_initial(cells[2].text.trim()).map_err(|message| {
|
||||||
|
LoadError::Design(vec![Diagnostic::error("web.scene.initial", message)
|
||||||
|
.at(module.relative.clone(), Some(cells[2].span))])
|
||||||
|
})?;
|
||||||
|
if is_initial {
|
||||||
|
initial += 1;
|
||||||
|
}
|
||||||
|
let content = source_ref(&target_module, &target_unit, target_unit.anchor_text());
|
||||||
|
let content_start = target_unit
|
||||||
|
.heading_span
|
||||||
|
.map(|(_, end)| end)
|
||||||
|
.unwrap_or(target_unit.span.0);
|
||||||
|
let content_blocks =
|
||||||
|
document::content_blocks(&target_module, (content_start, target_unit.span.1));
|
||||||
|
scenarios.push(Scenario {
|
||||||
|
state,
|
||||||
|
content,
|
||||||
|
content_blocks,
|
||||||
|
initial: is_initial,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if initial != 1 {
|
||||||
|
return Err(design_error(
|
||||||
|
"web.scene.initial",
|
||||||
|
format!("exactly one scene must be initial, found {initial}"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut interactions = Vec::new();
|
||||||
|
if let Some((_, table)) =
|
||||||
|
document::section_table(module, unit, "交互", &["当前", "事件", "下一状态"])?
|
||||||
|
{
|
||||||
|
if scenarios.is_empty() {
|
||||||
|
return Err(design_error(
|
||||||
|
"web.interaction.without_scene",
|
||||||
|
"`交互` requires a `场景` table",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if table.rows.len() > self.config.max_transitions {
|
||||||
|
return Err(design_error(
|
||||||
|
"web.limit.transitions",
|
||||||
|
format!("transition limit {} exceeded", self.config.max_transitions),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let states: BTreeSet<&str> = scenarios.iter().map(|item| item.state.as_str()).collect();
|
||||||
|
let initial_state = scenarios
|
||||||
|
.iter()
|
||||||
|
.find(|item| item.initial)
|
||||||
|
.map(|item| item.state.clone())
|
||||||
|
.unwrap_or_default();
|
||||||
|
let mut seen = BTreeSet::new();
|
||||||
|
for cells in &table.rows {
|
||||||
|
let values = plain_text(cells, module, "web.interaction.text")?;
|
||||||
|
let (current, event, next) =
|
||||||
|
(values[0].clone(), values[1].clone(), values[2].clone());
|
||||||
|
if !states.contains(current.as_str()) || !states.contains(next.as_str()) {
|
||||||
|
return Err(LoadError::Design(vec![Diagnostic::error(
|
||||||
|
"web.interaction.state",
|
||||||
|
format!(
|
||||||
|
"transition {current:?} -> {next:?} references an undeclared state"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.at(module.relative.clone(), Some(cells[0].span))]));
|
||||||
|
}
|
||||||
|
if event.is_empty() {
|
||||||
|
return Err(LoadError::Design(vec![Diagnostic::error(
|
||||||
|
"web.interaction.event",
|
||||||
|
"transition event label must not be empty",
|
||||||
|
)
|
||||||
|
.at(module.relative.clone(), Some(cells[1].span))]));
|
||||||
|
}
|
||||||
|
if !seen.insert((current.clone(), event.clone())) {
|
||||||
|
return Err(LoadError::Design(vec![Diagnostic::error(
|
||||||
|
"web.interaction.event_duplicate",
|
||||||
|
format!("event {event:?} is declared twice for state {current:?}"),
|
||||||
|
)
|
||||||
|
.at(module.relative.clone(), Some(cells[1].span))]));
|
||||||
|
}
|
||||||
|
interactions.push(Interaction {
|
||||||
|
current,
|
||||||
|
event,
|
||||||
|
next,
|
||||||
|
span: json_span(cells[0].span),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let mut reachable = BTreeSet::from([initial_state.clone()]);
|
||||||
|
let mut changed = true;
|
||||||
|
while changed {
|
||||||
|
changed = false;
|
||||||
|
for transition in &interactions {
|
||||||
|
if reachable.contains(&transition.current)
|
||||||
|
&& !reachable.contains(&transition.next)
|
||||||
|
{
|
||||||
|
reachable.insert(transition.next.clone());
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for state in &states {
|
||||||
|
if !reachable.contains(*state) {
|
||||||
|
return Err(design_error(
|
||||||
|
"web.interaction.unreachable",
|
||||||
|
format!("scene state {state:?} is not reachable from the initial state"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if scenarios.len() > 1 && interactions.is_empty() {
|
||||||
|
return Err(design_error(
|
||||||
|
"web.interaction.missing",
|
||||||
|
"multi-state `场景` requires an `交互` table",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
} else if scenarios.len() > 1 {
|
||||||
|
return Err(design_error(
|
||||||
|
"web.interaction.missing",
|
||||||
|
"multi-state `场景` requires an `交互` table",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let mut dependencies = Vec::new();
|
||||||
|
if let Some((_, table)) = document::section_table(module, unit, "依赖", &["组件", "原因"])?
|
||||||
|
{
|
||||||
|
for cells in &table.rows {
|
||||||
|
let link = single_link(&cells[0], &module.relative, cells[0].span)?;
|
||||||
|
if cells[0].text.trim() != link.text.trim() {
|
||||||
|
return Err(LoadError::Design(vec![Diagnostic::error(
|
||||||
|
"web.dependency.target",
|
||||||
|
"依赖 component cell must contain only the Link",
|
||||||
|
)
|
||||||
|
.at(module.relative.clone(), Some(cells[0].span))]));
|
||||||
|
}
|
||||||
|
let reason = cells[1].text.trim().to_string();
|
||||||
|
if reason.is_empty() {
|
||||||
|
return Err(LoadError::Design(vec![Diagnostic::error(
|
||||||
|
"web.dependency.reason",
|
||||||
|
"依赖 reason must not be empty",
|
||||||
|
)
|
||||||
|
.at(module.relative.clone(), Some(cells[1].span))]));
|
||||||
|
}
|
||||||
|
let (target_module, target_unit) =
|
||||||
|
self.resolve_dependency_component(module, link)?;
|
||||||
|
dependencies.push(Dependency {
|
||||||
|
target: normalized_key(&target_module, target_unit.anchor_text()),
|
||||||
|
reason,
|
||||||
|
span: json_span(cells[0].span),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut acceptance = None;
|
||||||
|
if let Some(section) = document::direct_sections(module, unit)
|
||||||
|
.into_iter()
|
||||||
|
.find(|section| section.name == "验收")
|
||||||
|
{
|
||||||
|
let start = section
|
||||||
|
.heading_span
|
||||||
|
.map(|(_, end)| end)
|
||||||
|
.unwrap_or(section.span.0);
|
||||||
|
let text = module
|
||||||
|
.text_span(start, section.span.1)
|
||||||
|
.unwrap_or_default()
|
||||||
|
.trim()
|
||||||
|
.to_string();
|
||||||
|
if text.is_empty() {
|
||||||
|
return Err(design_error(
|
||||||
|
"web.acceptance.empty",
|
||||||
|
"`验收` section must not be empty",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
acceptance = Some(Acceptance {
|
||||||
|
text,
|
||||||
|
span: json_span(section.span),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let content = match document::direct_sections(module, unit)
|
||||||
|
.into_iter()
|
||||||
|
.find(|section| section.name == "内容")
|
||||||
|
{
|
||||||
|
Some(section) => {
|
||||||
|
let start = section
|
||||||
|
.heading_span
|
||||||
|
.map(|(_, end)| end)
|
||||||
|
.unwrap_or(section.span.0);
|
||||||
|
document::content_blocks(module, (start, section.span.1))
|
||||||
|
}
|
||||||
|
None => Vec::new(),
|
||||||
|
};
|
||||||
self.stack.pop();
|
self.stack.pop();
|
||||||
|
if self.definitions.len() >= self.config.max_definitions {
|
||||||
|
return Err(design_error(
|
||||||
|
"web.limit.definitions",
|
||||||
|
format!("definition limit {} exceeded", self.config.max_definitions),
|
||||||
|
));
|
||||||
|
}
|
||||||
let definition = ComponentDef {
|
let definition = ComponentDef {
|
||||||
key: key.clone(),
|
key: key.clone(),
|
||||||
source: source_ref(module, unit, anchor),
|
source: source_ref(module, unit, anchor),
|
||||||
slots,
|
slots,
|
||||||
|
content,
|
||||||
|
inputs,
|
||||||
|
events,
|
||||||
|
scenarios,
|
||||||
|
interactions,
|
||||||
|
dependencies,
|
||||||
|
acceptance,
|
||||||
};
|
};
|
||||||
self.definitions.insert(key.clone(), definition);
|
self.definitions.insert(key.clone(), definition);
|
||||||
Ok(key)
|
Ok(key)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Loader {
|
||||||
|
fn verify_stable(&mut self) -> Result<(), LoadError> {
|
||||||
|
let modules: Vec<Module> = self.modules.values().cloned().collect();
|
||||||
|
for module in modules {
|
||||||
|
let fresh = analysis::analyze(&self.config.cli, &module.path, &self.root)?;
|
||||||
|
if fresh.source_digest != module.source_digest {
|
||||||
|
return Err(LoadError::Engine(vec![Diagnostic::error(
|
||||||
|
"web.engine.stale",
|
||||||
|
format!(
|
||||||
|
"source {} changed during one design load ({} -> {})",
|
||||||
|
module.relative, module.source_digest, fresh.source_digest
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.at(module.relative.clone(), None)]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn valid_state(state: &str) -> bool {
|
||||||
|
let mut chars = state.chars();
|
||||||
|
let Some(first) = chars.next() else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
first.is_ascii_lowercase()
|
||||||
|
&& chars.all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || matches!(ch, '_' | '-'))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn validate_design(definitions: &BTreeMap<String, ComponentDef>) -> Result<(), LoadError> {
|
||||||
|
// Dependencies must name loaded design components and stay acyclic.
|
||||||
|
let mut edges: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
|
||||||
|
for (key, definition) in definitions {
|
||||||
|
for dependency in &definition.dependencies {
|
||||||
|
if !definitions.contains_key(&dependency.target) {
|
||||||
|
return Err(LoadError::Design(vec![Diagnostic::error(
|
||||||
|
"web.dependency.unknown",
|
||||||
|
format!(
|
||||||
|
"依赖 target {:?} is not a loaded design component",
|
||||||
|
dependency.target
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.at(
|
||||||
|
definition.source.path.clone(),
|
||||||
|
Some((dependency.span.start, dependency.span.end)),
|
||||||
|
)]));
|
||||||
|
}
|
||||||
|
edges
|
||||||
|
.entry(key.as_str())
|
||||||
|
.or_default()
|
||||||
|
.push(dependency.target.as_str());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn visit<'a>(
|
||||||
|
node: &'a str,
|
||||||
|
edges: &BTreeMap<&'a str, Vec<&'a str>>,
|
||||||
|
visiting: &mut BTreeSet<&'a str>,
|
||||||
|
done: &mut BTreeSet<&'a str>,
|
||||||
|
) -> bool {
|
||||||
|
if done.contains(node) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if !visiting.insert(node) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if let Some(targets) = edges.get(node) {
|
||||||
|
for target in targets {
|
||||||
|
if !visit(target, edges, visiting, done) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
visiting.remove(node);
|
||||||
|
done.insert(node);
|
||||||
|
true
|
||||||
|
}
|
||||||
|
let mut done = BTreeSet::new();
|
||||||
|
for node in edges.keys() {
|
||||||
|
let mut visiting = BTreeSet::new();
|
||||||
|
if !visit(node, &edges, &mut visiting, &mut done) {
|
||||||
|
return Err(design_error(
|
||||||
|
"web.dependency.cycle",
|
||||||
|
"design dependency cycle requires coordination and cannot be claimed parallel",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Scene content must never be a design component declaration.
|
||||||
|
let keys: BTreeSet<String> = definitions.keys().cloned().collect();
|
||||||
|
for definition in definitions.values() {
|
||||||
|
for scenario in &definition.scenarios {
|
||||||
|
let target = normalized_key_from_source(&scenario.content);
|
||||||
|
if keys.contains(&target) {
|
||||||
|
return Err(design_error(
|
||||||
|
"web.scene.content_component",
|
||||||
|
format!(
|
||||||
|
"场景 content {:?} is a design component declaration",
|
||||||
|
target
|
||||||
|
),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn normalized_key_from_source(source: &SourceRef) -> String {
|
||||||
|
format!("{}#{}", source.path, source.anchor)
|
||||||
|
}
|
||||||
|
|
||||||
/// Load one explicit design unit and interpret the contract.
|
/// Load one explicit design unit and interpret the contract.
|
||||||
pub fn load(config: &LoadConfig) -> Result<Design, LoadError> {
|
pub fn load(config: &LoadConfig) -> Result<Design, LoadError> {
|
||||||
if config.unit.starts_with('#') {
|
if config.unit.starts_with('#') {
|
||||||
@@ -486,8 +1155,16 @@ pub fn load(config: &LoadConfig) -> Result<Design, LoadError> {
|
|||||||
let module = loader.analyze(&entry)?;
|
let module = loader.analyze(&entry)?;
|
||||||
let unit = document::knowledge_h2(&module, &config.unit)?;
|
let unit = document::knowledge_h2(&module, &config.unit)?;
|
||||||
let root_key = loader.load_definition(&module, &unit, &config.unit, 0)?;
|
let root_key = loader.load_definition(&module, &unit, &config.unit, 0)?;
|
||||||
|
validate_design(&loader.definitions)?;
|
||||||
|
loader.verify_stable()?;
|
||||||
let mut instances = Vec::new();
|
let mut instances = Vec::new();
|
||||||
collect_instances(&loader.definitions, &root_key, "root", &mut instances);
|
collect_instances(&loader.definitions, &root_key, "root", &mut instances);
|
||||||
|
if instances.len() > config.max_instances {
|
||||||
|
return Err(design_error(
|
||||||
|
"web.limit.instances",
|
||||||
|
format!("instance limit {} exceeded", config.max_instances),
|
||||||
|
));
|
||||||
|
}
|
||||||
let mut sources = loader
|
let mut sources = loader
|
||||||
.modules
|
.modules
|
||||||
.values()
|
.values()
|
||||||
@@ -556,6 +1233,45 @@ pub fn handoff(design: &Design) -> String {
|
|||||||
slot.slot, slot.row, slot.width, slot.target
|
slot.slot, slot.row, slot.width, slot.target
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
for input in &definition.inputs {
|
||||||
|
out.push_str(&format!(
|
||||||
|
"{indent} - input `{}` ({}) {}\n",
|
||||||
|
input.name, input.entry_type, input.description
|
||||||
|
));
|
||||||
|
}
|
||||||
|
for event in &definition.events {
|
||||||
|
out.push_str(&format!(
|
||||||
|
"{indent} - event `{}` ({}) {}\n",
|
||||||
|
event.name, event.data, event.description
|
||||||
|
));
|
||||||
|
}
|
||||||
|
for scenario in &definition.scenarios {
|
||||||
|
out.push_str(&format!(
|
||||||
|
"{indent} - scenario `{}`{} -> `{}#{}`\n",
|
||||||
|
scenario.state,
|
||||||
|
if scenario.initial { " (initial)" } else { "" },
|
||||||
|
scenario.content.path,
|
||||||
|
scenario.content.anchor
|
||||||
|
));
|
||||||
|
}
|
||||||
|
for interaction in &definition.interactions {
|
||||||
|
out.push_str(&format!(
|
||||||
|
"{indent} - transition `{}` --{}--> `{}`\n",
|
||||||
|
interaction.current, interaction.event, interaction.next
|
||||||
|
));
|
||||||
|
}
|
||||||
|
for dependency in &definition.dependencies {
|
||||||
|
out.push_str(&format!(
|
||||||
|
"{indent} - dependency `{}`: {}\n",
|
||||||
|
dependency.target, dependency.reason
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if let Some(acceptance) = &definition.acceptance {
|
||||||
|
out.push_str(&format!(
|
||||||
|
"{indent} - acceptance: {}\n",
|
||||||
|
acceptance.text.replace('\n', " ")
|
||||||
|
));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
out.push_str("\n## Sources\n\n");
|
out.push_str("\n## Sources\n\n");
|
||||||
|
|||||||
+348
-1
@@ -249,7 +249,7 @@ fn rejects_scope_anchor_and_cycle_errors() {
|
|||||||
// the deterministic rejection is the candidate diagnostic (never a guess).
|
// the deterministic rejection is the candidate diagnostic (never a guess).
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
design_code(load(&outside.config("index.mq.md", "工作台")).unwrap_err()),
|
design_code(load(&outside.config("index.mq.md", "工作台")).unwrap_err()),
|
||||||
"web.link.candidate"
|
"web.link.target_missing"
|
||||||
);
|
);
|
||||||
|
|
||||||
let missing = basic_project();
|
let missing = basic_project();
|
||||||
@@ -321,3 +321,350 @@ fn entry_must_be_mq_md_and_expose_analysis_schema() {
|
|||||||
missing.entry = project.path.join("nope.mq.md");
|
missing.entry = project.path.join("nope.mq.md");
|
||||||
assert_eq!(engine_code(load(&missing).unwrap_err()), "web.engine.entry");
|
assert_eq!(engine_code(load(&missing).unwrap_err()), "web.engine.entry");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const STATES: &str =
|
||||||
|
"# 状态内容\n\n## @knowledge 空状态\n\n暂无数据。\n\n## @knowledge 成功\n\n保存成功。\n";
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn loads_full_leaf_contract_inputs_events_scenarios_interactions_dependencies() {
|
||||||
|
let project = TempProject::new();
|
||||||
|
project.write(
|
||||||
|
"index.mq.md",
|
||||||
|
"# 页面\n\n## @knowledge 工作台\n\n### 组件\n\n| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | a | [任务面板](components/a.mq.md#甲) | 1fr |\n| 1 | b | [详情](components/b.mq.md#乙) | 2fr |\n",
|
||||||
|
);
|
||||||
|
project.write(
|
||||||
|
"components/a.mq.md",
|
||||||
|
"# A 组件\n\n## @knowledge 甲\n\n### 输入\n\n| 名称 | 类型 | 说明 |\n| --- | --- | --- |\n| 项目 | Text | 项目名 |\n\n### 事件\n\n| 名称 | 数据 | 说明 |\n| --- | --- | --- |\n| 提交 | Result | 提交结果 |\n\n### 场景\n\n| 状态 | 内容 | 初始 |\n| --- | --- | --- |\n| empty | [空状态](states.mq.md#空状态) | true |\n| done | [成功](states.mq.md#成功) | false |\n\n### 交互\n\n| 当前 | 事件 | 下一状态 |\n| --- | --- | --- |\n| empty | 模拟保存 | done |\n\n### 依赖\n\n| 组件 | 原因 |\n| --- | --- |\n| [详情](b.mq.md#乙) | 提交后展示详情 |\n\n### 验收\n\n- 模拟保存后显示成功状态。\n",
|
||||||
|
);
|
||||||
|
project.write("components/states.mq.md", STATES);
|
||||||
|
project.write(
|
||||||
|
"components/b.mq.md",
|
||||||
|
"# B 组件\n\n## @knowledge 乙\n\n### 内容\n\n详情正文。\n",
|
||||||
|
);
|
||||||
|
let design = load(&project.config("index.mq.md", "工作台")).expect("full contract load");
|
||||||
|
let a = &design.definitions["components/a.mq.md#甲"];
|
||||||
|
assert_eq!(a.inputs.len(), 1);
|
||||||
|
assert_eq!(a.inputs[0].name, "项目");
|
||||||
|
assert_eq!(a.events.len(), 1);
|
||||||
|
assert_eq!(a.events[0].name, "提交");
|
||||||
|
assert_eq!(a.scenarios.len(), 2);
|
||||||
|
assert_eq!(a.scenarios.iter().filter(|scene| scene.initial).count(), 1);
|
||||||
|
assert_eq!(a.scenarios[0].content.anchor, "空状态");
|
||||||
|
assert_eq!(a.interactions.len(), 1);
|
||||||
|
assert_eq!(a.interactions[0].next, "done");
|
||||||
|
assert_eq!(a.dependencies.len(), 1);
|
||||||
|
assert_eq!(a.dependencies[0].target, "components/b.mq.md#乙");
|
||||||
|
assert!(a.acceptance.as_ref().unwrap().text.contains("模拟保存"));
|
||||||
|
let text = handoff(&design);
|
||||||
|
assert!(text.contains("scenario `empty` (initial)"));
|
||||||
|
assert!(text.contains("transition `empty` --模拟保存--> `done`"));
|
||||||
|
assert!(text.contains("dependency `components/b.mq.md#乙`"));
|
||||||
|
assert!(text.contains("acceptance:"));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn leaf_project(sections: &str) -> TempProject {
|
||||||
|
let project = TempProject::new();
|
||||||
|
project.write(
|
||||||
|
"a.mq.md",
|
||||||
|
&format!("# A 组件\n\n## @knowledge 甲\n\n{sections}"),
|
||||||
|
);
|
||||||
|
project.write("states.mq.md", STATES);
|
||||||
|
project
|
||||||
|
}
|
||||||
|
|
||||||
|
fn scene_error(sections: &str) -> &'static str {
|
||||||
|
let project = leaf_project(sections);
|
||||||
|
design_code(load(&project.config("a.mq.md", "甲")).unwrap_err())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_invalid_scene_and_interaction_tables() {
|
||||||
|
let cases: &[(&str, &str)] = &[
|
||||||
|
(
|
||||||
|
"### 场景\n\n| 状态 | 内容 | 初始 |\n| --- | --- | --- |\n| a | [空](states.mq.md#空状态) | true |\n| b | [成](states.mq.md#成功) | true |\n\n### 交互\n\n| 当前 | 事件 | 下一状态 |\n| --- | --- | --- |\n| a | go | b |\n",
|
||||||
|
"web.scene.initial",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"### 场景\n\n| 状态 | 内容 | 初始 |\n| --- | --- | --- |\n| a | [空](states.mq.md#空状态) | true |\n| a | [成](states.mq.md#成功) | false |\n",
|
||||||
|
"web.scene.state_duplicate",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"### 场景\n\n| 状态 | 内容 | 初始 |\n| --- | --- | --- |\n| Bad | [空](states.mq.md#空状态) | true |\n",
|
||||||
|
"web.scene.state",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"### 场景\n\n| 状态 | 内容 | 初始 |\n| --- | --- | --- |\n| a | 纯文本 | true |\n",
|
||||||
|
"web.link.none",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"### 场景\n\n| 状态 | 内容 | 初始 |\n| --- | --- | --- |\n| a | [自己](#甲) | true |\n",
|
||||||
|
"web.scene.content_component",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"### 场景\n\n| 状态 | 内容 | 初始 |\n| --- | --- | --- |\n| a | [空](states.mq.md#空状态) | true |\n| b | [成](states.mq.md#成功) | false |\n",
|
||||||
|
"web.interaction.missing",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"### 场景\n\n| 状态 | 内容 | 初始 |\n| --- | --- | --- |\n| a | [空](states.mq.md#空状态) | true |\n| b | [成](states.mq.md#成功) | false |\n\n### 交互\n\n| 当前 | 事件 | 下一状态 |\n| --- | --- | --- |\n| b | back | a |\n",
|
||||||
|
"web.interaction.unreachable",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"### 场景\n\n| 状态 | 内容 | 初始 |\n| --- | --- | --- |\n| a | [空](states.mq.md#空状态) | true |\n\n### 交互\n\n| 当前 | 事件 | 下一状态 |\n| --- | --- | --- |\n| a | go | missing |\n",
|
||||||
|
"web.interaction.state",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"### 交互\n\n| 当前 | 事件 | 下一状态 |\n| --- | --- | --- |\n| a | go | b |\n",
|
||||||
|
"web.interaction.without_scene",
|
||||||
|
),
|
||||||
|
];
|
||||||
|
for (sections, expected) in cases {
|
||||||
|
assert_eq!(scene_error(sections), *expected, "case: {sections}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn scenes_are_only_allowed_on_leaf_components() {
|
||||||
|
let project = TempProject::new();
|
||||||
|
project.write(
|
||||||
|
"a.mq.md",
|
||||||
|
"# A 组件\n\n## @knowledge 甲\n\n### 组件\n\n| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | child | [B](b.mq.md#乙) | auto |\n\n### 场景\n\n| 状态 | 内容 | 初始 |\n| --- | --- | --- |\n| a | [空](states.mq.md#空状态) | true |\n",
|
||||||
|
);
|
||||||
|
project.write("b.mq.md", "# B 组件\n\n## @knowledge 乙\n\n### 内容\n\nx\n");
|
||||||
|
project.write("states.mq.md", STATES);
|
||||||
|
assert_eq!(
|
||||||
|
design_code(load(&project.config("a.mq.md", "甲")).unwrap_err()),
|
||||||
|
"web.scene.not_leaf"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_invalid_inputs_dependencies_and_acceptance() {
|
||||||
|
let project = leaf_project(
|
||||||
|
"### 输入\n\n| 名称 | 类型 | 说明 |\n| --- | --- | --- |\n| x | T | d |\n| x | T | d |\n",
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
design_code(load(&project.config("a.mq.md", "甲")).unwrap_err()),
|
||||||
|
"web.input.name"
|
||||||
|
);
|
||||||
|
|
||||||
|
let linked = leaf_project(
|
||||||
|
"### 输入\n\n| 名称 | 类型 | 说明 |\n| --- | --- | --- |\n| [x](states.mq.md#空状态) | T | d |\n",
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
design_code(load(&linked.config("a.mq.md", "甲")).unwrap_err()),
|
||||||
|
"web.input.text"
|
||||||
|
);
|
||||||
|
|
||||||
|
let unknown = leaf_project(
|
||||||
|
"### 依赖\n\n| 组件 | 原因 |\n| --- | --- |\n| [目标](target.mq.md#目标) | 需要 |\n",
|
||||||
|
);
|
||||||
|
unknown.write(
|
||||||
|
"target.mq.md",
|
||||||
|
"# 目标页面\n\n## @knowledge 目标\n\n### 内容\n\nx\n",
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
design_code(load(&unknown.config("a.mq.md", "甲")).unwrap_err()),
|
||||||
|
"web.dependency.unknown"
|
||||||
|
);
|
||||||
|
|
||||||
|
let empty = leaf_project("### 验收\n\n \n");
|
||||||
|
assert_eq!(
|
||||||
|
design_code(load(&empty.config("a.mq.md", "甲")).unwrap_err()),
|
||||||
|
"web.acceptance.empty"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_dependency_cycles() {
|
||||||
|
let project = TempProject::new();
|
||||||
|
project.write(
|
||||||
|
"index.mq.md",
|
||||||
|
"# 主页面\n\n## @knowledge 页面\n\n### 组件\n\n| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | a | [A](a.mq.md#甲) | auto |\n| 1 | b | [B](b.mq.md#乙) | auto |\n",
|
||||||
|
);
|
||||||
|
project.write(
|
||||||
|
"a.mq.md",
|
||||||
|
"# A 组件\n\n## @knowledge 甲\n\n### 依赖\n\n| 组件 | 原因 |\n| --- | --- |\n| [B](b.mq.md#乙) | 组合 |\n",
|
||||||
|
);
|
||||||
|
project.write(
|
||||||
|
"b.mq.md",
|
||||||
|
"# B 组件\n\n## @knowledge 乙\n\n### 依赖\n\n| 组件 | 原因 |\n| --- | --- |\n| [A](a.mq.md#甲) | 组合 |\n",
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
design_code(load(&project.config("index.mq.md", "页面")).unwrap_err()),
|
||||||
|
"web.dependency.cycle"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn enforces_per_file_and_slot_limits() {
|
||||||
|
let project = basic_project();
|
||||||
|
let mut per_file = project.config("index.mq.md", "工作台");
|
||||||
|
per_file.max_file_bytes = 16;
|
||||||
|
assert_eq!(
|
||||||
|
design_code(load(&per_file).unwrap_err()),
|
||||||
|
"web.limit.source"
|
||||||
|
);
|
||||||
|
|
||||||
|
let wide = TempProject::new();
|
||||||
|
let mut table = String::from("| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n");
|
||||||
|
for slot in 0..13 {
|
||||||
|
table.push_str(&format!(
|
||||||
|
"| 1 | s{slot} | [叶子](leaf.mq.md#叶子) | auto |\n"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
wide.write(
|
||||||
|
"index.mq.md",
|
||||||
|
&format!("# 页面\n\n## @knowledge 工作台\n\n### 组件\n\n{table}"),
|
||||||
|
);
|
||||||
|
wide.write("leaf.mq.md", LEAF);
|
||||||
|
assert_eq!(
|
||||||
|
design_code(load(&wide.config("index.mq.md", "工作台")).unwrap_err()),
|
||||||
|
"web.layout.slots_per_row"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn projects_safe_content_blocks_for_components_and_scenarios() {
|
||||||
|
let project = TempProject::new();
|
||||||
|
project.write(
|
||||||
|
"index.mq.md",
|
||||||
|
"# 页面\n\n## @knowledge 工作台\n\n### 内容\n\n普通段落。\n\n- 一\n- 二\n\n### 组件\n\n| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | a | [A](a.mq.md#甲) | auto |\n",
|
||||||
|
);
|
||||||
|
project.write(
|
||||||
|
"a.mq.md",
|
||||||
|
"# A 组件\n\n## @knowledge 甲\n\n### 内容\n\n这里是**正文**。\n\n### 场景\n\n| 状态 | 内容 | 初始 |\n| --- | --- | --- |\n| only | [样例](states.mq.md#空状态) | true |\n",
|
||||||
|
);
|
||||||
|
project.write("states.mq.md", STATES);
|
||||||
|
let design = load(&project.config("index.mq.md", "工作台")).expect("content load");
|
||||||
|
let root = &design.definitions["index.mq.md#工作台"];
|
||||||
|
let kinds: Vec<&str> = root
|
||||||
|
.content
|
||||||
|
.iter()
|
||||||
|
.map(|block| block.kind.as_str())
|
||||||
|
.collect();
|
||||||
|
assert!(kinds.contains(&"paragraph"));
|
||||||
|
assert!(kinds.contains(&"list"));
|
||||||
|
let a = &design.definitions["a.mq.md#甲"];
|
||||||
|
assert!(a
|
||||||
|
.scenarios
|
||||||
|
.iter()
|
||||||
|
.all(|scene| !scene.content_blocks.is_empty()));
|
||||||
|
let text = handoff(&design);
|
||||||
|
assert!(text.contains("scenario `only`"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn raw_html_is_exposed_as_an_inert_placeholder() {
|
||||||
|
let project = TempProject::new();
|
||||||
|
project.write(
|
||||||
|
"index.mq.md",
|
||||||
|
"# 页面\n\n## @knowledge 工作台\n\n### 内容\n\n<div onclick=\"alert(1)\">危险</div>\n",
|
||||||
|
);
|
||||||
|
let design = load(&project.config("index.mq.md", "工作台")).expect("html load");
|
||||||
|
let block = design.definitions["index.mq.md#工作台"]
|
||||||
|
.content
|
||||||
|
.iter()
|
||||||
|
.find(|block| block.kind == "placeholder")
|
||||||
|
.expect("raw html block");
|
||||||
|
assert!(block.text.contains("inert text"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_scope_escape_via_symlink_absolute_and_encoded_paths() {
|
||||||
|
let project = TempProject::new();
|
||||||
|
let outside_dir = project
|
||||||
|
.path
|
||||||
|
.parent()
|
||||||
|
.unwrap()
|
||||||
|
.join(format!("marqdo-web-design-outside-{}", std::process::id()));
|
||||||
|
std::fs::create_dir_all(&outside_dir).unwrap();
|
||||||
|
let outside = outside_dir.join("outside.mq.md");
|
||||||
|
std::fs::write(&outside, "# 外部\n\n## @knowledge 目标\n\n### 内容\n\nx\n").unwrap();
|
||||||
|
project.write(
|
||||||
|
"index.mq.md",
|
||||||
|
"# 页面\n\n## @knowledge 工作台\n\n### 组件\n\n| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | a | [外部](escape.mq.md#目标) | auto |\n",
|
||||||
|
);
|
||||||
|
match std::os::unix::fs::symlink(&outside, project.path.join("escape.mq.md")) {
|
||||||
|
Ok(()) => {
|
||||||
|
let error = load(&project.config("index.mq.md", "工作台")).unwrap_err();
|
||||||
|
let code = match &error {
|
||||||
|
Error::Design(items) | Error::Engine(items) => items[0].code,
|
||||||
|
};
|
||||||
|
assert_eq!(code, "web.link.outside_root", "{error:?}");
|
||||||
|
}
|
||||||
|
Err(error) => eprintln!("symlink unavailable, skipped: {error}"),
|
||||||
|
}
|
||||||
|
let _ = std::fs::remove_dir_all(&outside_dir);
|
||||||
|
|
||||||
|
let absolute = TempProject::new();
|
||||||
|
absolute.write(
|
||||||
|
"index.mq.md",
|
||||||
|
"# 页面\n\n## @knowledge 工作台\n\n### 组件\n\n| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | a | [绝对](/tmp/x.mq.md#目标) | auto |\n",
|
||||||
|
);
|
||||||
|
let error = load(&absolute.config("index.mq.md", "工作台")).unwrap_err();
|
||||||
|
let code = match &error {
|
||||||
|
Error::Design(items) | Error::Engine(items) => items[0].code,
|
||||||
|
};
|
||||||
|
assert!(
|
||||||
|
matches!(code, "web.link.candidate" | "web.link.absolute"),
|
||||||
|
"{error:?}"
|
||||||
|
);
|
||||||
|
|
||||||
|
let encoded = TempProject::new();
|
||||||
|
encoded.write(
|
||||||
|
"index.mq.md",
|
||||||
|
"# 页面\n\n## @knowledge 工作台\n\n### 组件\n\n| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | a | [穿越](%2e%2e/outside.mq.md#目标) | auto |\n",
|
||||||
|
);
|
||||||
|
let error = load(&encoded.config("index.mq.md", "工作台")).unwrap_err();
|
||||||
|
let code = match &error {
|
||||||
|
Error::Design(items) | Error::Engine(items) => items[0].code,
|
||||||
|
};
|
||||||
|
assert!(
|
||||||
|
matches!(code, "web.link.candidate" | "web.link.target_missing"),
|
||||||
|
"{error:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn detects_a_changed_source_digest_during_one_load() {
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
let project = basic_project();
|
||||||
|
let real_cli = cli();
|
||||||
|
let wrapper = project.path.join("fake-cli.sh");
|
||||||
|
let counter = project.path.join("calls.txt");
|
||||||
|
std::fs::write(
|
||||||
|
&wrapper,
|
||||||
|
format!(
|
||||||
|
"#!/bin/sh\ncount=0\n[ -f '{count}' ] && count=$(cat '{count}')\ncount=$((count+1))\necho \"$count\" > '{count}'\n\"{cli}\" \"$@\"\nstatus=$?\nif [ \"$count\" -ge 2 ] && [ \"$status\" -eq 0 ]; then\n emit=\"\"\n while [ \"$#\" -gt 0 ]; do\n if [ \"$1\" = \"--emit\" ]; then shift; emit=\"$1\"; fi\n shift\n done\n python3 - \"$emit\" <<'PY'\nimport json, sys\npath = sys.argv[1]\ndata = json.load(open(path))\ndata['modules'][0]['source_digest'] = '0' * 64\njson.dump(data, open(path, 'w'))\nPY\nfi\nexit \"$status\"\n",
|
||||||
|
cli = real_cli.display(),
|
||||||
|
count = counter.display(),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||||
|
let mut config = project.config("index.mq.md", "工作台");
|
||||||
|
config.cli = wrapper;
|
||||||
|
let error = load(&config).unwrap_err();
|
||||||
|
assert_eq!(engine_code(error), "web.engine.stale");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resolves_outside_scope_links_that_stay_inside_the_explicit_root() {
|
||||||
|
let project = TempProject::new();
|
||||||
|
project.write(
|
||||||
|
"components/a.mq.md",
|
||||||
|
"# A 组件\n\n## @knowledge 甲\n\n### 组件\n\n| 行 | 槽 | 组件 | 宽度 |\n| --- | --- | --- | --- |\n| 1 | b | [乙](../shared/b.mq.md#乙) | auto |\n",
|
||||||
|
);
|
||||||
|
project.write(
|
||||||
|
"shared/b.mq.md",
|
||||||
|
"# B 组件\n\n## @knowledge 乙\n\n### 内容\n\n共享正文。\n",
|
||||||
|
);
|
||||||
|
let mut config = project.config("components/a.mq.md", "甲");
|
||||||
|
config.root = project.path.clone();
|
||||||
|
let design = load(&config).expect("outside_scope link inside --root resolves");
|
||||||
|
assert_eq!(design.definitions.len(), 2);
|
||||||
|
assert_eq!(
|
||||||
|
design.definitions["components/a.mq.md#甲"].slots[0].target,
|
||||||
|
"shared/b.mq.md#乙"
|
||||||
|
);
|
||||||
|
}
|
||||||
Reference in new issue
Block a user