compose-lens 0.1.14

Loss-aware parsing, processing, validation, and rendering of Compose projects
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
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
//! Deterministic construction of new Compose documents from reviewed native values.

use std::{collections::BTreeSet, error::Error, fmt};

use crate::{
    model::{
        ComposeDocument, MemLimitUnit, ShmSizeUnit, StopGracePeriod, valid_generated_device_string,
        valid_generated_mem_amount, valid_generated_shm_amount, valid_generated_tmpfs_item, valid_hostname,
        valid_positive_pids_decimal, valid_pull_policy_duration, valid_ulimit_name,
    },
    source::SourceId,
    syntax::SyntaxDocument,
};

use super::write_quoted;

/// A generated Compose construction request is invalid or cannot be represented safely.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum GenerationError {
    /// A required value is empty.
    EmptyValue(&'static str),
    /// A value contains a NUL byte and cannot represent native container intent safely.
    ContainsNul(&'static str),
    /// A value contains a carriage return or line feed where one YAML string item is required.
    ContainsLineBreak(&'static str),
    /// An environment name contains Compose list-form's `=` separator.
    InvalidEnvironmentName,
    /// A custom container name does not satisfy Compose's portable name grammar.
    InvalidContainerName,
    /// A service hostname is empty, deferred, or outside the conservative RFC-1123 grammar.
    InvalidHostname,
    /// A custom pull interval does not match the documented Compose duration grammar.
    InvalidPullPolicyDuration,
    /// A finite PID limit is not a positive integral decimal.
    InvalidPidsLimit,
    /// A service shared-memory amount is not a canonical positive ASCII decimal.
    InvalidShmSize,
    /// A service memory-limit amount is not a canonical positive ASCII decimal.
    InvalidMemLimit,
    /// A service-level temporary-filesystem item is deferred, malformed, or provider-dependent.
    InvalidTmpfsItem,
    /// A generated short device or long-device member is empty where required, multiline, or deferred.
    InvalidDeviceValue(&'static str),
    /// A generated sysctl mapping name is empty, multiline, NUL-bearing, or expression-shaped.
    InvalidSysctlName,
    /// A generated sysctl value or list item is multiline, NUL-bearing, or expression-shaped.
    InvalidSysctlValue,
    /// A generated ulimit name is outside the portable lowercase ASCII grammar.
    InvalidUlimitName,
    /// A generated ulimit value is outside the supported portable decimal or unlimited set.
    InvalidUlimitValue,
    /// A generated ulimit range omitted its required soft or hard member.
    MissingUlimitRangeMember(&'static str),
    /// A stop grace period does not match the raw-preserving policy based on documented Compose units.
    InvalidStopGracePeriod,
    /// A short-form component contains its reserved separator.
    InvalidShortComponent(&'static str),
    /// A short bind spelling needed for `SELinux` cannot be encoded unambiguously.
    InvalidSelinuxBind,
    /// A singleton field was configured more than once.
    DuplicateField(&'static str),
    /// A named generated collection contains the same name more than once.
    DuplicateName {
        /// Collection whose name collided.
        kind: &'static str,
        /// Duplicate non-sensitive name.
        name: String,
    },
    /// A generated sequence contains an exact duplicate item.
    DuplicateItem(&'static str),
    /// A generated port used target port zero.
    InvalidPort,
    /// An `SCTP` port selected a host address without a published port.
    UnrepresentableSctpHostIp,
    /// A generated project contains no services.
    MissingService,
    /// `ComposeLens` could not parse its own deterministic generated bytes.
    InternalInvariant(&'static str),
}

impl fmt::Display for GenerationError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyValue(kind) => write!(formatter, "generated {kind} must not be empty"),
            Self::ContainsNul(kind) => write!(formatter, "generated {kind} must not contain a NUL byte"),
            Self::ContainsLineBreak(kind) => {
                write!(formatter, "generated {kind} must not contain a carriage return or line feed")
            }
            Self::InvalidEnvironmentName => formatter.write_str("generated environment name must not contain `=`"),
            Self::InvalidContainerName => {
                formatter.write_str("generated container name must match `[a-zA-Z0-9][a-zA-Z0-9_.-]+`")
            }
            Self::InvalidHostname => formatter.write_str(
                "generated hostname must be a resolved ASCII RFC-1123 name with labels of 1 to 63 characters and total length at most 253",
            ),
            Self::InvalidPullPolicyDuration => formatter.write_str(
                "generated pull policy duration must match integer `w`, `d`, `h`, `m`, and `s` components",
            ),
            Self::InvalidPidsLimit => {
                formatter.write_str("generated finite PID limit must be a positive integral decimal")
            }
            Self::InvalidShmSize => formatter.write_str(
                "generated shared-memory size must use a canonical positive ASCII-integer amount and an explicit documented lowercase unit",
            ),
            Self::InvalidMemLimit => formatter.write_str(
                "generated memory limit must use a canonical positive ASCII-integer amount and an explicit documented lowercase unit",
            ),
            Self::InvalidTmpfsItem => formatter.write_str(
                "generated tmpfs item must be a non-empty path optionally followed by a colon and non-empty comma-separated raw options",
            ),
            Self::InvalidDeviceValue(member) => write!(
                formatter,
                "generated device {member} must be a safe resolved single-line string{}",
                if matches!(*member, "short item" | "source") {
                    " and must not be empty"
                } else {
                    ""
                }
            ),
            Self::InvalidSysctlName => formatter
                .write_str("generated sysctl name must be a non-empty resolved single-line string"),
            Self::InvalidSysctlValue => formatter
                .write_str("generated sysctl value must be a resolved single-line string"),
            Self::InvalidUlimitName => formatter
                .write_str("generated ulimit name must match lowercase ASCII `[a-z]+`"),
            Self::InvalidUlimitValue => formatter
                .write_str("generated ulimit value must be `-1` or a non-negative ASCII decimal"),
            Self::MissingUlimitRangeMember(member) => {
                write!(formatter, "generated ulimit range is missing required `{member}`")
            }
            Self::InvalidStopGracePeriod => formatter.write_str(
                "generated stop grace period must match the ComposeLens duration policy using `us`, `ms`, `s`, `m`, or `h`, or contain an interpolation marker",
            ),
            Self::InvalidShortComponent(kind) => {
                write!(formatter, "generated {kind} contains its reserved short-form separator")
            }
            Self::InvalidSelinuxBind => formatter
                .write_str("generated SELinux bind source and target must not contain the short-syntax `:` separator"),
            Self::DuplicateField(field) => write!(formatter, "generated field `{field}` was configured more than once"),
            Self::DuplicateName { kind, name } => {
                write!(formatter, "generated {kind} `{name}` was added more than once")
            }
            Self::DuplicateItem(kind) => write!(formatter, "generated {kind} contains an exact duplicate item"),
            Self::InvalidPort => formatter.write_str("generated container target port must be greater than zero"),
            Self::UnrepresentableSctpHostIp => formatter.write_str(
                "generated SCTP port with a host address also requires a published port for Compose short syntax",
            ),
            Self::MissingService => formatter.write_str("generated Compose project requires at least one service"),
            Self::InternalInvariant(stage) => write!(formatter, "generated Compose document failed {stage} validation"),
        }
    }
}

impl Error for GenerationError {}

/// A plain or sensitive string used by generated Compose fields.
#[derive(Clone, Eq, PartialEq)]
pub struct GeneratedString {
    value: String,
    sensitive: bool,
}

impl GeneratedString {
    /// Creates a non-sensitive generated string.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::ContainsNul`] when the value contains a NUL byte.
    pub fn plain(value: impl Into<String>) -> Result<Self, GenerationError> {
        Self::new(value.into(), false)
    }

    /// Creates a sensitive generated string whose debug representation is redacted.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::ContainsNul`] when the value contains a NUL byte.
    pub fn sensitive(value: impl Into<String>) -> Result<Self, GenerationError> {
        Self::new(value.into(), true)
    }

    fn new(value: String, sensitive: bool) -> Result<Self, GenerationError> {
        if value.contains('\0') {
            return Err(GenerationError::ContainsNul("string"));
        }
        Ok(Self { value, sensitive })
    }

    /// Returns the generated value through an explicit access boundary.
    #[must_use]
    pub fn expose(&self) -> &str {
        &self.value
    }

    /// Reports whether debug output must redact this value.
    #[must_use]
    pub const fn is_sensitive(&self) -> bool {
        self.sensitive
    }
}

impl fmt::Debug for GeneratedString {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("GeneratedString")
            .field("value", &if self.sensitive { "<redacted>" } else { &self.value })
            .field("sensitive", &self.sensitive)
            .finish()
    }
}

/// Compose command form selected for a generated service.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum GeneratedCommand {
    /// Execute an exact argument vector without Compose shell parsing.
    Exec(Vec<GeneratedString>),
    /// Execute one Compose shell-form command.
    Shell(GeneratedString),
    /// Explicitly clear the image command.
    Empty,
}

/// Compose entrypoint form selected for a generated service.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum GeneratedEntrypoint {
    /// Emit an exact entrypoint list in authored argument order.
    List(Vec<GeneratedString>),
    /// Emit the short scalar string form.
    String(GeneratedString),
    /// Explicitly clear the entrypoint declared by the image.
    Empty,
}

/// A valid service-level Compose restart policy selected for generated output.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum GeneratedRestartPolicy {
    /// Never restart the container automatically.
    No,
    /// Always restart the container until it is removed.
    Always,
    /// Restart after an error, optionally with a maximum retry count.
    OnFailure {
        /// Maximum retries, or `None` for no explicit limit.
        maximum_retries: Option<u64>,
    },
    /// Restart except after an explicit stop or removal.
    UnlessStopped,
}

/// A documented service-level Compose image pull policy selected for generated output.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum GeneratedPullPolicy {
    /// Pull before every service start.
    Always,
    /// Never pull and rely on a cached image.
    Never,
    /// Pull only when the image is missing.
    Missing,
    /// Emit the retained `if_not_present` alias.
    IfNotPresentAlias,
    /// Build the image before starting the service.
    Build,
    /// Check once per day.
    Daily,
    /// Check once per week.
    Weekly,
    /// Check after an exact caller-supplied duration spelling.
    Every(GeneratedString),
}

/// A service-level Compose PID limit selected for generated output.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum GeneratedPidsLimit {
    /// Emit the documented unlimited spelling `-1`.
    Unlimited,
    /// Emit an exact positive integral decimal without fixed-width integer parsing.
    Finite(String),
}

/// A safe explicit service shared-memory size selected for generated Compose output.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum GeneratedShmSize {
    /// Emit one quoted amount and documented lowercase unit.
    Explicit {
        /// Canonical positive ASCII-integer amount without leading zeros.
        amount: GeneratedString,
        /// Explicit documented lowercase unit.
        unit: ShmSizeUnit,
    },
}

/// A safe explicit service memory limit selected for generated Compose output.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum GeneratedMemLimit {
    /// Emit one quoted amount and documented lowercase unit.
    Explicit {
        /// Canonical positive ASCII-integer amount without leading zeros.
        amount: GeneratedString,
        /// Explicit documented lowercase unit.
        unit: MemLimitUnit,
    },
}

/// The exact service-level `tmpfs` form selected for generated Compose output.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum GeneratedTmpfs {
    /// Emit one quoted scalar item.
    Scalar(GeneratedString),
    /// Emit one quoted ordered list, including an explicit empty list.
    List(Vec<GeneratedString>),
}

/// One generated long-syntax service device.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GeneratedLongDevice {
    source: GeneratedString,
    target: Option<GeneratedString>,
    permissions: Option<GeneratedString>,
}

impl GeneratedLongDevice {
    /// Creates a long device from safe resolved strings without interpreting device paths or permissions.
    ///
    /// # Errors
    ///
    /// Rejects an empty source and any NUL-bearing, multiline, or dollar-bearing member. NUL bytes
    /// are normally rejected while constructing [`GeneratedString`]. Empty optional target and
    /// permissions strings remain raw schema strings and are not assigned runtime meaning.
    pub fn new(
        source: GeneratedString,
        target: Option<GeneratedString>,
        permissions: Option<GeneratedString>,
    ) -> Result<Self, GenerationError> {
        validate_generated_device_member("source", &source, true)?;
        if let Some(target) = &target {
            validate_generated_device_member("target", target, false)?;
        }
        if let Some(permissions) = &permissions {
            validate_generated_device_member("permissions", permissions, false)?;
        }
        Ok(Self {
            source,
            target,
            permissions,
        })
    }

    /// Returns the exact generated source through its sensitivity boundary.
    #[must_use]
    pub const fn source(&self) -> &GeneratedString {
        &self.source
    }

    /// Returns the optional exact generated target.
    #[must_use]
    pub const fn target(&self) -> Option<&GeneratedString> {
        self.target.as_ref()
    }

    /// Returns the optional exact raw generated permissions string.
    #[must_use]
    pub const fn permissions(&self) -> Option<&GeneratedString> {
        self.permissions.as_ref()
    }

    fn is_sensitive(&self) -> bool {
        self.source.is_sensitive()
            || self.target.as_ref().is_some_and(GeneratedString::is_sensitive)
            || self.permissions.as_ref().is_some_and(GeneratedString::is_sensitive)
    }
}

/// One generated service device with explicit short or long syntax.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum GeneratedDevice {
    /// Emit one exact quoted raw short item.
    Short(GeneratedString),
    /// Emit one ordered long mapping.
    Long(GeneratedLongDevice),
}

impl GeneratedDevice {
    fn is_sensitive(&self) -> bool {
        match self {
            Self::Short(value) => value.is_sensitive(),
            Self::Long(value) => value.is_sensitive(),
        }
    }
}

/// One ordered mapping-form generated sysctl assignment.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GeneratedSysctl {
    name: String,
    value: GeneratedString,
}

impl GeneratedSysctl {
    /// Creates one resolved string-valued sysctl assignment.
    ///
    /// # Errors
    ///
    /// Rejects empty, multiline, NUL-bearing, or dollar-bearing names and multiline or
    /// dollar-bearing values. Values may be empty. NUL-bearing values are rejected while
    /// constructing [`GeneratedString`].
    pub fn new(name: impl Into<String>, value: GeneratedString) -> Result<Self, GenerationError> {
        let name = name.into();
        if name.is_empty()
            || name.contains(['\0', '\r', '\n'])
            || name.contains('$')
            || value.expose().contains(['\r', '\n', '$'])
        {
            return Err(if name.is_empty() || name.contains(['\0', '\r', '\n', '$']) {
                GenerationError::InvalidSysctlName
            } else {
                GenerationError::InvalidSysctlValue
            });
        }
        Ok(Self { name, value })
    }

    /// Returns the exact generated sysctl name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the exact quoted-string value through its sensitivity boundary.
    #[must_use]
    pub const fn value(&self) -> &GeneratedString {
        &self.value
    }
}

/// The mapping or list form selected for generated service `sysctls`.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum GeneratedSysctls {
    /// Ordered unique-name mapping assignments, including an explicit empty mapping.
    Map(Vec<GeneratedSysctl>),
    /// Ordered unique exact strings, including an explicit empty list.
    List(Vec<GeneratedString>),
}

/// The single or soft/hard form selected for one generated service limit.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum GeneratedUlimitValue {
    /// One value applies to both the soft and hard limit.
    Single(GeneratedString),
    /// Separate required soft and hard values.
    Range {
        /// Required soft limit; omission is rejected during construction.
        soft: Option<GeneratedString>,
        /// Required hard limit; omission is rejected during construction.
        hard: Option<GeneratedString>,
    },
}

/// One ordered generated service limit.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GeneratedUlimit {
    name: String,
    value: GeneratedUlimitValue,
}

impl GeneratedUlimit {
    /// Creates one validated named generated limit.
    ///
    /// # Errors
    ///
    /// Rejects non-lowercase names, missing range members, deferred/multiline/NUL-bearing values,
    /// and values other than `-1` or non-negative ASCII decimals.
    pub fn new(name: impl Into<String>, value: GeneratedUlimitValue) -> Result<Self, GenerationError> {
        let name = name.into();
        if !valid_ulimit_name(&name) {
            return Err(GenerationError::InvalidUlimitName);
        }
        match &value {
            GeneratedUlimitValue::Single(value) => validate_generated_ulimit_value(value)?,
            GeneratedUlimitValue::Range { soft, hard } => {
                let soft = soft.as_ref().ok_or(GenerationError::MissingUlimitRangeMember("soft"))?;
                let hard = hard.as_ref().ok_or(GenerationError::MissingUlimitRangeMember("hard"))?;
                validate_generated_ulimit_value(soft)?;
                validate_generated_ulimit_value(hard)?;
            }
        }
        Ok(Self { name, value })
    }

    /// Creates one validated single-form generated limit.
    ///
    /// # Errors
    ///
    /// Returns the same name and value validation errors as [`Self::new`].
    pub fn single(name: impl Into<String>, value: GeneratedString) -> Result<Self, GenerationError> {
        Self::new(name, GeneratedUlimitValue::Single(value))
    }

    /// Creates one validated soft/hard generated limit.
    ///
    /// # Errors
    ///
    /// Returns the same name and value validation errors as [`Self::new`].
    pub fn range(
        name: impl Into<String>,
        soft: GeneratedString,
        hard: GeneratedString,
    ) -> Result<Self, GenerationError> {
        Self::new(
            name,
            GeneratedUlimitValue::Range {
                soft: Some(soft),
                hard: Some(hard),
            },
        )
    }

    /// Returns the lowercase limit name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the selected single or soft/hard form.
    #[must_use]
    pub const fn value(&self) -> &GeneratedUlimitValue {
        &self.value
    }

    fn is_sensitive(&self) -> bool {
        match &self.value {
            GeneratedUlimitValue::Single(value) => value.is_sensitive(),
            GeneratedUlimitValue::Range { soft, hard } => {
                soft.iter().chain(hard.iter()).any(GeneratedString::is_sensitive)
            }
        }
    }
}

/// Ordered generated service limits, including an explicit empty mapping.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GeneratedUlimits {
    entries: Vec<GeneratedUlimit>,
}

impl GeneratedUlimits {
    /// Creates an ordered unique-name limit mapping.
    ///
    /// # Errors
    ///
    /// Rejects duplicate names without reordering the retained entries.
    pub fn new(entries: Vec<GeneratedUlimit>) -> Result<Self, GenerationError> {
        let mut seen = BTreeSet::new();
        for entry in &entries {
            if !seen.insert(entry.name()) {
                return Err(GenerationError::DuplicateName {
                    kind: "ulimit",
                    name: entry.name().to_owned(),
                });
            }
        }
        Ok(Self { entries })
    }

    /// Returns limits in generated output order.
    #[must_use]
    pub fn entries(&self) -> &[GeneratedUlimit] {
        &self.entries
    }

    /// Reports whether generation will emit an explicit empty mapping.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

/// A resolved service hostname selected for generated Compose output.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum GeneratedHostname {
    /// Emit one exact resolved hostname after conservative RFC-1123 validation.
    Resolved(GeneratedString),
}

/// One ordered Compose environment entry.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GeneratedEnvironment {
    name: String,
    value: Option<GeneratedString>,
}

/// Explicit parser mode for one generated long-syntax `env_file` entry.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum GeneratedEnvironmentFileFormat {
    /// Preserve raw environment-file values without Compose interpolation or quote processing.
    Raw,
}

/// One ordered generated Compose `env_file` declaration.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum GeneratedEnvironmentFile {
    /// Scalar path syntax with Compose defaults.
    Short(GeneratedString),
    /// Mapping syntax with independently selected options.
    Long {
        /// Environment-file path.
        path: GeneratedString,
        /// Explicit required/optional behavior, or source-format default when omitted.
        required: Option<bool>,
        /// Explicit parser mode, or source-format default when omitted.
        format: Option<GeneratedEnvironmentFileFormat>,
    },
}

/// One generated service metadata label.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GeneratedLabel {
    name: String,
    value: GeneratedString,
}

impl GeneratedLabel {
    /// Creates a label with an explicit string value, including an empty value.
    ///
    /// # Errors
    ///
    /// Rejects an empty or NUL-bearing label name. Values are already validated by
    /// [`GeneratedString`].
    pub fn new(name: impl Into<String>, value: GeneratedString) -> Result<Self, GenerationError> {
        Ok(Self {
            name: required("label name", name.into())?,
            value,
        })
    }

    /// Returns the label name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the label value through its explicit sensitivity boundary.
    #[must_use]
    pub const fn value(&self) -> &GeneratedString {
        &self.value
    }
}

impl GeneratedEnvironment {
    /// Creates a literal `NAME=value` entry.
    ///
    /// # Errors
    ///
    /// Rejects an empty/NUL-bearing name or a name containing `=`.
    pub fn literal(name: impl Into<String>, value: GeneratedString) -> Result<Self, GenerationError> {
        Ok(Self {
            name: environment_name(name.into())?,
            value: Some(value),
        })
    }

    /// Creates a host-resolved key-only environment entry.
    ///
    /// # Errors
    ///
    /// Rejects an empty/NUL-bearing name or a name containing `=`.
    pub fn host(name: impl Into<String>) -> Result<Self, GenerationError> {
        Ok(Self {
            name: environment_name(name.into())?,
            value: None,
        })
    }

    /// Returns the environment name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the optional literal value.
    #[must_use]
    pub const fn value(&self) -> Option<&GeneratedString> {
        self.value.as_ref()
    }
}

impl GeneratedEnvironmentFile {
    /// Creates one scalar short-syntax declaration.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::EmptyValue`] for an empty path. NUL-bearing paths are rejected
    /// while constructing [`GeneratedString`].
    pub fn short(path: GeneratedString) -> Result<Self, GenerationError> {
        require_generated_string("environment-file path", &path)?;
        Ok(Self::Short(path))
    }

    /// Creates one mapping long-syntax declaration.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::EmptyValue`] for an empty path. NUL-bearing paths are rejected
    /// while constructing [`GeneratedString`].
    pub fn long(
        path: GeneratedString,
        required: Option<bool>,
        format: Option<GeneratedEnvironmentFileFormat>,
    ) -> Result<Self, GenerationError> {
        require_generated_string("environment-file path", &path)?;
        Ok(Self::Long { path, required, format })
    }

    /// Returns the environment-file path through its explicit sensitivity boundary.
    #[must_use]
    pub const fn path(&self) -> &GeneratedString {
        match self {
            Self::Short(path) | Self::Long { path, .. } => path,
        }
    }

    /// Returns the explicitly selected required/optional behavior for long syntax.
    #[must_use]
    pub const fn required(&self) -> Option<bool> {
        match self {
            Self::Short(_) => None,
            Self::Long { required, .. } => *required,
        }
    }

    /// Returns the explicitly selected parser mode for long syntax.
    #[must_use]
    pub const fn format(&self) -> Option<GeneratedEnvironmentFileFormat> {
        match self {
            Self::Short(_) => None,
            Self::Long { format, .. } => *format,
        }
    }

    /// Reports whether debug output must redact this declaration's path.
    #[must_use]
    pub const fn is_sensitive(&self) -> bool {
        self.path().is_sensitive()
    }
}

/// One ordered Compose `extra_hosts` relationship.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GeneratedExtraHost {
    hostname: String,
    address: String,
}

impl GeneratedExtraHost {
    /// Creates a short-form `hostname=address` relationship.
    ///
    /// # Errors
    ///
    /// Rejects empty/NUL-bearing values and the unambiguous short-form separator `=`.
    pub fn new(hostname: impl Into<String>, address: impl Into<String>) -> Result<Self, GenerationError> {
        let hostname = short_component("extra-host hostname", hostname.into(), '=')?;
        let address = short_component("extra-host address", address.into(), '=')?;
        Ok(Self { hostname, address })
    }

    /// Returns the hostname.
    #[must_use]
    pub fn hostname(&self) -> &str {
        &self.hostname
    }

    /// Returns the address or implementation token.
    #[must_use]
    pub fn address(&self) -> &str {
        &self.address
    }
}

/// Transport protocol for one generated published port.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum GeneratedProtocol {
    /// Transmission Control Protocol.
    Tcp,
    /// User Datagram Protocol.
    Udp,
    /// Stream Control Transmission Protocol.
    Sctp,
}

impl GeneratedProtocol {
    const fn as_str(self) -> &'static str {
        match self {
            Self::Tcp => "tcp",
            Self::Udp => "udp",
            Self::Sctp => "sctp",
        }
    }
}

/// One generated Compose port entry with protocol-aware syntax selection.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GeneratedPort {
    target: u16,
    published: Option<u16>,
    host_ip: Option<String>,
    protocol: GeneratedProtocol,
}

impl GeneratedPort {
    /// Creates a generated port without normalizing its declared transport.
    ///
    /// # Errors
    ///
    /// Rejects target port zero, an empty/NUL-bearing host address, and an `SCTP` host address
    /// without a published port. `SCTP` uses Compose short syntax because the specification's
    /// long form only defines `tcp` and `udp` protocols.
    pub fn new(
        target: u16,
        published: Option<u16>,
        host_ip: Option<String>,
        protocol: GeneratedProtocol,
    ) -> Result<Self, GenerationError> {
        if target == 0 {
            return Err(GenerationError::InvalidPort);
        }
        if let Some(host_ip) = host_ip.as_deref() {
            required("port host address", host_ip.to_owned())?;
            if protocol == GeneratedProtocol::Sctp && published.is_none() {
                return Err(GenerationError::UnrepresentableSctpHostIp);
            }
        }
        Ok(Self {
            target,
            published,
            host_ip,
            protocol,
        })
    }

    /// Returns the container port.
    #[must_use]
    pub const fn target(&self) -> u16 {
        self.target
    }

    /// Returns the optional host port.
    #[must_use]
    pub const fn published(&self) -> Option<u16> {
        self.published
    }

    /// Returns the optional host-address spelling.
    #[must_use]
    pub fn host_ip(&self) -> Option<&str> {
        self.host_ip.as_deref()
    }

    /// Returns the transport protocol.
    #[must_use]
    pub const fn protocol(&self) -> GeneratedProtocol {
        self.protocol
    }
}

/// `SELinux` relabel option that requires Compose short bind syntax.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum GeneratedSelinux {
    /// Private unshared relabel (`Z`).
    Private,
    /// Shared relabel (`z`).
    Shared,
}

impl GeneratedSelinux {
    const fn as_str(self) -> &'static str {
        match self {
            Self::Private => "Z",
            Self::Shared => "z",
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
enum GeneratedMountKind {
    Volume {
        source: String,
    },
    Bind {
        source: String,
        selinux: Option<GeneratedSelinux>,
    },
    Anonymous,
}

/// One generated service mount with deliberate short/long syntax selection.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GeneratedMount {
    kind: GeneratedMountKind,
    target: String,
    read_only: bool,
}

impl GeneratedMount {
    /// Creates a long-form named-volume mount.
    ///
    /// # Errors
    ///
    /// Rejects empty or NUL-bearing source and target values.
    pub fn volume(
        source: impl Into<String>,
        target: impl Into<String>,
        read_only: bool,
    ) -> Result<Self, GenerationError> {
        Ok(Self {
            kind: GeneratedMountKind::Volume {
                source: required("volume source", source.into())?,
            },
            target: required("mount target", target.into())?,
            read_only,
        })
    }

    /// Creates a bind mount. `SELinux` relabel intent selects short syntax deliberately.
    ///
    /// # Errors
    ///
    /// Rejects empty/NUL-bearing values. When `selinux` is present, also rejects `:` in source or
    /// target because Compose only honors the relabel option in the short form used here.
    pub fn bind(
        source: impl Into<String>,
        target: impl Into<String>,
        read_only: bool,
        selinux: Option<GeneratedSelinux>,
    ) -> Result<Self, GenerationError> {
        let source = required("bind source", source.into())?;
        let target = required("mount target", target.into())?;
        if selinux.is_some() && (source.contains(':') || target.contains(':')) {
            return Err(GenerationError::InvalidSelinuxBind);
        }
        Ok(Self {
            kind: GeneratedMountKind::Bind { source, selinux },
            target,
            read_only,
        })
    }

    /// Creates a long-form anonymous-volume mount.
    ///
    /// # Errors
    ///
    /// Rejects an empty or NUL-bearing target.
    pub fn anonymous(target: impl Into<String>, read_only: bool) -> Result<Self, GenerationError> {
        Ok(Self {
            kind: GeneratedMountKind::Anonymous,
            target: required("mount target", target.into())?,
            read_only,
        })
    }

    /// Returns the container target path.
    #[must_use]
    pub fn target(&self) -> &str {
        &self.target
    }

    /// Reports whether the mount is read-only.
    #[must_use]
    pub const fn read_only(&self) -> bool {
        self.read_only
    }
}

/// One generated service network attachment and its ordered aliases.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GeneratedNetworkAttachment {
    name: String,
    aliases: Vec<String>,
}

impl GeneratedNetworkAttachment {
    /// Creates an attachment without aliases.
    ///
    /// # Errors
    ///
    /// Rejects an empty or NUL-bearing network name.
    pub fn new(name: impl Into<String>) -> Result<Self, GenerationError> {
        Ok(Self {
            name: required("network name", name.into())?,
            aliases: Vec::new(),
        })
    }

    /// Adds one ordered alias.
    ///
    /// # Errors
    ///
    /// Rejects an empty or NUL-bearing alias.
    pub fn add_alias(&mut self, alias: impl Into<String>) -> Result<(), GenerationError> {
        self.aliases.push(required("network alias", alias.into())?);
        Ok(())
    }

    /// Returns the network name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns aliases in insertion order.
    #[must_use]
    pub fn aliases(&self) -> &[String] {
        &self.aliases
    }
}

/// One top-level network or volume lifecycle definition.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GeneratedResource {
    name: String,
    external: bool,
    custom_name: Option<String>,
}

impl GeneratedResource {
    /// Creates an application-owned resource definition.
    ///
    /// # Errors
    ///
    /// Rejects an empty or NUL-bearing name.
    pub fn application(name: impl Into<String>) -> Result<Self, GenerationError> {
        Ok(Self {
            name: required("resource name", name.into())?,
            external: false,
            custom_name: None,
        })
    }

    /// Creates an externally managed resource definition.
    ///
    /// # Errors
    ///
    /// Rejects an empty or NUL-bearing name.
    pub fn external(name: impl Into<String>) -> Result<Self, GenerationError> {
        Ok(Self {
            name: required("resource name", name.into())?,
            external: true,
            custom_name: None,
        })
    }

    /// Sets the exact platform-level resource name once.
    ///
    /// This prevents Compose project scoping from changing a reviewed runtime resource name.
    ///
    /// # Errors
    ///
    /// Rejects an empty/NUL-bearing name and duplicate configuration.
    pub fn set_custom_name(&mut self, name: impl Into<String>) -> Result<(), GenerationError> {
        let name = required("custom resource name", name.into())?;
        set_once(&mut self.custom_name, name, "resource name")
    }

    /// Returns the resource name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Reports whether Compose should reuse an external resource.
    #[must_use]
    pub const fn is_external(&self) -> bool {
        self.external
    }

    /// Returns the optional exact platform-level resource name.
    #[must_use]
    pub fn custom_name(&self) -> Option<&str> {
        self.custom_name.as_deref()
    }
}

/// A typed generated Compose service definition.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GeneratedService {
    name: String,
    hostname: Option<GeneratedHostname>,
    container_name: Option<GeneratedString>,
    image: Option<GeneratedString>,
    entrypoint: Option<GeneratedEntrypoint>,
    command: Option<GeneratedCommand>,
    init: Option<bool>,
    environment_files: Vec<GeneratedEnvironmentFile>,
    environment: Vec<GeneratedEnvironment>,
    labels: Vec<GeneratedLabel>,
    user: Option<GeneratedString>,
    userns_mode: Option<GeneratedString>,
    group_add: Vec<GeneratedString>,
    cap_add: Option<Vec<GeneratedString>>,
    cap_drop: Option<Vec<GeneratedString>>,
    devices: Option<Vec<GeneratedDevice>>,
    working_dir: Option<GeneratedString>,
    read_only: Option<bool>,
    pids_limit: Option<GeneratedPidsLimit>,
    shm_size: Option<GeneratedShmSize>,
    mem_limit: Option<GeneratedMemLimit>,
    tmpfs: Option<GeneratedTmpfs>,
    sysctls: Option<GeneratedSysctls>,
    ulimits: Option<GeneratedUlimits>,
    pull_policy: Option<GeneratedPullPolicy>,
    restart: Option<GeneratedRestartPolicy>,
    stop_signal: Option<GeneratedString>,
    stop_grace_period: Option<GeneratedString>,
    extra_hosts: Vec<GeneratedExtraHost>,
    ports: Vec<GeneratedPort>,
    mounts: Vec<GeneratedMount>,
    networks: Vec<GeneratedNetworkAttachment>,
}

impl GeneratedService {
    /// Creates an empty service with a validated name.
    ///
    /// # Errors
    ///
    /// Rejects an empty or NUL-bearing name.
    pub fn new(name: impl Into<String>) -> Result<Self, GenerationError> {
        Ok(Self {
            name: required("service name", name.into())?,
            hostname: None,
            container_name: None,
            image: None,
            entrypoint: None,
            command: None,
            init: None,
            environment_files: Vec::new(),
            environment: Vec::new(),
            labels: Vec::new(),
            user: None,
            userns_mode: None,
            group_add: Vec::new(),
            cap_add: None,
            cap_drop: None,
            devices: None,
            working_dir: None,
            read_only: None,
            pids_limit: None,
            shm_size: None,
            mem_limit: None,
            tmpfs: None,
            sysctls: None,
            ulimits: None,
            pull_policy: None,
            restart: None,
            stop_signal: None,
            stop_grace_period: None,
            extra_hosts: Vec::new(),
            ports: Vec::new(),
            mounts: Vec::new(),
            networks: Vec::new(),
        })
    }

    /// Returns the service name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Sets one resolved RFC-1123 service hostname exactly once.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::InvalidHostname`] for an empty, expression-shaped, non-ASCII,
    /// overlong, or otherwise invalid hostname, or [`GenerationError::DuplicateField`] when
    /// already configured.
    pub fn set_hostname(&mut self, hostname: GeneratedHostname) -> Result<(), GenerationError> {
        let GeneratedHostname::Resolved(value) = &hostname;
        if !valid_hostname(value.expose()) {
            return Err(GenerationError::InvalidHostname);
        }
        set_once(&mut self.hostname, hostname, "hostname")
    }

    /// Sets the custom runtime container name exactly once.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::InvalidContainerName`] when the value does not match Compose's
    /// portable container-name grammar or [`GenerationError::DuplicateField`] when already
    /// configured.
    pub fn set_container_name(&mut self, name: GeneratedString) -> Result<(), GenerationError> {
        if !valid_container_name(name.expose()) {
            return Err(GenerationError::InvalidContainerName);
        }
        set_once(&mut self.container_name, name, "container_name")
    }

    /// Sets the service image exactly once.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::EmptyValue`] for an empty image or
    /// [`GenerationError::DuplicateField`] when already configured.
    pub fn set_image(&mut self, image: GeneratedString) -> Result<(), GenerationError> {
        require_generated_string("service image", &image)?;
        set_once(&mut self.image, image, "image")
    }

    /// Sets the Compose entrypoint form exactly once.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::DuplicateField`] when already configured.
    pub fn set_entrypoint(&mut self, entrypoint: GeneratedEntrypoint) -> Result<(), GenerationError> {
        set_once(&mut self.entrypoint, entrypoint, "entrypoint")
    }

    /// Sets the Compose command form exactly once.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::DuplicateField`] when already configured.
    pub fn set_command(&mut self, command: GeneratedCommand) -> Result<(), GenerationError> {
        set_once(&mut self.command, command, "command")
    }

    /// Sets the Compose init-process choice exactly once.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::DuplicateField`] when already configured.
    pub fn set_init(&mut self, init: bool) -> Result<(), GenerationError> {
        set_once(&mut self.init, init, "init")
    }

    /// Adds one ordered environment-file declaration.
    pub fn add_environment_file(&mut self, environment_file: GeneratedEnvironmentFile) {
        self.environment_files.push(environment_file);
    }

    /// Adds one ordered environment entry.
    pub fn add_environment(&mut self, environment: GeneratedEnvironment) {
        self.environment.push(environment);
    }

    /// Adds one uniquely named service metadata label.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::DuplicateName`] when the service already defines the label.
    pub fn add_label(&mut self, label: GeneratedLabel) -> Result<(), GenerationError> {
        if self.labels.iter().any(|candidate| candidate.name == label.name) {
            return Err(GenerationError::DuplicateName {
                kind: "service label",
                name: label.name,
            });
        }
        self.labels.push(label);
        Ok(())
    }

    /// Sets the combined Compose `user[:group]` value exactly once.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::DuplicateField`] when already configured.
    pub fn set_user(&mut self, user: GeneratedString) -> Result<(), GenerationError> {
        set_once(&mut self.user, user, "user")
    }

    /// Sets the user-namespace mode exactly once.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::EmptyValue`] for an empty mode or
    /// [`GenerationError::DuplicateField`] when already configured.
    pub fn set_userns_mode(&mut self, mode: GeneratedString) -> Result<(), GenerationError> {
        require_generated_string("user namespace mode", &mode)?;
        set_once(&mut self.userns_mode, mode, "userns_mode")
    }

    /// Adds one ordered supplementary group.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::EmptyValue`] for an empty group.
    pub fn add_supplementary_group(&mut self, group: GeneratedString) -> Result<(), GenerationError> {
        require_generated_string("supplementary group", &group)?;
        self.group_add.push(group);
        Ok(())
    }

    /// Sets the complete ordered `cap_add` sequence exactly once.
    ///
    /// An empty vector is retained as explicit `cap_add: []`; never calling this method omits the
    /// field. Values preserve exact case and ordering. No capability whitelist is applied.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::EmptyValue`] for an empty item,
    /// [`GenerationError::ContainsLineBreak`] for a carriage return or line feed,
    /// [`GenerationError::DuplicateItem`] for an exact case-sensitive duplicate, or
    /// [`GenerationError::DuplicateField`] when already configured. NUL bytes are rejected while
    /// constructing [`GeneratedString`].
    pub fn set_cap_add(&mut self, capabilities: Vec<GeneratedString>) -> Result<(), GenerationError> {
        let mut seen = BTreeSet::new();
        for capability in &capabilities {
            require_generated_string("cap_add item", capability)?;
            if capability.expose().contains('\r') || capability.expose().contains('\n') {
                return Err(GenerationError::ContainsLineBreak("cap_add item"));
            }
            if !seen.insert(capability.expose()) {
                return Err(GenerationError::DuplicateItem("cap_add"));
            }
        }
        set_once(&mut self.cap_add, capabilities, "cap_add")
    }

    /// Returns the configured `cap_add` sequence, distinguishing omission from an empty vector.
    #[must_use]
    pub fn cap_add(&self) -> Option<&[GeneratedString]> {
        self.cap_add.as_deref()
    }

    /// Sets the complete ordered `cap_drop` sequence exactly once.
    ///
    /// An empty vector is retained as explicit `cap_drop: []`; never calling this method omits the
    /// field. Values preserve exact case and ordering. No capability whitelist is applied.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::EmptyValue`] for an empty item,
    /// [`GenerationError::ContainsLineBreak`] for a carriage return or line feed,
    /// [`GenerationError::DuplicateItem`] for an exact case-sensitive duplicate, or
    /// [`GenerationError::DuplicateField`] when already configured. NUL bytes are rejected while
    /// constructing [`GeneratedString`].
    pub fn set_cap_drop(&mut self, capabilities: Vec<GeneratedString>) -> Result<(), GenerationError> {
        let mut seen = BTreeSet::new();
        for capability in &capabilities {
            require_generated_string("cap_drop item", capability)?;
            if capability.expose().contains('\r') || capability.expose().contains('\n') {
                return Err(GenerationError::ContainsLineBreak("cap_drop item"));
            }
            if !seen.insert(capability.expose()) {
                return Err(GenerationError::DuplicateItem("cap_drop"));
            }
        }
        set_once(&mut self.cap_drop, capabilities, "cap_drop")
    }

    /// Returns the configured `cap_drop` sequence, distinguishing omission from an empty vector.
    #[must_use]
    pub fn cap_drop(&self) -> Option<&[GeneratedString]> {
        self.cap_drop.as_deref()
    }

    /// Sets the complete ordered mixed short/long `devices` sequence exactly once.
    ///
    /// An empty vector is emitted as `devices: []`; omission remains distinct. Exact duplicate
    /// items and caller order are preserved. This validates only safe resolved YAML output and
    /// does not inspect host devices, split colon triples, validate CDI, normalize permissions,
    /// or claim runtime access.
    ///
    /// # Errors
    ///
    /// Rejects empty short items and empty long sources, plus NUL-bearing, multiline, or
    /// dollar-bearing values. NUL bytes are normally rejected while constructing
    /// [`GeneratedString`]. Returns [`GenerationError::DuplicateField`] when already configured.
    pub fn set_devices(&mut self, devices: Vec<GeneratedDevice>) -> Result<(), GenerationError> {
        for device in &devices {
            match device {
                GeneratedDevice::Short(value) => {
                    validate_generated_device_member("short item", value, true)?;
                }
                GeneratedDevice::Long(value) => {
                    validate_generated_device_member("source", value.source(), true)?;
                    if let Some(target) = value.target() {
                        validate_generated_device_member("target", target, false)?;
                    }
                    if let Some(permissions) = value.permissions() {
                        validate_generated_device_member("permissions", permissions, false)?;
                    }
                }
            }
        }
        set_once(&mut self.devices, devices, "devices")
    }

    /// Returns configured devices, distinguishing omission from an explicit empty sequence.
    #[must_use]
    pub fn devices(&self) -> Option<&[GeneratedDevice]> {
        self.devices.as_deref()
    }

    /// Sets the container working directory exactly once.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::EmptyValue`] for an empty directory or
    /// [`GenerationError::DuplicateField`] when already configured.
    pub fn set_working_dir(&mut self, directory: GeneratedString) -> Result<(), GenerationError> {
        require_generated_string("working directory", &directory)?;
        set_once(&mut self.working_dir, directory, "working_dir")
    }

    /// Sets the read-only-root choice exactly once.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::DuplicateField`] when already configured.
    pub fn set_read_only(&mut self, read_only: bool) -> Result<(), GenerationError> {
        set_once(&mut self.read_only, read_only, "read_only")
    }

    /// Sets an unlimited or positive finite service PID limit exactly once.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::InvalidPidsLimit`] when a finite spelling is empty, zero,
    /// signed, fractional, exponent-shaped, or otherwise not ASCII decimal, or
    /// [`GenerationError::DuplicateField`] when already configured.
    pub fn set_pids_limit(&mut self, limit: GeneratedPidsLimit) -> Result<(), GenerationError> {
        if let GeneratedPidsLimit::Finite(decimal) = &limit {
            if !valid_positive_pids_decimal(decimal) {
                return Err(GenerationError::InvalidPidsLimit);
            }
        }
        set_once(&mut self.pids_limit, limit, "pids_limit")
    }

    /// Sets one explicit positive service shared-memory size exactly once.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::InvalidShmSize`] when the amount is empty, zero, has leading
    /// zeros, a sign, fraction, exponent, whitespace, or non-ASCII digits, or
    /// [`GenerationError::DuplicateField`] when already configured.
    pub fn set_shm_size(&mut self, size: GeneratedShmSize) -> Result<(), GenerationError> {
        let GeneratedShmSize::Explicit { amount, .. } = &size;
        if !valid_generated_shm_amount(amount.expose()) {
            return Err(GenerationError::InvalidShmSize);
        }
        set_once(&mut self.shm_size, size, "shm_size")
    }

    /// Sets one explicit positive service memory limit exactly once.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::InvalidMemLimit`] when the amount is empty, zero, has leading
    /// zeros, a sign, fraction, exponent, whitespace, or non-ASCII digits, or
    /// [`GenerationError::DuplicateField`] when already configured.
    pub fn set_mem_limit(&mut self, limit: GeneratedMemLimit) -> Result<(), GenerationError> {
        let GeneratedMemLimit::Explicit { amount, .. } = &limit;
        if !valid_generated_mem_amount(amount.expose()) {
            return Err(GenerationError::InvalidMemLimit);
        }
        set_once(&mut self.mem_limit, limit, "mem_limit")
    }

    /// Sets the complete scalar or list service-level `tmpfs` form exactly once.
    ///
    /// An empty list is retained explicitly. Item spelling, ordering, and case remain unchanged.
    ///
    /// # Errors
    ///
    /// Rejects empty, multiline, deferred, or structurally malformed items. Documented `mode`,
    /// `uid`, and `gid` assignments and other well-shaped raw target options remain exact, including
    /// duplicate list entries. NUL bytes are rejected while constructing [`GeneratedString`]. Returns
    /// [`GenerationError::DuplicateField`] when already configured.
    pub fn set_tmpfs(&mut self, tmpfs: GeneratedTmpfs) -> Result<(), GenerationError> {
        let items = match &tmpfs {
            GeneratedTmpfs::Scalar(item) => std::slice::from_ref(item),
            GeneratedTmpfs::List(items) => items.as_slice(),
        };
        for item in items {
            require_generated_string("tmpfs item", item)?;
            if item.expose().contains('\r') || item.expose().contains('\n') {
                return Err(GenerationError::ContainsLineBreak("tmpfs item"));
            }
            if !valid_generated_tmpfs_item(item.expose()) {
                return Err(GenerationError::InvalidTmpfsItem);
            }
        }
        set_once(&mut self.tmpfs, tmpfs, "tmpfs")
    }

    /// Returns the configured scalar or list form, distinguishing omission from an empty list.
    #[must_use]
    pub const fn tmpfs(&self) -> Option<&GeneratedTmpfs> {
        self.tmpfs.as_ref()
    }

    /// Sets the complete mapping or list `sysctls` form exactly once.
    ///
    /// Empty collections remain explicit. Mapping names and list strings must be exact-unique;
    /// neither form applies namespace validation or runtime coercion.
    ///
    /// # Errors
    ///
    /// Rejects duplicate map names, duplicate exact list items, multiline or dollar-bearing list
    /// items, and duplicate field configuration. NUL-bearing list items are rejected while
    /// constructing [`GeneratedString`].
    pub fn set_sysctls(&mut self, sysctls: GeneratedSysctls) -> Result<(), GenerationError> {
        let mut seen = BTreeSet::new();
        match &sysctls {
            GeneratedSysctls::Map(entries) => {
                for entry in entries {
                    if !seen.insert(entry.name()) {
                        return Err(GenerationError::DuplicateName {
                            kind: "sysctl",
                            name: entry.name().to_owned(),
                        });
                    }
                }
            }
            GeneratedSysctls::List(items) => {
                for item in items {
                    if item.expose().contains(['\r', '\n', '$']) {
                        return Err(GenerationError::InvalidSysctlValue);
                    }
                    if !seen.insert(item.expose()) {
                        return Err(GenerationError::DuplicateItem("sysctls"));
                    }
                }
            }
        }
        set_once(&mut self.sysctls, sysctls, "sysctls")
    }

    /// Returns the configured form, distinguishing omission from explicit empty collections.
    #[must_use]
    pub const fn sysctls(&self) -> Option<&GeneratedSysctls> {
        self.sysctls.as_ref()
    }

    /// Sets the complete ordered service `ulimits` mapping exactly once.
    ///
    /// An empty mapping remains explicit. Values are already validated while constructing
    /// [`GeneratedUlimit`] and names are unique by construction in [`GeneratedUlimits`].
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::DuplicateField`] when already configured.
    pub fn set_ulimits(&mut self, ulimits: GeneratedUlimits) -> Result<(), GenerationError> {
        set_once(&mut self.ulimits, ulimits, "ulimits")
    }

    /// Returns configured ordered limits, distinguishing omission from an explicit empty mapping.
    #[must_use]
    pub const fn ulimits(&self) -> Option<&GeneratedUlimits> {
        self.ulimits.as_ref()
    }

    /// Sets a documented service image pull policy exactly once.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::InvalidPullPolicyDuration`] for an invalid custom interval or
    /// [`GenerationError::DuplicateField`] when already configured.
    pub fn set_pull_policy(&mut self, policy: GeneratedPullPolicy) -> Result<(), GenerationError> {
        if let GeneratedPullPolicy::Every(duration) = &policy {
            if !valid_pull_policy_duration(duration.expose()) {
                return Err(GenerationError::InvalidPullPolicyDuration);
            }
        }
        set_once(&mut self.pull_policy, policy, "pull_policy")
    }

    /// Sets the service-level restart policy exactly once.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::DuplicateField`] when already configured.
    pub fn set_restart(&mut self, restart: GeneratedRestartPolicy) -> Result<(), GenerationError> {
        set_once(&mut self.restart, restart, "restart")
    }

    /// Sets the service stop signal exactly once without imposing a signal-token grammar.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::DuplicateField`] when already configured. Quoted empty values
    /// are preserved; NUL-bearing values are rejected while constructing [`GeneratedString`].
    pub fn set_stop_signal(&mut self, signal: GeneratedString) -> Result<(), GenerationError> {
        set_once(&mut self.stop_signal, signal, "stop_signal")
    }

    /// Sets the raw-preserving service stop grace period exactly once.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::InvalidStopGracePeriod`] when the value does not match the
    /// `ComposeLens` raw-preserving duration policy or dollar-marker convention, or
    /// [`GenerationError::DuplicateField`] when already configured.
    pub fn set_stop_grace_period(&mut self, period: GeneratedString) -> Result<(), GenerationError> {
        if !StopGracePeriod::parse(period.expose().to_owned()).is_valid() {
            return Err(GenerationError::InvalidStopGracePeriod);
        }
        set_once(&mut self.stop_grace_period, period, "stop_grace_period")
    }

    /// Adds one ordered host mapping.
    pub fn add_extra_host(&mut self, host: GeneratedExtraHost) {
        self.extra_hosts.push(host);
    }

    /// Adds one ordered published-port declaration.
    pub fn add_port(&mut self, port: GeneratedPort) {
        self.ports.push(port);
    }

    /// Adds one ordered mount.
    pub fn add_mount(&mut self, mount: GeneratedMount) {
        self.mounts.push(mount);
    }

    /// Adds one uniquely named network attachment.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::DuplicateName`] when the service already uses the network.
    pub fn add_network(&mut self, network: GeneratedNetworkAttachment) -> Result<(), GenerationError> {
        if self.networks.iter().any(|candidate| candidate.name == network.name) {
            return Err(GenerationError::DuplicateName {
                kind: "service network",
                name: network.name,
            });
        }
        self.networks.push(network);
        Ok(())
    }

    fn is_sensitive(&self) -> bool {
        matches!(
            self.hostname.as_ref(),
            Some(GeneratedHostname::Resolved(hostname)) if hostname.is_sensitive()
        ) || self.image.as_ref().is_some_and(GeneratedString::is_sensitive)
            || self.entrypoint.as_ref().is_some_and(entrypoint_is_sensitive)
            || self.command.as_ref().is_some_and(command_is_sensitive)
            || self
                .environment_files
                .iter()
                .any(GeneratedEnvironmentFile::is_sensitive)
            || self
                .environment
                .iter()
                .filter_map(GeneratedEnvironment::value)
                .any(GeneratedString::is_sensitive)
            || self.labels.iter().any(|label| label.value.is_sensitive())
            || matches!(
                self.pull_policy.as_ref(),
                Some(GeneratedPullPolicy::Every(duration)) if duration.is_sensitive()
            )
            || matches!(
                self.shm_size.as_ref(),
                Some(GeneratedShmSize::Explicit { amount, .. }) if amount.is_sensitive()
            )
            || matches!(
                self.mem_limit.as_ref(),
                Some(GeneratedMemLimit::Explicit { amount, .. }) if amount.is_sensitive()
            )
            || match self.tmpfs.as_ref() {
                Some(GeneratedTmpfs::Scalar(item)) => item.is_sensitive(),
                Some(GeneratedTmpfs::List(items)) => items.iter().any(GeneratedString::is_sensitive),
                None => false,
            }
            || match self.sysctls.as_ref() {
                Some(GeneratedSysctls::Map(entries)) => entries.iter().any(|entry| entry.value.is_sensitive()),
                Some(GeneratedSysctls::List(items)) => items.iter().any(GeneratedString::is_sensitive),
                None => false,
            }
            || self
                .ulimits
                .as_ref()
                .is_some_and(|limits| limits.entries.iter().any(GeneratedUlimit::is_sensitive))
            || [
                self.user.as_ref(),
                self.userns_mode.as_ref(),
                self.working_dir.as_ref(),
                self.stop_signal.as_ref(),
                self.stop_grace_period.as_ref(),
            ]
            .into_iter()
            .flatten()
            .any(GeneratedString::is_sensitive)
            || self.group_add.iter().any(GeneratedString::is_sensitive)
            || self
                .cap_add
                .as_ref()
                .is_some_and(|items| items.iter().any(GeneratedString::is_sensitive))
            || self
                .cap_drop
                .as_ref()
                .is_some_and(|items| items.iter().any(GeneratedString::is_sensitive))
            || self
                .devices
                .as_ref()
                .is_some_and(|items| items.iter().any(GeneratedDevice::is_sensitive))
    }
}

/// Builder for one new deterministic Compose document.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct ComposeDocumentBuilder {
    name: Option<String>,
    services: Vec<GeneratedService>,
    networks: Vec<GeneratedResource>,
    volumes: Vec<GeneratedResource>,
}

impl ComposeDocumentBuilder {
    /// Creates an empty generated project.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            name: None,
            services: Vec::new(),
            networks: Vec::new(),
            volumes: Vec::new(),
        }
    }

    /// Sets the optional top-level Compose project name exactly once.
    ///
    /// # Errors
    ///
    /// Rejects empty/NUL-bearing names and duplicate configuration.
    pub fn set_name(&mut self, name: impl Into<String>) -> Result<(), GenerationError> {
        let name = required("project name", name.into())?;
        set_once(&mut self.name, name, "name")
    }

    /// Adds one uniquely named service in output order.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::DuplicateName`] for a duplicate service name.
    pub fn add_service(&mut self, service: GeneratedService) -> Result<(), GenerationError> {
        insert_named(&mut self.services, service, "service", GeneratedService::name)
    }

    /// Adds one uniquely named top-level network in output order.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::DuplicateName`] for a duplicate network name.
    pub fn add_network(&mut self, network: GeneratedResource) -> Result<(), GenerationError> {
        insert_named(&mut self.networks, network, "network", GeneratedResource::name)
    }

    /// Adds one uniquely named top-level volume in output order.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::DuplicateName`] for a duplicate volume name.
    pub fn add_volume(&mut self, volume: GeneratedResource) -> Result<(), GenerationError> {
        insert_named(&mut self.volumes, volume, "volume", GeneratedResource::name)
    }

    /// Generates YAML and parses it back through `ComposeLens`'s syntax and typed-model boundaries.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::MissingService`] for an empty project or
    /// [`GenerationError::InternalInvariant`] if `ComposeLens` cannot parse its own output.
    pub fn build(self, source_id: SourceId) -> Result<GeneratedComposeDocument, GenerationError> {
        if self.services.is_empty() {
            return Err(GenerationError::MissingService);
        }
        let sensitive = self.services.iter().any(GeneratedService::is_sensitive);
        let text = render_document(&self);
        let syntax = SyntaxDocument::parse(source_id, text.clone())
            .map_err(|_| GenerationError::InternalInvariant("syntax-tree"))?;
        if !syntax.is_valid() {
            return Err(GenerationError::InternalInvariant("syntax"));
        }
        let model = ComposeDocument::parse(syntax.document());
        if !model.is_valid() {
            return Err(GenerationError::InternalInvariant("typed-model"));
        }
        let document = model
            .document()
            .cloned()
            .ok_or(GenerationError::InternalInvariant("document-root"))?;
        Ok(GeneratedComposeDocument {
            text,
            sensitive,
            document,
        })
    }
}

/// Parse-back-validated deterministic generated Compose document.
#[derive(Clone, Eq, PartialEq)]
pub struct GeneratedComposeDocument {
    text: String,
    sensitive: bool,
    document: ComposeDocument,
}

impl GeneratedComposeDocument {
    /// Returns the deployable generated YAML through an explicit access boundary.
    #[must_use]
    pub fn text(&self) -> &str {
        &self.text
    }

    /// Returns the parse-back-validated native Compose model.
    #[must_use]
    pub const fn document(&self) -> &ComposeDocument {
        &self.document
    }

    /// Reports whether generated output contains a caller-marked sensitive value.
    #[must_use]
    pub const fn is_sensitive(&self) -> bool {
        self.sensitive
    }
}

impl fmt::Debug for GeneratedComposeDocument {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("GeneratedComposeDocument")
            .field("text", &if self.sensitive { "<redacted>" } else { &self.text })
            .field("sensitive", &self.sensitive)
            .field("document", &if self.sensitive { "<redacted>" } else { "validated" })
            .finish()
    }
}

fn render_document(project: &ComposeDocumentBuilder) -> String {
    let mut output = String::new();
    if let Some(name) = &project.name {
        output.push_str("name: ");
        write_quoted(&mut output, name);
        output.push('\n');
    }
    output.push_str("services:\n");
    for service in &project.services {
        write_indent(&mut output, 1);
        write_quoted(&mut output, &service.name);
        output.push_str(":\n");
        render_service(&mut output, service);
    }
    render_resources(&mut output, "networks", &project.networks);
    render_resources(&mut output, "volumes", &project.volumes);
    output
}

fn render_service(output: &mut String, service: &GeneratedService) {
    if let Some(GeneratedHostname::Resolved(hostname)) = &service.hostname {
        render_optional_string(output, "hostname", Some(hostname));
    }
    render_optional_string(output, "container_name", service.container_name.as_ref());
    render_optional_string(output, "image", service.image.as_ref());
    if let Some(entrypoint) = &service.entrypoint {
        render_entrypoint(output, entrypoint);
    }
    if let Some(command) = &service.command {
        render_command(output, command);
    }
    if let Some(init) = service.init {
        write_field(output, 2, "init");
        output.push_str(if init { "true\n" } else { "false\n" });
    }
    render_environment_files(output, &service.environment_files);
    render_environment(output, &service.environment);
    render_labels(output, &service.labels);
    render_optional_string(output, "user", service.user.as_ref());
    render_optional_string(output, "userns_mode", service.userns_mode.as_ref());
    render_string_sequence(output, "group_add", &service.group_add);
    if let Some(capabilities) = &service.cap_add {
        render_configured_string_sequence(output, "cap_add", capabilities);
    }
    if let Some(capabilities) = &service.cap_drop {
        render_configured_string_sequence(output, "cap_drop", capabilities);
    }
    render_optional_string(output, "working_dir", service.working_dir.as_ref());
    if let Some(read_only) = service.read_only {
        write_field(output, 2, "read_only");
        output.push_str(if read_only { "true\n" } else { "false\n" });
    }
    if let Some(pids_limit) = &service.pids_limit {
        render_pids_limit(output, pids_limit);
    }
    if let Some(shm_size) = &service.shm_size {
        render_shm_size(output, shm_size);
    }
    if let Some(mem_limit) = &service.mem_limit {
        render_mem_limit(output, mem_limit);
    }
    if let Some(devices) = &service.devices {
        render_devices(output, devices);
    }
    if let Some(tmpfs) = &service.tmpfs {
        render_tmpfs(output, tmpfs);
    }
    if let Some(sysctls) = &service.sysctls {
        render_sysctls(output, sysctls);
    }
    if let Some(ulimits) = &service.ulimits {
        render_ulimits(output, ulimits);
    }
    if let Some(pull_policy) = &service.pull_policy {
        render_pull_policy(output, pull_policy);
    }
    if let Some(restart) = service.restart {
        render_restart(output, restart);
    }
    render_optional_string(output, "stop_signal", service.stop_signal.as_ref());
    render_optional_string(output, "stop_grace_period", service.stop_grace_period.as_ref());
    render_extra_hosts(output, &service.extra_hosts);
    render_ports(output, &service.ports);
    render_mounts(output, &service.mounts);
    render_networks(output, &service.networks);
}

fn render_pids_limit(output: &mut String, limit: &GeneratedPidsLimit) {
    write_field(output, 2, "pids_limit");
    match limit {
        GeneratedPidsLimit::Unlimited => output.push_str("-1\n"),
        GeneratedPidsLimit::Finite(decimal) => {
            output.push_str(decimal);
            output.push('\n');
        }
    }
}

fn render_shm_size(output: &mut String, size: &GeneratedShmSize) {
    let GeneratedShmSize::Explicit { amount, unit } = size;
    write_field(output, 2, "shm_size");
    write_quoted(output, &format!("{}{}", amount.expose(), unit.as_str()));
    output.push('\n');
}

fn render_mem_limit(output: &mut String, limit: &GeneratedMemLimit) {
    let GeneratedMemLimit::Explicit { amount, unit } = limit;
    write_field(output, 2, "mem_limit");
    write_quoted(output, &format!("{}{}", amount.expose(), unit.as_str()));
    output.push('\n');
}

fn render_devices(output: &mut String, devices: &[GeneratedDevice]) {
    if devices.is_empty() {
        output.push_str("    devices: []\n");
        return;
    }
    output.push_str("    devices:\n");
    for device in devices {
        match device {
            GeneratedDevice::Short(value) => {
                output.push_str("      - ");
                write_quoted(output, value.expose());
                output.push('\n');
            }
            GeneratedDevice::Long(value) => {
                output.push_str("      - source: ");
                write_quoted(output, value.source().expose());
                output.push('\n');
                if let Some(target) = value.target() {
                    output.push_str("        target: ");
                    write_quoted(output, target.expose());
                    output.push('\n');
                }
                if let Some(permissions) = value.permissions() {
                    output.push_str("        permissions: ");
                    write_quoted(output, permissions.expose());
                    output.push('\n');
                }
            }
        }
    }
}

fn render_tmpfs(output: &mut String, tmpfs: &GeneratedTmpfs) {
    match tmpfs {
        GeneratedTmpfs::Scalar(item) => render_optional_string(output, "tmpfs", Some(item)),
        GeneratedTmpfs::List(items) => render_configured_string_sequence(output, "tmpfs", items),
    }
}

fn render_sysctls(output: &mut String, sysctls: &GeneratedSysctls) {
    match sysctls {
        GeneratedSysctls::Map(entries) if entries.is_empty() => output.push_str("    sysctls: {}\n"),
        GeneratedSysctls::Map(entries) => {
            output.push_str("    sysctls:\n");
            for entry in entries {
                write_indent(output, 3);
                write_quoted(output, entry.name());
                output.push_str(": ");
                write_quoted(output, entry.value().expose());
                output.push('\n');
            }
        }
        GeneratedSysctls::List(items) => render_configured_string_sequence(output, "sysctls", items),
    }
}

fn render_ulimits(output: &mut String, ulimits: &GeneratedUlimits) {
    if ulimits.entries.is_empty() {
        output.push_str("    ulimits: {}\n");
        return;
    }
    output.push_str("    ulimits:\n");
    for limit in &ulimits.entries {
        write_indent(output, 3);
        write_quoted(output, limit.name());
        match limit.value() {
            GeneratedUlimitValue::Single(value) => {
                output.push_str(": ");
                write_quoted(output, value.expose());
                output.push('\n');
            }
            GeneratedUlimitValue::Range {
                soft: Some(soft),
                hard: Some(hard),
            } => {
                output.push_str(":\n");
                write_indent(output, 4);
                output.push_str("soft: ");
                write_quoted(output, soft.expose());
                output.push('\n');
                write_indent(output, 4);
                output.push_str("hard: ");
                write_quoted(output, hard.expose());
                output.push('\n');
            }
            GeneratedUlimitValue::Range { .. } => {
                unreachable!("generated ulimit ranges are validated during construction")
            }
        }
    }
}

fn render_pull_policy(output: &mut String, policy: &GeneratedPullPolicy) {
    write_field(output, 2, "pull_policy");
    let value = match policy {
        GeneratedPullPolicy::Always => "always".to_owned(),
        GeneratedPullPolicy::Never => "never".to_owned(),
        GeneratedPullPolicy::Missing => "missing".to_owned(),
        GeneratedPullPolicy::IfNotPresentAlias => "if_not_present".to_owned(),
        GeneratedPullPolicy::Build => "build".to_owned(),
        GeneratedPullPolicy::Daily => "daily".to_owned(),
        GeneratedPullPolicy::Weekly => "weekly".to_owned(),
        GeneratedPullPolicy::Every(duration) => format!("every_{}", duration.expose()),
    };
    write_quoted(output, &value);
    output.push('\n');
}

fn render_entrypoint(output: &mut String, entrypoint: &GeneratedEntrypoint) {
    match entrypoint {
        GeneratedEntrypoint::List(arguments) if arguments.is_empty() => output.push_str("    entrypoint: []\n"),
        GeneratedEntrypoint::List(arguments) => render_string_sequence(output, "entrypoint", arguments),
        GeneratedEntrypoint::String(entrypoint) => render_optional_string(output, "entrypoint", Some(entrypoint)),
        GeneratedEntrypoint::Empty => output.push_str("    entrypoint: []\n"),
    }
}

fn render_restart(output: &mut String, restart: GeneratedRestartPolicy) {
    write_field(output, 2, "restart");
    let value = match restart {
        GeneratedRestartPolicy::No => "no".to_owned(),
        GeneratedRestartPolicy::Always => "always".to_owned(),
        GeneratedRestartPolicy::OnFailure { maximum_retries: None } => "on-failure".to_owned(),
        GeneratedRestartPolicy::OnFailure {
            maximum_retries: Some(maximum_retries),
        } => format!("on-failure:{maximum_retries}"),
        GeneratedRestartPolicy::UnlessStopped => "unless-stopped".to_owned(),
    };
    write_quoted(output, &value);
    output.push('\n');
}

fn render_optional_string(output: &mut String, key: &str, value: Option<&GeneratedString>) {
    if let Some(value) = value {
        write_field(output, 2, key);
        write_quoted(output, value.expose());
        output.push('\n');
    }
}

fn render_command(output: &mut String, command: &GeneratedCommand) {
    match command {
        GeneratedCommand::Exec(arguments) if arguments.is_empty() => output.push_str("    command: []\n"),
        GeneratedCommand::Exec(arguments) => render_string_sequence(output, "command", arguments),
        GeneratedCommand::Shell(command) => render_optional_string(output, "command", Some(command)),
        GeneratedCommand::Empty => output.push_str("    command: []\n"),
    }
}

fn render_environment(output: &mut String, environment: &[GeneratedEnvironment]) {
    if environment.is_empty() {
        return;
    }
    output.push_str("    environment:\n");
    for variable in environment {
        output.push_str("      - ");
        let value = variable.value.as_ref().map_or_else(
            || variable.name.clone(),
            |value| format!("{}={}", variable.name, value.expose()),
        );
        write_quoted(output, &value);
        output.push('\n');
    }
}

fn render_environment_files(output: &mut String, environment_files: &[GeneratedEnvironmentFile]) {
    if environment_files.is_empty() {
        return;
    }
    output.push_str("    env_file:\n");
    for environment_file in environment_files {
        match environment_file {
            GeneratedEnvironmentFile::Short(path) => {
                output.push_str("      - ");
                write_quoted(output, path.expose());
                output.push('\n');
            }
            GeneratedEnvironmentFile::Long { path, required, format } => {
                output.push_str("      - path: ");
                write_quoted(output, path.expose());
                output.push('\n');
                if let Some(required) = required {
                    output.push_str("        required: ");
                    output.push_str(if *required { "true\n" } else { "false\n" });
                }
                if let Some(format) = format {
                    output.push_str("        format: ");
                    write_quoted(
                        output,
                        match format {
                            GeneratedEnvironmentFileFormat::Raw => "raw",
                        },
                    );
                    output.push('\n');
                }
            }
        }
    }
}

fn render_labels(output: &mut String, labels: &[GeneratedLabel]) {
    if labels.is_empty() {
        return;
    }
    output.push_str("    labels:\n");
    for label in labels {
        output.push_str("      ");
        write_quoted(output, &label.name);
        output.push_str(": ");
        write_quoted(output, label.value.expose());
        output.push('\n');
    }
}

fn render_string_sequence(output: &mut String, key: &str, values: &[GeneratedString]) {
    if values.is_empty() {
        return;
    }
    write_indent(output, 2);
    output.push_str(key);
    output.push_str(":\n");
    for value in values {
        output.push_str("      - ");
        write_quoted(output, value.expose());
        output.push('\n');
    }
}

fn render_configured_string_sequence(output: &mut String, key: &str, values: &[GeneratedString]) {
    if values.is_empty() {
        write_indent(output, 2);
        output.push_str(key);
        output.push_str(": []\n");
    } else {
        render_string_sequence(output, key, values);
    }
}

fn render_extra_hosts(output: &mut String, hosts: &[GeneratedExtraHost]) {
    if hosts.is_empty() {
        return;
    }
    output.push_str("    extra_hosts:\n");
    for host in hosts {
        output.push_str("      - ");
        write_quoted(output, &format!("{}={}", host.hostname, host.address));
        output.push('\n');
    }
}

fn render_ports(output: &mut String, ports: &[GeneratedPort]) {
    if ports.is_empty() {
        return;
    }
    output.push_str("    ports:\n");
    for port in ports {
        if port.protocol == GeneratedProtocol::Sctp {
            render_short_sctp_port(output, port);
            continue;
        }
        output.push_str("      - target: ");
        output.push_str(&port.target.to_string());
        output.push('\n');
        if let Some(published) = port.published {
            output.push_str("        published: ");
            write_quoted(output, &published.to_string());
            output.push('\n');
        }
        if let Some(host_ip) = &port.host_ip {
            output.push_str("        host_ip: ");
            write_quoted(output, host_ip);
            output.push('\n');
        }
        output.push_str("        protocol: ");
        write_quoted(output, port.protocol.as_str());
        output.push('\n');
    }
}

fn render_short_sctp_port(output: &mut String, port: &GeneratedPort) {
    let mut value = String::new();
    if let Some(host_ip) = &port.host_ip {
        if host_ip.contains(':') && !(host_ip.starts_with('[') && host_ip.ends_with(']')) {
            value.push('[');
            value.push_str(host_ip);
            value.push(']');
        } else {
            value.push_str(host_ip);
        }
        value.push(':');
    }
    if let Some(published) = port.published {
        value.push_str(&published.to_string());
        value.push(':');
    }
    value.push_str(&port.target.to_string());
    value.push_str("/sctp");

    output.push_str("      - ");
    write_quoted(output, &value);
    output.push('\n');
}

fn render_mounts(output: &mut String, mounts: &[GeneratedMount]) {
    if mounts.is_empty() {
        return;
    }
    output.push_str("    volumes:\n");
    for mount in mounts {
        match &mount.kind {
            GeneratedMountKind::Bind {
                source,
                selinux: Some(selinux),
            } => render_selinux_bind(output, source, mount, *selinux),
            kind => render_long_mount(output, kind, mount),
        }
    }
}

fn render_selinux_bind(output: &mut String, source: &str, mount: &GeneratedMount, selinux: GeneratedSelinux) {
    let mut value = format!("{source}:{}:{}", mount.target, selinux.as_str());
    if mount.read_only {
        value.push_str(",ro");
    }
    output.push_str("      - ");
    write_quoted(output, &value);
    output.push('\n');
}

fn render_long_mount(output: &mut String, kind: &GeneratedMountKind, mount: &GeneratedMount) {
    let (mount_type, source) = match kind {
        GeneratedMountKind::Volume { source } => ("volume", Some(source.as_str())),
        GeneratedMountKind::Bind { source, selinux: None } => ("bind", Some(source.as_str())),
        GeneratedMountKind::Anonymous => ("volume", None),
        GeneratedMountKind::Bind { selinux: Some(_), .. } => return,
    };
    output.push_str("      - type: ");
    write_quoted(output, mount_type);
    output.push('\n');
    if let Some(source) = source {
        output.push_str("        source: ");
        write_quoted(output, source);
        output.push('\n');
    }
    output.push_str("        target: ");
    write_quoted(output, &mount.target);
    output.push('\n');
    if mount.read_only {
        output.push_str("        read_only: true\n");
    }
}

fn render_networks(output: &mut String, networks: &[GeneratedNetworkAttachment]) {
    if networks.is_empty() {
        return;
    }
    output.push_str("    networks:\n");
    for network in networks {
        output.push_str("      ");
        write_quoted(output, &network.name);
        if network.aliases.is_empty() {
            output.push_str(": {}\n");
        } else {
            output.push_str(":\n        aliases:\n");
            for alias in &network.aliases {
                output.push_str("          - ");
                write_quoted(output, alias);
                output.push('\n');
            }
        }
    }
}

fn render_resources(output: &mut String, section: &str, resources: &[GeneratedResource]) {
    if resources.is_empty() {
        return;
    }
    output.push_str(section);
    output.push_str(":\n");
    for resource in resources {
        output.push_str("  ");
        write_quoted(output, &resource.name);
        if !resource.external && resource.custom_name.is_none() {
            output.push_str(": {}\n");
            continue;
        }
        output.push_str(":\n");
        if let Some(custom_name) = &resource.custom_name {
            output.push_str("    name: ");
            write_quoted(output, custom_name);
            output.push('\n');
        }
        if resource.external {
            output.push_str("    external: true\n");
        }
    }
}

fn write_field(output: &mut String, depth: usize, key: &str) {
    write_indent(output, depth);
    output.push_str(key);
    output.push_str(": ");
}

fn write_indent(output: &mut String, depth: usize) {
    for _ in 0..depth {
        output.push_str("  ");
    }
}

fn required(kind: &'static str, value: String) -> Result<String, GenerationError> {
    if value.is_empty() {
        return Err(GenerationError::EmptyValue(kind));
    }
    if value.contains('\0') {
        return Err(GenerationError::ContainsNul(kind));
    }
    Ok(value)
}

fn require_generated_string(kind: &'static str, value: &GeneratedString) -> Result<(), GenerationError> {
    if value.expose().is_empty() {
        return Err(GenerationError::EmptyValue(kind));
    }
    Ok(())
}

fn validate_generated_device_member(
    member: &'static str,
    value: &GeneratedString,
    require_non_empty: bool,
) -> Result<(), GenerationError> {
    if valid_generated_device_string(value.expose(), require_non_empty) {
        Ok(())
    } else {
        Err(GenerationError::InvalidDeviceValue(member))
    }
}

fn validate_generated_ulimit_value(value: &GeneratedString) -> Result<(), GenerationError> {
    let value = value.expose();
    if value.contains(['\r', '\n', '$'])
        || (value != "-1" && (value.is_empty() || !value.bytes().all(|byte| byte.is_ascii_digit())))
    {
        return Err(GenerationError::InvalidUlimitValue);
    }
    Ok(())
}

fn environment_name(value: String) -> Result<String, GenerationError> {
    let value = required("environment name", value)?;
    if value.contains('=') {
        return Err(GenerationError::InvalidEnvironmentName);
    }
    Ok(value)
}

fn valid_container_name(value: &str) -> bool {
    let mut bytes = value.bytes();
    bytes.next().is_some_and(|byte| byte.is_ascii_alphanumeric())
        && bytes
            .next()
            .is_some_and(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'-'))
        && bytes.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'-'))
}

fn short_component(kind: &'static str, value: String, separator: char) -> Result<String, GenerationError> {
    let value = required(kind, value)?;
    if value.contains(separator) {
        return Err(GenerationError::InvalidShortComponent(kind));
    }
    Ok(value)
}

fn set_once<T>(slot: &mut Option<T>, value: T, field: &'static str) -> Result<(), GenerationError> {
    if slot.is_some() {
        return Err(GenerationError::DuplicateField(field));
    }
    *slot = Some(value);
    Ok(())
}

fn insert_named<T>(
    values: &mut Vec<T>,
    value: T,
    kind: &'static str,
    name: impl Fn(&T) -> &str,
) -> Result<(), GenerationError> {
    let value_name = name(&value);
    if values.iter().any(|candidate| name(candidate) == value_name) {
        return Err(GenerationError::DuplicateName {
            kind,
            name: value_name.to_owned(),
        });
    }
    values.push(value);
    Ok(())
}

fn command_is_sensitive(command: &GeneratedCommand) -> bool {
    match command {
        GeneratedCommand::Exec(arguments) => arguments.iter().any(GeneratedString::is_sensitive),
        GeneratedCommand::Shell(command) => command.is_sensitive(),
        GeneratedCommand::Empty => false,
    }
}

fn entrypoint_is_sensitive(entrypoint: &GeneratedEntrypoint) -> bool {
    match entrypoint {
        GeneratedEntrypoint::List(arguments) => arguments.iter().any(GeneratedString::is_sensitive),
        GeneratedEntrypoint::String(entrypoint) => entrypoint.is_sensitive(),
        GeneratedEntrypoint::Empty => false,
    }
}