flm-core 0.7.0

FLM semantic markup framework — core library, built on techy
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
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
//! The feature `compose`: the stages that assemble each output's entry artifact from the
//! output's regions through a **compose template**, a text with named places for those
//! regions, and the service slots of the template engines and of the compose templates.
//!
//! An output region is one named part of an output's entry artifact (the document's
//! content, each piece placed beside it, and on HTML the stylesheets, the scripts, the
//! title and the language), which the backend writes once into the table
//! `flm.output.<backend>.regions` ([`Regions`]). The entry artifact is the artifact that
//! represents the output as a whole: the HTML page, the printed text, the recomposed LaTeX
//! document ([`ArtifactSet`]). The backend's final stage assembles the entry artifact
//! from those regions in a layout of the backend's own ([`crate::core::region`]). The
//! feature `compose` is a second way to assemble them: through the compose template that
//! the settings choose, so that a program chooses what surrounds the document's content.
//!
//! # A host registers the feature
//!
//! The feature is not among the standard features that
//! [`stdlib::add_features`](crate::stdlib::add_features) adds. The
//! composer of an output provides the same capability as the backend's final stage, and
//! a plan chooses between two stages that provide one capability only by a stage the
//! plan request prefers or by a capability marked as the default; with neither, the plan
//! fails ([`PlanError::Contested`](crate::core::plan::PlanError::Contested)). So a host
//! that registers the feature also prefers the composer of each output it renders
//! ([`stage_name`]; [`Overrides::prefer`](crate::core::plan::Overrides::prefer)). A
//! registry without the feature has one stage per output that assembles the entry
//! artifact, the backend's final stage. Where a host registers the feature but the
//! settings switch it off, the host leaves it out of the registry, and the backend's
//! final stage assembles each output.
//!
//! # Template engines and compose templates
//!
//! The feature declares two service slots, to which any feature of any package may
//! contribute. A service slot is the declaration, by the feature that owns an
//! interaction, of a dotted name, the type of the values the slot takes and its arity
//! ([`crate::core::services`]). A feature of another package contributes to them as a
//! peer ([`FeatureBuilder::peer_slot`]), so that its registry still builds where
//! `compose` is switched off.
//!
//! - [`ENGINES_SLOT`] (`flm.compose.engines`) takes the **template engines**, each a
//!   [`TemplateEngine`] with a name. `compose` contributes `content-only`, which places
//!   the content and the pieces with nothing around them ([`engines`]); a host
//!   contributes the engines of the template languages it reads.
//! - [`TEMPLATES_SLOT`] (`flm.compose.templates`) takes the **compose templates**, each a
//!   [`Template`]: its name, the output it serves, its engine, its text, the pieces it
//!   accepts and those it requires, and its own settings with their defaults.
//!   [`Template::from_data`] makes one from a description given as data, whose keys
//!   `name` and `output` give the compose template's name and the output it serves, and
//!   whose key `main` gives the path of the file that holds the compose template's text,
//!   relative to the folder of the description; without `main`, the text is empty.
//!   `compose` contributes none.
//!
//! # The settings of a compose template
//!
//! A compose template's own settings are written under the render option
//! `template_config`, at `template_config.OUTPUT.NAME` ([`ComposeOptions`]). The feature
//! lets another feature declare the schema of each of these entries
//! ([`SettingsDecl::open_entries`], [`EntryDecl`](crate::core::settings::EntryDecl)): the
//! feature that contributes a compose template declares its settings
//! ([`declare_settings`]), from the JSON Schema of the compose template
//! ([`Template::settings`]), each of whose `properties` is one setting with its type, its
//! description, its default and its marks. A source of settings that writes one setting
//! of a compose template leaves the others as the lower sources write them, and a key that
//! the schema lacks is left out with a warning; the defaults are the compose template's
//! ([`Template::config`]).
//!
//! # The stage of each output
//!
//! The feature registers one stage per output made of output regions, that is, per
//! output for which a backend contributes a regions output ([`RegionsOutput`]) to the
//! service slot `flm.output.regions` ([`REGIONS_SLOT`]; [`served_output`]). A regions
//! output is a backend's statement that its output is made of output regions: which table
//! holds them and which capability its final stage provides. The stages are registered in
//! the feature's second round of registration, a [`Finalizer`] that runs once every
//! feature has registered, so every backend has contributed to that service slot by then.
//!
//! The stage of an output, `flm.compose.<output>` ([`stage_name`]), is called the
//! *composer* in this module. It writes the output's artifact set into the same table as
//! the backend's final stage and provides the same capability, so a plan can schedule
//! either one; the host prefers the composer (see [above](self#a-host-registers-the-feature)).
//!
//! The composer reads the output's regions and the files that the output's stages write
//! beside the entry artifact (the style file of the recomposed LaTeX, the copies of
//! images), applies the compose template that the render option [`ComposeOptions`]
//! chooses for the output ([`chosen_template`]), and writes the entry artifact and those
//! files as the output's artifact set ([`ArtifactSet::insert_entry_with`]). It reports a
//! problem as the Error [`TemplateFailed`]; the output is then not made. It reports each
//! warning of the template engine as the Warning [`TemplateWarning`]; the output is still
//! made.
//!
//! # What a compose template reads
//!
//! | Name | What it is |
//! |---|---|
//! | `regions` | every output region, by name, as text: `content`; each piece's name; on HTML `styles`, `scripts`, `title` (the words of the page's title, escaped for HTML: the words of the document's title piece, else the title that the render option `html.title` gives) and `lang` (the language tag, present only when the render option `html.lang` gives one); on the recomposed LaTeX `style-package`, when the output has a style file |
//! | `pieces` | the regions that are pieces, by name, in the order of the output's regions; each has `text`, `words` (its displayed characters as plain text) and `place` (`before-content` or `after-content`) |
//! | `metadata` | the document's metadata ([`DocMeta`]): `title`, `author`, `date`, and every other entry the program gives, each value as it is given. `author` is a list with one map per author, a name alone included: `name`, `affiliation` (a list), `email` (where the author has one), `note` (a list) and the author's other keys. The title, the date and an author's name, affiliations and notes are the texts the author wrote, FLM source and not plain text (`A \emph{fine} paper`); a compose template that shows them uses the pieces instead: `pieces["flm.metadata.title"].text` for the HTML, or `.words` for plain words |
//! | `config` | the compose template's own settings: its defaults, with the values that the render option `template_config` gives for it on the output written over them key by key |
//! | `artifacts` | the path of each file the compose template ships, by the file's name ([below](self#files-a-compose-template-ships)): `artifacts.style` gives `paper-style.css`; for a folder it ships, the folder's path, with no trailing slash: `artifacts.icons` gives `paper-icons`, and a page writes `{{ artifacts.icons }}/check.svg` |
//!
//! A compose template that refers to a value that nothing provides cannot be applied: the
//! value is not taken as an empty text.
//!
//! # Files a compose template ships
//!
//! A compose template may ship files of its own, written beside the entry artifact: a
//! stylesheet, a script, a logo. It ships them in two ways: the files its description
//! lists, and the files its template engine ships while it applies it
//! ([below](self#a-file-shipped-while-the-template-is-applied)).
//!
//! The files of the description ([`Template::artifacts`], [`TemplateArtifact`]; the key
//! `artifacts` of its description, [`Template::from_data`]) each have a name, and the
//! identity of each is `compose:<name>`. The composer asks the program's naming of files (the
//! service slot `flm.artifacts.namer`, [`ArtifactNamer`]) for the path of each, and gives
//! the paths to the compose template as the value `artifacts`. A path is relative to the
//! folder where the program writes the output's files, which is where the entry file lies
//! under a host's usual naming. A file marked to be applied (the field `apply` of
//! [`TemplateArtifact::File`]) is applied as a template of the same template engine
//! ([`TemplateEngine::render_text`]), with the context of the entry artifact, its value
//! `html` set to whether the file's media type is `text/html`; the result is the file's
//! content. The composer then adds each file to the output's artifact set, with its media
//! type and extension, and the entry artifact links to each ([`Artifact::refs`]). A
//! compose template that ships files cannot be applied where no package in use provides a
//! naming of files. The composer takes the list from the template engine
//! ([`TemplateEngine::artifacts`]), once per application and before naming the files.
//! By default it is the compose template's own list; an engine whose compose templates
//! choose their files when they are applied gives them there.
//!
//! A compose template may also ship a whole folder as one file of this list (the key
//! `dir` of its description in place of `file`; [`TemplateArtifact::Folder`]): every
//! file under the folder, at any depth, by its path relative to the folder. The composer
//! asks the naming of files for the folder's path (a path with no extension,
//! [`ArtifactRef::folder`]), gives that path to the compose template, with no trailing
//! slash, and adds a folder artifact ([`Artifact::folder`]) to the output's artifact set;
//! the program writes each of its files under that folder with its own path. A folder is
//! never applied as a template, and its files' media types come from their extensions.
//!
//! ## A file shipped while the template is applied
//!
//! A template engine whose language ships a file, where the compose template names it as
//! it is applied, hands the file to the composer through the handle [`TemplateShipper`]
//! that it receives in [`TemplateEngine::render`] and [`TemplateEngine::render_text`]
//! ([`ShippedFile`]: a stem, an extension, a media type and the bytes), and writes the
//! path that the handle returns. The composer makes one handle per application, which
//! serves every call of that application. A file's identity is `compose:<stem>-<digest>`:
//! its stem, every character other than an ASCII letter, a digit, `-` and `_` written `_`,
//! and eight hexadecimal digits of a digest of its bytes and its media type, so that the
//! same file shipped twice is one file, under the one path. Its path is the naming of
//! files' path for that identity, its media type and its extension. Once the compose
//! template is applied, the composer adds the shipped files to the output's artifact set,
//! after the files of the description, in the order in which they were first shipped, and
//! the entry artifact links to each. Where no package in use provides a naming of files,
//! the handle refuses the file, and the compose template cannot be applied.
//!
//! The template engine also reports a warning through the handle
//! ([`TemplateShipper::warn`]), which it also receives in [`TemplateEngine::artifacts`],
//! for example the use of a kept copy of a downloaded file
//! that could not be downloaded again. The composer reports each distinct warning once
//! per application as the Warning [`TemplateWarning`], whether the compose template is
//! applied or not.
//!
//! # Files a compose template includes
//!
//! A compose template's text, and the text of a file it ships and applies, may include
//! other files, as its template engine's language provides: a file applied as a template
//! of the same engine, with the same context, or a file whose text is written as it is.
//! Each text carries its *place*: the file it was read from, given as a qualified path, a
//! path with a root such as `ext+NAME:templates/html/page/page.html` or
//! `std:templates/html/simple/simple.html` ([`Template::source`], the field `source` of
//! [`TemplateArtifact::File`]). The template engine reads an included file when the
//! compose template is applied, so that its name may be computed and need not be listed
//! ahead; a path written without a root is read beside the file of the text that writes it.
//! This crate reads no file of its own: the template engine reads through the program
//! that provides it, which records each read.
//!
//! # On HTML: one element per region, and the composer's table
//!
//! On HTML, the composer writes the content and each piece inside a `<div>` element whose
//! identifier is derived from the region's name ([`region_id`]: `flm-region-content`,
//! `flm-region-flm.metadata.title`), before the compose template places it, whichever
//! compose template is used. The composer also writes the table [`HTML_REGIONS`]
//! (`flm.compose.html.regions`, a [`ComposedRegions`]), which holds:
//!
//! - the HTML that the page holds under the identifier of the content and of each piece;
//! - the words of the page's title (the region `title`);
//! - the rest of the page, everything outside those regions (the field `skeleton`): the
//!   page with exactly what the table holds left out, and everything else kept, namely the
//!   stylesheets, the scripts, the language, the compose template's own markup, and the
//!   words of each piece wherever the compose template writes them.
//!
//! The table holds what a page can bring up to date by itself: an element found by its
//! identifier, and the page's title, which has its place in every page. The words of a
//! piece have no such place, so a change of them is a change of the rest of the page.
//! The regions in the table and the rest of the page together make up the whole page, so
//! two builds of one document that differ anywhere differ either in the rest of the page
//! or in one entry of the table. A live preview can compare two builds this way, to tell
//! a change of one region, which it applies in place, from a change of the page.
//!
//! # Which pieces a render builds
//!
//! A piece is a document-level value that a backend places before or after the document's
//! content, such as the title, the list of footnotes or the bibliography ([`Piece`]). The
//! pieces that a compose template accepts are the pieces that a render request places on
//! the backend of the compose template's output: the host sets the library's selection of
//! pieces for that backend from the chosen compose template ([`accepted_pieces`],
//! [`select_pieces`]), so that a piece that the compose template does not place is never
//! built. The pieces that the compose template *requires* ([`Template::requires`]) are
//! placed although a piece may be declared off by default: [`select_pieces`] includes
//! them. When the plan is built, the composer declares that it reads each required piece;
//! a plan in which no stage provides a required piece therefore fails to build, with an
//! error that gives the piece's name.
//!
//! # Map of the items
//!
//! - [`ComposeFeature`], [`FEATURE`]: the feature.
//! - [`ENGINES_SLOT`], [`TemplateEngine`], [`engines`] ([`ContentOnlyEngine`]): the
//!   template engines.
//! - [`TEMPLATES_SLOT`], [`Template`], [`Template::from_data`], [`Accepts`],
//!   [`Delimiters`], [`TemplateArtifact`]: the compose templates.
//! - [`declare_settings`]: the settings of the compose templates a feature contributes.
//! - [`TemplateContext`], [`PieceValue`]: what a template engine is given.
//! - [`TemplateShipper`], [`ShippedFile`]: a file a template engine ships, and a warning it
//!   reports, while it applies a compose template.
//! - [`ComposeOptions`], [`TemplateChoice`], [`DEFAULT_TEMPLATE`], [`chosen_template`]:
//!   choosing a compose template.
//! - [`served_output`], [`stage_name`], [`accepted_pieces`], [`select_pieces`]: what the
//!   host calls when it prepares the plan of an output.
//! - [`HTML_REGIONS`], [`ComposedRegions`], [`ComposedRegion`], [`ComposedKind`],
//!   [`region_id`], [`REGION_ID_PREFIX`]: the composer's table on HTML.
//! - [`TemplateFailed`], [`TemplateWarning`]: the conditions of a compose template that
//!   cannot be applied and of a warning of its template engine.

pub mod engines;

use std::collections::BTreeMap;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::sync::{Arc, Mutex, PoisonError};

use crate::core::artifact::{
    Artifact, ArtifactId, ArtifactNamer, ArtifactRef, ArtifactSet, NamingScope, RelPath, digest_name, media_type_of,
    name_safe,
};
use crate::core::data::store::StageOut;
use crate::core::data::table::{PieceClass, ProjectCx, Table, TableHandle, TableName};
use crate::core::piece::{Piece, PieceDecl};
use crate::core::plan::PlanCx;
use crate::core::region::{self, Region, Regions, RegionsOutput};
use crate::core::registry::{BuildError, FeatureBuilder, FeatureInfo, Finalizer, FlmFeature, FlmRegistry};
use crate::core::run::StageCx;
use crate::core::services::Arity;
use crate::core::settings::{Mark, SettingsDecl, SettingsError, SettingsErrorKind, rewrite_marked};
use crate::core::stage::{Effect, Needs, Scope, Stage, StageDecl};
use crate::lang::{FlmOrigin, FlmSpan};
use crate::model::digest::Fnv1a64;
use crate::model::names::Name;
use crate::model::options::{Bind, OptionKey, hash_value};
use crate::stdlib::backends::pieces::{self as core_pieces, PiecesRenderOptions};
use crate::stdlib::backends::html;
use crate::stdlib::backends::html::escape::escape_attr_into;
use crate::stdlib::backends::lowering::{NAMER_SLOT, REGIONS_SLOT};
use crate::stdlib::features::metadata::{
    AFFILIATION_KEY, AUTHOR_KEY, DocMeta, EMAIL_KEY, MetaAuthor, MetaText, NAME_KEY, NOTE_KEY,
};
use crate::techy::error::{Diagnostic, DiagnosticInfo};
use crate::techy::serialize::SerialValue;
use crate::techy::source::{Source, SourceSpan};
use serde_json::{Map, Value};

pub use engines::{CONTENT_ONLY, ContentOnlyEngine};

/// The name under which the feature is registered, `compose`.
pub const FEATURE: &str = "compose";

/// The name of the service slot `flm.compose.engines`, which takes any number of
/// template engines ([`TemplateEngine`]), each with a name. Where several engines have
/// the name a template gives, the engine of the feature placed last in the feature order
/// applies.
pub const ENGINES_SLOT: &str = "flm.compose.engines";

/// The name of the service slot `flm.compose.templates`, which takes any number of compose
/// templates ([`Template`]), each with a name and the output it serves.
pub const TEMPLATES_SLOT: &str = "flm.compose.templates";

/// The name of the compose template that a render uses when the settings choose none,
/// `simple`. The feature ships no compose template of that name: a host contributes the
/// compose templates it offers, and where none of them serves an output under the chosen
/// name, the composer of that output reports [`TemplateFailed`].
pub const DEFAULT_TEMPLATE: &str = "simple";

/// The prefix of the identifier of the element that holds a region on HTML, `flm-region-`:
/// see [`region_id`].
pub const REGION_ID_PREFIX: &str = "flm-region-";

/// The typed name of the composer's table on HTML, `flm.compose.html.regions`
/// ([`ComposedRegions`]): the HTML that the page holds under each region's identifier, the
/// words of the page's title, and the rest of the page. See the [module
/// documentation](self#on-html-one-element-per-region-and-the-composers-table).
pub const HTML_REGIONS: TableName<ComposedRegions> = TableName::new("flm.compose.html.regions");

/// Condition `flm.compose.template-failed` (Error): the chosen compose template cannot be
/// applied. The stage `flm.compose.<output>` reports it when the settings that choose the
/// compose template cannot be read, when no compose template of the chosen name serves
/// the output or more than one does, when its template engine is not registered,
/// when the output's regions, the files written beside the entry artifact or the
/// document's metadata cannot be read, when its template engine cannot give the files it
/// ships ([`TemplateEngine::artifacts`]), when it ships files and no package in use
/// provides a naming of files, when its text or the text of a file it applies does not
/// compile or refers to a value that nothing provides, or when the output's artifact set
/// cannot be written. The output is then not made, with one exception: when a file that
/// the compose template ships cannot be added to the artifact set after the entry artifact
/// was written, the output is made without that file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TemplateFailed {
    /// The compose template's name; `None` when the settings that choose it cannot be read.
    pub template: Option<String>,
    /// The name of the output it was applied for.
    pub output: String,
    /// What went wrong, as the template engine, the search for the compose template or the
    /// failed read states it.
    pub detail: String,
}

impl fmt::Display for TemplateFailed {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.template {
            Some(template) => write!(
                f,
                "the compose template `{template}` for the output `{}` cannot be applied: {}",
                self.output, self.detail
            ),
            None => write!(f, "the compose template for the output `{}` cannot be chosen: {}", self.output, self.detail),
        }
    }
}

impl DiagnosticInfo for TemplateFailed {
    const IDENTIFIER: &'static str = "flm.compose.template-failed";
}

/// Condition `flm.compose.template-warning` (Warning): the template engine reported a
/// warning while it applied the chosen compose template ([`TemplateShipper::warn`]). The
/// stage `flm.compose.<output>` reports each distinct warning once per application, in
/// the order first given; the output is made.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TemplateWarning {
    /// The compose template's name.
    pub template: String,
    /// The name of the output it was applied for.
    pub output: String,
    /// What is wrong, as the template engine states it.
    pub detail: String,
}

impl fmt::Display for TemplateWarning {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} (compose template ‘{}’ for the output ‘{}’)", self.detail, self.template, self.output)
    }
}

impl DiagnosticInfo for TemplateWarning {
    const IDENTIFIER: &'static str = "flm.compose.template-warning";
}

// --- the outputs the composer serves ---------------------------------------------------------

/// Returns what a backend states about the output `output` of `registry` when that output
/// is made of output regions ([`RegionsOutput`], contributed to the service slot
/// [`REGIONS_SLOT`]), and `None` otherwise. The composer serves exactly those outputs.
///
/// The output is matched by the table of its artifact set: an output of another name
/// whose artifact set is written to the table of such an output is served as that output,
/// with that output's compose templates. Where several backends state one table, the
/// statement of the feature placed last in the feature order applies.
pub fn served_output<'r>(registry: &'r FlmRegistry, output: &str) -> Option<&'r RegionsOutput> {
    let table = &registry.output(output)?.def.table;
    registry
        .services()
        .services_by_precedence_named::<RegionsOutput>(REGIONS_SLOT)
        .find(|served| &served.document == table)
}

/// Returns whether `output` is written by the HTML backend: a value that a compose template
/// writes is then escaped for HTML, and every region placed carries its name.
fn is_html(output: &RegionsOutput) -> bool {
    output.backend.as_str() == html::BACKEND
}

/// Returns the name of the composer's stage for the output `output`,
/// `flm.compose.<output>`.
pub fn stage_name(output: &str) -> String {
    format!("flm.compose.{output}")
}

/// Returns the identifier of the element that holds the region `name` on HTML:
/// [`REGION_ID_PREFIX`] followed by the name as it is written, dots included (a `.` is
/// allowed in an HTML identifier). Two distinct names therefore never share an
/// identifier, and the name is read back from the identifier by removing the prefix. The
/// identifier is derived from the name alone, so adding a region never changes the
/// identifier of another.
///
/// # Examples
///
/// ```
/// use flm_core::stdlib::features::compose::region_id;
///
/// assert_eq!(region_id("content"), "flm-region-content");
/// assert_eq!(region_id("flm.metadata.title"), "flm-region-flm.metadata.title");
/// assert_ne!(region_id("a.b-c"), region_id("a-b.c"));
/// ```
pub fn region_id(name: &str) -> String {
    format!("{REGION_ID_PREFIX}{name}")
}

/// Returns the element that holds a region on HTML, written around `inside`: a `<div>`
/// whose `id` is [`region_id`] of `name`, escaped as an attribute value.
fn region_element(name: &str, inside: &str) -> String {
    let mut id = String::new();
    escape_attr_into(&mut id, &region_id(name));
    if inside.is_empty() {
        format!("<div id=\"{id}\"></div>")
    } else {
        format!("<div id=\"{id}\">\n{inside}\n</div>")
    }
}

// --- templates and engines ---------------------------------------------------------------------

/// Which pieces a compose template accepts: every piece, or the pieces listed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Accepts {
    /// Every piece that the registry declares.
    All,
    /// The pieces listed, and no other.
    Only(Vec<Name>),
}

/// The three pairs of delimiters of a compose template written in a Jinja-like template
/// language (such as the language of a host's `minijinja` engine), for a compose template
/// whose output itself uses the usual ones (`{% %}`, `{{ }}`, `{# #}`), such as LaTeX. A
/// template engine that reads no delimiters ignores them.
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Delimiters {
    /// The start and the end of a statement.
    pub block: (String, String),
    /// The start and the end of a place for a value.
    pub variable: (String, String),
    /// The start and the end of a comment.
    pub comment: (String, String),
}

/// A compose template: a text with named places for an output's regions, applied by a
/// template engine (see the [module documentation](self)).
///
/// A feature contributes one to [`TEMPLATES_SLOT`]; [`Template::from_data`] makes one from
/// a description given as data and the readers of the files it gives.
#[derive(Debug, Clone, PartialEq)]
pub struct Template {
    /// The compose template's name, which the setting `compose.template` gives.
    /// [`Template::from_data`] reads it from the key `name` of the description.
    pub name: String,
    /// The package that ships the compose template, as messages show it (for instance the
    /// name of a compiled package, or the identity of an extension's package,
    /// `<identity>#<package>`). A
    /// problem with two compose templates of the same name gives the packages that ship
    /// them.
    pub package: String,
    /// The name of the output it serves. [`Template::from_data`] reads it from the key
    /// `output` of the description.
    pub output: String,
    /// The name of the template engine that applies it.
    pub engine: String,
    /// Its text, in the template engine's language; empty for a template engine that reads
    /// no text (`content-only`). [`Template::from_data`] reads it from the file that the key
    /// `main` of the description gives, and leaves it empty without `main`.
    pub text: String,
    /// The place of its text: the qualified path of the file that the text was read from
    /// (`ext+NAME:templates/html/page/page.html`, `std:templates/html/simple/simple.html`;
    /// see the [module documentation](self#files-a-compose-template-includes)). A template
    /// engine reads a path written without a root beside that file. `None` for a text that
    /// no file holds: a compose template made in code, or a description without `main`.
    pub source: Option<String>,
    /// The pieces it accepts: the pieces that a render request places on the backend of
    /// the compose template's output ([`accepted_pieces`]).
    pub accepts: Accepts,
    /// The pieces it requires: each is placed although it may be declared off by default
    /// ([`select_pieces`]), and a plan in which no stage provides one of them fails.
    pub requires: Vec<Name>,
    /// Its own settings, with their defaults, which the render option `template_config`
    /// can change ([`ComposeOptions::template_config`]). [`Template::from_data`] reads them
    /// from the `default` of each setting of [`settings`](Template::settings). For a
    /// compose template written as a module of an extension, they are the defaults that
    /// the module's `describe` returns.
    pub config: Map<String, Value>,
    /// The JSON Schema of its own settings: an object schema, each of whose `properties`
    /// is one setting with its type, its `description`, its `default` and its marks
    /// ([`Mark`]). The feature that contributes the compose template declares it as the
    /// entry `template_config.OUTPUT.NAME` of the feature `compose`
    /// ([`declare_settings`]).
    ///
    /// - [`Template::from_data`] reads it from the key `settings` of the description; a
    ///   description without that key gives a schema with no setting.
    /// - For a compose template written as a module of an extension, it is the schema
    ///   that the extension declares for the module, each setting given the default that
    ///   [`config`](Template::config) holds.
    /// - It is `None` for a compose template that declares nothing of its settings (one
    ///   made in code): what is written for it is given to it as written.
    pub settings: Option<Value>,
    /// The delimiters of its language, where they differ from the template engine's
    /// usual ones.
    pub delimiters: Option<Delimiters>,
    /// The files it ships, in the order of its description (see the [module
    /// documentation](self#files-a-compose-template-ships)).
    pub artifacts: Vec<TemplateArtifact>,
}

/// A file that a template engine ships while it applies a compose template, which the
/// composer writes beside the entry artifact (see the [module
/// documentation](self#files-a-compose-template-ships)).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ShippedFile {
    /// The stem of the file's name (`notes` for `notes.css`), with which the name of the
    /// shipped file begins.
    pub stem: String,
    /// The file's extension, without the dot (`css`).
    pub extension: String,
    /// The file's media type (`text/css`).
    pub media_type: String,
    /// The file's content.
    pub bytes: Vec<u8>,
}

/// The handle through which a template engine ships a file, and reports a warning, while it
/// applies a compose template ([`TemplateEngine::render`], [`TemplateEngine::render_text`];
/// [`TemplateEngine::artifacts`] reports a warning through it).
///
/// The composer makes one per application of a compose template and gives it to every
/// call of that application.
pub trait TemplateShipper: Send + Sync {
    /// Hands the composer the warning `detail`, a text for a person to read that states
    /// what is wrong (for instance a downloaded file whose kept copy was used past its
    /// expiry). The compose template is still applied; the composer reports each warning
    /// as a [`TemplateWarning`], in the order first given. Giving the same text again in
    /// the same application reports nothing more.
    fn warn(&self, detail: String);

    /// Hands `file` to the composer, which writes it beside the entry artifact, and
    /// returns the file's path, as a compose template reads the paths of the files it
    /// ships ([`TemplateContext::artifacts`]). Shipping the same file again returns the
    /// same path and ships nothing more.
    ///
    /// # Errors
    ///
    /// Returns a text, for a person to read, that says why the file cannot be shipped: for
    /// instance no package in use provides the program's naming of files. A template
    /// engine reports it as it is, and the compose template cannot be applied.
    fn ship(&self, file: ShippedFile) -> Result<String, String>;
}

/// One file, or one folder, a compose template ships, written beside the entry artifact
/// (see the [module documentation](self#files-a-compose-template-ships)).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TemplateArtifact {
    /// One file (the key `file` of the description).
    File {
        /// The file's name, by which the compose template reads its path
        /// (`artifacts.<name>`); its identity is `compose:<name>`.
        name: String,
        /// The file's extension, without the dot (`css`).
        extension: String,
        /// The file's media type (`text/css`).
        media_type: String,
        /// Whether the composer applies the bytes, as text, as a template before writing
        /// them.
        apply: bool,
        /// The file's content, as the compose template's package holds it.
        bytes: Vec<u8>,
        /// The place of the file: the qualified path it was read from (see the [module
        /// documentation](self#files-a-compose-template-includes)), which a template
        /// engine gives a text it applies ([`TemplateEngine::render_text`]). `None` for a
        /// content that no file holds.
        source: Option<String>,
    },
    /// A folder (the key `dir` of the description), shipped as one folder artifact
    /// ([`Artifact::folder`]).
    Folder {
        /// The folder's name, by which the compose template reads its path
        /// (`artifacts.<name>`); its identity is `compose:<name>`.
        name: String,
        /// The files of the folder, each by its path relative to the folder (forward
        /// slashes, no leading slash) and its content, in the order the folder reader of
        /// [`Template::from_data`] gives them (the lexical order of the paths). It is
        /// never empty.
        files: Vec<(String, Vec<u8>)>,
    },
}

impl TemplateArtifact {
    /// Returns the name of the file or folder, by which the compose template reads its
    /// path (`artifacts.<name>`).
    pub fn name(&self) -> &str {
        match self {
            TemplateArtifact::File { name, .. } | TemplateArtifact::Folder { name, .. } => name,
        }
    }
}

/// The pieces that a description accepts, as written: `all`, or a list of piece names.
#[derive(serde::Deserialize)]
#[serde(untagged)]
enum AcceptsData {
    All(String),
    Only(Vec<String>),
}

/// A compose template's description, as written.
#[derive(serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct Description {
    name: String,
    output: String,
    engine: String,
    #[serde(default)]
    main: Option<String>,
    accepts: AcceptsData,
    #[serde(default)]
    requires: Vec<String>,
    #[serde(default)]
    settings: Option<Value>,
    #[serde(default)]
    delimiters: Option<Delimiters>,
    #[serde(default)]
    artifacts: Map<String, Value>,
}

/// The description of one file or folder a compose template ships, as written.
#[derive(serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct ArtifactDescription {
    #[serde(default)]
    file: Option<String>,
    #[serde(default)]
    dir: Option<String>,
    #[serde(default)]
    template: Option<bool>,
    #[serde(default)]
    media_type: Option<String>,
}

/// Returns the extension of the file `file` (a path whose parts are separated by `/`): what
/// follows the last `.` of its last part, when that `.` neither begins nor ends the part.
fn extension_of_file(file: &str) -> Option<&str> {
    let last = file.rsplit('/').next().unwrap_or(file);
    match last.rfind('.') {
        Some(dot) if dot > 0 && dot + 1 < last.len() => Some(&last[dot + 1..]),
        _ => None,
    }
}

/// The reader of the files a description lists, as [`Template::from_data`] takes it.
type FileReader<'a> = &'a dyn Fn(&str) -> Result<Option<Vec<u8>>, String>;

/// The reader of the folders a description lists, as [`Template::from_data`] takes it.
type FolderReader<'a> = &'a dyn Fn(&str) -> Result<Option<Vec<(String, Vec<u8>)>>, String>;

/// The place of a file a description lists, as [`Template::from_data`] takes it.
type PlaceOf<'a> = &'a dyn Fn(&str) -> Option<String>;

/// Returns the schema of the settings of the compose template `template` that its
/// description gives as `settings` (an object schema with no setting when it gives none),
/// and the default of each setting.
fn template_settings(template: &str, settings: Option<Value>) -> Result<(Value, Map<String, Value>), String> {
    let Some(settings) = settings else {
        return Ok((serde_json::json!({ "type": "object", "properties": {} }), Map::new()));
    };
    let Some(properties) = settings.get("properties").and_then(Value::as_object) else {
        return Err(format!(
            "Invalid ‘settings’ of the compose template ‘{template}’: it must be a JSON Schema of an object, with \
             ‘properties’ giving each setting's schema"
        ));
    };
    let mut config = Map::new();
    for (key, property) in properties {
        match property.get("default") {
            Some(default) => {
                config.insert(key.clone(), default.clone());
            }
            None => return Err(format!("Missing ‘default’ of the setting ‘{key}’ of the compose template ‘{template}’")),
        }
    }
    Ok((settings, config))
}

/// Returns the file or folder `name` that the description `description` of the compose
/// template `template` (of template engine `engine`) lists, read through `files` or
/// `folders`, a file at the place that `place` gives.
fn template_artifact(
    template: &str,
    engine: &str,
    name: &str,
    description: Value,
    files: FileReader<'_>,
    folders: FolderReader<'_>,
    place: PlaceOf<'_>,
) -> Result<TemplateArtifact, String> {
    let description: ArtifactDescription = serde_json::from_value(description).map_err(|error| {
        format!("the artifact `{name}` of the compose template `{template}` cannot be read: {error}")
    })?;
    let file = match (&description.file, &description.dir) {
        (Some(_), Some(_)) => {
            return Err(format!(
                "the artifact `{name}` of the compose template `{template}` gives both `file` and `dir`; give one"
            ));
        }
        (None, Some(dir)) => return template_folder(template, name, dir, &description, folders),
        (Some(file), None) => file.as_str(),
        (None, None) => {
            return Err(format!("the artifact `{name}` of the compose template `{template}` must give `file` or `dir`"));
        }
    };
    let apply = description.template.unwrap_or(false);
    if apply && engine == CONTENT_ONLY {
        return Err(format!(
            "the artifact `{name}` of the compose template `{template}` sets `template` to `true`, and the \
             template engine `{CONTENT_ONLY}` applies no text"
        ));
    }
    let Some(extension) = extension_of_file(file) else {
        return Err(format!(
            "the file `{file}` of the artifact `{name}` of the compose template `{template}` must have an \
             extension"
        ));
    };
    let media_type = match description.media_type.as_deref().or_else(|| media_type_of(extension)) {
        Some(media_type) => media_type.to_string(),
        None => {
            return Err(format!(
                "the artifact `{name}` of the compose template `{template}` must give `media_type`, since \
                 the extension `{extension}` of its file `{file}` has no known media type"
            ));
        }
    };
    let bytes = match files(file) {
        Ok(Some(bytes)) => bytes,
        Ok(None) => {
            return Err(format!(
                "the file `{file}` of the artifact `{name}` of the compose template `{template}` is not a \
                 file of the compose template's package"
            ));
        }
        Err(error) => {
            return Err(format!(
                "the file `{file}` of the artifact `{name}` of the compose template `{template}` cannot be \
                 read: {error}"
            ));
        }
    };
    if apply && std::str::from_utf8(&bytes).is_err() {
        return Err(format!(
            "the file `{file}` of the artifact `{name}` of the compose template `{template}` must be text, \
             since `template` is `true`"
        ));
    }
    Ok(TemplateArtifact::File {
        name: name.to_string(),
        extension: extension.to_string(),
        media_type,
        apply,
        bytes,
        source: place(file),
    })
}

/// Returns the folder `dir` that the artifact `name` of the compose template `template`
/// ships (its description `description`), read through `folders`.
fn template_folder(
    template: &str,
    name: &str,
    dir: &str,
    description: &ArtifactDescription,
    folders: FolderReader<'_>,
) -> Result<TemplateArtifact, String> {
    let given: Vec<&str> = [("template", description.template.is_some()), ("media_type", description.media_type.is_some())]
        .into_iter()
        .filter_map(|(key, given)| given.then_some(key))
        .collect();
    if !given.is_empty() {
        let verb = if given.len() == 1 { "applies" } else { "apply" };
        return Err(format!(
            "the artifact `{name}` of the compose template `{template}` gives `dir` together with `{}`, which {verb} \
             to a file only",
            given.join("` and `")
        ));
    }
    match folders(dir)? {
        None => Err(format!("the shipped folder `{dir}` of the compose template `{template}` does not exist")),
        Some(files) if files.is_empty() => {
            Err(format!("the shipped folder `{dir}` of the compose template `{template}` holds no file"))
        }
        Some(files) => Ok(TemplateArtifact::Folder { name: name.to_string(), files }),
    }
}

impl Template {
    /// The compose template of the package `package` (the factory's name), from its
    /// description as data, `text`, which reads the file of its text, `files`, which reads
    /// a file the description lists, `folders`, which reads a folder it lists,
    /// `place`, which gives the place of a file it reads, and `path`, which reads a path
    /// that a setting's `default` writes.
    ///
    /// The description is a map of these keys:
    ///
    /// - `name`: the compose template's name, by which the setting `compose.template`
    ///   chooses it;
    /// - `output`: the output the compose template serves;
    /// - `engine`: the name of its template engine;
    /// - `main` (optional): the path of the file that holds its text, relative to the
    ///   folder of the description; without it, the compose template's text is empty;
    /// - `accepts`: the pieces it accepts, `all` or a list of piece names;
    /// - `requires` (optional): the pieces it requires, a list of piece names;
    /// - `settings` (optional): the JSON Schema of its own settings
    ///   ([`Template::settings`]), an object schema whose `properties` are the settings,
    ///   each with its `type`, its `description` (plain text), its `default` and its marks
    ///   (`x-flm-marks`); every setting gives a `default`, and these are the compose
    ///   template's defaults ([`Template::config`]), each text of a default that the
    ///   schema marks [`Mark::Path`] as `path` gives
    ///   it; without it, the compose template has no setting;
    /// - `delimiters` (optional): the delimiters of its language where they differ from
    ///   the usual ones ([`Delimiters`]);
    /// - `artifacts` (optional): the files and folders it ships (see the [module
    ///   documentation](self#files-a-compose-template-ships)), a map from each one's name
    ///   to a map of these keys: `file`, the file's path, relative to the folder of the
    ///   description, whose extension is the artifact's; `template` (optional, default
    ///   `false`), whether the file's text is applied as a template of the same engine;
    ///   `media_type` (optional), the file's media type, by default the one its extension
    ///   gives ([`media_type_of`]). In place of `file`, the key `dir` gives the path of a
    ///   folder, relative to the folder of the description, shipped whole as one folder
    ///   artifact ([`TemplateArtifact::Folder`]); `template` and `media_type` are refused
    ///   with it, since a folder is never applied as a template and its files' media types
    ///   come from their extensions.
    ///
    /// `text(path)` returns the text of the file at `path` as the description's `main`
    /// writes it, `Ok(None)` when there is no such file, and `Err` with a text for a person
    /// when it cannot be read. It is called once when the description gives `main`, and not
    /// at all otherwise.
    ///
    /// `files(path)` returns the bytes of the file at `path` as the description writes it,
    /// `Ok(None)` when there is no such file, and `Err` with a text for a person when it
    /// cannot be read. It is called once per file listed.
    ///
    /// `folders(path)` returns the files of the folder at `path` as the description writes
    /// it, each by its path relative to that folder (forward slashes, no leading slash) and
    /// its bytes, listed at every depth in lexical order of the paths; `Ok(None)` when
    /// there is no such folder; and `Err` with a complete text for a person when the folder
    /// cannot be shipped (it cannot be read, or its path is refused), which `from_data`
    /// returns as it is. The reader decides which names it leaves out (an extension's
    /// reader leaves out the names beginning with `.`). It is called once per folder
    /// listed.
    ///
    /// `place(path)` returns the place of the file at `path` as the description writes it:
    /// the qualified path of the file (see the [module
    /// documentation](self#files-a-compose-template-includes)), or `None` where the files
    /// read have no qualified paths. It is called for the text and for each file listed,
    /// once each has been read, and gives [`Template::source`] and the field `source` of
    /// [`TemplateArtifact::File`].
    ///
    /// `path(written)` returns the path `written`, a text of a setting's `default` that the
    /// schema marks as a path, as the reader of the setting receives it: a qualified path,
    /// a bare path given the root and the folder of the description; or `Err` with a text
    /// for a person when the path has no meaning there. The defaults of
    /// [`config`](Template::config) and of [`settings`](Template::settings) both hold its
    /// answer.
    ///
    /// # Examples
    ///
    /// ```
    /// use flm_core::stdlib::features::compose::{Accepts, Template};
    /// use serde_json::json;
    ///
    /// let template = Template::from_data(
    ///     "mine",
    ///     json!({ "name": "page", "output": "html", "engine": "host", "main": "page.html", "accepts": "all" }),
    ///     &|path| Ok((path == "page.html").then(|| String::from("<main>{{ regions.content }}</main>"))),
    ///     &|_| Ok(None),
    ///     &|_| Ok(None),
    ///     &|path| Some(format!("ext+mine:{path}")),
    ///     &|written| Ok(format!("ext+mine:{written}")),
    /// )
    /// .unwrap();
    /// assert_eq!((template.name.as_str(), template.output.as_str()), ("page", "html"));
    /// assert_eq!(template.accepts, Accepts::All);
    /// assert_eq!(template.text, "<main>{{ regions.content }}</main>");
    /// assert_eq!(template.source.as_deref(), Some("ext+mine:page.html"));
    /// ```
    ///
    /// # Errors
    ///
    /// Returns a text, for a person to read, that says what is wrong:
    ///
    /// - the description cannot be read: it is not a map, it holds an unknown key, it
    ///   lacks `name`, `output`, `engine` or `accepts`, a value has the wrong shape,
    ///   `accepts` is neither `all` nor a list of names, `settings` is not an object
    ///   schema with `properties`, a setting gives no `default`, or `path` refuses the
    ///   path of a default;
    /// - its text cannot be read: there is no file at `main`, or it cannot be read (the
    ///   text of `text`'s `Err`);
    /// - a file it lists cannot be shipped: there is no such file, it cannot be read, it
    ///   has no extension, its media type is not known, or it is applied as a template
    ///   while it is not text or the engine is `content-only`;
    /// - a folder it lists cannot be shipped: the artifact gives both `file` and `dir`, or
    ///   neither, or `dir` together with `template` or `media_type`, there is no such
    ///   folder, it holds no file, or the text of `folders`'s `Err`.
    // The readers' types are spelled out, so that their contracts read in the signature.
    #[allow(clippy::type_complexity)]
    pub fn from_data(
        package: &str,
        description: Value,
        text: &dyn Fn(&str) -> Result<Option<String>, String>,
        files: &dyn Fn(&str) -> Result<Option<Vec<u8>>, String>,
        folders: &dyn Fn(&str) -> Result<Option<Vec<(String, Vec<u8>)>>, String>,
        place: &dyn Fn(&str) -> Option<String>,
        path: &dyn Fn(&str) -> Result<String, String>,
    ) -> Result<Template, String> {
        // A description that cannot be read is named by its `name` where it gives one.
        let given_name = description.get("name").and_then(Value::as_str).map(str::to_string);
        let description: Description = serde_json::from_value(description).map_err(|error| match given_name {
            Some(name) => format!("the description of the compose template `{name}` cannot be read: {error}"),
            None => format!("the description of a compose template cannot be read: {error}"),
        })?;
        let name = description.name.as_str();
        let accepts = match description.accepts {
            AcceptsData::All(all) if all == "all" => Accepts::All,
            AcceptsData::All(other) => {
                return Err(format!(
                    "in the description of the compose template `{name}`, `accepts` must be `all` or a list \
                     of piece names, not `{other}`"
                ));
            }
            AcceptsData::Only(names) => Accepts::Only(names.into_iter().map(Name::from).collect()),
        };
        let (template_text, source) = match description.main.as_deref() {
            None => (String::new(), None),
            Some(main) => match text(main) {
                Ok(Some(read)) => (read, place(main)),
                Ok(None) => {
                    return Err(format!(
                        "the text `{main}` that `main` gives for the compose template `{name}` is not a file of \
                         the compose template's package"
                    ));
                }
                Err(error) => {
                    return Err(format!(
                        "the text `{main}` that `main` gives for the compose template `{name}` cannot be read: \
                         {error}"
                    ));
                }
            },
        };
        let (mut settings, mut config) = template_settings(name, description.settings)?;
        rewrite_marked(&settings, Mark::Path, &mut config, &mut |written| path(written))
            .map_err(|detail| format!("{detail} (a default of the compose template ‘{name}’)"))?;
        // The schema states each setting's default as the compose template receives it.
        if let Some(properties) = settings.get_mut("properties").and_then(Value::as_object_mut) {
            for (key, property) in properties.iter_mut() {
                if let (Some(default), Some(property)) = (config.get(key), property.as_object_mut()) {
                    property.insert(String::from("default"), default.clone());
                }
            }
        }
        let mut artifacts = Vec::new();
        for (artifact, data) in description.artifacts {
            artifacts.push(template_artifact(name, &description.engine, &artifact, data, files, folders, place)?);
        }
        Ok(Template {
            name: description.name,
            package: String::from(package),
            output: description.output,
            engine: description.engine,
            text: template_text,
            source,
            accepts,
            requires: description.requires.into_iter().map(Name::from).collect(),
            config,
            settings: Some(settings),
            delimiters: description.delimiters,
            artifacts,
        })
    }
}

/// One piece as a compose template reads it: see the [module
/// documentation](self#what-a-compose-template-reads).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PieceValue {
    /// The piece's name.
    pub name: String,
    /// Where the backend places it: `before-content` or `after-content`.
    pub place: String,
    /// Its text in the output's format; on HTML, inside the element that carries the
    /// piece's name ([`region_id`]).
    pub text: String,
    /// Its displayed characters as plain text.
    pub words: String,
}

/// What a compose template reads: see the [module
/// documentation](self#what-a-compose-template-reads). The stage hands it to the template
/// engine together with the compose template.
#[derive(Debug, Clone, PartialEq)]
pub struct TemplateContext {
    /// Whether the output is HTML. A template engine then escapes for HTML every value
    /// that the compose template writes, except a region and a piece's text, which are
    /// already HTML.
    pub html: bool,
    /// Every output region, by name, as text, in the backend's order; on HTML, the content
    /// and each piece inside the element that carries its name.
    pub regions: Vec<(String, String)>,
    /// The regions that are pieces, in the backend's order.
    pub pieces: Vec<PieceValue>,
    /// The document's metadata, as data.
    pub metadata: Value,
    /// The compose template's own settings: its defaults, with the values of the render
    /// option `template_config` written over them.
    pub config: Map<String, Value>,
    /// The path of each file the compose template ships, as (name, path), in the order
    /// in which its template engine gives them ([`TemplateEngine::artifacts`]; by default
    /// the order of its description, [`Template::artifacts`]). A path is relative to the
    /// folder where the program writes the output's files, where the entry file lies
    /// under a host's usual naming of files. A template engine exposes them as the value
    /// `artifacts`, a map from name to path.
    pub artifacts: Vec<(String, String)>,
}

/// A template engine: the code that applies a compose template written in its language to
/// a [`TemplateContext`].
///
/// A feature contributes one to [`ENGINES_SLOT`]; a compose template refers to its
/// template engine by name ([`Template::engine`]).
pub trait TemplateEngine: Send + Sync {
    /// Returns the engine's name, by which a compose template refers to it.
    fn name(&self) -> &str;

    /// Returns the text of the compose template `template` applied to `context`.
    ///
    /// # Errors
    ///
    /// Returns a text, for a person to read, that says why the compose template cannot be
    /// applied: for instance its text does not compile, or it refers to a value that
    /// `context` does not provide. The stage reports it in [`TemplateFailed`].
    ///
    /// An engine whose language includes other files reads a path written without a
    /// root beside the place of the text that writes it ([`Template::source`]).
    ///
    /// An engine whose language ships a file hands it to `shipper` and writes the path it
    /// returns. The pointer is shared, so that the engine can keep it where a function of
    /// its language must own what it holds.
    fn render(
        &self,
        template: &Template,
        context: &TemplateContext,
        shipper: &Arc<dyn TemplateShipper>,
    ) -> Result<String, String>;

    /// Returns the files the compose template `template` ships when it is applied to
    /// `context`, which the composer names and writes beside the entry artifact, in this
    /// order, and whose paths it then gives to [`render`](Self::render) in
    /// [`TemplateContext::artifacts`]. The composer calls it once per application, before
    /// it names the files, so `context` holds no path yet: its `artifacts` is empty.
    ///
    /// The default returns the compose template's own list ([`Template::artifacts`]). An
    /// engine whose compose templates choose their files when they are applied returns
    /// them here. `shipper` is the handle of the same application that
    /// [`render`](Self::render) receives, through which the engine reports a warning while
    /// it reads the files.
    ///
    /// # Errors
    ///
    /// Returns a text, for a person to read, that says why the files cannot be given. The
    /// stage reports it in [`TemplateFailed`], as for [`render`](Self::render).
    fn artifacts(
        &self,
        template: &Template,
        context: &TemplateContext,
        shipper: &Arc<dyn TemplateShipper>,
    ) -> Result<Vec<TemplateArtifact>, String> {
        let _ = (context, shipper);
        Ok(template.artifacts.clone())
    }

    /// Applies `text`, written in this engine's language under the settings of `template`
    /// (its name, its delimiters), to `context`, and returns the result. `place` is the
    /// place of `text` (see the [module
    /// documentation](self#files-a-compose-template-includes)), `None` for a text that no
    /// file holds. The composer calls it for a file the compose template ships and applies
    /// (the fields `apply` and `source` of [`TemplateArtifact::File`]).
    ///
    /// The default applies [`render`](Self::render) to a copy of `template` whose text is
    /// `text` and whose place is `place`, which serves an engine that reads the compose
    /// template's text. An engine ships files through `shipper` as
    /// [`render`](Self::render) does.
    ///
    /// # Errors
    ///
    /// As [`render`](Self::render).
    fn render_text(
        &self,
        template: &Template,
        text: &str,
        place: Option<&str>,
        context: &TemplateContext,
        shipper: &Arc<dyn TemplateShipper>,
    ) -> Result<String, String> {
        let source = place.map(str::to_string);
        self.render(&Template { text: text.to_string(), source, ..template.clone() }, context, shipper)
    }
}

// --- the settings --------------------------------------------------------------------------

/// Which compose template a render uses: one name for every output, or a name per output.
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
#[serde(untagged)]
pub enum TemplateChoice {
    /// The compose template of this name, for whichever output a render request makes.
    Name(String),
    /// A compose template's name per output's name; an output not listed takes
    /// [`DEFAULT_TEMPLATE`].
    ByOutput(BTreeMap<String, String>),
}

impl TemplateChoice {
    /// Returns the name of the compose template chosen for the output `output`.
    pub fn for_output(&self, output: &str) -> &str {
        match self {
            TemplateChoice::Name(name) => name,
            TemplateChoice::ByOutput(names) => {
                names.get(output).map(String::as_str).unwrap_or(DEFAULT_TEMPLATE)
            }
        }
    }
}

/// The render options of the feature `compose`, set per render request: the compose
/// template each output is assembled with, and each compose template's own settings.
///
/// It is an option type bound to the render request ([`Bind::Render`];
/// [`crate::model::options`]). A host combines its value from its sources of settings.
///
/// # Examples
///
/// ```
/// use flm_core::stdlib::features::compose::{ComposeOptions, DEFAULT_TEMPLATE};
///
/// assert_eq!(ComposeOptions::default().template.for_output("html"), DEFAULT_TEMPLATE);
/// ```
#[derive(Debug, Clone, PartialEq, serde::Deserialize, schemars::JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct ComposeOptions {
    /// The compose template: a name, or a map from an output's name to a compose
    /// template's name. The default is [`DEFAULT_TEMPLATE`], `simple`, for every output.
    pub template: TemplateChoice,
    /// A map from an output's name to a map from a compose template's name to that
    /// compose template's own settings for that output, written over its defaults key by
    /// key: `{latex-rendered: {simple: {documentclass: report}}}`. Two compose templates of
    /// the same name for two outputs are two compose templates, so their settings are
    /// given apart ([`ComposeOptions::config_for`]). An output's name that names no output
    /// a render makes is never read, as in [`TemplateChoice::ByOutput`].
    pub template_config: BTreeMap<String, BTreeMap<String, Map<String, Value>>>,
}

impl ComposeOptions {
    /// Returns the settings that [`template_config`](Self::template_config) gives for the
    /// compose template `template` of the output `output`, if it gives any.
    pub fn config_for(&self, output: &str, template: &str) -> Option<&Map<String, Value>> {
        self.template_config.get(output)?.get(template)
    }
}

impl Default for ComposeOptions {
    fn default() -> ComposeOptions {
        ComposeOptions {
            template: TemplateChoice::Name(String::from(DEFAULT_TEMPLATE)),
            template_config: BTreeMap::new(),
        }
    }
}

// An option type is part of a plan's key, so it hashes, and two values it holds equal hash
// equal: the settings of a template are data, whose maps are equal whatever the order of
// their entries, so they are hashed with every map's entries in the order of their keys.
impl Hash for ComposeOptions {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.template.hash(state);
        for (output, templates) in &self.template_config {
            output.hash(state);
            for (name, config) in templates {
                name.hash(state);
                hash_value(&Value::Object(config.clone()), state);
            }
        }
    }
}

/// Returns the declaration of the feature's settings: the fields of [`ComposeOptions`]
/// are its keys, set per render request. `template_config`, each output's map in it and
/// each compose template's settings are combined key by key across the sources of
/// settings, so that a source that writes one setting of a compose template leaves the
/// others as the lower sources write them; `false` is a value like any other there. The
/// settings of each compose template are an entry that another feature declares
/// ([`declare_settings`]).
fn settings() -> SettingsDecl {
    SettingsDecl::new(FEATURE)
        .options::<ComposeOptions>(
            Bind::Render,
            "The compose template each output is assembled with (`template`: a name, or a map \
             from an output's name to a compose template's name), and each compose template's \
             own settings (`template_config`, a map from an output's name to a map from a \
             compose template's name to its settings for that output). Set per render request.",
        )
        .merge_entries("template_config", no_entries)
        .merge_entries("template_config.*", no_entries)
        .merge_entries("template_config.*.*", no_entries)
        .open_entries("template_config.*.*")
}

/// Returns `decl`, the settings declaration of a feature that contributes the compose
/// templates `templates`, declaring the settings of each one that has a schema
/// ([`Template::settings`]) as the entry `template_config.OUTPUT.NAME` of the feature
/// `compose` ([`declare_template_settings`]).
///
/// # Errors
///
/// A [`SettingsError`] of the kind [`SettingsErrorKind::InvalidDeclaration`] for two
/// compose templates with a schema, of one output and one name, at the path
/// `compose.template_config.OUTPUT.NAME`; and the [`SettingsError`] of a schema whose marks
/// are faulty, as [`SettingsDecl::entry_data`] states.
pub fn declare_settings(mut decl: SettingsDecl, templates: &[Template]) -> Result<SettingsDecl, SettingsError> {
    for (index, template) in templates.iter().enumerate() {
        let Some(schema) = &template.settings else { continue };
        let path = format!("template_config.{}.{}", template.output, template.name);
        let earlier = templates[..index].iter().any(|other| {
            other.settings.is_some() && other.output == template.output && other.name == template.name
        });
        if earlier {
            return Err(SettingsError {
                path: format!("{FEATURE}.{path}"),
                kind: SettingsErrorKind::InvalidDeclaration,
                detail: format!(
                    "Duplicate compose template ‘{}’ for the output ‘{}’ in the package ‘{}’",
                    template.name, template.output, template.package
                ),
            });
        }
        decl = declare_template_settings(decl, &template.output, &template.name, schema.clone())?;
    }
    Ok(decl)
}

/// Returns `decl`, the settings declaration of a feature that contributes the compose
/// template `name` of the output `output`, declaring `schema`, the JSON Schema of the
/// compose template's settings, as the entry `template_config.OUTPUT.NAME` of the
/// feature `compose` ([`SettingsDecl::entry_data`]), labeled `compose template ‘NAME’
/// for the output ‘OUTPUT’`. A schema without a `description` gets one that names the
/// compose template. [`declare_settings`] declares the compose templates of a list this
/// way; a feature that contributes a compose template known by its name and its output
/// before it is made (a template module of an extension) calls this directly.
///
/// # Errors
///
/// The [`SettingsError`] of a schema whose marks are faulty, as
/// [`SettingsDecl::entry_data`] states.
pub fn declare_template_settings(
    decl: SettingsDecl,
    output: &str,
    name: &str,
    mut schema: Value,
) -> Result<SettingsDecl, SettingsError> {
    if let Value::Object(object) = &mut schema {
        if !object.contains_key("description") {
            let described = format!("The settings of the compose template ‘{name}’ of the output ‘{output}’.");
            let mut with = Map::new();
            with.insert(String::from("description"), Value::from(described));
            with.extend(std::mem::take(object));
            *object = with;
        }
    }
    let path = format!("template_config.{output}.{name}");
    let label = format!("compose template ‘{name}’ for the output ‘{output}’");
    decl.entry_data(FEATURE, path, label, schema)
}

/// The default entries of each level of `template_config`: none.
fn no_entries() -> Result<Value, String> {
    Ok(Value::Object(Map::new()))
}

// --- choosing a template -----------------------------------------------------------------------

/// Returns the compose template of the registry `registry` that `options` chooses for the
/// output `output`.
///
/// # Errors
///
/// Returns a text, for a person to read, when no compose template of the chosen name
/// serves the output (the text lists those that do, or says that none does), or when
/// several do (the text gives each package that ships one and how many it ships).
pub fn chosen_template<'r>(
    registry: &'r FlmRegistry,
    options: &ComposeOptions,
    output: &str,
) -> Result<&'r Template, String> {
    let name = options.template.for_output(output);
    let mut matching = registry
        .services()
        .services_named::<Template>(TEMPLATES_SLOT)
        .filter(|template| template.name == name && template.output == output);
    let first = matching.next();
    if let Some(template) = first {
        let others: Vec<&Template> = matching.collect();
        if !others.is_empty() {
            // Each package that ships one, with how many it ships.
            let mut packages: Vec<(&str, usize)> = Vec::new();
            for template in std::iter::once(template).chain(others) {
                match packages.iter_mut().find(|(package, _)| *package == template.package) {
                    Some((_, count)) => *count += 1,
                    None => packages.push((template.package.as_str(), 1)),
                }
            }
            let shipped: Vec<String> =
                packages.iter().map(|(package, count)| format!("the package ‘{package}’ ships {count}")).collect();
            return Err(format!(
                "only one compose template named ‘{name}’ for the output ‘{output}’ may be in use; {}",
                shipped.join(", ")
            ));
        }
    }
    first.ok_or_else(|| {
            let known: Vec<&str> = registry
                .services()
                .services_named::<Template>(TEMPLATES_SLOT)
                .filter(|template| template.output == output)
                .map(|template| template.name.as_str())
                .collect();
            if known.is_empty() {
                format!(
                    "the compose template `{name}` must be one of the compose templates for the output \
                     `{output}`, and no package in use ships one for that output"
                )
            } else {
                format!(
                    "the compose template `{name}` must be one of the compose templates for the output \
                     `{output}`: `{}`",
                    known.join("`, `")
                )
            }
        })
}

/// Returns the pieces that the compose template `template` accepts among those that
/// `registry` declares, in the order of their declarations: the selection of pieces that
/// a host writes for the output's backend into [`PiecesRenderOptions::backends`].
pub fn accepted_pieces(registry: &FlmRegistry, template: &Template) -> Vec<Name> {
    core_pieces::declared_pieces(registry)
        .filter(|decl| match &template.accepts {
            Accepts::All => true,
            Accepts::Only(names) => names.contains(&decl.name),
        })
        .map(|decl| decl.name.clone())
        .collect()
}

/// Sets, in `pieces`, the selection of pieces of the backend of `output` to the pieces
/// that the compose template `template` accepts ([`accepted_pieces`]), and adds the
/// pieces it requires ([`Template::requires`]) to the pieces placed although declared off
/// by default ([`PiecesRenderOptions::include`]), so that what the compose template
/// requires is placed.
///
/// The host calls it when it prepares the plan of an output that the composer serves.
pub fn select_pieces(
    registry: &FlmRegistry,
    template: &Template,
    output: &RegionsOutput,
    pieces: &mut PiecesRenderOptions,
) {
    pieces.backends.insert(
        output.backend.clone(),
        accepted_pieces(registry, template).into_iter().collect(),
    );
    pieces.include.extend(template.requires.iter().cloned());
}

// --- the composer's table on HTML ----------------------------------------------------------

/// What one region's place in the page holds: HTML, or plain words.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ComposedKind {
    /// HTML, placed inside the element that carries the region's identifier.
    Html,
    /// Plain words, placed where no element is allowed: the words of the page's title
    /// (the region [`title`](region::TITLE), placed in `<title>`), kept under that
    /// region's identifier. A piece's words are not in the table but in the rest of the
    /// page (see the [module
    /// documentation](self#on-html-one-element-per-region-and-the-composers-table)).
    Words,
}

/// One region as the page holds it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ComposedRegion {
    /// The identifier: [`region_id`] of the region's name.
    pub id: String,
    /// The region's name.
    pub name: String,
    /// Whether the text is HTML or words.
    pub kind: ComposedKind,
    /// The text: the HTML inside the element, or the words.
    pub text: String,
}

/// The composer's table on HTML, [`HTML_REGIONS`]: each region that the composer placed,
/// and the rest of the page (see the [module
/// documentation](self#on-html-one-element-per-region-and-the-composers-table)).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ComposedRegions {
    /// The rest of the page, everything outside its regions: the page with exactly what
    /// [`regions`](Self::regions) holds left out, that is with every element that carries
    /// a region's identifier empty and the title's words empty, and everything else as in
    /// the page (the stylesheets, the scripts, the language, the compose template's own
    /// markup, each piece's words). The regions and the rest of the page together make up
    /// the page, so two builds that differ anywhere differ in the rest of the page or in
    /// an entry of [`regions`](Self::regions).
    pub skeleton: String,
    /// Each region that the composer placed (the content and the pieces), and the words of
    /// the page's title.
    pub regions: Vec<ComposedRegion>,
}

impl ComposedRegions {
    /// Returns the region with the identifier `id`, if there is one.
    pub fn get(&self, id: &str) -> Option<&ComposedRegion> {
        self.regions.iter().find(|region| region.id == id)
    }
}

impl Table for ComposedRegions {
    /// The table has one writer per run: a second write replaces the first.
    fn absorb(&mut self, piece: ComposedRegions) {
        *self = piece;
    }

    /// `{skeleton, regions: [{id, name, kind, text}]}`.
    fn project(&self, _cx: &dyn ProjectCx) -> SerialValue {
        let regions = self
            .regions
            .iter()
            .map(|region| {
                SerialValue::Map(vec![
                    (String::from("id"), SerialValue::Str(region.id.clone())),
                    (String::from("name"), SerialValue::Str(region.name.clone())),
                    (
                        String::from("kind"),
                        SerialValue::Str(String::from(match region.kind {
                            ComposedKind::Html => "html",
                            ComposedKind::Words => "words",
                        })),
                    ),
                    (String::from("text"), SerialValue::Str(region.text.clone())),
                ])
            })
            .collect();
        SerialValue::Map(vec![
            (String::from("skeleton"), SerialValue::Str(self.skeleton.clone())),
            (String::from("regions"), SerialValue::List(regions)),
        ])
    }

    fn piece_class(&self) -> PieceClass {
        PieceClass::DocumentFact
    }
}

// --- the feature ---------------------------------------------------------------------------

/// The feature `compose`: see the [module documentation](self). A host registers it; it
/// is not among the standard features that
/// [`stdlib::add_features`](crate::stdlib::add_features) adds.
#[derive(Debug, Default, Clone, Copy)]
pub struct ComposeFeature;

impl ComposeFeature {
    /// The feature `compose`: the two service slots, the template engine `content-only`,
    /// the table `flm.compose.html.regions`, a composer per regions output. It contributes
    /// no compose template.
    pub fn new() -> ComposeFeature {
        ComposeFeature
    }
}

impl FlmFeature for ComposeFeature {
    fn info(&self) -> FeatureInfo {
        FeatureInfo::new(FEATURE, "Templates").docs(
            "the template engines, the compose templates, and for each output a stage that \
             assembles the output from its content and its other parts through the chosen \
             compose template",
        )
    }

    fn settings(&self) -> Option<SettingsDecl> {
        Some(settings())
    }

    fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
        b.service_slot::<dyn TemplateEngine>(
            ENGINES_SLOT,
            Arity::OrderedMany,
            "the template engines, each with a name",
        )?;
        b.service_slot::<Template>(
            TEMPLATES_SLOT,
            Arity::OrderedMany,
            "the compose templates, each with a name and the output it serves",
        )?;
        b.contribute_to::<dyn TemplateEngine>(ENGINES_SLOT, Arc::new(ContentOnlyEngine))?;
        b.table(
            HTML_REGIONS,
            "the HTML that the page holds under each region's identifier, the words of the page's \
             title, and the rest of the page outside those regions",
        )?;
        b.finalizer(Arc::new(RegisterStages))
    }
}

/// The second round of the feature's registration ([`Finalizer`]): registers one stage
/// per output that a backend of the registry states is made of output regions, once every
/// feature has contributed to [`REGIONS_SLOT`].
struct RegisterStages;

impl Finalizer for RegisterStages {
    fn finalize(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
        let outputs: Vec<RegionsOutput> = b
            .services()
            .map(|services| services.services_named::<RegionsOutput>(REGIONS_SLOT).cloned().collect())
            .unwrap_or_default();
        for output in outputs {
            b.stage(Arc::new(ComposeStage { output }))?;
        }
        Ok(())
    }
}

// --- the stage -----------------------------------------------------------------------------

/// The composer's stage for one output, `flm.compose.<output>`: see the [module
/// documentation](self).
struct ComposeStage {
    output: RegionsOutput,
}

/// Returns an empty span whose origin is the stage `stage`, for a problem that has no
/// place in the document.
fn nowhere(stage: &str) -> FlmSpan {
    let source = Arc::new(Source::new("").with_origin(FlmOrigin::synthetic(stage)));
    SourceSpan::new(&source, 0..0)
}

impl ComposeStage {
    fn regions_table(&self) -> TableHandle<Regions> {
        self.output.regions.clone()
    }

    fn document_table(&self) -> TableHandle<ArtifactSet> {
        TableHandle::new(self.output.document.clone())
    }

    fn fail(&self, out: &mut StageOut<'_>, template: Option<&str>, detail: impl ToString) {
        out.diags.push(Diagnostic::error(
            TemplateFailed {
                template: template.map(String::from),
                output: self.output.output.to_string(),
                detail: detail.to_string(),
            },
            nowhere(&stage_name(self.output.output.as_str())),
        ));
    }
}

impl Stage for ComposeStage {
    fn decl(&self) -> StageDecl {
        let mut decl =
            StageDecl::new(stage_name(self.output.output.as_str()), Effect::Compute, Scope::Document)
                .writes(self.document_table());
        if self.output.capability != self.output.document {
            decl = decl.provides(self.output.capability.clone());
        }
        if is_html(&self.output) {
            decl = decl.writes(HTML_REGIONS);
        }
        decl.docs(format!(
            "assembles the `{}` output's entry artifact from its output regions through the \
             chosen compose template",
            self.output.output
        ))
    }

    fn needs(&self, cx: &PlanCx<'_>) -> Needs {
        let mut needs = Needs::new().reads(self.regions_table()).option::<ComposeOptions>();
        for artifacts in &self.output.artifacts {
            needs = needs.reads_opt(artifacts.clone());
        }
        // The metadata is read where a feature of the registry declares it.
        if cx.registry().option_decl(&OptionKey::of::<DocMeta>()).is_some() {
            needs = needs.option::<DocMeta>();
        }
        // A required piece is read, so that a plan in which nobody provides it fails.
        let default = ComposeOptions::default();
        let options = cx.render_option::<ComposeOptions>().unwrap_or(&default);
        if let Ok(template) = chosen_template(cx.registry(), options, self.output.output.as_str()) {
            let declared: Vec<&PieceDecl> = core_pieces::declared_pieces(cx.registry()).collect();
            for name in &template.requires {
                // A piece nobody declares is read under its table's usual name, which is
                // the piece's, so that the plan fails naming it.
                let table = match declared.iter().find(|decl| &decl.name == name) {
                    Some(decl) => decl.table.clone(),
                    None => TableHandle::<Piece>::new(name.clone()),
                };
                needs = needs.reads(table);
            }
        }
        needs
    }

    fn run(&self, cx: &StageCx<'_>, out: &mut StageOut<'_>) {
        let options = match cx.option::<ComposeOptions>() {
            Ok(options) => options,
            Err(error) => return self.fail(out, None, error),
        };
        let name = options.template.for_output(self.output.output.as_str());
        let template = match chosen_template(cx.registry(), options, self.output.output.as_str()) {
            Ok(template) => template,
            Err(detail) => return self.fail(out, Some(name), detail),
        };
        let Some(engine) = cx
            .registry()
            .services()
            .services_by_precedence_named::<dyn TemplateEngine>(ENGINES_SLOT)
            .find(|engine| engine.name() == template.engine)
        else {
            return self.fail(out, Some(name), format!("the template engine `{}`, in which the template is written, must be provided by a package in use, and none provides it", template.engine));
        };
        let regions = match cx.get(&self.regions_table()) {
            Ok(Some(regions)) => regions,
            Ok(None) => return,
            Err(error) => return self.fail(out, Some(name), error),
        };
        let mut beside = Vec::new();
        for artifacts in &self.output.artifacts {
            match cx.get(artifacts) {
                Ok(set) => beside.extend(set),
                Err(error) => return self.fail(out, Some(name), error),
            }
        }
        // The metadata is read where a feature of the registry declares it, as the plan
        // does; a failed read is reported as the stage's other failed reads are.
        let metadata = if cx.registry().option_decl(&OptionKey::of::<DocMeta>()).is_some() {
            match cx.option::<DocMeta>() {
                Ok(meta) => meta_value(meta),
                Err(error) => return self.fail(out, Some(name), error),
            }
        } else {
            Value::Object(Map::new())
        };
        let mut config = template.config.clone();
        if let Some(given) = options.config_for(&template.output, &template.name) {
            for (key, value) in given {
                config.insert(key.clone(), value.clone());
            }
        }
        let mut context = context(&self.output, regions, metadata, config, Vec::new());
        let namer = cx.services_all().shared_service_named::<dyn ArtifactNamer>(NAMER_SLOT).cloned();
        let scope = NamingScope::of(cx.registry(), cx.plan().demands());
        let shipper = Arc::new(Shipper { namer, scope, shipped: Mutex::new(Vec::new()), warnings: Mutex::new(Vec::new()) });
        let handle: Arc<dyn TemplateShipper> = shipper.clone();
        // The warnings of the template engine are reported whether the application
        // succeeds or fails.
        'applied: {
            // The files the compose template ships, as its template engine answers them for
            // this context, which holds no path yet; then their paths, from the naming of
            // files, which the compose template reads.
            let artifacts = match engine.artifacts(template, &context, &handle) {
                Ok(artifacts) => artifacts,
                Err(detail) => break 'applied self.fail(out, Some(name), detail),
            };
            let mut paths = Vec::new();
            if !artifacts.is_empty() {
                let Some(namer) = &shipper.namer else {
                    let names: Vec<&str> = artifacts.iter().map(TemplateArtifact::name).collect();
                    break 'applied self.fail(
                        out,
                        Some(name),
                        format!(
                            "the compose template ships the files `{}`, and naming them needs the program's naming \
                             of files (the service slot `{NAMER_SLOT}`), which no package in use provides",
                            names.join("`, `")
                        ),
                    );
                };
                for artifact in &artifacts {
                    let id = artifact_id(artifact);
                    let named = match artifact {
                        TemplateArtifact::File { media_type, extension, .. } => ArtifactRef {
                            id: &id,
                            entry: false,
                            media_type,
                            extension: Some(extension),
                            output: None,
                            folder: false,
                        },
                        TemplateArtifact::Folder { .. } => {
                            ArtifactRef { id: &id, entry: false, media_type: "", extension: None, output: None, folder: true }
                        }
                    };
                    paths.push((artifact.name().to_string(), namer.url_of(&named, &shipper.scope).as_str().to_string()));
                }
            }
            context.artifacts = paths;
            let mut shipped = Vec::new();
            for artifact in &artifacts {
                let (artifact_name, extension, media_type, apply, bytes, place) = match artifact {
                    TemplateArtifact::File { name, extension, media_type, apply, bytes, source } => {
                        (name, extension, media_type, *apply, bytes, source.as_deref())
                    }
                    TemplateArtifact::Folder { files, .. } => {
                        let files = files.iter().map(|(path, bytes)| (RelPath::new(path.as_str()), bytes.clone())).collect();
                        shipped.push(Artifact::folder(artifact_id(artifact), files));
                        continue;
                    }
                };
                let bytes = if apply {
                    let Ok(text) = std::str::from_utf8(bytes) else {
                        let detail = format!(
                            "in the artifact `{artifact_name}`: its content must be text, since it is applied as a template"
                        );
                        break 'applied self.fail(out, Some(name), detail);
                    };
                    let mut applied = context.clone();
                    applied.html = media_type == "text/html";
                    match engine.render_text(template, text, place, &applied, &handle) {
                        Ok(text) => text.into_bytes(),
                        Err(detail) => {
                            break 'applied self.fail(out, Some(name), format!("in the artifact `{artifact_name}`: {detail}"));
                        }
                    }
                } else {
                    bytes.clone()
                };
                shipped.push(Artifact::bytes(artifact_id(artifact), media_type.clone(), bytes).with_extension(extension.clone()));
            }
            let text = match engine.render(template, &context, &handle) {
                Ok(text) => text,
                Err(detail) => break 'applied self.fail(out, Some(name), detail),
            };
            let composed = if is_html(&self.output) {
                let empty = context_with_regions_left_out(regions, &context);
                match engine.render(template, &empty, &handle) {
                    Ok(skeleton) => Some(composed_regions(regions, skeleton)),
                    Err(detail) => break 'applied self.fail(out, Some(name), detail),
                }
            } else {
                None
            };
            shipped.extend(shipper.take());
            let mut entry =
                Artifact::bytes(regions.entry.clone(), regions.media_type.clone(), text.into_bytes())
                    .as_entry();
            entry.refs.extend(regions.refs.iter().cloned());
            entry.refs.extend(shipped.iter().map(|artifact| artifact.id.clone()));
            let set = match out.table(&self.document_table()) {
                Ok(set) => set,
                Err(error) => break 'applied self.fail(out, Some(name), error),
            };
            let reports = match set.insert_entry_with(entry, &beside) {
                Ok(reports) => reports,
                Err(violation) => break 'applied self.fail(out, Some(name), violation),
            };
            let refused: Vec<_> = shipped.into_iter().filter_map(|artifact| set.insert(artifact).err()).collect();
            reports.into_iter().for_each(|report| out.diags.push(report));
            for violation in refused {
                self.fail(out, Some(name), violation);
            }
            if let Some(composed) = composed {
                match out.table(HTML_REGIONS) {
                    Ok(table) => *table = composed,
                    Err(error) => self.fail(out, Some(name), error),
                }
            }
        }
        for detail in shipper.take_warnings() {
            out.diags.push(Diagnostic::warning(
                TemplateWarning { template: name.to_string(), output: self.output.output.to_string(), detail },
                nowhere(&stage_name(self.output.output.as_str())),
            ));
        }
    }
}

/// The composer's [`TemplateShipper`] for one application of a compose template: it names
/// each file it is handed and keeps it, until the composer adds the files to the output's
/// artifact set, and keeps each warning given to [`warn`](TemplateShipper::warn), until the
/// composer reports it.
struct Shipper {
    /// The program's naming of files, where a package in use provides it.
    namer: Option<Arc<dyn ArtifactNamer>>,
    /// The scope in which the files are named.
    scope: NamingScope,
    /// The files shipped so far, in the order of their first shipping, each with its path.
    shipped: Mutex<Vec<(Artifact, String)>>,
    /// The warnings of the template engine, each once, in the order first given.
    warnings: Mutex<Vec<String>>,
}

impl Shipper {
    /// Returns the files shipped, in the order of their first shipping.
    fn take(&self) -> Vec<Artifact> {
        let mut shipped = self.shipped.lock().unwrap_or_else(PoisonError::into_inner);
        std::mem::take(&mut *shipped).into_iter().map(|(artifact, _)| artifact).collect()
    }

    /// Returns the warnings of the template engine, each once, in the order first given.
    fn take_warnings(&self) -> Vec<String> {
        std::mem::take(&mut *self.warnings.lock().unwrap_or_else(PoisonError::into_inner))
    }
}

impl TemplateShipper for Shipper {
    fn warn(&self, detail: String) {
        let mut warnings = self.warnings.lock().unwrap_or_else(PoisonError::into_inner);
        if !warnings.contains(&detail) {
            warnings.push(detail);
        }
    }

    fn ship(&self, file: ShippedFile) -> Result<String, String> {
        let ShippedFile { stem, extension, media_type, bytes } = file;
        let Some(namer) = &self.namer else {
            return Err(format!("Missing naming of files for the shipped file ‘{stem}.{extension}’ (service slot ‘{NAMER_SLOT}’)"));
        };
        let mut digest = Fnv1a64::new();
        digest.write_bytes(&bytes);
        digest.write_str(&media_type);
        let id = ArtifactId::new(FEATURE, digest_name(&name_safe(&stem), &digest));
        let mut shipped = self.shipped.lock().unwrap_or_else(PoisonError::into_inner);
        if let Some((_, path)) = shipped.iter().find(|(artifact, _)| artifact.id == id) {
            return Ok(path.clone());
        }
        let named =
            ArtifactRef { id: &id, entry: false, media_type: &media_type, extension: Some(&extension), output: None, folder: false };
        let path = namer.url_of(&named, &self.scope).as_str().to_string();
        let artifact = Artifact::bytes(id, media_type, bytes).with_extension(extension);
        shipped.push((artifact, path.clone()));
        Ok(path)
    }
}

/// Returns the metadata as a compose template reads it: see the [module
/// documentation](self#what-a-compose-template-reads).
fn meta_value(meta: &DocMeta) -> Value {
    let mut map = Map::new();
    if let Some(title) = &meta.title {
        map.insert(String::from("title"), Value::String(title.text.clone()));
    }
    if !meta.authors.is_empty() {
        map.insert(String::from(AUTHOR_KEY), Value::Array(meta.authors.iter().map(author_value).collect()));
    }
    if let Some(date) = &meta.date {
        map.insert(String::from("date"), Value::String(date.text.clone()));
    }
    for (key, value) in &meta.other {
        map.insert(key.clone(), value.clone());
    }
    Value::Object(map)
}

/// Returns one author as a compose template reads it: a map holding `name`,
/// `affiliation` (a list), `email` (when the author has one), `note` (a list) and the
/// author's other keys, each text as the author wrote it.
fn author_value(author: &MetaAuthor) -> Value {
    let texts = |texts: &[MetaText]| Value::Array(texts.iter().map(|text| Value::String(text.text.clone())).collect());
    let mut map = Map::new();
    map.insert(String::from(NAME_KEY), Value::String(author.name.text.clone()));
    map.insert(String::from(AFFILIATION_KEY), texts(&author.affiliations));
    if let Some(email) = &author.email {
        map.insert(String::from(EMAIL_KEY), Value::String(email.text.clone()));
    }
    map.insert(String::from(NOTE_KEY), texts(&author.notes));
    for (key, value) in &author.other {
        map.insert(key.clone(), value.clone());
    }
    Value::Object(map)
}

/// Returns the text of `region` as a compose template places it: on HTML, the content and
/// each piece inside the element that carries its name.
fn placed(output: &RegionsOutput, region: &Region) -> String {
    let name = region.name.as_str();
    let text = region.text();
    if is_html(output) && composed_kind(region) == Some(ComposedKind::Html) {
        region_element(name, &text)
    } else {
        text
    }
}

/// Returns the identity of the file `artifact` that a compose template ships,
/// `compose:<name>`.
fn artifact_id(artifact: &TemplateArtifact) -> ArtifactId {
    ArtifactId::new(FEATURE, artifact.name())
}

/// Returns what a compose template reads, from the output's regions, the metadata, the
/// compose template's settings and the paths of the files it ships.
fn context(
    output: &RegionsOutput,
    regions: &Regions,
    metadata: Value,
    config: Map<String, Value>,
    artifacts: Vec<(String, String)>,
) -> TemplateContext {
    let mut values = Vec::new();
    let mut pieces = Vec::new();
    for region in &regions.regions {
        let text = placed(output, region);
        if let Some(place) = region.piece {
            pieces.push(PieceValue {
                name: region.name.to_string(),
                place: String::from(place.as_str()),
                text: text.clone(),
                words: region.words.clone().unwrap_or_default(),
            });
        }
        values.push((region.name.to_string(), text));
    }
    TemplateContext { html: is_html(output), regions: values, pieces, metadata, config, artifacts }
}

/// Returns how the composer's table on HTML holds `region`: the content and each piece as
/// HTML, the words of the page's title as words, and every other region not at all (it is
/// then part of the rest of the page, as each piece's words are). The regions in the table
/// and the rest of the page together make up the page, so this one rule decides both
/// ([`composed_regions`], [`context_with_regions_left_out`]).
fn composed_kind(region: &Region) -> Option<ComposedKind> {
    if region.piece.is_some() || region.name.as_str() == region::CONTENT {
        Some(ComposedKind::Html)
    } else if region.name.as_str() == region::TITLE {
        Some(ComposedKind::Words)
    } else {
        None
    }
}

/// Returns `context` with exactly the regions of the composer's table left out
/// ([`composed_kind`]): the content and each piece placed in its element with nothing
/// inside, the title's words empty, and every other region (the stylesheets, the scripts,
/// the language) and each piece's words as in the page. Applying the compose template to
/// it gives the rest of the page.
fn context_with_regions_left_out(regions: &Regions, context: &TemplateContext) -> TemplateContext {
    let mut empty = context.clone();
    for (name, text) in &mut empty.regions {
        let Some(region) = regions.get(name) else { continue };
        match composed_kind(region) {
            Some(ComposedKind::Html) => *text = region_element(name, ""),
            Some(ComposedKind::Words) => text.clear(),
            None => {}
        }
    }
    for piece in &mut empty.pieces {
        piece.text = region_element(&piece.name, "");
    }
    empty
}

/// Returns the composer's table on HTML, from the output's regions and the rest of the page
/// `skeleton`.
fn composed_regions(regions: &Regions, skeleton: String) -> ComposedRegions {
    let mut composed = Vec::new();
    for region in &regions.regions {
        let Some(kind) = composed_kind(region) else { continue };
        let text = match kind {
            ComposedKind::Html => region.text(),
            ComposedKind::Words => region.words.clone().unwrap_or_default(),
        };
        let name = region.name.as_str();
        composed.push(ComposedRegion { id: region_id(name), name: String::from(name), kind, text });
    }
    ComposedRegions { skeleton, regions: composed }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::hash_map::DefaultHasher;

    fn hash_of(options: &ComposeOptions) -> u64 {
        let mut hasher = DefaultHasher::new();
        options.hash(&mut hasher);
        hasher.finish()
    }

    #[test]
    fn two_equal_options_hash_equal_whatever_the_order_of_their_entries() {
        let with = |entries: &[(&str, Value)]| {
            let mut config = Map::new();
            for (key, value) in entries {
                config.insert(String::from(*key), value.clone());
            }
            let mut options = ComposeOptions::default();
            options.template_config.entry(String::from("html")).or_default().insert(String::from("simple"), config);
            options
        };
        let inner = |a: i64, b: i64| {
            let mut map = Map::new();
            map.insert(String::from("a"), Value::from(a));
            map.insert(String::from("b"), Value::from(b));
            map
        };
        let mut reversed = Map::new();
        reversed.insert(String::from("b"), Value::from(2));
        reversed.insert(String::from("a"), Value::from(1));
        let first = with(&[("x", Value::from("one")), ("y", Value::Object(inner(1, 2)))]);
        let second = with(&[("y", Value::Object(reversed)), ("x", Value::from("one"))]);
        assert_eq!(first, second);
        assert_eq!(hash_of(&first), hash_of(&second));
        let other = with(&[("x", Value::from("one")), ("y", Value::Object(inner(1, 3)))]);
        assert_ne!(hash_of(&first), hash_of(&other));
    }

    #[test]
    fn a_repeated_warning_is_kept_once_in_the_order_first_given() {
        let shipper = Shipper { namer: None, scope: NamingScope::default(), shipped: Mutex::new(Vec::new()), warnings: Mutex::new(Vec::new()) };
        shipper.warn(String::from("first"));
        shipper.warn(String::from("second"));
        shipper.warn(String::from("first"));
        assert_eq!(shipper.take_warnings(), vec![String::from("first"), String::from("second")]);
    }
}