Skip to main content

str_format/
meta.rs

1//! `._meta` 的解析、类型化提取与**归一化**(TOML → 规范 JSON)。
2//!
3//! 保注释写回与新建模板见 [`crate::meta_edit`]。
4
5use std::path::Path;
6
7use serde_json::{Map as JMap, Value as JValue};
8use toml_edit::{DocumentMut, Item, Table};
9
10use crate::error::{Error, Issue, Result, code};
11use crate::util;
12
13// ─────────────────────────── 规范 4.9:键序与表序 ───────────────────────────
14
15/// 顶层裸键的规范顺序(必须写在任何表头之前)。
16pub const TOP_BARE_KEYS: &[&str] = &[
17    "str",
18    "spec",
19    "kind",
20    "id",
21    "name",
22    "type",
23    "title",
24    "summary",
25    "tags",
26    "revision",
27    "created_at",
28    "updated_at",
29    "schema",
30];
31
32/// 表 / 数组表的规范顺序。
33pub const TABLE_ORDER: &[&str] = &["policies", "authors", "refs", "entries", "ext"];
34
35/// `[policies]` 内键序。
36pub const POLICIES_KEYS: &[&str] = &[
37    "id_version",
38    "max_depth",
39    "manifest",
40    "sha256",
41    "ignore",
42    "gitignore",
43    "large_asset_bytes",
44    "deep_tree_warn",
45];
46
47/// `[[authors]]` 内键序。
48pub const AUTHOR_KEYS: &[&str] = &["id", "name", "role", "at"];
49
50/// `[[refs]]` 内键序。
51pub const REF_KEYS: &[&str] = &["id", "target", "rel", "title", "order", "note"];
52
53/// `[[entries]]` 内键序。
54pub const ENTRY_KEYS: &[&str] = &[
55    "path",
56    "role",
57    "id",
58    "type",
59    "title",
60    "summary",
61    "order",
62    "media_type",
63    "size",
64    "sha256",
65    "count",
66    "schema",
67    "optional",
68    "note",
69];
70
71/// root 允许的顶层键。
72pub const ROOT_ALLOWED: &[&str] = &[
73    "str", "spec", "kind", "id", "name", "type", "title", "summary", "tags", "revision",
74    "created_at", "updated_at", "schema", "policies", "authors", "refs", "entries", "ext",
75];
76
77/// node / branch 允许的顶层键(无 `policies`)。
78pub const BRANCH_ALLOWED: &[&str] = &[
79    "str", "spec", "kind", "id", "name", "type", "title", "summary", "tags", "revision",
80    "created_at", "updated_at", "schema", "authors", "refs", "entries", "ext",
81];
82
83// ─────────────────────────── 模型 ───────────────────────────
84
85/// `kind` 档位。
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub enum Kind {
88    /// ROOT(深度 0)。
89    Root,
90    /// 独立节点(深度 1)。
91    Node,
92    /// 关联分支(深度 ≥2)。
93    Branch,
94}
95
96impl Kind {
97    /// 字面量。
98    pub fn as_str(self) -> &'static str {
99        match self {
100            Kind::Root => "root",
101            Kind::Node => "node",
102            Kind::Branch => "branch",
103        }
104    }
105
106    /// 解析字面量。
107    pub fn parse(s: &str) -> Option<Kind> {
108        match s {
109            "root" => Some(Kind::Root),
110            "node" => Some(Kind::Node),
111            "branch" => Some(Kind::Branch),
112            _ => None,
113        }
114    }
115
116    /// root 与 node/branch 的允许键集。
117    pub fn allowed_top_keys(self) -> &'static [&'static str] {
118        match self {
119            Kind::Root => ROOT_ALLOWED,
120            _ => BRANCH_ALLOWED,
121        }
122    }
123}
124
125/// 清单策略(`policies.manifest`)。
126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127pub enum ManifestPolicy {
128    /// 清单不一致为 error。
129    Strict,
130    /// 清单不一致仅告警。
131    Advisory,
132}
133
134/// 指纹策略(`policies.sha256`)。
135#[derive(Debug, Clone, Copy, PartialEq, Eq)]
136pub enum ShaPolicy {
137    /// 文件类条目必须有 `size` + `sha256`。
138    Required,
139    /// 可选。
140    Optional,
141    /// 完全不校验。
142    Off,
143}
144
145/// 校验策略(仅 root)。
146#[derive(Debug, Clone, PartialEq, Eq)]
147pub struct Policies {
148    /// UUID 版本要求。
149    pub id_version: usize,
150    /// 分支树最大深度。
151    pub max_depth: usize,
152    /// 清单策略。
153    pub manifest: ManifestPolicy,
154    /// 指纹策略。
155    pub sha256: ShaPolicy,
156    /// 忽略名单(gitignore 语义模式,bundle 内相对路径)。
157    pub ignore: Vec<String>,
158    /// 是否自动检测并应用 `.gitignore`(规范 4.7,默认开)。
159    pub gitignore: bool,
160    /// 大文件告警阈值。
161    pub large_asset_bytes: u64,
162    /// 深树告警阈值。
163    pub deep_tree_warn: usize,
164}
165
166impl Default for Policies {
167    fn default() -> Self {
168        Self {
169            id_version: 7,
170            max_depth: 32,
171            manifest: ManifestPolicy::Strict,
172            sha256: ShaPolicy::Required,
173            ignore: Vec::new(),
174            gitignore: true,
175            large_asset_bytes: 10 * 1024 * 1024,
176            deep_tree_warn: 16,
177        }
178    }
179}
180
181/// `[[authors]]` 元素。
182#[derive(Debug, Clone, Default, PartialEq, Eq)]
183pub struct Author {
184    /// 稳定标识符。
185    pub id: String,
186    /// 展示名。
187    pub name: Option<String>,
188    /// 角色。
189    pub role: String,
190    /// 参与时间。
191    pub at: Option<String>,
192}
193
194/// `[[refs]]` 元素(跨枝关联线)。
195#[derive(Debug, Clone, Default, PartialEq, Eq)]
196pub struct RefItem {
197    /// 关联线自身 id。
198    pub id: String,
199    /// 目标分支 id。
200    pub target: String,
201    /// 关联语义。
202    pub rel: String,
203    /// 标签。
204    pub title: Option<String>,
205    /// 排序键。
206    pub order: Option<i64>,
207    /// 备注。
208    pub note: Option<String>,
209}
210
211/// `[[entries]]` 元素(本目录内容清单)。
212#[derive(Debug, Clone, Default, PartialEq, Eq)]
213pub struct Entry {
214    /// 单段路径。
215    pub path: String,
216    /// 角色。
217    pub role: String,
218    /// 子分支 id(`node` / `branch`)。
219    pub id: Option<String>,
220    /// 子分支类型。
221    pub r#type: Option<String>,
222    /// 展示名。
223    pub title: Option<String>,
224    /// 摘要。
225    pub summary: Option<String>,
226    /// 排序键。
227    pub order: Option<i64>,
228    /// IANA 媒体类型。
229    pub media_type: Option<String>,
230    /// 字节数。
231    pub size: Option<i64>,
232    /// 内容指纹。
233    pub sha256: Option<String>,
234    /// 直接子项数(`dir`)。
235    pub count: Option<i64>,
236    /// 该文件遵循的 Schema。
237    pub schema: Option<String>,
238    /// 是否允许缺失。
239    pub optional: bool,
240    /// 备注。
241    pub note: Option<String>,
242}
243
244impl Entry {
245    /// 是否为分支条目(`node` / `branch`)。
246    pub fn is_branch(&self) -> bool {
247        self.role == "node" || self.role == "branch"
248    }
249
250    /// 是否为文件类条目(需要指纹)。
251    pub fn is_file_like(&self) -> bool {
252        self.role == "payload" || self.role == "asset"
253    }
254}
255
256/// 一份 `._meta` 的完整内容:保序文档 + 类型化视图。
257#[derive(Debug)]
258pub struct Meta {
259    /// 保注释、保顺序的 TOML 文档(写回用)。
260    pub doc: DocumentMut,
261    /// `str` 主版本。
262    pub str_version: Option<i64>,
263    /// 规范版本。
264    pub spec: Option<String>,
265    /// 档位。
266    pub kind_raw: Option<String>,
267    /// 解析出的档位。
268    pub kind: Option<Kind>,
269    /// 自身 id。
270    pub id: Option<String>,
271    /// bundle 短名(root)。
272    pub name: Option<String>,
273    /// 类型。
274    pub r#type: Option<String>,
275    /// 标题。
276    pub title: Option<String>,
277    /// 摘要。
278    pub summary: Option<String>,
279    /// 标签。
280    pub tags: Vec<String>,
281    /// 修订号。
282    pub revision: Option<i64>,
283    /// 创建时间。
284    pub created_at: Option<String>,
285    /// 更新时间。
286    pub updated_at: Option<String>,
287    /// payload schema 引用。
288    pub schema: Option<String>,
289    /// 策略。
290    pub policies: Policies,
291    /// 贡献者。
292    pub authors: Vec<Author>,
293    /// 跨枝关联。
294    pub refs: Vec<RefItem>,
295    /// 内容清单。
296    pub entries: Vec<Entry>,
297}
298
299/// 加载结果。
300pub enum MetaLoad {
301    /// 解析成功(可能带有字段级问题)。
302    Ok(Box<Meta>, Vec<Issue>),
303    /// 解析失败(`E_PARSE`),无法构建模型。
304    Failed(Vec<Issue>),
305}
306
307/// 从磁盘读取并解析一份 `._meta`。
308pub fn load(path: &Path, rel: &str) -> Result<MetaLoad> {
309    let bytes = std::fs::read(path).map_err(|e| Error::io(path, e))?;
310    let mut issues = Vec::new();
311
312    // 编码:UTF-8 无 BOM
313    if bytes.starts_with(&[0xEF, 0xBB, 0xBF]) {
314        issues.push(Issue::error(
315            code::PARSE,
316            rel,
317            "文件含 UTF-8 BOM,规范要求 UTF-8 无 BOM",
318        ));
319        return Ok(MetaLoad::Failed(issues));
320    }
321    let text = match std::str::from_utf8(&bytes) {
322        Ok(t) => t,
323        Err(e) => {
324            issues.push(Issue::error(
325                code::PARSE,
326                rel,
327                format!("编码非 UTF-8:{e}"),
328            ));
329            return Ok(MetaLoad::Failed(issues));
330        }
331    };
332
333    let doc: DocumentMut = match text.parse() {
334        Ok(d) => d,
335        Err(e) => {
336            issues.push(Issue::error(code::PARSE, rel, format!("TOML 解析失败:{e}")));
337            return Ok(MetaLoad::Failed(issues));
338        }
339    };
340
341    let (meta, mut field_issues) = extract(doc, rel);
342    issues.append(&mut field_issues);
343    Ok(MetaLoad::Ok(Box::new(meta), issues))
344}
345
346/// 从已解析的文档构建类型化视图。
347pub fn extract(doc: DocumentMut, rel: &str) -> (Meta, Vec<Issue>) {
348    let mut cx = Ctx {
349        rel: rel.to_string(),
350        issues: Vec::new(),
351    };
352    let table = doc.as_table().clone();
353
354    let str_version = cx.opt_int(&table, "str");
355    let spec = cx.opt_str(&table, "spec");
356    let kind_raw = cx.opt_str(&table, "kind");
357    let kind = match kind_raw.as_deref() {
358        Some(s) => match Kind::parse(s) {
359            Some(k) => Some(k),
360            None => {
361                cx.err(
362                    code::KIND_INVALID,
363                    format!("`kind` = {s:?} 非法(应为 root / node / branch)"),
364                );
365                None
366            }
367        },
368        None => {
369            cx.err(code::SCHEMA_FIELD, "缺少必填字段 `kind`");
370            None
371        }
372    };
373
374    let allowed = kind.map(|k| k.allowed_top_keys()).unwrap_or(BRANCH_ALLOWED);
375    cx.check_unknown(&table, allowed);
376
377    // 注意:TOML 无法表达空的数组表,故 `entries` / `refs` 为空时整表省略,
378    // 归一化时补 `[]`(规范 4.1 / 4.9)。
379    for key in ["id", "revision", "created_at", "updated_at"] {
380        if table.get(key).is_none() {
381            cx.err(code::SCHEMA_FIELD, format!("缺少必填字段 `{key}`"));
382        }
383    }
384
385    let id = cx.opt_str(&table, "id");
386    let name = cx.opt_str(&table, "name");
387    let r#type = cx.opt_str(&table, "type");
388    let title = cx.opt_str(&table, "title");
389    let summary = cx.opt_str(&table, "summary");
390    let tags = cx.opt_str_array(&table, "tags").unwrap_or_default();
391    let revision = cx.opt_int(&table, "revision");
392    let created_at = cx.opt_dt(&table, "created_at");
393    let updated_at = cx.opt_dt(&table, "updated_at");
394    let schema = cx.opt_str(&table, "schema");
395
396    // `[policies]`(仅 root)
397    let mut policies = Policies::default();
398    if let Some(item) = table.get("policies") {
399        match item.as_table() {
400            Some(pt) => {
401                if kind != Some(Kind::Root) {
402                    cx.err(
403                        code::SCHEMA_FIELD,
404                        "`[policies]` 只能出现在 root 的 `._meta` 中",
405                    );
406                }
407                cx.check_unknown(pt, POLICIES_KEYS);
408                if let Some(v) = cx.opt_int(pt, "id_version") {
409                    policies.id_version = v.max(0) as usize;
410                }
411                if let Some(v) = cx.opt_int(pt, "max_depth") {
412                    policies.max_depth = v.max(1) as usize;
413                }
414                if let Some(v) = cx.opt_str(pt, "manifest") {
415                    policies.manifest = match v.as_str() {
416                        "strict" => ManifestPolicy::Strict,
417                        "advisory" => ManifestPolicy::Advisory,
418                        _ => {
419                            cx.err(
420                                code::SCHEMA_FIELD,
421                                format!("`policies.manifest` = {v:?} 非法(strict / advisory)"),
422                            );
423                            policies.manifest
424                        }
425                    };
426                }
427                if let Some(v) = cx.opt_str(pt, "sha256") {
428                    policies.sha256 = match v.as_str() {
429                        "required" => ShaPolicy::Required,
430                        "optional" => ShaPolicy::Optional,
431                        "off" => ShaPolicy::Off,
432                        _ => {
433                            cx.err(
434                                code::SCHEMA_FIELD,
435                                format!("`policies.sha256` = {v:?} 非法(required / optional / off)"),
436                            );
437                            policies.sha256
438                        }
439                    };
440                }
441                if let Some(v) = cx.opt_str_array(pt, "ignore") {
442                    policies.ignore = v.into_iter().filter(|s| !s.trim().is_empty()).collect();
443                }
444                if let Some(item) = pt.get("gitignore") {
445                    match item.as_bool() {
446                        Some(b) => policies.gitignore = b,
447                        None => cx.err(
448                            code::SCHEMA_FIELD,
449                            "`policies.gitignore` 必须是布尔值",
450                        ),
451                    }
452                }
453                if let Some(v) = cx.opt_int(pt, "large_asset_bytes") {
454                    policies.large_asset_bytes = v.max(0) as u64;
455                }
456                if let Some(v) = cx.opt_int(pt, "deep_tree_warn") {
457                    policies.deep_tree_warn = v.max(1) as usize;
458                }
459            }
460            None => cx.err(code::SCHEMA_FIELD, "`policies` 必须是表 `[policies]`"),
461        }
462    }
463
464    // `[[authors]]`
465    let mut authors = Vec::new();
466    if let Some(aot) = table.get("authors").and_then(|i| i.as_array_of_tables()) {
467        for (i, t) in aot.iter().enumerate() {
468            cx.set_rel(&format!("{rel} #authors[{i}]"));
469            cx.check_unknown(t, AUTHOR_KEYS);
470            let aid = cx.req_str(t, "id").unwrap_or_default();
471            let role = cx.req_str(t, "role").unwrap_or_default();
472            let aname = cx.opt_str(t, "name");
473            let at = cx.opt_dt(t, "at");
474            authors.push(Author {
475                id: aid,
476                name: aname,
477                role,
478                at,
479            });
480        }
481        cx.set_rel(rel);
482    } else if table.get("authors").is_some() {
483        cx.err(code::SCHEMA_FIELD, "`authors` 必须是数组表 `[[authors]]`");
484    }
485
486    // `[[refs]]`
487    let mut refs = Vec::new();
488    if let Some(aot) = table.get("refs").and_then(|i| i.as_array_of_tables()) {
489        for (i, t) in aot.iter().enumerate() {
490            cx.set_rel(&format!("{rel} #refs[{i}]"));
491            cx.check_unknown(t, REF_KEYS);
492            refs.push(RefItem {
493                id: cx.req_str(t, "id").unwrap_or_default(),
494                target: cx.req_str(t, "target").unwrap_or_default(),
495                rel: cx.req_str(t, "rel").unwrap_or_default(),
496                title: cx.opt_str(t, "title"),
497                order: cx.opt_int(t, "order"),
498                note: cx.opt_str(t, "note"),
499            });
500        }
501        cx.set_rel(rel);
502    } else if table.get("refs").is_some() {
503        cx.err(code::SCHEMA_FIELD, "`refs` 必须是数组表 `[[refs]]`");
504    }
505
506    // `[[entries]]`
507    let mut entries = Vec::new();
508    if let Some(aot) = table.get("entries").and_then(|i| i.as_array_of_tables()) {
509        for (i, t) in aot.iter().enumerate() {
510            cx.set_rel(&format!("{rel} #entries[{i}]"));
511            cx.check_unknown(t, ENTRY_KEYS);
512            let path = cx.req_str(t, "path").unwrap_or_default();
513            let role = cx.req_str(t, "role").unwrap_or_default();
514            if path.contains('/') {
515                cx.err(
516                    code::SCHEMA_FIELD,
517                    format!("`entries[].path` = {path:?} 必须是单段路径(不含 `/`)"),
518                );
519            }
520            let e = Entry {
521                path,
522                role,
523                id: cx.opt_str(t, "id"),
524                r#type: cx.opt_str(t, "type"),
525                title: cx.opt_str(t, "title"),
526                summary: cx.opt_str(t, "summary"),
527                order: cx.opt_int(t, "order"),
528                media_type: cx.opt_str(t, "media_type"),
529                size: cx.opt_int(t, "size"),
530                sha256: cx.opt_str(t, "sha256"),
531                count: cx.opt_int(t, "count"),
532                schema: cx.opt_str(t, "schema"),
533                optional: cx.opt_bool(t, "optional").unwrap_or(false),
534                note: cx.opt_str(t, "note"),
535            };
536            entries.push(e);
537        }
538        cx.set_rel(rel);
539    } else if table.get("entries").is_some() {
540        cx.err(code::SCHEMA_FIELD, "`entries` 必须是数组表 `[[entries]]`");
541    }
542
543    let meta = Meta {
544        doc,
545        str_version,
546        spec,
547        kind_raw,
548        kind,
549        id,
550        name,
551        r#type,
552        title,
553        summary,
554        tags,
555        revision,
556        created_at,
557        updated_at,
558        schema,
559        policies,
560        authors,
561        refs,
562        entries,
563    };
564    (meta, cx.issues)
565}
566
567// ─────────────────────────── 规范 4.9:确定性序列化 ───────────────────────────
568
569/// 规范 §4.9 的**全量规范化**:顶层裸键序 → 表序 → 各表内键序 → `entries` / `refs` 集合排序,
570/// 最后重设文档位置使顺序真正落到磁盘字节上。
571///
572/// 只调整**书写顺序**,不改动任何字段值:`toml_edit` 的键/项装饰(注释、空行)随项一起搬运,
573/// 因此注释保真(规范 4.1 / DoD 16)。
574pub fn canonicalize_doc(doc: &mut DocumentMut) {
575    // 1) 顶层:值项(裸键)按 `TOP_BARE_KEYS`,表项按 `TABLE_ORDER`。
576    //    未知的值项排在已知裸键之后、表项之前 —— 否则未知裸键会被排到表头之后,直接产出非法 TOML。
577    let top_rank = |k: &str, it: &Item| -> usize {
578        match it {
579            Item::Table(_) | Item::ArrayOfTables(_) => {
580                TOP_BARE_KEYS.len()
581                    + 1
582                    + TABLE_ORDER
583                        .iter()
584                        .position(|x| *x == k)
585                        .unwrap_or(TABLE_ORDER.len())
586            }
587            _ => TOP_BARE_KEYS
588                .iter()
589                .position(|x| *x == k)
590                .unwrap_or(TOP_BARE_KEYS.len()),
591        }
592    };
593    doc.as_table_mut()
594        .sort_values_by(|k1, i1, k2, i2| top_rank(k1.get(), i1).cmp(&top_rank(k2.get(), i2)));
595
596    // 2) 各表内的键序。
597    for (key, order) in [
598        ("policies", POLICIES_KEYS),
599        ("authors", AUTHOR_KEYS),
600        ("refs", REF_KEYS),
601        ("entries", ENTRY_KEYS),
602    ] {
603        let rank = |k: &str| order.iter().position(|x| *x == k).unwrap_or(usize::MAX);
604        match doc.as_table_mut().get_mut(key) {
605            Some(Item::Table(t)) => {
606                t.sort_values_by(|k1, _, k2, _| rank(k1.get()).cmp(&rank(k2.get())));
607            }
608            Some(Item::ArrayOfTables(a)) => {
609                for t in a.iter_mut() {
610                    t.sort_values_by(|k1, _, k2, _| rank(k1.get()).cmp(&rank(k2.get())));
611                }
612            }
613            _ => {}
614        }
615    }
616
617    // 3) 集合排序(§4.9「各自按 `order` 稳定排序」)。
618    sort_collections_in(doc);
619
620    // 4) 位置重设,见 `renumber_positions_in`。
621    renumber_positions_in(doc);
622}
623
624/// `entries` / `refs` 的排序键:`(order, path|id)`,缺 `order` 视为最大。
625fn collection_sort_key(t: &Table) -> (i64, String) {
626    let order = t
627        .get("order")
628        .and_then(Item::as_integer)
629        .unwrap_or(i64::MAX);
630    let id = t
631        .get("path")
632        .or_else(|| t.get("id"))
633        .and_then(Item::as_str)
634        .unwrap_or("")
635        .to_string();
636    (order, id)
637}
638
639/// 就地重排 `entries` / `refs` 的元素(不改变元素自身的 `doc_position`)。
640fn sort_collections_in(doc: &mut DocumentMut) {
641    for key in ["entries", "refs"] {
642        let Some(aot) = doc
643            .as_table_mut()
644            .get_mut(key)
645            .and_then(Item::as_array_of_tables_mut)
646        else {
647            continue;
648        };
649        let mut items: Vec<Table> = aot.iter().cloned().collect();
650        items.sort_by_key(collection_sort_key);
651        for (slot, table) in aot.iter_mut().zip(items) {
652            *slot = table;
653        }
654    }
655}
656
657/// 依**前序遍历顺序**重设整篇文档每个表的 `doc_position`。
658///
659/// `toml_edit` 的 `DocumentMut::fmt` 会用 `Table::position()` 把表「搬回原始位置」:
660/// 只重排内容而不重设位置,序列化结果仍保持解析时的旧顺序 —— 这正是 `sort_collections()`
661/// 此前「改了等于没改」的根因。前序赋值保证位置序 == 遍历序 ==(规范化后的)书写顺序。
662fn renumber_positions_in(doc: &mut DocumentMut) {
663    fn walk(t: &mut Table, pos: &mut isize) {
664        *pos += 1;
665        t.set_position(Some(*pos));
666        for (_, item) in t.iter_mut() {
667            match item {
668                Item::Table(child) => walk(child, pos),
669                Item::ArrayOfTables(a) => {
670                    for child in a.iter_mut() {
671                        walk(child, pos);
672                    }
673                }
674                _ => {}
675            }
676        }
677    }
678    let mut pos = 0isize;
679    walk(doc.as_table_mut(), &mut pos);
680}
681
682// ─────────────────────────── 归一化(TOML → 规范 JSON)───────────────────────────
683
684impl Meta {
685    /// 归一化为**规范 JSON**:顶层裸键与各表按 4.9 的键序/表序输出,
686    /// 未知键原样保留,使其可被 JSON Schema 校验器与 AI 稳定消费。
687    pub fn to_json(&self) -> JValue {
688        let table = self.doc.as_table();
689        let mut map = JMap::new();
690
691        for key in TOP_BARE_KEYS {
692            if let Some(item) = table.get(key) {
693                map.insert((*key).to_string(), item_to_json(item));
694            }
695        }
696        if let Some(item) = table.get("policies") {
697            match item.as_table() {
698                Some(t) => {
699                    map.insert("policies".into(), table_to_json(t, POLICIES_KEYS));
700                }
701                None => {
702                    map.insert("policies".into(), item_to_json(item));
703                }
704            }
705        }
706        if let Some(aot) = table.get("authors").and_then(|i| i.as_array_of_tables()) {
707            map.insert(
708                "authors".into(),
709                JValue::Array(
710                    aot.iter()
711                        .map(|t| table_to_json(t, AUTHOR_KEYS))
712                        .collect(),
713                ),
714            );
715        }
716        // `refs` 为空(TOML 无法表达空数组表)时补 `[]`
717        map.insert(
718            "refs".into(),
719            match table.get("refs").and_then(|i| i.as_array_of_tables()) {
720                Some(aot) => JValue::Array(
721                    aot.iter()
722                        .map(|t| table_to_json(t, REF_KEYS))
723                        .collect(),
724                ),
725                None => JValue::Array(Vec::new()),
726            },
727        );
728        map.insert(
729            "entries".into(),
730            match table.get("entries").and_then(|i| i.as_array_of_tables()) {
731                Some(aot) => JValue::Array(
732                    aot.iter()
733                        .map(|t| table_to_json(t, ENTRY_KEYS))
734                        .collect(),
735                ),
736                None => JValue::Array(Vec::new()),
737            },
738        );
739        if let Some(item) = table.get("ext") {
740            map.insert("ext".into(), item_to_json(item));
741        }
742        // 未知键原样保留(前向兼容)
743        for (k, v) in table.iter() {
744            if !map.contains_key(k) {
745                map.insert(k.to_string(), item_to_json(v));
746            }
747        }
748        JValue::Object(map)
749    }
750
751    /// 按 `(order, path|id)` 重排 `entries` / `refs`,并重设文档位置使新顺序真正落盘。
752    pub fn sort_collections(&mut self) {
753        sort_collections_in(&mut self.doc);
754        renumber_positions_in(&mut self.doc);
755    }
756
757    /// 规范 §4.9 全量规范化(顶层键序 + 表序 + 表内键序 + 集合排序)。
758    pub fn canonicalize(&mut self) {
759        canonicalize_doc(&mut self.doc);
760    }
761
762    /// 校验序号等基础合法性(`E_REVISION_STALE` 的可判定部分)。
763    pub fn revision_issues(&self, rel: &str) -> Vec<Issue> {
764        let mut out = Vec::new();
765        match self.revision {
766            None => {}
767            Some(r) if r < 1 => out.push(Issue::error(
768                code::REVISION_STALE,
769                rel,
770                format!("`revision` = {r},必须为 ≥ 1 的整数"),
771            )),
772            Some(_) => {}
773        }
774        if let (Some(c), Some(u)) = (self.created_at.as_deref(), self.updated_at.as_deref()) {
775            match (util::parse_rfc3339(c), util::parse_rfc3339(u)) {
776                (Some(cd), Some(ud)) if ud < cd => out.push(Issue::error(
777                    code::REVISION_STALE,
778                    rel,
779                    format!("`updated_at`({u})早于 `created_at`({c})"),
780                )),
781                _ => {}
782            }
783        }
784        out
785    }
786}
787
788/// TOML `Item` → JSON。
789fn item_to_json(item: &Item) -> JValue {
790    match item {
791        Item::None => JValue::Null,
792        Item::Value(v) => value_to_json(v),
793        Item::Table(t) => {
794            let mut m = JMap::new();
795            for (k, v) in t.iter() {
796                m.insert(k.to_string(), item_to_json(v));
797            }
798            JValue::Object(m)
799        }
800        Item::ArrayOfTables(aot) => JValue::Array(
801            aot.iter()
802                .map(|t| {
803                    let mut m = JMap::new();
804                    for (k, v) in t.iter() {
805                        m.insert(k.to_string(), item_to_json(v));
806                    }
807                    JValue::Object(m)
808                })
809                .collect(),
810        ),
811    }
812}
813
814/// TOML `Value` → JSON。
815fn value_to_json(v: &toml_edit::Value) -> JValue {
816    if let Some(s) = v.as_str() {
817        return JValue::String(s.to_string());
818    }
819    if let Some(i) = v.as_integer() {
820        return JValue::from(i);
821    }
822    if let Some(f) = v.as_float() {
823        return serde_json::Number::from_f64(f)
824            .map(JValue::Number)
825            .unwrap_or(JValue::Null);
826    }
827    if let Some(b) = v.as_bool() {
828        return JValue::Bool(b);
829    }
830    if let Some(d) = v.as_datetime() {
831        return JValue::String(d.to_string());
832    }
833    if let Some(a) = v.as_array() {
834        return JValue::Array(a.iter().map(value_to_json).collect());
835    }
836    if let Some(t) = v.as_inline_table() {
837        let mut m = JMap::new();
838        for (k, val) in t.iter() {
839            m.insert(k.to_string(), value_to_json(val));
840        }
841        return JValue::Object(m);
842    }
843    JValue::Null
844}
845
846/// 表 → JSON(先按 `order` 输出已知键,再补未知键)。
847fn table_to_json(table: &Table, order: &[&str]) -> JValue {
848    let mut m = JMap::new();
849    for k in order {
850        if let Some(v) = table.get(k) {
851            m.insert((*k).to_string(), item_to_json(v));
852        }
853    }
854    for (k, v) in table.iter() {
855        if !m.contains_key(k) {
856            m.insert(k.to_string(), item_to_json(v));
857        }
858    }
859    JValue::Object(m)
860}
861
862// ─────────────────────────── 提取辅助 ───────────────────────────
863
864/// 提取上下文:累积字段级问题。
865struct Ctx {
866    rel: String,
867    issues: Vec<Issue>,
868}
869
870impl Ctx {
871    fn set_rel(&mut self, rel: &str) {
872        self.rel = rel.to_string();
873    }
874
875    fn err(&mut self, code: &'static str, message: impl Into<String>) {
876        self.issues
877            .push(Issue::error(code, self.rel.clone(), message));
878    }
879
880    fn check_unknown(&mut self, t: &Table, allowed: &[&str]) {
881        for (k, _) in t.iter() {
882            if !allowed.contains(&k) {
883                self.err(
884                    code::SCHEMA_FIELD,
885                    format!("未知字段 `{k}`(扩展请放入 `[ext]`)"),
886                );
887            }
888        }
889    }
890
891    fn req_str(&mut self, t: &Table, key: &str) -> Option<String> {
892        match t.get(key) {
893            None => {
894                self.err(code::SCHEMA_FIELD, format!("缺少必填字段 `{key}`"));
895                None
896            }
897            Some(item) => match item.as_str() {
898                Some(s) => Some(s.to_string()),
899                None => {
900                    self.err(code::SCHEMA_FIELD, format!("`{key}` 必须是字符串"));
901                    None
902                }
903            },
904        }
905    }
906
907    fn opt_str(&mut self, t: &Table, key: &str) -> Option<String> {
908        match t.get(key) {
909            None => None,
910            Some(item) => match item.as_str() {
911                Some(s) => Some(s.to_string()),
912                None => {
913                    self.err(code::SCHEMA_FIELD, format!("`{key}` 必须是字符串"));
914                    None
915                }
916            },
917        }
918    }
919
920    fn opt_int(&mut self, t: &Table, key: &str) -> Option<i64> {
921        match t.get(key) {
922            None => None,
923            Some(item) => match item.as_integer() {
924                Some(i) => Some(i),
925                None => {
926                    self.err(code::SCHEMA_FIELD, format!("`{key}` 必须是整数"));
927                    None
928                }
929            },
930        }
931    }
932
933    fn opt_bool(&mut self, t: &Table, key: &str) -> Option<bool> {
934        match t.get(key) {
935            None => None,
936            Some(item) => match item.as_bool() {
937                Some(b) => Some(b),
938                None => {
939                    self.err(code::SCHEMA_FIELD, format!("`{key}` 必须是布尔值"));
940                    None
941                }
942            },
943        }
944    }
945
946    /// 读取 TOML 原生 offset date-time;写成字符串或缺少时区偏移均报 `E_PARSE`。
947    fn opt_dt(&mut self, t: &Table, key: &str) -> Option<String> {
948        let Some(item) = t.get(key) else {
949            return None;
950        };
951        if item.as_str().is_some() {
952            self.err(
953                code::PARSE,
954                format!("`{key}` 必须使用 TOML 原生 offset date-time,不得写成字符串"),
955            );
956            return None;
957        }
958        match item.as_datetime() {
959            Some(d) => {
960                if d.date.is_none() || d.time.is_none() || d.offset.is_none() {
961                    self.err(
962                        code::PARSE,
963                        format!("`{key}` 必须是带时区偏移的 offset date-time(如 2026-09-14T10:03:11+08:00)"),
964                    );
965                    return None;
966                }
967                Some(d.to_string())
968            }
969            None => {
970                self.err(
971                    code::PARSE,
972                    format!("`{key}` 必须是 offset date-time"),
973                );
974                None
975            }
976        }
977    }
978
979    fn opt_str_array(&mut self, t: &Table, key: &str) -> Option<Vec<String>> {
980        let Some(item) = t.get(key) else {
981            return None;
982        };
983        let Some(arr) = item.as_array() else {
984            self.err(code::SCHEMA_FIELD, format!("`{key}` 必须是字符串数组"));
985            return None;
986        };
987        let mut out = Vec::new();
988        for v in arr.iter() {
989            match v.as_str() {
990                Some(s) => out.push(s.to_string()),
991                None => {
992                    self.err(code::SCHEMA_FIELD, format!("`{key}` 的元素必须是字符串"));
993                }
994            }
995        }
996        Some(out)
997    }
998}