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
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
//! Quill configuration parsing and normalization.
use std::collections::{BTreeSet, HashMap, HashSet};
use std::error::Error as StdError;
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use crate::error::{Diagnostic, Severity};
use crate::value::QuillValue;
use super::types::{RICHTEXT_INLINE_TOKEN_MSG, UI_ORDER_REMOVED_MSG};
use super::{BodyCardSchema, CardSchema, FieldSchema, FieldType, GroupRegistry, UiCardSchema};
/// Canonical string text for a bare scalar unambiguously representable as a
/// string — a boolean (`true`/`false`) or number (`47`, `1.0`). `None` for
/// `null` (≡ absent), strings (already strings), and collections.
///
/// Shared by [`QuillConfig::coerce_value_strict`] (to adopt the value) and
/// `validation::validate_value` (to accept it), so coercion and validation
/// never disagree about which bare scalars a `string` field accepts.
pub(crate) fn scalar_as_string(value: &serde_json::Value) -> Option<String> {
match value {
serde_json::Value::Bool(b) => Some(b.to_string()),
serde_json::Value::Number(n) => Some(n.to_string()),
_ => None,
}
}
/// Reduce a lenient value to its authored-string form: a bare string, the
/// sole element of a length-1 array when that element is a string (the
/// array-unwrap leniency), or a bare scalar's canonical text (via
/// [`scalar_as_string`]). `None` for anything else (a multi-element array, an
/// object, null), leaving the caller's own fallback to apply.
///
/// Shared by the `String` and `Content` coercion branches, which both reduce
/// a lenient value to a string before adopting it (as the field value itself,
/// or as markdown to import).
fn lenient_string(value: &serde_json::Value) -> Option<String> {
if let Some(s) = value.as_str() {
return Some(s.to_string());
}
if let Some(s) = value
.as_array()
.filter(|a| a.len() == 1)
.and_then(|a| a[0].as_str())
{
return Some(s.to_string());
}
scalar_as_string(value)
}
/// Top-level configuration for a Quillmark project
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct QuillConfig {
/// Quill package name
pub name: String,
/// Human-readable description of the quill itself (parsed from
/// `quill.description`). Distinct from `main.description`, which describes
/// the main card's schema.
pub description: String,
/// The entry-point card schema (parsed from the Quill.yaml `main:` section).
pub main: CardSchema,
/// Named, composable card-kind schemas (parsed from the Quill.yaml
/// `card_kinds:` section). Does not include `main`.
pub card_kinds: Vec<CardSchema>,
/// Backend to use for rendering (e.g., "typst", "html")
pub backend: String,
/// Version of the Quillmark spec
pub version: String,
/// Author of the project
pub author: String,
/// Backend-specific configuration parsed from the top-level YAML section
/// whose key matches `backend` (e.g. `[typst]`, `[html]`).
#[serde(default)]
pub backend_config: HashMap<String, QuillValue>,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct CardSchemaDef {
pub description: Option<String>,
// Declared so `deny_unknown_fields` accepts a `fields:` block on a card.
// Fields are parsed separately via `parse_fields` (per-field diagnostics).
#[allow(dead_code)]
pub fields: Option<serde_json::Map<String, serde_json::Value>>,
pub ui: Option<UiCardSchema>,
pub body: Option<BodyCardSchema>,
}
/// Depth context for [`QuillConfig::validate_field_schema_shape`]. Encodes
/// which shapes are legal at the current nesting level, so the one-level
/// nesting contract is enforced by a single recursive walk.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ShapePosition {
/// A field declared directly on a card: scalar, object, or array.
Top,
/// An array's `items`: scalar or object (typed-table row), not an array.
ArrayItem,
/// An object's property: scalar only.
Leaf,
}
#[derive(Debug, Clone, thiserror::Error, PartialEq, Eq)]
pub enum CoercionError {
#[error("cannot coerce `{value}` to type `{target}` at `{path}`: {reason}")]
Uncoercible {
path: String,
value: String,
target: String,
reason: String,
},
}
/// Write-side leniency mode for [`QuillConfig::conform_value`] — the one axis
/// that separates the render floor's forgiving coercion from a strict typed
/// write.
///
/// The dispatch is shared; only the arms that *defer to the validation layer*
/// or *cross type boundaries* branch on this. See `conform_value`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Leniency {
/// The render floor's forgiving cascade (today's `coerce_value_strict`
/// behavior, unchanged): cross-type scalar coercions apply and a shape a
/// type cannot adopt falls through unchanged for the validation layer to
/// report.
Render,
/// A strict typed write ([`Card::commit_field`](crate::document::Card::commit_field)):
/// value-parsing normalizations still apply (`"3"` → `3`, a bare scalar
/// wraps into a singleton array, richtext markdown imports to content), but
/// cross-type `Boolean`↔`Number` coercions are dropped and every
/// defer-to-validation fall-through becomes a `CoercionError` — so a
/// mismatched value fails at the write, not silently at a later render.
///
/// "Strict" is asymmetric by target, not absolute: `string` and `array` are
/// universal sinks, so a scalar→`string` (`true` → `"true"`) and a
/// scalar→singleton-`array` wrap stay lenient even here (both are lossless,
/// unambiguous, and author-intended); only the lossy/ambiguous crossings —
/// scalar→`object`, `String`→`number`/`bool`, `Boolean`↔`Number` — are
/// rejected. A strict write thus still reshapes toward `string`/`array`
/// while refusing to invent structure or reinterpret a scalar's type.
Write,
}
impl QuillConfig {
/// Returns a named card-kind schema by name.
pub fn card_kind(&self, name: &str) -> Option<&CardSchema> {
self.card_kinds.iter().find(|card| card.name == name)
}
/// Full schema including `ui` hints.
///
/// Describes the user-fillable fields of the main card and each named
/// card kind. The quill reference (constructed as `name@version` from
/// quill metadata) and card-kind discriminators are document-level
/// metadata, not fields, so they do not appear here.
///
/// Key order is the ordering contract: fields, nested properties, and card
/// kinds all emit in declaration order (`preserve_order` end-to-end), so a
/// consumer walking the maps in key order renders the authored layout.
pub fn schema(&self) -> serde_json::Value {
let mut obj = serde_json::Map::new();
let main_value =
serde_json::to_value(&self.main).expect("CardSchema is always serializable");
obj.insert("main".to_string(), main_value);
if !self.card_kinds.is_empty() {
let mut card_kinds = serde_json::Map::new();
for card in &self.card_kinds {
let card_value =
serde_json::to_value(card).expect("CardSchema is always serializable");
card_kinds.insert(card.name.clone(), card_value);
}
obj.insert(
"card_kinds".to_string(),
serde_json::Value::Object(card_kinds),
);
}
serde_json::Value::Object(obj)
}
/// Coerce typed payload fields (IndexMap of user fields only).
pub fn coerce_payload(
&self,
payload: &IndexMap<String, QuillValue>,
) -> Result<IndexMap<String, QuillValue>, CoercionError> {
let mut coerced: IndexMap<String, QuillValue> = IndexMap::new();
for (field_name, field_value) in payload {
if let Some(field_schema) = self.main.fields.get(field_name) {
let path = field_name.as_str();
coerced.insert(
field_name.clone(),
Self::conform_value(field_value, field_schema, path, Leniency::Render)?,
);
} else {
coerced.insert(field_name.clone(), field_value.clone());
}
}
Ok(coerced)
}
/// Coerce typed fields for a single card (IndexMap of user fields only).
///
/// Returns the input unchanged when the card kind is unknown.
pub fn coerce_card(
&self,
card_kind: &str,
fields: &IndexMap<String, QuillValue>,
) -> Result<IndexMap<String, QuillValue>, CoercionError> {
let Some(card_schema) = self.card_kind(card_kind) else {
return Ok(fields.clone());
};
let mut coerced: IndexMap<String, QuillValue> = IndexMap::new();
for (field_name, field_value) in fields {
if let Some(field_schema) = card_schema.fields.get(field_name) {
let path = format!("card_kinds.{card_kind}.{field_name}");
coerced.insert(
field_name.clone(),
Self::conform_value(field_value, field_schema, &path, Leniency::Render)?,
);
} else {
coerced.insert(field_name.clone(), field_value.clone());
}
}
Ok(coerced)
}
/// Validate a typed [`crate::document::Document`] against this configuration.
pub fn validate_document(
&self,
doc: &crate::document::Document,
) -> Result<(), Vec<super::validation::ValidationError>> {
super::validation::validate_typed_document(self, doc)
}
/// The one write-side per-type dispatch: given a value, a field's schema,
/// and a [`Leniency`] mode, validate/normalize the value to the canonical
/// form the type stores. `Render` is the render floor's forgiving coercion
/// (the former `coerce_value_strict`, behavior-preserving); `Write` is the
/// strict typed-write commit driving [`Card::commit_field`](crate::document::Card::commit_field).
///
/// Validation keeps its own read-only dispatch (`validation::validate_value`),
/// synced with this via the shared helpers `scalar_as_string` /
/// `decode_richtext_value`.
pub(crate) fn conform_value(
value: &QuillValue,
field_schema: &super::FieldSchema,
path: &str,
mode: Leniency,
) -> Result<QuillValue, CoercionError> {
use super::FieldType;
let json_value = value.as_json();
// Null ≡ absent: a present-null value (`field:`, `field: null`,
// `field: ~`) carries no data, so it passes through coercion unchanged
// for every type rather than failing as a mismatch. The render floor
// and the validation layer treat it the same as an omitted field. This
// also preserves a `!must_fill` marker riding on `value` (the fill flag
// is never part of the JSON projection).
if json_value.is_null() {
return Ok(value.clone());
}
match field_schema.r#type {
FieldType::Array => {
let arr = if let Some(a) = json_value.as_array() {
a.clone()
} else {
vec![json_value.clone()]
};
// Every array carries an element schema (`items`). Coerce each
// element against it: scalar items (`string[]`, `integer[]`,
// `richtext[]`) coerce element-wise; object items recurse into
// the element's `properties` via the Object branch.
if let Some(items) = &field_schema.items {
let mut out = Vec::with_capacity(arr.len());
for (idx, elem) in arr.iter().enumerate() {
let coerced = Self::conform_value(
&QuillValue::from_json(elem.clone()),
items,
&format!("{path}[{idx}]"),
mode,
)?;
out.push(coerced.into_json());
}
Ok(QuillValue::from_json(serde_json::Value::Array(out)))
} else {
// Defensive fallback: schema-load rejects any array without
// `items` (quill::array_missing_items), so a validated
// config never reaches here — pass the array through as-is.
Ok(QuillValue::from_json(serde_json::Value::Array(arr)))
}
}
FieldType::Boolean => {
if let Some(b) = json_value.as_bool() {
return Ok(QuillValue::from_json(serde_json::Value::Bool(b)));
}
if let Some(s) = json_value.as_str() {
let lower = s.to_lowercase();
if lower == "true" {
return Ok(QuillValue::from_json(serde_json::Value::Bool(true)));
} else if lower == "false" {
return Ok(QuillValue::from_json(serde_json::Value::Bool(false)));
}
}
// Cross-type number→boolean is a render-floor leniency; a strict
// write requires an actual boolean or its `"true"`/`"false"` text.
if mode == Leniency::Render {
if let Some(n) = json_value.as_i64() {
return Ok(QuillValue::from_json(serde_json::Value::Bool(n != 0)));
}
if let Some(n) = json_value.as_f64() {
if n.is_nan() {
return Ok(QuillValue::from_json(serde_json::Value::Bool(false)));
}
return Ok(QuillValue::from_json(serde_json::Value::Bool(
n.abs() > f64::EPSILON,
)));
}
}
Err(CoercionError::Uncoercible {
path: path.to_string(),
value: json_value.to_string(),
target: "boolean".to_string(),
reason: "value is not coercible to boolean".to_string(),
})
}
FieldType::Number => {
if json_value.is_number() {
return Ok(value.clone());
}
if let Some(s) = json_value.as_str() {
if let Ok(i) = s.parse::<i64>() {
return Ok(QuillValue::from_json(serde_json::Number::from(i).into()));
}
if let Ok(f) = s.parse::<f64>() {
if let Some(num) = serde_json::Number::from_f64(f) {
return Ok(QuillValue::from_json(num.into()));
}
}
return Err(CoercionError::Uncoercible {
path: path.to_string(),
value: s.to_string(),
target: "number".to_string(),
reason: "string is not a valid number".to_string(),
});
}
// Cross-type boolean→number is a render-floor leniency only.
if mode == Leniency::Render {
if let Some(b) = json_value.as_bool() {
let n = if b { 1 } else { 0 };
return Ok(QuillValue::from_json(serde_json::Value::Number(
serde_json::Number::from(n),
)));
}
}
Err(CoercionError::Uncoercible {
path: path.to_string(),
value: json_value.to_string(),
target: "number".to_string(),
reason: "value is not coercible to number".to_string(),
})
}
FieldType::Integer => {
if let Some(i) = json_value.as_i64() {
return Ok(QuillValue::from_json(serde_json::Number::from(i).into()));
}
if let Some(u) = json_value.as_u64() {
if let Ok(i) = i64::try_from(u) {
return Ok(QuillValue::from_json(serde_json::Number::from(i).into()));
}
return Err(CoercionError::Uncoercible {
path: path.to_string(),
value: json_value.to_string(),
target: "integer".to_string(),
reason: "integer value exceeds i64 range".to_string(),
});
}
if let Some(s) = json_value.as_str() {
if let Ok(i) = s.parse::<i64>() {
return Ok(QuillValue::from_json(serde_json::Number::from(i).into()));
}
return Err(CoercionError::Uncoercible {
path: path.to_string(),
value: s.to_string(),
target: "integer".to_string(),
reason: "string is not a valid integer".to_string(),
});
}
// Cross-type boolean→integer is a render-floor leniency only.
if mode == Leniency::Render {
if let Some(b) = json_value.as_bool() {
let n = if b { 1 } else { 0 };
return Ok(QuillValue::from_json(serde_json::Value::Number(
serde_json::Number::from(n),
)));
}
}
Err(CoercionError::Uncoercible {
path: path.to_string(),
value: json_value.to_string(),
target: "integer".to_string(),
reason: "value is not coercible to integer".to_string(),
})
}
// Enum is open scalar data drawn from a closed domain — coerced as a
// string here; domain membership is checked at the validation layer
// (an out-of-domain string is a value error, not a type error).
FieldType::String | FieldType::Enum => {
if json_value.is_string() {
return Ok(value.clone());
}
// Gracious leniency: unwrap a length-1 array's sole string
// element, or adopt a bare bool/number's canonical text (an
// author writing `verified: true` for a `string` field), rather
// than reject it. Null is handled above; other collections fall
// through.
if let Some(text) = lenient_string(json_value) {
return Ok(QuillValue::from_json(serde_json::Value::String(text)));
}
// A non-stringifiable shape (object, multi-element array): the
// render floor defers to validation, a strict write fails now.
match mode {
Leniency::Render => Ok(value.clone()),
Leniency::Write => Err(CoercionError::Uncoercible {
path: path.to_string(),
value: json_value.to_string(),
target: field_schema.r#type.as_str().to_string(),
reason: "value is not a string".to_string(),
}),
}
}
FieldType::PlainText { inline } => {
// Plaintext rides the same content as richtext but through the
// *literal* codec: a string is imported verbatim via
// `from_plaintext` (no markdown parsing, no escaping), an
// already-structured content is validated plain. A wire content
// carrying marks or islands is rejected, not silently stripped —
// matching the `inline` precedent and keeping coercion lossless.
let plain_check =
|rt: &quillmark_content::Content| -> Result<(), CoercionError> {
if !rt.is_plain() {
return Err(CoercionError::Uncoercible {
path: path.to_string(),
value: "<plaintext>".to_string(),
target: "plaintext".to_string(),
reason: "plaintext carries no marks, islands, or block \
formatting (lists, quotes, headings)"
.to_string(),
});
}
if inline && !rt.is_inline() {
return Err(CoercionError::Uncoercible {
path: path.to_string(),
value: "<plaintext>".to_string(),
target: "plaintext(inline)".to_string(),
reason: "plaintext(inline) requires a single line".to_string(),
});
}
Ok(())
};
if json_value.is_object() {
let rt = quillmark_content::serial::from_canonical_value(json_value).map_err(
|e| CoercionError::Uncoercible {
path: path.to_string(),
value: "<object>".to_string(),
target: "plaintext".to_string(),
reason: format!("not a valid richtext content: {e}"),
},
)?;
plain_check(&rt)?;
return Ok(QuillValue::from_json(
quillmark_content::serial::to_canonical_value(&rt),
));
}
// Reduce to the authored literal string via the shared leniency
// cascade, then import verbatim.
let Some(text) = lenient_string(json_value) else {
return match mode {
Leniency::Render => Ok(value.clone()),
Leniency::Write => Err(CoercionError::Uncoercible {
path: path.to_string(),
value: json_value.to_string(),
target: "plaintext".to_string(),
reason: "value is not a plaintext string or content".to_string(),
}),
};
};
let rt = quillmark_content::from_plaintext(&text);
plain_check(&rt)?;
Ok(QuillValue::from_json(
quillmark_content::serial::to_canonical_value(&rt),
))
}
FieldType::RichText { inline } => {
// The seam carries the content, so coercion commits the content
// form: an already-structured value (editor / re-render) is
// validated and re-canonicalized; an authored markdown string is
// imported. Determinism is inherited from `import` being pure.
// An `inline` field additionally requires the resulting content to
// be single-`Para` (`richtext(inline)`): editors mount a one-line
// surface, so multi-block content is a coercion error here, in
// lockstep with the validation-layer `richtext::not_inline` check.
//
// This is the deliberately-lenient sibling of
// `document::decode_richtext_value` (used by the strict wire /
// literal / validation sites): the string branch below reduces a
// bare scalar or length-1 array to text before importing, which
// the strict decoder must not do, so it stays open-coded here.
let inline_check =
|rt: &quillmark_content::Content| -> Result<(), CoercionError> {
if inline && !rt.is_inline() {
return Err(CoercionError::Uncoercible {
path: path.to_string(),
value: "<richtext>".to_string(),
target: "richtext(inline)".to_string(),
reason: "richtext(inline) requires a single paragraph line \
with no list/quote container and no islands"
.to_string(),
});
}
Ok(())
};
// A strict write uses `decode_richtext_value` semantics — a
// canonical content object or a markdown string, nothing else. No
// scalar→string reduction (the render floor's lenient cascade
// below): a bare scalar for a richtext field fails the write. The
// messages mirror `Card::commit_field`'s richtext error variants,
// which the bindings key on.
if mode == Leniency::Write {
let content = match crate::document::decode_richtext_value(json_value) {
Some(result) => result.map_err(|e| CoercionError::Uncoercible {
path: path.to_string(),
value: "<richtext>".to_string(),
target: "richtext".to_string(),
reason: e.into_message(),
})?,
None => {
return Err(CoercionError::Uncoercible {
path: path.to_string(),
value: json_value.to_string(),
target: "richtext".to_string(),
reason: format!(
"expected a richtext content object or a markdown string, got {}",
match json_value {
serde_json::Value::Bool(_) => "a boolean",
serde_json::Value::Number(_) => "a number",
serde_json::Value::Array(_) => "an array",
_ => "an unsupported value",
}
),
})
}
};
inline_check(&content)?;
return Ok(QuillValue::from_json(
quillmark_content::serial::to_canonical_value(&content),
));
}
if json_value.is_object() {
let rt = quillmark_content::serial::from_canonical_value(json_value).map_err(
|e| CoercionError::Uncoercible {
path: path.to_string(),
value: "<object>".to_string(),
target: "richtext".to_string(),
reason: format!("not a valid richtext content: {e}"),
},
)?;
inline_check(&rt)?;
return Ok(QuillValue::from_json(
quillmark_content::serial::to_canonical_value(&rt),
));
}
// Reduce to the authored markdown string via the shared
// leniency cascade (bare string, length-1 array unwrap, or bare
// scalar), then import.
let Some(markdown) = lenient_string(json_value) else {
// A shape that is neither content nor stringifiable (e.g. a
// multi-element array): leave it for the validation layer to
// report, matching the String branch's fall-through.
return Ok(value.clone());
};
let rt = quillmark_content::import::from_markdown(&markdown).map_err(|e| {
CoercionError::Uncoercible {
path: path.to_string(),
value: markdown.clone(),
target: "richtext".to_string(),
reason: format!("markdown import failed: {e}"),
}
})?;
inline_check(&rt)?;
Ok(QuillValue::from_json(
quillmark_content::serial::to_canonical_value(&rt),
))
}
FieldType::Date | FieldType::DateTime => {
if json_value.is_null() {
return Ok(QuillValue::from_json(serde_json::Value::Null));
}
let text = if let Some(s) = json_value.as_str() {
if s.is_empty() {
return Ok(QuillValue::from_json(serde_json::Value::Null));
}
s.to_string()
} else if let Some(arr) = json_value.as_array() {
if arr.len() == 1 {
if let Some(s) = arr[0].as_str() {
s.to_string()
} else {
return Err(CoercionError::Uncoercible {
path: path.to_string(),
value: json_value.to_string(),
target: field_schema.r#type.as_str().to_string(),
reason: "value must be a string".to_string(),
});
}
} else {
return Err(CoercionError::Uncoercible {
path: path.to_string(),
value: json_value.to_string(),
target: field_schema.r#type.as_str().to_string(),
reason: "value must be a single string".to_string(),
});
}
} else {
return Err(CoercionError::Uncoercible {
path: path.to_string(),
value: json_value.to_string(),
target: field_schema.r#type.as_str().to_string(),
reason: "value must be a string".to_string(),
});
};
// The two date types share extraction and verbatim storage;
// only the grammar differs. A `date` rejects any time component,
// a `datetime` rejects offsets/space/fraction/bare-date — neither
// truncates, so the stored string is exactly the authored one.
let (valid, reason) = match field_schema.r#type {
FieldType::Date => {
(super::formats::is_valid_date(&text), "invalid date format")
}
_ => (
super::formats::is_valid_datetime(&text),
"invalid datetime format",
),
};
if valid {
Ok(QuillValue::from_json(serde_json::Value::String(text)))
} else {
Err(CoercionError::Uncoercible {
path: path.to_string(),
value: text,
target: field_schema.r#type.as_str().to_string(),
reason: reason.to_string(),
})
}
}
FieldType::Object => {
if let Some(obj) = json_value.as_object() {
if let Some(props) = &field_schema.properties {
let coerced_obj = Self::coerce_object_props(obj, props, path, mode)?;
Ok(QuillValue::from_json(serde_json::Value::Object(
coerced_obj,
)))
} else {
Ok(value.clone())
}
} else {
// A non-object value: the render floor defers to validation,
// a strict write fails now.
match mode {
Leniency::Render => Ok(value.clone()),
Leniency::Write => Err(CoercionError::Uncoercible {
path: path.to_string(),
value: json_value.to_string(),
target: "object".to_string(),
reason: "value is not an object".to_string(),
}),
}
}
}
}
}
/// Walk `obj`'s keys, coercing any that match `props` against the matching
/// schema and copying any others through verbatim. `parent_path` is the
/// breadcrumb for the enclosing scope (e.g. `"foo[3]"` or `"foo"`); each
/// child's path is `"{parent_path}.{k}"`.
fn coerce_object_props(
obj: &serde_json::Map<String, serde_json::Value>,
props: &IndexMap<String, Box<super::FieldSchema>>,
parent_path: &str,
mode: Leniency,
) -> Result<serde_json::Map<String, serde_json::Value>, CoercionError> {
let mut out = serde_json::Map::new();
for (k, v) in obj {
if let Some(prop_schema) = props.get(k) {
let child_path = format!("{parent_path}.{k}");
out.insert(
k.clone(),
Self::conform_value(
&QuillValue::from_json(v.clone()),
prop_schema,
&child_path,
mode,
)?
.into_json(),
);
} else {
out.insert(k.clone(), v.clone());
}
}
Ok(out)
}
/// Recursively validate a field's structural shape, enforcing the
/// one-level nesting contract in a single pass. The `position` records
/// what shapes are legal at the current depth:
///
/// - [`ShapePosition::Top`] — a field declared directly on a card: scalar,
/// `object` (typed dictionary), or `array` (primitive list or typed
/// table).
/// - [`ShapePosition::ArrayItem`] — an array's `items`: a scalar or an
/// `object` (the typed-table row), but **not** another array.
/// - [`ShapePosition::Leaf`] — an object's property (whether a top-level
/// typed dictionary or a typed-table row): scalar only. No deeper
/// containers, so `array<object<array>>` and `object<array>` are
/// rejected here.
///
/// Returns the first violation as a ready-to-push [`Diagnostic`] whose
/// message names `owner` (the field-name path, e.g. `rows[].tags`), or
/// `None` when the shape is valid.
fn validate_field_schema_shape(
schema: &FieldSchema,
owner: &str,
position: ShapePosition,
) -> Option<Diagnostic> {
let err = |code: &str, message: String| {
Some(Diagnostic::new(Severity::Error, message).with_code(code.to_string()))
};
// `items` is only meaningful on arrays; `properties` only on objects.
if schema.r#type != FieldType::Array && schema.items.is_some() {
return err(
"quill::items_not_supported",
format!(
"Field '{owner}' declares 'items' but is not type: array. \
'items' (the element schema) is only valid on array fields."
),
);
}
// `inline` on a non-richtext field is rejected earlier and once, when
// `from_quill_value` folds the wire key into the `FieldType` enum
// (`resolve_richtext_inline`); no second check belongs here.
// `ui.group` clusters card-level fields only — the blueprint's grouping
// pass never descends into object properties or array items, so a nested
// `group` is an inert knob. Reject it rather than let it silently do
// nothing, the same dead-knob class this walk exists to catch.
if position != ShapePosition::Top
&& schema.ui.as_ref().and_then(|u| u.group.as_ref()).is_some()
{
return err(
"quill::nested_group_not_supported",
format!(
"Field '{owner}' sets ui.group in a nested position. Grouping applies \
only to card-level fields; an object property or array item cannot \
join a group."
),
);
}
match schema.r#type {
FieldType::Object => {
// An object nested inside another object (a Leaf position) is
// the classic "nested type: object" rejection.
if position == ShapePosition::Leaf {
return err(
"quill::nested_object_not_supported",
format!(
"Field '{owner}' uses a nested type: object, which is not supported. \
An object's properties may only be scalars."
),
);
}
let Some(props) = &schema.properties else {
return err(
"quill::object_missing_properties",
format!(
"Field '{owner}' has type: object but no properties defined. \
Declare a properties map, or use type: array with \
items: {{ type: object, properties: … }} for a list of objects."
),
);
};
if props.is_empty() {
return err(
"quill::object_empty_properties",
format!(
"Field '{owner}' has type: object with an empty properties map. \
Declare at least one property, or remove the field entirely."
),
);
}
// Object properties are leaves — scalars only.
props.iter().find_map(|(name, prop)| {
Self::validate_field_schema_shape(
prop,
&format!("{owner}.{name}"),
ShapePosition::Leaf,
)
})
}
FieldType::Array => {
// An array may sit at the top level only; an array element may
// not itself be an array, and neither may an object property.
if position != ShapePosition::Top {
return err(
"quill::nested_array_not_supported",
format!(
"Field '{owner}' declares a nested array, which is not supported. \
Array elements must be scalars or objects, and object properties \
may only be scalars."
),
);
}
if schema.properties.is_some() {
return err(
"quill::array_properties_not_supported",
format!(
"Field '{owner}' is type: array with a bare 'properties' map. \
Declare the element type under 'items' instead — for a list \
of objects use items: {{ type: object, properties: … }}."
),
);
}
let Some(items) = &schema.items else {
return err(
"quill::array_missing_items",
format!(
"Field '{owner}' has type: array but no 'items' element schema. \
Declare the element type, e.g. items: {{ type: string }} \
for a list of strings or items: {{ type: object, \
properties: … }} for a list of objects."
),
);
};
Self::validate_field_schema_shape(
items,
&format!("{owner}[]"),
ShapePosition::ArrayItem,
)
}
// Scalars are leaves; nothing further to validate.
_ => None,
}
}
/// Reject multi-line descriptions. Single-line is required so the leading
/// `# <description>` blueprint slot stays one line and the field-comment
/// stack remains parseable for LLM consumers.
fn validate_description_singleline(
desc: Option<&str>,
owner_label: &str,
errors: &mut Vec<Diagnostic>,
) {
if let Some(d) = desc {
if d.contains('\n') {
errors.push(
Diagnostic::new(
Severity::Error,
format!(
"{} description must be a single line; multi-line \
descriptions are not allowed.",
owner_label
),
)
.with_code("quill::description_multiline".to_string()),
);
}
}
}
/// Reject `>`, `;`, `|` in enum literals. These characters are reserved by
/// the blueprint inline annotation grammar (`<format>` close, role
/// separator, enum value separator) and have no escape syntax.
fn validate_enum_literals(
field: &FieldSchema,
owner_label: &str,
errors: &mut Vec<Diagnostic>,
) {
if let Some(values) = &field.enum_values {
for v in values {
if v.contains('>') || v.contains(';') || v.contains('|') {
errors.push(
Diagnostic::new(
Severity::Error,
format!(
"{} enum value '{}' contains a reserved character \
('>', ';', or '|') that conflicts with the \
blueprint inline annotation grammar.",
owner_label, v
),
)
.with_code("quill::format_literal_reserved_char".to_string()),
);
}
}
}
}
/// Recursively validate field-level blueprint constraints across the field,
/// any nested object properties, and an array's element schema (`items`).
fn validate_field_blueprint_constraints(
schema: &FieldSchema,
owner_label: &str,
errors: &mut Vec<Diagnostic>,
) {
Self::validate_description_singleline(schema.description.as_deref(), owner_label, errors);
Self::validate_enum_literals(schema, owner_label, errors);
if let Some(v) = &schema.example {
Self::validate_schema_slot("example", v, schema, owner_label, errors);
}
if let Some(v) = &schema.default {
Self::validate_schema_slot("default", v, schema, owner_label, errors);
}
if let Some(props) = &schema.properties {
for (name, prop) in props {
let nested = format!("{}.{}", owner_label, name);
Self::validate_field_blueprint_constraints(prop, &nested, errors);
}
}
if let Some(items) = &schema.items {
let nested = format!("{}[]", owner_label);
Self::validate_field_blueprint_constraints(items, &nested, errors);
}
}
/// Validate a card's group registry and every card-level field's `ui.group`
/// reference against it. Nested `ui.group` is already rejected upstream by
/// [`validate_field_schema_shape`](Self::validate_field_schema_shape), so
/// only card-level fields are considered here.
///
/// With a registry present, `ui.group` is a *reference*: registry ids carry
/// the same snake_case discipline as field keys and must be unique, and a
/// reference to an id the registry does not declare is `quill::unknown_group`
/// (the "no mixing implicit and declared" rule falls out of this — with a
/// registry there is no implicit fallback). With no registry, each `ui.group`
/// is a deprecated implicit group (label-as-identity, today's semantics
/// untouched) and the card earns one `quill::implicit_group` warning.
fn validate_card_groups(
label: &str,
card: &CardSchema,
errors: &mut Vec<Diagnostic>,
warnings: &mut Vec<Diagnostic>,
) {
let referenced: Vec<&str> = card
.fields
.values()
.filter_map(|f| f.ui.as_ref().and_then(|u| u.group.as_deref()))
.collect();
match card.ui.as_ref().and_then(|u| u.groups.as_ref()) {
Some(GroupRegistry(groups)) => {
let mut ids: HashSet<&str> = HashSet::new();
for g in groups {
if !Self::is_snake_case_identifier(&g.id) {
errors.push(
Diagnostic::new(
Severity::Error,
format!(
"{label} group id '{}' must be snake_case (lowercase letters, \
digits, and underscores only); the display label goes in \
'title:'.",
g.id
),
)
.with_code("quill::invalid_group_id".to_string()),
);
}
// Insert regardless of snake_case validity so a reference to
// an ill-named id resolves — one diagnostic, not a cascade.
if !ids.insert(g.id.as_str()) {
errors.push(
Diagnostic::new(
Severity::Error,
format!("{label} declares group '{}' more than once.", g.id),
)
.with_code("quill::duplicate_group".to_string()),
);
}
}
// One diagnostic per distinct unresolved reference.
let unresolved: BTreeSet<&str> =
referenced.iter().copied().filter(|g| !ids.contains(g)).collect();
for group in unresolved {
errors.push(
Diagnostic::new(
Severity::Error,
format!(
"{label} field references group '{group}', which is not declared \
in ui.groups. Add it to the registry, or fix the reference."
),
)
.with_code("quill::unknown_group".to_string()),
);
}
}
None => {
if !referenced.is_empty() {
warnings.push(
Diagnostic::new(
Severity::Warning,
format!(
"{label} uses ui.group without a ui.groups registry (implicit \
groups). Declare the groups under the card's ui.groups; implicit \
groups are deprecated and become an error in a future release."
),
)
.with_code("quill::implicit_group".to_string())
.with_hint(
"Add a ui.groups registry listing each group id, and reference the id \
from each field's ui.group."
.to_string(),
),
);
}
}
}
}
/// Validate a single `example:` or `default:` literal against the declared
/// schema, pushing `quill::*`-namespaced [`Diagnostic`]s for any violations.
///
/// Delegates type/enum/format/recursion checking to
/// [`super::validation::validate_schema_literal`] — the shared conformance
/// primitive — then converts each [`ValidationError`] into a Quill.yaml
/// load-time diagnostic with the appropriate `quill::{slot}_*` error code
/// and author-friendly hint.
fn validate_schema_slot(
slot: &str,
value: &QuillValue,
schema: &FieldSchema,
owner_label: &str,
errors: &mut Vec<Diagnostic>,
) {
use super::validation::{validate_schema_literal, ValidationError};
for violation in validate_schema_literal(schema, value, owner_label) {
let diag = match &violation {
ValidationError::TypeMismatch {
path,
actual,
source_token,
..
} => {
// Use the field's declared `type:` verbatim (`datetime`,
// `markdown`, …); the validator's `expected` collapses those
// to `string`, which would misreport the author's intent.
let declared = schema.r#type.as_str();
// validation.rs uses "number" for all non-integer JSON numbers;
// display as "float" so messages match the YAML author's mental model.
let display_actual = if actual == "number" {
"float"
} else {
actual.as_str()
};
// Show the offending value's content. A top-level mismatch
// renders the original literal (so arrays/objects show their
// contents); a nested mismatch is always a scalar, whose
// verbatim token is already the full value.
let preview = if path.as_str() == owner_label {
Self::literal_preview(value.as_json())
} else {
Self::truncate_preview(source_token)
};
let hint = if actual == "number" || actual == "integer" {
let schema_type = if actual == "integer" {
"integer"
} else {
"number"
};
format!(
"Quote the {slot} as \"{raw}\" if the value is intentionally a \
string, or change the field type to '{schema_type}'.",
raw = source_token.trim_matches('"'),
)
} else if actual == "string" {
format!(
"Remove the quotes around the {slot} value to keep it a {declared}."
)
} else {
format!(
"Make the {slot} value a {declared}, or change the field type to match."
)
};
Diagnostic::new(
Severity::Error,
format!(
"{owner_label} declares type '{declared}' but {slot} is {display_actual} ({preview})."
),
)
.with_code(format!("quill::{slot}_type_mismatch"))
.with_hint(hint)
}
ValidationError::EnumViolation {
path,
value: val,
allowed,
} => {
let values_str = allowed
.iter()
.map(|v| format!("\"{}\"", v))
.collect::<Vec<_>>()
.join(", ");
Diagnostic::new(
Severity::Error,
format!(
"{path} {slot} \"{val}\" is not one of the declared enum values [{values_str}]."
),
)
.with_code(format!("quill::{slot}_not_in_enum"))
.with_hint(format!("Set the {slot} to one of: {values_str}."))
}
ValidationError::FormatViolation { path, format } => Diagnostic::new(
Severity::Error,
format!("{path} {slot} has an invalid {format} format."),
)
.with_code(format!("quill::{slot}_format_violation"))
.with_hint(format!("Provide a valid {format} value for the {slot}.")),
// UnknownCard, BodyDisabled do not apply to schema literals.
_ => continue,
};
errors.push(diag);
}
}
/// Render a short, quoted preview of a value for an error message. Strings
/// are quoted; everything else uses its JSON form. Long renderings are
/// truncated (see [`Self::truncate_preview`]).
fn literal_preview(value: &serde_json::Value) -> String {
let raw = match value {
serde_json::Value::String(s) => format!("\"{}\"", s),
other => other.to_string(),
};
Self::truncate_preview(&raw)
}
/// Truncate an already-rendered preview token to at most 60 characters,
/// appending an ellipsis when it overflows.
fn truncate_preview(raw: &str) -> String {
const MAX: usize = 60;
if raw.chars().count() > MAX {
let truncated: String = raw.chars().take(MAX).collect();
format!("{}…", truncated)
} else {
raw.to_string()
}
}
/// Parse fields from a JSON map into `FieldSchema`s (both `main.fields` and
/// a card kind's `fields`). Declaration order rides the map itself: the
/// source map preserves key order (serde_json's `preserve_order`) and the
/// returned `IndexMap` keeps insertion order, so no ordering pass runs.
/// `context` labels error messages (e.g. `"field schema"`,
/// `"card_kind 'note' field"`).
fn parse_fields(
fields_map: &serde_json::Map<String, serde_json::Value>,
context: &str,
errors: &mut Vec<Diagnostic>,
) -> IndexMap<String, FieldSchema> {
let mut fields = IndexMap::new();
for (field_name, field_value) in fields_map {
if !Self::is_snake_case_identifier(field_name) {
errors.push(
Diagnostic::new(
Severity::Error,
format!(
"Invalid {} '{}': field keys must be snake_case \
(lowercase letters, digits, and underscores only), \
and capitalized field keys are reserved.",
context, field_name
),
)
.with_code("quill::invalid_field_name".to_string()),
);
continue;
}
let quill_value = QuillValue::from_json(field_value.clone());
match FieldSchema::from_quill_value(field_name.clone(), &quill_value) {
Ok(schema) => {
// One recursive pass enforces the whole shape contract:
// containers carry the right child schema (`object` →
// `properties`, `array` → `items`), and nesting stops after
// one structural level (a typed table is the deepest shape).
if let Some(diag) =
Self::validate_field_schema_shape(&schema, field_name, ShapePosition::Top)
{
errors.push(diag);
continue;
}
let owner = format!("{} '{}'", context, field_name);
Self::validate_field_blueprint_constraints(&schema, &owner, errors);
fields.insert(field_name.clone(), schema);
}
Err(e) => {
let hint = Self::field_parse_hint(field_value);
let mut diag = Diagnostic::new(
Severity::Error,
format!("Failed to parse {} '{}': {}", context, field_name, e),
)
.with_code("quill::field_parse_error".to_string());
if let Some(h) = hint {
diag = diag.with_hint(h);
}
errors.push(diag);
}
}
}
fields
}
/// Produce an actionable hint for common field schema mistakes based on the raw value.
fn field_parse_hint(field_value: &serde_json::Value) -> Option<String> {
if let Some(obj) = field_value.as_object() {
if obj.contains_key("title") {
return Some(
"'title' is not a valid field key; use 'description' instead.".to_string(),
);
}
if obj
.get("ui")
.and_then(|u| u.as_object())
.is_some_and(|u| u.contains_key("order"))
{
return Some(format!("{UI_ORDER_REMOVED_MSG}."));
}
if obj.get("type").and_then(|v| v.as_str()) == Some("richtext(inline)") {
return Some(format!("{RICHTEXT_INLINE_TOKEN_MSG}."));
}
if obj.get("type").and_then(|v| v.as_str()) == Some("markdown") {
return Some(
"'markdown' is no longer a field type; use type: richtext (block) \
or type: richtext with inline: true."
.to_string(),
);
}
}
None
}
fn is_snake_case_identifier(name: &str) -> bool {
let mut chars = name.chars();
match chars.next() {
Some(c) if c.is_ascii_lowercase() => {}
_ => return false,
}
chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
}
fn is_valid_quill_name(name: &str) -> bool {
name == "__default__" || Self::is_snake_case_identifier(name)
}
/// Parse QuillConfig from YAML content
pub fn from_yaml(yaml_content: &str) -> Result<Self, Box<dyn StdError + Send + Sync>> {
match Self::from_yaml_with_warnings(yaml_content) {
Ok((config, _warnings)) => Ok(config),
Err(diags) => {
let msg = diags
.iter()
.map(|d| d.fmt_pretty())
.collect::<Vec<_>>()
.join("\n");
Err(msg.into())
}
}
}
/// Parse QuillConfig from YAML content while collecting non-fatal warnings.
///
/// Returns `Ok((config, warnings))` on success, or `Err(errors)` containing all
/// parse/validation errors when the config is invalid. Errors are always collected
/// exhaustively — callers see every problem, not just the first.
pub fn from_yaml_with_warnings(
yaml_content: &str,
) -> Result<(Self, Vec<Diagnostic>), Vec<Diagnostic>> {
let mut warnings: Vec<Diagnostic> = Vec::new();
let mut errors: Vec<Diagnostic> = Vec::new();
// Parse YAML into serde_json::Value via serde_saphyr. The depth budget
// bounds nesting so an untrusted Quill.yaml cannot overflow the stack.
// Note: serde_json with "preserve_order" feature is required for this to work as expected
let quill_yaml_val: serde_json::Value = match serde_saphyr::from_str_with_options(
yaml_content,
crate::document::limits::yaml_parse_options(),
) {
Ok(v) => v,
Err(e) => {
return Err(vec![Diagnostic::new(
Severity::Error,
format!("Failed to parse Quill.yaml: {}", e),
)
.with_code("quill::yaml_parse_error".to_string())]);
}
};
// Extract [quill] section (required) — fail immediately if absent since all
// subsequent validation depends on it.
let quill_section = match quill_yaml_val.get("quill") {
Some(v) => v,
None => {
return Err(vec![Diagnostic::new(
Severity::Error,
"Missing required 'quill' section in Quill.yaml".to_string(),
)
.with_code("quill::missing_section".to_string())
.with_hint(
"Add a 'quill:' section with name, backend, version, and description."
.to_string(),
)]);
}
};
// Validate that no unknown keys appear in the [quill] section.
const KNOWN_QUILL_KEYS: &[&str] =
&["name", "backend", "description", "version", "author", "ui"];
if let Some(quill_obj) = quill_section.as_object() {
for key in quill_obj.keys() {
if !KNOWN_QUILL_KEYS.contains(&key.as_str()) {
errors.push(
Diagnostic::new(
Severity::Error,
format!("Unknown key '{}' in 'quill:' section", key),
)
.with_code("quill::unknown_key".to_string())
.with_hint(format!("Valid keys are: {}", KNOWN_QUILL_KEYS.join(", "))),
);
}
}
}
// Extract required fields — collect all missing-field errors before returning.
let name = match quill_section.get("name").and_then(|v| v.as_str()) {
Some(n) => {
if !Self::is_valid_quill_name(n) {
errors.push(
Diagnostic::new(
Severity::Error,
format!(
"Invalid Quill name '{}': quill.name must be snake_case \
(lowercase letters, digits, and underscores only).",
n
),
)
.with_code("quill::invalid_name".to_string())
.with_hint(format!(
"Rename '{}' to '{}'",
n,
n.to_lowercase().replace('-', "_")
)),
);
}
n.to_string()
}
None => {
errors.push(
Diagnostic::new(
Severity::Error,
"Missing required 'name' field in 'quill' section".to_string(),
)
.with_code("quill::missing_name".to_string())
.with_hint(
"Add 'name: your_quill_name' under the 'quill:' section.".to_string(),
),
);
String::new()
}
};
let backend = match quill_section.get("backend").and_then(|v| v.as_str()) {
Some(b) => b.to_string(),
None => {
errors.push(
Diagnostic::new(
Severity::Error,
"Missing required 'backend' field in 'quill' section".to_string(),
)
.with_code("quill::missing_backend".to_string())
.with_hint("Add 'backend: typst' (or another supported backend).".to_string()),
);
String::new()
}
};
let description = match quill_section.get("description").and_then(|v| v.as_str()) {
Some(d) if !d.trim().is_empty() => {
Self::validate_description_singleline(Some(d), "quill", &mut errors);
d.to_string()
}
Some(_) => {
errors.push(
Diagnostic::new(
Severity::Error,
"'description' field in 'quill' section cannot be empty".to_string(),
)
.with_code("quill::empty_description".to_string()),
);
String::new()
}
None => {
errors.push(
Diagnostic::new(
Severity::Error,
"Missing required 'description' field in 'quill' section".to_string(),
)
.with_code("quill::missing_description".to_string())
.with_hint("Add a brief 'description:' of what this quill is for.".to_string()),
);
String::new()
}
};
// Extract the required `version` field.
let version = match quill_section.get("version") {
Some(version_val) => {
// Handle version as string or number (YAML might parse 1.0 as number)
let raw = if let Some(s) = version_val.as_str() {
s.to_string()
} else if let Some(n) = version_val.as_f64() {
n.to_string()
} else {
errors.push(
Diagnostic::new(
Severity::Error,
"Invalid 'version' field format".to_string(),
)
.with_code("quill::invalid_version".to_string())
.with_hint("Use semver format: '1.0' or '1.0.0'.".to_string()),
);
String::new()
};
if !raw.is_empty() {
use std::str::FromStr;
if let Err(e) = crate::version::Version::from_str(&raw) {
errors.push(
Diagnostic::new(
Severity::Error,
format!("Invalid version '{}': {}", raw, e),
)
.with_code("quill::invalid_version".to_string())
.with_hint("Use semver format: '1.0' or '1.0.0'.".to_string()),
);
}
}
raw
}
None => {
errors.push(
Diagnostic::new(
Severity::Error,
"Missing required 'version' field in 'quill' section".to_string(),
)
.with_code("quill::missing_version".to_string())
.with_hint("Add 'version: 1.0' under the 'quill:' section.".to_string()),
);
String::new()
}
};
let author = quill_section
.get("author")
.and_then(|v| v.as_str())
.map(|s| s.to_string())
.unwrap_or_else(|| "Unknown".to_string());
let ui_section: Option<UiCardSchema> = match quill_section.get("ui").cloned() {
None => None,
Some(v) => match serde_json::from_value::<UiCardSchema>(v) {
Ok(parsed) => Some(parsed),
Err(e) => {
errors.push(
Diagnostic::new(
Severity::Error,
format!("Invalid 'quill.ui' block: {}", e),
)
.with_code("quill::invalid_ui".to_string())
.with_hint("Valid keys under 'ui' are: title, groups.".to_string()),
);
None
}
},
};
// Extract optional backend-specific section (keyed by `quill.backend`).
let mut backend_config = HashMap::new();
if !backend.is_empty() {
if let Some(section_val) = quill_yaml_val.get(&backend) {
if let Some(table) = section_val.as_object() {
for (key, value) in table {
backend_config.insert(key.clone(), QuillValue::from_json(value.clone()));
}
}
}
}
// Reject unknown top-level sections. Known sections are: quill, main, card_kinds,
// and the backend name (e.g. typst). Everything else is a mistake. `fields` gets
// a targeted hint since it's the most common shape mistake.
if let Some(top_obj) = quill_yaml_val.as_object() {
for key in top_obj.keys() {
let is_known = key == "quill"
|| key == "main"
|| key == "card_kinds"
|| (!backend.is_empty() && key == &backend);
if is_known {
continue;
}
let mut diag = Diagnostic::new(
Severity::Error,
format!("Unknown top-level section '{}'", key),
)
.with_code("quill::unknown_section".to_string());
diag = if key == "fields" {
diag.with_hint(
"Root-level `fields` is not supported; use `main.fields` instead."
.to_string(),
)
} else {
diag.with_hint(format!(
"Valid top-level sections are: quill, main, card_kinds{}",
if backend.is_empty() {
String::new()
} else {
format!(", {}", backend)
}
))
};
errors.push(diag);
}
}
let main_obj_opt = quill_yaml_val.get("main").and_then(|v| v.as_object());
// Extract main.fields (optional)
let fields = if let Some(fields_map) = main_obj_opt
.and_then(|main_obj| main_obj.get("fields"))
.and_then(|v| v.as_object())
{
Self::parse_fields(fields_map, "field schema", &mut errors)
} else {
IndexMap::new()
};
// Extract main.ui (optional). Fail loudly on malformed UI metadata rather
// than silently dropping it — see `quill.ui` handling above.
let main_ui: Option<UiCardSchema> = match main_obj_opt
.and_then(|main_obj| main_obj.get("ui"))
.cloned()
{
None => None,
Some(v) => match serde_json::from_value::<UiCardSchema>(v) {
Ok(parsed) => Some(parsed),
Err(e) => {
errors.push(
Diagnostic::new(Severity::Error, format!("Invalid 'main.ui' block: {}", e))
.with_code("quill::invalid_ui".to_string())
.with_hint("Valid keys under 'ui' are: title, groups.".to_string()),
);
None
}
},
};
// Extract main.body (optional). Fail loudly on malformed body metadata.
let main_body: Option<BodyCardSchema> = match main_obj_opt
.and_then(|main_obj| main_obj.get("body"))
.cloned()
{
None => None,
Some(v) => match serde_json::from_value::<BodyCardSchema>(v) {
Ok(parsed) => Some(parsed),
Err(e) => {
errors.push(
Diagnostic::new(
Severity::Error,
format!("Invalid 'main.body' block: {}", e),
)
.with_code("quill::invalid_body".to_string())
.with_hint("Valid keys under 'body' are: enabled, example.".to_string()),
);
None
}
},
};
// Extract main.description (optional, authored under `main:` like any
// other card kind). This is independent of `quill.description`.
let main_description = main_obj_opt
.and_then(|main_obj| main_obj.get("description"))
.and_then(|v| v.as_str())
.map(|s| s.to_string());
Self::validate_description_singleline(main_description.as_deref(), "main", &mut errors);
// The main entry-point card.
let mut main = CardSchema {
name: "main".to_string(),
description: main_description,
fields,
ui: main_ui.or(ui_section),
body: main_body,
};
// Extract [card_kinds] section (optional)
let mut card_kinds: Vec<CardSchema> = Vec::new();
if let Some(card_kinds_val) = quill_yaml_val.get("card_kinds") {
match card_kinds_val.as_object() {
None => {
errors.push(
Diagnostic::new(
Severity::Error,
"'card_kinds' section must be an object (mapping of kind names to schemas)".to_string(),
)
.with_code("quill::invalid_card_kinds".to_string()),
);
}
Some(card_kinds_table) => {
for (card_name, card_value) in card_kinds_table {
if !crate::document::is_valid_kind_name(card_name) {
errors.push(
Diagnostic::new(
Severity::Error,
format!(
"Invalid card-kind name '{}': names must match \
[a-z_][a-z0-9_]* (lowercase letters, digits, and underscores only).",
card_name
),
)
.with_code("quill::invalid_card_name".to_string()),
);
continue;
}
// Parse card basic info using serde
let card_def: CardSchemaDef =
match serde_json::from_value(card_value.clone()) {
Ok(d) => d,
Err(e) => {
errors.push(
Diagnostic::new(
Severity::Error,
format!(
"Failed to parse card_kind '{}': {}",
card_name, e
),
)
.with_code("quill::invalid_card_schema".to_string()),
);
continue;
}
};
// Parse card fields
let card_fields = if let Some(card_fields_table) =
card_value.get("fields").and_then(|v| v.as_object())
{
Self::parse_fields(
card_fields_table,
&format!("card_kind '{}' field", card_name),
&mut errors,
)
} else {
IndexMap::new()
};
Self::validate_description_singleline(
card_def.description.as_deref(),
&format!("card_kind '{}'", card_name),
&mut errors,
);
card_kinds.push(CardSchema {
name: card_name.clone(),
description: card_def.description,
fields: card_fields,
ui: card_def.ui,
body: card_def.body,
});
}
}
}
}
// Warn when `body.example` is set together with `body.enabled: false` —
// the example has no effect since the body editor is disabled.
let warn_example_unused = |label: &str,
body: &Option<BodyCardSchema>|
-> Option<Diagnostic> {
let body = body.as_ref()?;
if body.enabled == Some(false) && body.example.is_some() {
Some(
Diagnostic::new(
Severity::Warning,
format!(
"`{label}.body.example` is set but `{label}.body.enabled` is false; the example will have no effect"
),
)
.with_code("quill::body_example_unused".to_string())
.with_hint(
"Set `body.enabled: true` to surface the example, or remove `body.example`."
.to_string(),
),
)
} else {
None
}
};
if let Some(d) = warn_example_unused("main", &main.body) {
warnings.push(d);
}
for card in &card_kinds {
if let Some(d) = warn_example_unused(&format!("card_kinds.{}", card.name), &card.body) {
warnings.push(d);
}
}
// Validate each card's group registry and its fields' group references.
Self::validate_card_groups("main", &main, &mut errors, &mut warnings);
for card in &card_kinds {
Self::validate_card_groups(
&format!("card_kinds.{}", card.name),
card,
&mut errors,
&mut warnings,
);
}
// Error when `body.example` contains a line that the document parser
// would interpret as a `~~~` card-yaml block opener. Such a line would
// start a new metadata block, corrupting document structure.
let err_example_contains_fence = |label: &str,
body: &Option<BodyCardSchema>|
-> Option<Diagnostic> {
let example = body.as_ref()?.example.as_deref()?;
if example_contains_fence_line(example) {
Some(
Diagnostic::new(
Severity::Error,
format!(
"`{label}.body.example` contains a line that would be parsed as a `~~~` card-yaml block opener; this would corrupt the blueprint"
),
)
.with_code("quill::body_example_contains_fence".to_string())
.with_hint(
"Remove or reword any column-zero line that opens a card-yaml block (`~~~`, a longer tilde run, or `~~~card-yaml`). For a literal fenced code block, use a backtick fence (```).".to_string(),
),
)
} else {
None
}
};
if let Some(d) = err_example_contains_fence("main", &main.body) {
errors.push(d);
}
for card in &card_kinds {
if let Some(d) =
err_example_contains_fence(&format!("card_kinds.{}", card.name), &card.body)
{
errors.push(d);
}
}
// Import every richtext `default` / `example` / `body.example` literal
// once into its canonical-content companion cache — a pure function of the
// Quill.yaml bytes, never serialized. This is where `richtext(inline)`
// violations and malformed richtext literals surface as load errors, and
// where seeding and the render floor later read a pre-validated content
// instead of re-importing the markdown per document.
populate_card_content(&mut main, "main", &mut errors);
for card in &mut card_kinds {
let label = format!("card_kinds.{}", card.name);
populate_card_content(card, &label, &mut errors);
}
if !errors.is_empty() {
return Err(errors);
}
Ok((
QuillConfig {
name,
description,
main,
card_kinds,
backend,
version,
author,
backend_config,
},
warnings,
))
}
}
/// Returns true if any line in `text` would be parsed as a card-yaml block
/// opener by the document parser, which would corrupt the blueprint's document
/// structure when the example is embedded verbatim as body content.
///
/// Delegates to the parser's own opener predicate
/// ([`crate::document::fences::is_card_yaml_opener_line`]) so the guard stays
/// in lock-step with fence detection: a column-zero tilde fence (three or more
/// tildes) whose info string is empty or `card-yaml`. Backtick fences,
/// language-tagged `~~~` fences, and indented fences are ordinary code blocks
/// and are not flagged.
fn example_contains_fence_line(text: &str) -> bool {
text.lines().any(|line| {
let line = line.strip_suffix('\r').unwrap_or(line);
crate::document::fences::is_card_yaml_opener_line(line)
})
}
/// Whether a field's type tree contains any content leaf — the gate for caching
/// a content companion. Both `richtext` and its literal-codec sibling `plaintext`
/// are content leaves; a scalar (`string`, `integer`, `enum`, …) never carries
/// one; an `array<richtext>` or an `object` with a content property does.
fn field_contains_content(field: &FieldSchema) -> bool {
match &field.r#type {
FieldType::RichText { .. } | FieldType::PlainText { .. } => true,
FieldType::Array => field.items.as_deref().is_some_and(field_contains_content),
FieldType::Object => field
.properties
.as_ref()
.is_some_and(|p| p.values().any(|f| field_contains_content(f))),
_ => false,
}
}
/// Populate a field's `default_content` / `example_content` companion caches from
/// its markdown literals. No-op for a non-richtext field; a failed import or a
/// `richtext(inline)` violation is appended to `errors` as a load diagnostic.
fn populate_field_content(field: &mut FieldSchema, owner: &str, errors: &mut Vec<Diagnostic>) {
if !field_contains_content(field) {
return;
}
if let Some(default) = field.default.clone() {
match literal_content(&default, field, &format!("{owner} `default`")) {
Ok(content) => field.default_content = content,
Err(d) => errors.push(d),
}
}
if let Some(example) = field.example.clone() {
match literal_content(&example, field, &format!("{owner} `example`")) {
Ok(content) => field.example_content = content,
Err(d) => errors.push(d),
}
}
}
/// Populate every content companion on a card: each field's
/// `default`/`example`, and the card's `body.example` (block richtext — no
/// inline constraint; skipped when the body is disabled, since its example is
/// inert).
fn populate_card_content(card: &mut CardSchema, label: &str, errors: &mut Vec<Diagnostic>) {
for (name, field) in card.fields.iter_mut() {
populate_field_content(field, &format!("{label} field `{name}`"), errors);
}
let body_enabled = card.body.as_ref().is_none_or(|b| b.enabled != Some(false));
if body_enabled {
if let Some(body) = card.body.as_mut() {
if let Some(example) = body.example.clone() {
match crate::document::import_body(&example) {
Ok(rt) => {
body.example_content = Some(QuillValue::from_json(
quillmark_content::serial::to_canonical_value(&rt),
));
}
Err(e) => errors.push(
Diagnostic::new(
Severity::Error,
format!("Failed to import {label} `body.example`: {e}"),
)
.with_code("quill::richtext_example_import".to_string()),
),
}
}
}
}
}
/// Compute the canonical-content form of a richtext-bearing schema literal
/// (`default` / `example`), importing every markdown leaf once and enforcing
/// `richtext(inline)`. Recurses through `array` / `object` shapes, converting
/// only their richtext leaves and passing other elements through unchanged.
/// `Ok(None)` when the literal carries no importable richtext (a null value, or
/// a field the gate already cleared as non-richtext); `Err` is a load error.
fn literal_content(
value: &QuillValue,
field: &FieldSchema,
label: &str,
) -> Result<Option<QuillValue>, Diagnostic> {
let json = value.as_json();
// Null ≡ absent — no data to import, so no companion is cached.
if json.is_null() {
return Ok(None);
}
match &field.r#type {
FieldType::RichText { inline } => {
let rt = match crate::document::decode_richtext_value(json) {
Some(Ok(rt)) => rt,
Some(Err(e)) => {
let reason = match e {
crate::document::RichtextDecodeError::BadMarkdown(m) => {
format!("markdown import failed: {m}")
}
crate::document::RichtextDecodeError::NotContent(m) => {
format!("not a valid richtext content: {m}")
}
};
return Err(richtext_literal_error(label, &reason));
}
None => {
return Err(richtext_literal_error(
label,
"expected a markdown string (richtext literals are authored as markdown)",
));
}
};
if *inline && !rt.is_inline() {
return Err(richtext_inline_error(label));
}
Ok(Some(QuillValue::from_json(
quillmark_content::serial::to_canonical_value(&rt),
)))
}
FieldType::PlainText { inline } => {
// Plaintext literals are authored as literal strings and imported
// verbatim (never markdown), so the cached content is plain by
// construction; a content-object literal is revalidated. Shares the
// one object-vs-string dispatch with the validation shape check.
let rt = match crate::document::decode_plaintext_value(json) {
Some(Ok(rt)) => rt,
Some(Err(e)) => {
return Err(richtext_literal_error(
label,
&format!("not a valid richtext content: {e}"),
))
}
None => {
return Err(richtext_literal_error(
label,
"expected a plaintext string (plaintext literals are authored as literal text)",
))
}
};
if !rt.is_plain() {
return Err(richtext_literal_error(
label,
"plaintext carries no marks, islands, or block formatting",
));
}
if *inline && !rt.is_inline() {
return Err(richtext_inline_error(label));
}
Ok(Some(QuillValue::from_json(
quillmark_content::serial::to_canonical_value(&rt),
)))
}
FieldType::Array => {
let Some(items) = field.items.as_deref() else {
return Ok(None);
};
if !field_contains_content(items) {
return Ok(None);
}
let arr = json.as_array().cloned().unwrap_or_default();
let mut out = Vec::with_capacity(arr.len());
for (idx, elem) in arr.iter().enumerate() {
let elem_v = QuillValue::from_json(elem.clone());
let content =
literal_content(&elem_v, items, &format!("{label}[{idx}]"))?.unwrap_or(elem_v);
out.push(content.into_json());
}
Ok(Some(QuillValue::from_json(serde_json::Value::Array(out))))
}
FieldType::Object => {
let Some(props) = field.properties.as_ref() else {
return Ok(None);
};
if !props.values().any(|f| field_contains_content(f)) {
return Ok(None);
}
let obj = json.as_object().cloned().unwrap_or_default();
let mut out = serde_json::Map::new();
for (k, v) in &obj {
let converted = match props.get(k) {
Some(pschema) => {
let pv = QuillValue::from_json(v.clone());
literal_content(&pv, pschema, &format!("{label}.{k}"))?
.map(QuillValue::into_json)
.unwrap_or_else(|| v.clone())
}
None => v.clone(),
};
out.insert(k.clone(), converted);
}
Ok(Some(QuillValue::from_json(serde_json::Value::Object(out))))
}
_ => Ok(None),
}
}
/// A load diagnostic for a richtext schema literal that failed to import.
fn richtext_literal_error(label: &str, reason: &str) -> Diagnostic {
Diagnostic::new(
Severity::Error,
format!("Failed to import richtext {label}: {reason}"),
)
.with_code("quill::richtext_example_import".to_string())
}
/// A load diagnostic for a `richtext(inline)` schema literal whose content spans
/// more than a single paragraph.
fn richtext_inline_error(label: &str) -> Diagnostic {
Diagnostic::new(
Severity::Error,
format!(
"richtext(inline) {label} must be a single paragraph (no blank lines, \
headings, lists, quotes, or tables)"
),
)
.with_code("richtext::not_inline".to_string())
.with_hint(
"Reduce the value to one paragraph, or change the field `type:` to `richtext`.".to_string(),
)
}