yang-base 0.6.0

个人使用构建后端服务器
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
//! 构建期交叉校验、引用收集与确定性排序。

use crate::datasource::DatasourceId;
use crate::definition::{
    ActionRef, AddonSpec, BuildError, FieldKind, FieldRef, ParamSource, TableName,
};
use crate::router::middleware::MiddlewareRole;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};

use super::schema_contains_binary_field;

pub(super) fn resolve_param_fields(addons: &mut [AddonSpec]) -> Result<(), BuildError> {
    // 按逻辑数据源收集字段:同源内允许参数引用其它表;跨源引用不解析。
    let mut by_source: BTreeMap<DatasourceId, BTreeMap<FieldRef, crate::definition::FieldSpec>> =
        BTreeMap::new();
    for table in addons
        .iter()
        .flat_map(|addon| &addon.modules)
        .filter_map(|module| module.table.as_ref())
    {
        let source = table.datasource.clone().unwrap_or_default();
        let fields = by_source.entry(source).or_default();
        for field in &table.fields {
            fields.insert(
                crate::definition::FieldRef::new(table.name.clone(), field.name.clone()),
                field.clone(),
            );
        }
    }

    for module in addons.iter_mut().flat_map(|addon| &mut addon.modules) {
        let source = module
            .table
            .as_ref()
            .and_then(|table| table.datasource.clone())
            .or_else(|| module.datasource.clone())
            .unwrap_or_default();
        let definitions = by_source.get(&source).cloned().unwrap_or_default();

        for action in module.actions_mut() {
            for param in &mut action.params {
                let Some(reference) = &param.field else {
                    continue;
                };
                let field =
                    definitions
                        .get(reference)
                        .ok_or_else(|| BuildError::InvalidReference {
                            kind: "Field",
                            reference: reference.to_string(),
                        })?;
                param.kind.get_or_insert(field.kind);
                param.required |= field.is_required();
                if param.validation.min_length.is_none() {
                    param.validation.min_length = field.validation.min_length;
                }
                if param.validation.max_length.is_none() {
                    param.validation.max_length = field.validation.max_length;
                }
                if param.validation.minimum.is_none() {
                    param.validation.minimum = field.validation.minimum.clone();
                }
                if param.validation.maximum.is_none() {
                    param.validation.maximum = field.validation.maximum.clone();
                }
                if param.validation.pattern.is_none() {
                    param.validation.pattern = field.validation.pattern.clone();
                }
                if param.presentation.title.is_empty() {
                    param.presentation.title = field.presentation.title.clone();
                }
                if param.presentation.description.is_empty() {
                    param.presentation.description = field.presentation.description.clone();
                }
                if param.presentation.widget.is_none() {
                    param.presentation.widget = field.presentation.widget;
                }
            }
        }
    }
    Ok(())
}

fn duplicate(kind: &'static str, name: impl ToString) -> BuildError {
    BuildError::DuplicateName {
        kind,
        name: name.to_string(),
    }
}

fn insert_unique<T: Ord + Clone + ToString>(
    set: &mut BTreeSet<T>,
    value: &T,
    kind: &'static str,
) -> Result<(), BuildError> {
    if set.insert(value.clone()) {
        Ok(())
    } else {
        Err(duplicate(kind, value.to_string()))
    }
}

pub(super) fn validate_unique_addons(addons: &[AddonSpec]) -> Result<(), BuildError> {
    let mut names = BTreeSet::new();
    for addon in addons {
        insert_unique(&mut names, &addon.name, "Addon")?;
    }
    Ok(())
}

pub(super) fn validate_dependencies(addons: &[AddonSpec]) -> Result<(), BuildError> {
    let names: BTreeSet<_> = addons.iter().map(|addon| addon.name.clone()).collect();
    for addon in addons {
        let mut dependencies = BTreeSet::new();
        for dependency in &addon.dependencies {
            insert_unique(&mut dependencies, dependency, "Addon dependency")?;
            if !names.contains(dependency) {
                return Err(BuildError::DependencyMissing {
                    addon: addon.name.to_string(),
                    dependency: dependency.to_string(),
                });
            }
        }
    }
    Ok(())
}

pub(super) fn validate_module_ownership(addons: &[AddonSpec]) -> Result<(), BuildError> {
    for addon in addons {
        for module in &addon.modules {
            let owner = module.name.as_str().split('.').next().unwrap_or_default();
            if owner != addon.name.as_str() {
                return Err(BuildError::InvalidReference {
                    kind: "Module owner",
                    reference: format!("{} -> {}", addon.name, module.name),
                });
            }
        }
    }
    Ok(())
}

pub(super) fn validate_unique_modules(addons: &[AddonSpec]) -> Result<(), BuildError> {
    let mut names = BTreeSet::new();
    for module in addons.iter().flat_map(|addon| &addon.modules) {
        insert_unique(&mut names, &module.name, "Module")?;
    }
    Ok(())
}

pub(super) fn validate_module_contents(addons: &[AddonSpec]) -> Result<(), BuildError> {
    let mut tables: BTreeSet<(DatasourceId, TableName)> = BTreeSet::new();
    let mut operations = BTreeSet::new();
    for module in addons.iter().flat_map(|addon| &addon.modules) {
        if let Some(table) = &module.table {
            let source = table
                .datasource
                .clone()
                .or_else(|| module.datasource.clone())
                .unwrap_or_default();
            if let Some(module_source) = &module.datasource {
                if module_source != &source {
                    return Err(BuildError::InvalidReference {
                        kind: "Datasource",
                        reference: format!(
                            "{}: 模块数据源 {} 与表数据源 {} 不一致",
                            module.name, module_source, source
                        ),
                    });
                }
            }
            if !tables.insert((source.clone(), table.name.clone())) {
                return Err(duplicate("Table", format!("{source}.{}", table.name)));
            }
            let mut fields = BTreeSet::new();
            let mut tenant_key = None;
            for field in &table.fields {
                insert_unique(&mut fields, &field.name, "Field")?;
                if field.tenant_key && tenant_key.replace(&field.name).is_some() {
                    return Err(BuildError::InvalidFieldDefinition {
                        table: table.name.to_string(),
                        field: field.name.to_string(),
                        reason: "同一表只能声明一个 tenant_key".to_string(),
                    });
                }
                if matches!(field.kind, FieldKind::Table | FieldKind::Tree)
                    && field.relation.is_none()
                {
                    return Err(BuildError::InvalidFieldDefinition {
                        table: table.name.to_string(),
                        field: field.name.to_string(),
                        reason: "Table/Tree 字段必须声明 relation".to_string(),
                    });
                }
                if !matches!(field.kind, FieldKind::Table | FieldKind::Tree)
                    && field.relation.is_some()
                {
                    return Err(BuildError::InvalidFieldDefinition {
                        table: table.name.to_string(),
                        field: field.name.to_string(),
                        reason: "只有 Table/Tree 字段可以声明 relation".to_string(),
                    });
                }
                // I-5:服务端关键词搜索只会命中文本列;允许非文本字段声明
                // searchable 等于让 UI 投影的 search_fields 说谎,构建期拒绝。
                if field.access.searchable
                    && !matches!(field.kind, FieldKind::Str | FieldKind::Text)
                {
                    return Err(BuildError::InvalidFieldDefinition {
                        table: table.name.to_string(),
                        field: field.name.to_string(),
                        reason: "只有文本字段(Str/Text)可以声明 searchable".to_string(),
                    });
                }
            }
        }

        let mut actions = BTreeSet::new();
        let mut module_permissions = BTreeSet::new();
        for permission in &module.default_permissions {
            if permission.trim().is_empty() {
                return Err(BuildError::InvalidReference {
                    kind: "Module permission",
                    reference: format!("{} -> 空权限", module.name),
                });
            }
            insert_unique(&mut module_permissions, permission, "Module permission")?;
        }
        for action in module.actions() {
            insert_unique(&mut actions, &action.name, "Action")?;
            if let Some(error) = &action.contract_error {
                return Err(BuildError::InvalidReference {
                    kind: "Action schema",
                    reference: format!("{}.{} -> {error}", module.name, action.name),
                });
            }
            if action.display_name.trim().is_empty() {
                return Err(BuildError::InvalidReference {
                    kind: "Action display_name",
                    reference: format!("{}.{}", module.name, action.name),
                });
            }
            if !(100..=599).contains(&action.success_status) {
                return Err(BuildError::InvalidReference {
                    kind: "Action success_status",
                    reference: format!(
                        "{}.{} -> {}",
                        module.name, action.name, action.success_status
                    ),
                });
            }
            validate_action_media(module, action)?;
            let mut permissions = BTreeSet::new();
            for permission in &action.permissions {
                if permission.trim().is_empty() {
                    return Err(BuildError::InvalidReference {
                        kind: "Action permission",
                        reference: format!("{}.{} -> 空权限", module.name, action.name),
                    });
                }
                insert_unique(&mut permissions, permission, "Action permission")?;
            }
            if action.route.operation_id.trim().is_empty() {
                return Err(BuildError::InvalidRoute {
                    method: action.route.method.as_str().to_string(),
                    path: action.route.path.clone(),
                    reason: "operation_id 不能为空".to_string(),
                });
            }
            if !operations.insert(action.route.operation_id.clone()) {
                return Err(duplicate("operation_id", &action.route.operation_id));
            }
            let mut params = BTreeSet::new();
            for param in &action.params {
                let identity = (param.source, param.name.clone());
                if !params.insert(identity) {
                    return Err(duplicate("Param", &param.name));
                }
                if param.source == ParamSource::Path
                    && !action
                        .route
                        .path
                        .contains(&format!("{{{}}}", param.name.as_str()))
                {
                    return Err(BuildError::InvalidReference {
                        kind: "Path param",
                        reference: format!("{} -> {}", param.name, action.route.path),
                    });
                }
            }
        }

        let mut views = BTreeSet::new();
        for view in &module.views {
            insert_unique(&mut views, &view.name, "View")?;
        }
    }

    // 外键目标必须与源表在同一逻辑数据源;应用级外部表(不在模块表集合中)允许,
    // 由 schema 同步阶段决定是否可建。
    let mut table_sources: BTreeMap<TableName, BTreeSet<DatasourceId>> = BTreeMap::new();
    for (source, name) in &tables {
        table_sources
            .entry(name.clone())
            .or_default()
            .insert(source.clone());
    }
    for module in addons.iter().flat_map(|addon| &addon.modules) {
        let Some(table) = &module.table else {
            continue;
        };
        let source = table
            .datasource
            .clone()
            .or_else(|| module.datasource.clone())
            .unwrap_or_default();
        for foreign_key in &table.foreign_keys {
            for referenced in &foreign_key.referenced_fields {
                if let Some(sources) = table_sources.get(referenced.table()) {
                    if !sources.contains(&source) {
                        return Err(BuildError::InvalidReference {
                            kind: "ForeignKey",
                            reference: format!(
                                "{}: 目标 {}.{} 不在数据源 {}",
                                foreign_key.name,
                                referenced.table(),
                                referenced.field(),
                                source
                            ),
                        });
                    }
                }
            }
        }
    }
    Ok(())
}

pub(super) fn validate_middleware_order(addons: &[AddonSpec]) -> Result<(), BuildError> {
    for module in addons.iter().flat_map(|addon| &addon.modules) {
        let mut authentication_dependent_seen = None;
        for middleware in module.middlewares() {
            match middleware.role() {
                MiddlewareRole::TenantResolution => {
                    authentication_dependent_seen = Some("TenantResolverMiddleware")
                }
                MiddlewareRole::StepUpProtection => {
                    authentication_dependent_seen = Some("StepUpMiddleware")
                }
                MiddlewareRole::Authentication if authentication_dependent_seen.is_some() => {
                    return Err(BuildError::InvalidReference {
                        kind: "Middleware order",
                        reference: format!(
                            "{}: TokenAuthMiddleware 必须先于 {} 注册",
                            module.name,
                            authentication_dependent_seen.unwrap_or("身份依赖中间件")
                        ),
                    });
                }
                MiddlewareRole::Unspecified | MiddlewareRole::Authentication => {}
            }
        }
    }
    Ok(())
}

fn validate_action_media(
    module: &crate::definition::ModuleSpec,
    action: &crate::definition::ActionSpec,
) -> Result<(), BuildError> {
    let invalid = |reason: &str| BuildError::InvalidReference {
        kind: "Action request media",
        reference: format!("{}.{} -> {reason}", module.name, action.name),
    };
    // C-1 双向强制:二进制文件字段(UploadedFile,schema 形态为 format: binary)
    // 只能出现在 multipart Action 中,multipart Action 也必须至少声明一个文件字段。
    let has_binary_input = schema_contains_binary_field(&action.input_schema);
    match (action.request_media_type, action.multipart.as_ref()) {
        (crate::definition::ActionMediaType::Json, None) => {
            if has_binary_input {
                return Err(invalid(
                    "JSON Action 的输入不得包含二进制文件字段(应声明 multipart 请求)",
                ));
            }
            return Ok(());
        }
        (crate::definition::ActionMediaType::Json, Some(_)) => {
            return Err(invalid("JSON Action 不得携带 multipart 配置"));
        }
        (crate::definition::ActionMediaType::Multipart, None) => {
            return Err(invalid("multipart Action 缺少资源限制"));
        }
        (crate::definition::ActionMediaType::Multipart, Some(_)) => {}
    }
    if !matches!(
        action.route.method,
        crate::definition::HttpMethod::Post
            | crate::definition::HttpMethod::Put
            | crate::definition::HttpMethod::Patch
    ) {
        return Err(invalid("multipart 只允许 POST/PUT/PATCH"));
    }

    let multipart = action
        .multipart
        .as_ref()
        .ok_or_else(|| invalid("multipart Action 缺少资源限制"))?;
    if multipart.max_files == 0 {
        return Err(invalid("max_files 必须大于 0"));
    }
    if multipart.max_file_bytes == 0 || multipart.max_total_bytes == 0 {
        return Err(invalid("文件与请求字节上限必须大于 0"));
    }
    if multipart.max_file_bytes > multipart.max_total_bytes {
        return Err(invalid("max_file_bytes 不能大于 max_total_bytes"));
    }
    if multipart.max_text_field_bytes == 0 {
        return Err(invalid("文本字段字节上限必须大于 0"));
    }
    if multipart.max_text_field_bytes > multipart.max_total_bytes {
        return Err(invalid("max_text_field_bytes 不能大于 max_total_bytes"));
    }
    if multipart.allowed_content_types.is_empty() {
        return Err(invalid("allowed_content_types 不能为空"));
    }
    let mut content_types = BTreeSet::new();
    for content_type in &multipart.allowed_content_types {
        // "*/*" 是唯一允许的通配写法:传输层据此跳过文件 part 的客户端 MIME 校验
        // (对齐 TS 导入端点只按扩展名判断);其余仍必须是精确 MIME 类型。
        if content_type != "*/*" && !is_exact_mime_type(content_type) {
            return Err(invalid(
                "allowed_content_types 必须是小写精确 MIME 类型或 \"*/*\"",
            ));
        }
        if !content_types.insert(content_type) {
            return Err(invalid("allowed_content_types 不能重复"));
        }
    }
    if !has_binary_input {
        return Err(invalid("multipart Action 的输入必须至少声明一个文件字段"));
    }
    Ok(())
}

fn is_exact_mime_type(value: &str) -> bool {
    let Some((top, subtype)) = value.split_once('/') else {
        return false;
    };
    !top.is_empty()
        && !subtype.is_empty()
        && !subtype.contains('/')
        && top.bytes().all(is_mime_token_byte)
        && subtype.bytes().all(is_mime_token_byte)
}

fn is_mime_token_byte(value: u8) -> bool {
    value.is_ascii_lowercase()
        || value.is_ascii_digit()
        || matches!(
            value,
            b'!' | b'#'
                | b'$'
                | b'%'
                | b'&'
                | b'\''
                | b'+'
                | b'-'
                | b'.'
                | b'^'
                | b'_'
                | b'`'
                | b'|'
                | b'~'
        )
}

pub(super) fn collect_fields(
    addons: &[AddonSpec],
) -> Result<BTreeMap<(DatasourceId, TableName), BTreeSet<crate::definition::FieldName>>, BuildError>
{
    let mut result = BTreeMap::new();
    for table in addons
        .iter()
        .flat_map(|addon| &addon.modules)
        .filter_map(|module| module.table.as_ref())
    {
        let fields = table
            .fields
            .iter()
            .map(|field| field.name.clone())
            .collect();
        let source = table.datasource.clone().unwrap_or_default();
        if result
            .insert((source, table.name.clone()), fields)
            .is_some()
        {
            return Err(duplicate("Table", &table.name));
        }
    }
    Ok(result)
}

pub(super) fn collect_actions(addons: &[AddonSpec]) -> Result<BTreeSet<ActionRef>, BuildError> {
    let mut result = BTreeSet::new();
    for module in addons.iter().flat_map(|addon| &addon.modules) {
        for action in module.actions() {
            let reference = ActionRef::new(module.name.clone(), action.name.clone());
            insert_unique(&mut result, &reference, "Action")?;
        }
    }
    Ok(result)
}

pub(super) fn collect_views(
    addons: &[AddonSpec],
) -> Result<BTreeSet<crate::definition::ViewRef>, BuildError> {
    let mut result = BTreeSet::new();
    for module in addons.iter().flat_map(|addon| &addon.modules) {
        for view in &module.views {
            let reference = crate::definition::ViewRef::new(module.name.clone(), view.name.clone());
            insert_unique(&mut result, &reference, "View")?;
        }
    }
    Ok(result)
}

fn validate_field_ref(
    source: &DatasourceId,
    reference: &FieldRef,
    fields: &BTreeMap<(DatasourceId, TableName), BTreeSet<crate::definition::FieldName>>,
) -> Result<(), BuildError> {
    if fields
        .get(&(source.clone(), reference.table().clone()))
        .is_some_and(|table| table.contains(reference.field()))
    {
        Ok(())
    } else {
        Err(BuildError::InvalidReference {
            kind: "Field",
            reference: reference.to_string(),
        })
    }
}

fn validate_action_ref(
    reference: &ActionRef,
    actions: &BTreeSet<ActionRef>,
) -> Result<(), BuildError> {
    if actions.contains(reference) {
        Ok(())
    } else {
        Err(BuildError::InvalidReference {
            kind: "Action",
            reference: reference.to_string(),
        })
    }
}

pub(super) fn validate_references(
    addons: &[AddonSpec],
    fields: &BTreeMap<(DatasourceId, TableName), BTreeSet<crate::definition::FieldName>>,
    actions: &BTreeSet<ActionRef>,
    views: &BTreeSet<crate::definition::ViewRef>,
) -> Result<(), BuildError> {
    for module in addons.iter().flat_map(|addon| &addon.modules) {
        let source = module
            .table
            .as_ref()
            .and_then(|table| table.datasource.clone())
            .or_else(|| module.datasource.clone())
            .unwrap_or_default();
        for middleware in module.middlewares() {
            if let Some(target) = middleware.target_action() {
                if target.module() != &module.name {
                    return Err(BuildError::InvalidReference {
                        kind: "Middleware Action",
                        reference: target.to_string(),
                    });
                }
                validate_action_ref(target, actions).map_err(|_| BuildError::InvalidReference {
                    kind: "Middleware Action",
                    reference: target.to_string(),
                })?;
            }
        }
        if let Some(table) = &module.table {
            for field in &table.fields {
                if let Some(relation) = &field.relation {
                    validate_field_ref(&source, relation, fields)?;
                }
                if let Some(select) = &field.select {
                    if field.relation.is_none() {
                        return Err(BuildError::InvalidReference {
                            kind: "Relation Options Field",
                            reference: format!("{}.{}: {select}", table.name, field.name),
                        });
                    }
                    validate_action_ref(select, actions)?;
                }
                for display in &field.presentation.display {
                    validate_field_ref(&source, display, fields)?;
                    let same_target_table = field
                        .relation
                        .as_ref()
                        .is_some_and(|relation| display.table() == relation.table());
                    if !same_target_table {
                        return Err(BuildError::InvalidReference {
                            kind: "Relation Display Field",
                            reference: format!("{}.{}: {display}", table.name, field.name),
                        });
                    }
                }
            }
        }
        for action in module.actions() {
            for param in &action.params {
                if let Some(field) = &param.field {
                    validate_field_ref(&source, field, fields)?;
                }
            }
            for call in &action.calls {
                validate_action_ref(call, actions)?;
            }
        }
        for view in &module.views {
            let view_ref = crate::definition::ViewRef::new(module.name.clone(), view.name.clone());
            if !views.contains(&view_ref) {
                return Err(BuildError::InvalidReference {
                    kind: "View",
                    reference: view_ref.to_string(),
                });
            }
            for field in &view.fields {
                validate_field_ref(&source, field, fields)?;
                // View 是同一主表的多场景投影:数据源固定为 module.table。
                // 跨表字段会被编译成“本表列”,请求期要么静默读到主表同名列,
                // 要么报 FieldNotFound;在构建期明确拒绝这种非法定义。
                // 无主表 Module 的 views 仍由 compile 阶段整体跳过,保持既有语义。
                if module
                    .table
                    .as_ref()
                    .is_some_and(|table| field.table() != &table.name)
                {
                    return Err(BuildError::InvalidReference {
                        kind: "View Field",
                        reference: format!("{view_ref}: {field}"),
                    });
                }
            }
            if let Some(tree) = &view.tree {
                let table = module
                    .table
                    .as_ref()
                    .ok_or_else(|| BuildError::InvalidReference {
                        kind: "Tree View",
                        reference: format!("{view_ref}: 缺少主表"),
                    })?;
                let tree_fields = [&tree.id_field, &tree.parent_field, &tree.label_field];
                if tree.id_field == tree.parent_field {
                    return Err(BuildError::InvalidReference {
                        kind: "Tree View",
                        reference: format!("{view_ref}: id/parent 字段必须不同"),
                    });
                }
                // 树节点数硬天花板:View 只能下调,不能把查询 LIMIT 抬到无界(H7/M25)。
                const TREE_MAX_NODES_CEILING: usize = crate::table::DEFAULT_TREE_MAX_NODES;
                if let Some(limit) = tree.max_nodes {
                    if limit == 0 || limit > TREE_MAX_NODES_CEILING {
                        return Err(BuildError::InvalidReference {
                            kind: "Tree View",
                            reference: format!(
                                "{view_ref}: max_nodes 必须在 1..={TREE_MAX_NODES_CEILING} 之间"
                            ),
                        });
                    }
                }
                for field in tree_fields {
                    validate_field_ref(&source, field, fields)?;
                    if field.table() != &table.name || !view.fields.contains(field) {
                        return Err(BuildError::InvalidReference {
                            kind: "Tree View Field",
                            reference: format!("{view_ref}: {field}"),
                        });
                    }
                }
            }
            for action in &view.actions {
                validate_action_ref(action, actions)?;
            }
        }
    }
    Ok(())
}

#[derive(Default)]
struct RouteRegistry {
    matcher: matchit::Router<()>,
    methods_by_path: HashMap<String, HashSet<&'static str>>,
}

impl RouteRegistry {
    fn insert(&mut self, method: &'static str, path: &str) -> Result<(), BuildError> {
        validate_route(method, path)?;
        if let Some(methods) = self.methods_by_path.get_mut(path) {
            if methods.insert(method) {
                return Ok(());
            }
            let detail =
                if RESERVED_FRAMEWORK_ROUTES
                    .iter()
                    .any(|(reserved_method, reserved_path)| {
                        *reserved_method == method && *reserved_path == path
                    })
                {
                    " (框架保留路由,Action 不可占用)".to_string()
                } else {
                    String::new()
                };
            return Err(route_conflict(method, path, detail));
        }
        self.matcher
            .insert(path.to_string(), ())
            .map_err(|error| route_conflict(method, path, format!(" ({error})")))?;
        self.methods_by_path
            .insert(path.to_string(), HashSet::from([method]));
        Ok(())
    }
}

fn validate_route(method: &str, path: &str) -> Result<(), BuildError> {
    if !path.starts_with('/') || path.contains(['?', '#']) || path.chars().any(char::is_whitespace)
    {
        return Err(BuildError::InvalidRoute {
            method: method.to_string(),
            path: path.to_string(),
            reason: "path 必须是无 query/fragment/空白的绝对路径".to_string(),
        });
    }
    if path
        .split('/')
        .any(|segment| segment.starts_with([':', '*']))
    {
        return Err(BuildError::InvalidRoute {
            method: method.to_string(),
            path: path.to_string(),
            reason: "path 必须使用 Axum 0.8 的 {name}/{*name} 参数语法".to_string(),
        });
    }
    let mut matcher = matchit::Router::new();
    matcher
        .insert(path.to_string(), ())
        .map_err(|error| BuildError::InvalidRoute {
            method: method.to_string(),
            path: path.to_string(),
            reason: error.to_string(),
        })?;
    Ok(())
}

fn route_conflict(method: &str, path: &str, detail: String) -> BuildError {
    BuildError::RouteConflict {
        method: method.to_string(),
        path: path.to_string(),
        detail,
    }
}

/// 传输层无条件注册的框架路由 `(method, path)`。Action 若声明同一 method+path,
/// `axum::Router::route` 会直接 panic(不返回 Result),故必须在构建期拒绝。
/// 该常量是唯一事实源,`transport/axum.rs` 注册健康端点时必须与本表一致。
pub(crate) const RESERVED_FRAMEWORK_ROUTES: &[(&str, &str)] =
    &[("GET", "/health/live"), ("GET", "/health/ready")];

pub(super) fn validate_routes(addons: &[AddonSpec]) -> Result<(), BuildError> {
    let mut routes = RouteRegistry::default();
    // 框架保留路由先占座:与 axum 的注册顺序一致(框架路由先于 Action),
    // 使冲突在构建期以 RouteConflict 暴露,而不是留到 router() 里由 axum panic。
    for &(method, path) in RESERVED_FRAMEWORK_ROUTES {
        routes.insert(method, path)?;
    }
    for action in addons
        .iter()
        .flat_map(|addon| &addon.modules)
        .flat_map(|module| module.actions())
    {
        routes.insert(action.route.method.as_str(), &action.route.path)?;
    }
    Ok(())
}

pub(super) fn sort_definitions(addons: &mut [AddonSpec]) {
    for addon in addons.iter_mut() {
        addon.dependencies.sort();
        addon
            .modules
            .sort_by(|left, right| left.name.cmp(&right.name));
        for module in &mut addon.modules {
            module.default_permissions.sort();
            if let Some(table) = &mut module.table {
                table
                    .fields
                    .sort_by(|left, right| left.name.cmp(&right.name));
            }
            module.sort_actions();
            for action in module.actions_mut() {
                action.params.sort_by(|left, right| {
                    (left.source, &left.name).cmp(&(right.source, &right.name))
                });
                action.calls.sort();
                action.permissions.sort();
                action.tags.sort();
            }
            module
                .views
                .sort_by(|left, right| left.name.cmp(&right.name));
        }
    }
    addons.sort_by(|left, right| left.name.cmp(&right.name));
}