docx-templating 1.0.0

Rust library for DOCX templating with variable replacement, conditionals, and loops
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
# DOCX Templater - Product Specification

**Version:** 0.1.0 (Pre-implementation)  
**Document Date:** 2026-08-13  
**Status:** Design Specification  
**Target Version:** 1.0.0

---

## Document Scope

This specification describes the complete functional and technical requirements for `docx-templating`, a Rust library providing template-based document generation for `.docx` (Microsoft Word) files.

**What This Document Covers:**

- Complete functional capabilities (user stories)
- Business rules and invariants
- Technical architecture and constraints
- Quality requirements (testing, performance, security)
- Implementation roadmap with prioritization

**What This Document Does NOT Cover:**

- Specific implementation details (class names, method signatures)
- Line-by-line code organization
- Deployment/distribution strategy beyond library publication

---

## Table of Contents

1. [System Overview](#system-overview)
2. [Functional Specifications](#functional-specifications)
3. [Business Rules & Invariants](#business-rules--invariants)
4. [Technical Architecture](#technical-architecture)
5. [Quality Requirements](#quality-requirements)
6. [Performance & Reliability](#performance--reliability)
7. [Security Requirements](#security-requirements)
8. [Implementation Roadmap](#implementation-roadmap)
9. [Open Questions](#open-questions)

---

## 1. System Overview

### 1.1 Purpose

`docx-templating` is a Rust library that enables developers to generate Microsoft Word documents (`.docx`) from templates with variable placeholders, conditional sections, and loops. It provides a Rust-native alternative to the Node.js `docxtemplater` library, with a focus on type safety, performance, and correctness.

### 1.2 Target Users

**Primary:** Rust developers building applications that need to generate formatted documents (invoices, reports, contracts, letters) from templates.

**Secondary:** Teams migrating from Node.js/JavaScript document generation to Rust ecosystems.

### 1.3 Core Value Proposition

- **Template-driven generation:** Designers create templates in Word, developers supply data
- **Type-safe data binding:** Rust structs serialize directly to template context
- **Correct DOCX output:** Generated documents open reliably in Microsoft Word
- **Safe by default:** No XML injection, automatic escaping, validation before rendering

### 1.4 High-Level Architecture

The crate is a pipeline with a pure core and two adapters around it:

```
┌──────────────────────────────────────────────┐
│ Public API                                   │
│ Template, Context, IntoContext,              │
│ RenderedDocument, TemplateOptions, Error     │
└───────────────────┬──────────────────────────┘
                    │
┌───────────────────▼──────────────────────────┐
│ Adapters                                     │
│ docx: parse and serialize WordprocessingML   │
│ package: read and write the DOCX ZIP package │
└───────────────────┬──────────────────────────┘
                    │
┌───────────────────▼──────────────────────────┐
│ Domain (pure, no IO)                         │
│ document tree, binding, placement,           │
│ resolved plan, evaluator                     │
└──────────────────────────────────────────────┘
```

**Design Principle:** The domain is the innermost layer and depends on nothing
outside `std`. The adapters depend on the domain and are the only place that
knows DOCX is XML inside a ZIP. The public API depends on both.
`tests/architecture.rs` enforces the boundary: nothing under `src/domain` may
reference `quick_xml`, `zip`, the filesystem, IO, or the adapters.

---

## 2. Functional Specifications

### 2.1 Template Loading

#### Story 2.1.1: Load Template from File Path

**As a** developer,  
**I want** to load a DOCX template from a file path,  
**So that** I can use existing template files stored on disk.

**Acceptance Criteria:**

- Given a valid file path to a `.docx` file
- When the template is loaded
- Then the DOCX package is validated
- And template syntax is parsed
- And errors are reported immediately (fail-fast)
- And the template is ready for rendering

**Error Cases:**

- File does not exist → `Io` error
- File is not a valid ZIP archive → `PackageError::MalformedArchive`
- Required DOCX parts are missing → `PackageError::MissingRequiredPart`
- Template syntax is invalid → `Placement(BindingError::Syntax)` with the part name and a span

---

#### Story 2.1.2: Load Template from Reader

**As a** developer,  
**I want** to load a DOCX template from any `Read + Seek` source,  
**So that** I can work with templates from HTTP streams, databases, or embedded resources.

**Acceptance Criteria:**

- Given a readable, seekable stream containing DOCX data
- When the template is loaded
- Then the template loads identically to file-based loading
- And the stream is consumed fully
- And resources are released properly

---

#### Story 2.1.3: Load Template from Byte Buffer

**As a** developer,  
**I want** to load a DOCX template from a `Vec<u8>`,  
**So that** I can work with in-memory template data.

**Acceptance Criteria:**

- Given a byte buffer containing valid DOCX data
- When the template is loaded
- Then the template loads without file system access
- And the buffer is not unnecessarily copied

---

### 2.2 Variable Replacement

#### Story 2.2.1: Replace Simple Variables

**As a** developer,  
**I want** to replace placeholders like `{{name}}` with values from context,  
**So that** I can generate personalized documents.

**Acceptance Criteria:**

- Given a template containing `{{variable}}`
- And a context with `{"variable": "value"}`
- When rendered
- Then all occurrences of `{{variable}}` are replaced with `"value"`
- And the replacement text is XML-escaped
- And original formatting is preserved

**Example:**

- Template: `Hello {{name}}!`
- Context: `{"name": "Ada Lovelace"}`
- Output: `Hello Ada Lovelace!`

---

#### Story 2.2.2: Replace Nested Object Properties

**As a** developer,  
**I want** to access nested object properties using dot notation,  
**So that** I can work with structured data.

**Acceptance Criteria:**

- Given a template containing `{{user.name}}`
- And a context with `{"user": {"name": "Grace Hopper"}}`
- When rendered
- Then `{{user.name}}` resolves to `"Grace Hopper"`
- And undefined paths are handled according to missing value policy

**Example:**

- Template: `Invoice for {{customer.name}} at {{customer.address.city}}`
- Context: `{"customer": {"name": "Ada", "address": {"city": "London"}}}`
- Output: `Invoice for Ada at London`

---

#### Story 2.2.3: Replace Array Element by Index

**As a** developer,  
**I want** to access array elements using numeric indices,  
**So that** I can reference specific items.

**Acceptance Criteria:**

- Given a template containing `{{items.0.name}}`
- And a context with `{"items": [{"name": "First"}, {"name": "Second"}]}`
- When rendered
- Then `{{items.0.name}}` resolves to `"First"`

---

#### Story 2.2.4: Handle Missing Values

**As a** developer,  
**I want** to configure how missing values are handled,  
**So that** I can control behavior when template data is incomplete.

**Acceptance Criteria:**

- Given a template containing `{{missing}}`
- And a context without `missing` field
- When rendered with policy `Empty`
- Then the placeholder is replaced with empty string
- When rendered with policy `KeepPlaceholder`
- Then the placeholder text remains unchanged
- When rendered with policy `Fail`
- Then a `RenderError::MissingValue` error is returned

---

### 2.3 Conditional Sections

#### Story 2.3.1: Show/Hide Content Based on Condition

**As a** developer,  
**I want** to conditionally include or exclude document sections,  
**So that** I can generate different content for different scenarios.

**Acceptance Criteria:**

- Given a template containing:
  ```
  {% if customer.vip %}
  VIP benefits apply
  {% endif %}
  ```
- And a context with `{"customer": {"vip": true}}`
- When rendered
- Then the content between tags is included
- When context has `{"customer": {"vip": false}}`
- Then the content is removed

---

#### Story 2.3.2: Conditional with Else Branch

**As a** developer,  
**I want** to show alternative content when a condition is false,  
**So that** I can handle both cases.

**Acceptance Criteria:**

- Given a template containing:
  ```
  {% if user.active %}
  Welcome back!
  {% else %}
  Your account is inactive.
  {% endif %}
  ```
- And a context with `{"user": {"active": true}}`
- When rendered
- Then only "Welcome back!" appears
- When context has `{"user": {"active": false}}`
- Then only "Your account is inactive." appears

---

#### Story 2.3.3: Negated Conditions

**As a** developer,  
**I want** to test for false/absent values using `not`,  
**So that** I can express negative conditions.

**Acceptance Criteria:**

- Given a template containing `{% if not user.disabled %}`
- And a context with `{"user": {"disabled": false}}`
- When rendered
- Then the block content is included
- When context has `{"user": {"disabled": true}}`
- Then the block content is excluded

---

#### Story 2.3.4: Else If Chains

**As a** developer,  
**I want** to test several conditions in order,  
**So that** mutually exclusive cases stay readable in one block.

**Acceptance Criteria:**

- Given a template containing:
  ```
  {% if status == "open" %}
  Open
  {% elif status == "pending" %}
  Pending
  {% elif status == "closed" %}
  Closed
  {% else %}
  Unknown
  {% endif %}
  ```
- And a context with `{"status": "pending"}`
- When rendered
- Then only "Pending" appears
- And the chosen branch is the first condition that is true
- And a later branch that would fail on its own is never evaluated
- And an `elif` after `{% else %}` is rejected when the template loads

---

### 2.4 Loops

#### Story 2.4.1: Iterate Over Array Items

**As a** developer,  
**I want** to repeat content for each item in an array,  
**So that** I can generate tables, lists, and repeated sections.

**Acceptance Criteria:**

- Given a template containing:
  ```
  {% for item in items %}
  - {{item.name}}
  {% endfor %}
  ```
- And a context with:
  ```json
  { "items": [{ "name": "Apple" }, { "name": "Banana" }] }
  ```
- When rendered
- Then two paragraphs are generated, one for each item
- And each iteration has its own scope with `item` bound

**Example Output:**

```
- Apple
- Banana
```

---

#### Story 2.4.2: Handle Empty Arrays

**As a** developer,  
**I want** empty arrays to produce no output,  
**So that** optional sections disappear when no data exists.

**Acceptance Criteria:**

- Given a template containing a for loop
- And a context with an empty array
- When rendered
- Then the template paragraph/row is removed
- And no placeholder artifacts remain

---

#### Story 2.4.3: Loop Over Primitives

**As a** developer,  
**I want** to iterate over arrays of strings/numbers,  
**So that** I can work with simple lists.

**Acceptance Criteria:**

- Given a template containing:
  ```
  {% for tag in tags %}
  {{.}}
  {% endfor %}
  ```
- And a context with `{"tags": ["rust", "docx", "template"]}`
- When rendered
- Then each tag value is accessible via `.` (current item)
- And each tag value is also accessible through the loop variable, so `{{tag}}` and `{{.}}` render the same text

---

### 2.5 Table Operations

#### Story 2.5.1: Duplicate Table Rows

**As a** developer,  
**I want** to place loop markers inside table rows,  
**So that** I can generate dynamic tables.

**Acceptance Criteria:**

- Given a table template with loop markers in a row:
  ```
  | {% for item in items %} {{item.sku}} | {{item.qty}} {% endfor %} |
  ```
- And a context with multiple items
- When rendered
- Then one table row is generated per item
- And table structure remains valid
- And cell formatting is preserved

---

#### Story 2.5.2: Conditional Table Rows

**As a** developer,  
**I want** to conditionally include table rows,  
**So that** I can show/hide rows based on data.

**Acceptance Criteria:**

- Given a table with conditional row markers
- When the condition is true
- Then the row appears
- When the condition is false
- Then the row is removed
- And the table remains structurally valid

---

### 2.6 Multi-Part Processing

#### Story 2.6.1: Process Headers and Footers

**As a** developer,  
**I want** to apply templating to document headers and footers,  
**So that** I can customize these sections per document.

**Acceptance Criteria:**

- Given a template with placeholders in header/footer parts
- And options configured with `headers_and_footers(true)`
- When rendered
- Then header and footer placeholders are replaced
- And main document is also processed

---

#### Story 2.6.2: Process Footnotes

**As a** developer,  
**I want** to optionally process footnotes,  
**So that** I can control which parts are templated.

**Acceptance Criteria:**

- Given a template with footnotes containing placeholders
- And options configured with footnotes enabled
- When rendered
- Then footnote content is templated
- When footnotes are disabled
- Then footnote parts are copied unchanged

---

### 2.7 Output Generation

#### Story 2.7.1: Generate In-Memory Document

**As a** developer,  
**I want** to render templates to memory,  
**So that** I can stream results or store them without file system access.

**Acceptance Criteria:**

- Given a rendered template
- When I call `.into_bytes()`
- Then I receive a complete DOCX file as `Vec<u8>`
- And the bytes represent a valid ZIP/DOCX archive

---

#### Story 2.7.2: Write Document to File

**As a** developer,  
**I want** to save rendered documents directly to disk,  
**So that** I have a convenient output method.

**Acceptance Criteria:**

- Given a rendered template
- When I call `.write_to_file(path)`
- Then the DOCX is written to the specified path
- And parent directories are created if needed
- And I/O errors are properly reported

---

#### Story 2.7.3: Write Document to Stream

**As a** developer,  
**I want** to write rendered documents to any `Write` stream,  
**So that** I can integrate with HTTP responses, pipes, or custom destinations.

**Acceptance Criteria:**

- Given a rendered template
- When I call `.write_to_writer(writer)`
- Then the complete DOCX is written to the stream
- And the writer is flushed

---

### 2.8 Context Creation

#### Story 2.8.1: Create Context from JSON Value

**As a** developer,  
**I want** to create context from `serde_json::Value`,  
**So that** I can work with dynamic data structures.

**Acceptance Criteria:**

- Given a `serde_json::Value` containing template data
- When I create a context from it
- Then path lookups resolve correctly
- And nested objects and arrays are accessible

---

#### Story 2.8.2: Create Context from Rust Structs

**As a** developer,  
**I want** to create context from typed Rust structs,  
**So that** I can leverage compile-time type safety.

**Acceptance Criteria:**

- Given a Rust struct implementing `Serialize`
- When I create context via `Context::from_serialize(&value)`
- Then the struct serializes to JSON internally
- And all fields are accessible in templates
- And serialization errors are reported

---

## 3. Business Rules & Invariants

### 3.1 Template Syntax Rules

**BR-001: Placeholder Delimiters**  
Variable placeholders MUST use double curly braces: `{{expression}}`. Single braces are literal text.

**BR-002: Block Tag Delimiters**  
Block tags (if, elif, for, else, endif, endfor) MUST use `{%` and `%}` delimiters.

**BR-003: Balanced Delimiters**  
All opening delimiters (`{{`, `{%`) MUST have matching closing delimiters (`}}`, `%}`). Unclosed delimiters produce a `BindingError::Syntax` error that names the part and the span.

**BR-004: Block Nesting**  
Block tags MUST be properly nested. `{% if %}` MUST close with `{% endif %}` before any outer block closes. Mismatched terminators produce a `BindingError::Syntax` error.

**BR-005: Else Placement**  
`{% else %}` tags MUST appear only inside `{% if %}` blocks, after the if condition and before `{% endif %}`. Orphaned else tags produce syntax errors.

**BR-006: Filter Syntax**  
A value expression MAY apply filters after a pipe: `{{name | upper}}`. A filter argument follows a colon as a quoted string or a bare token: `{{nickname | default: "friend"}}`, `{{amount | round: 2}}`. Filters may chain: `{{name | trim | upper}}`.

**BR-007: Filter Evaluation Order**  
Filters apply left to right, each receiving the result of the one before it. An unregistered filter produces `RenderError::UnknownFilter`. A filter that rejects its value produces `RenderError::FilterFailed` with the reason. Both errors name the filter and the DOCX part.

**BR-008: Missing Values With Filters**  
A missing path resolves to null when at least one filter is present, so `default` can supply a fallback. A bare missing path still follows `MissingValuePolicy`.

**BR-009: Number and Date Filters**  
The built in number filters are `round`, `fixed`, `thousands` and `percent`. They accept a JSON number or a numeric string and report `RenderError::FilterFailed` for anything else. `round` takes an optional count of decimal places, defaulting to zero, and rounds half away from zero. `fixed` requires the count and returns text with exactly that many decimal places. `thousands` groups the integer digits in threes with an optional separator and does not round. `percent` takes an optional count, multiplies by 100 and appends `%`. With the `dates` feature on, `date` formats an ISO 8601 date, an instant or epoch seconds with a `strftime` pattern, and `timezone` converts an instant to an IANA zone or attaches a zone to a value without one. A value without an offset keeps its clock time, so attaching a zone does not shift it.

---

### 3.2 Path Resolution Rules

**BR-010: Dot Notation**  
Path segments are separated by `.` (dot). `user.name` resolves as: get field "user", then get field "name" from the result.

**BR-011: Array Indexing**  
Numeric path segments resolve as array indices. `items.0` accesses the first element of the `items` array.

**BR-012: Current Item Reference**  
Inside a loop, `.` (single dot) refers to the current iteration value. The loop variable also refers to the same value, so `{% for item in items %}{{item}}{% endfor %}` renders an array of strings or numbers. When the element is an object, a field must be named, as in `{{item.name}}`; rendering the object itself produces `RenderError::CannotConvertToText` with the value type `object`.

**BR-013: Missing Field Behavior**  
When a path segment does not exist, behavior depends on `MissingValuePolicy`:

- `Empty`: Replace with empty string
- `KeepPlaceholder`: Leave original placeholder text
- `Fail`: Return `RenderError::MissingValue` error

**BR-014: Type Mismatch Errors**  
Attempting to access a field on a non-object value produces `RenderError::TypeMismatch` with expected vs. actual types.

**BR-015: Comparison Expressions**  
A condition MAY compare two value expressions with `==`, `!=`, `<`, `<=`, `>`, `>=`: `{% if total > 100 %}`, `{% if status == "open" %}`. The operands may be paths, literals, filtered paths or parenthesized expressions. Equality compares any two values and treats numeric spellings of the same number as equal. Ordering compares two numbers or two strings; any other pairing produces `RenderError::InvalidComparison` naming both types. Comparisons are allowed in conditions only, so a comparison used as text or as a loop iterable produces `RenderError::ExpressionNotSupported`.

**BR-016: Boolean Logic**  
A condition MAY combine expressions with `and`, `or`, `not` and parentheses: `{% if active and verified %}`, `{% if not (draft or revised) %}`. `not` binds tighter than `and`, and `and` binds tighter than `or`; parentheses override that order. `and` returns false and stops without evaluating its right side when the left side is falsy, and `or` returns true and stops when the left side is truthy, so a comparison that would fail on the skipped side never runs.

**BR-017: Arithmetic Expressions**  
A placeholder or condition MAY compute with `+`, `-`, `*`, `/` and `%`: `{{price * quantity}}`, `{{(subtotal - discount) | fixed: 2}}`. `*`, `/` and `%` bind tighter than `+` and `-`, parentheses override that order, and a leading `-` negates a value. Both operands MUST be numbers; any other value produces `RenderError::ArithmeticType`, and division or remainder by zero produces `RenderError::DivisionByZero`. Integer operands produce an integer result when the operation is exact, so `{{2 * 3}}` writes `6` and `{{10 / 4}}` writes `2.5`. A filter written after an arithmetic expression applies to the whole result.

**BR-018: Else If Placement**  
`{% elif expression %}` tags MUST appear only inside an `{% if %}` block, before that block's `{% else %}` tag, and MAY appear several times. The renderer tries the `if` condition first, then each `elif` in source order, then `else`, and keeps only the first true branch. Branches after the winning one are never evaluated. An `elif` with no open `if` produces `BindingError::UnexpectedTag`, and an `elif` after `{% else %}` produces `BindingError::MultipleTagsInBlock`.

---

### 3.3 Truthiness Rules

**BR-020: Falsy Values**  
The following values are considered false in conditionals:

- `null`
- `false` (boolean)
- `0` (number)
- `""` (empty string)
- `[]` (empty array)
- `{}` (empty object)

**BR-021: Truthy Values**  
All other values are considered true:

- `true` (boolean)
- Non-zero numbers
- Non-empty strings
- Non-empty arrays
- Non-empty objects

**BR-022: Negation**  
The `not` operator inverts truthiness: `{% if not x %}` includes content when `x` is falsy.

---

### 3.4 XML Safety Rules

**BR-030: Mandatory Escaping**  
All user-provided text MUST be XML-escaped before insertion. The following characters MUST be escaped:

- `<` → `&lt;`
- `>` → `&gt;`
- `&` → `&amp;`
- `"` → `&quot;`
- `'` → `&apos;`

**BR-031: No Raw XML Injection**  
Version 1.0 does NOT support raw XML injection. All text values are treated as plain text.

**BR-032: Whitespace Preservation**  
When inserted text contains leading or trailing whitespace, the XML attribute `xml:space="preserve"` MUST be set on the containing text node.

---

### 3.5 Loop Rules

**BR-040: Iterable Types**  
Loops MUST operate on array values. Attempting to loop over non-array values produces `RenderError::ExpectedIterable` error.

**BR-041: Empty Array Handling**  
When looping over an empty array, the template paragraph/row MUST be removed entirely. No empty placeholder should remain.

**BR-042: Loop Scope**  
Each loop iteration creates a new scope. The loop variable shadows any outer variable with the same name for the duration of the loop body.

**BR-043: Nested Loop Access**  
Inner loops can access outer loop variables. Variable resolution checks innermost scope first, then outer scopes.

**BR-044: Loop Metadata**  
Inside a loop, `@index`, `@first` and `@last` describe the current iteration. `@index` is zero based, `@first` is true on the first iteration and `@last` is true on the last one. The three values resolve in text, filters and conditions. They always refer to the innermost loop. A metadata name used outside a loop produces `RenderError::MetaOutsideLoop`, and an unknown name produces a render error that names it.

---

### 3.6 DOCX Structure Rules

**BR-050: Package Validation**  
Every DOCX template MUST contain these required parts:

- `[Content_Types].xml`
- `_rels/.rels`
- `word/document.xml`

Missing required parts produce `PackageError::MissingRequiredPart` error.

**BR-051: Path Traversal Protection**  
ZIP entries with path traversal sequences (`../`, absolute paths) MUST be rejected with `PackageError::UnsupportedEntry` error.

**BR-052: Block Placement Constraints**  
Conditional and loop blocks MUST align with valid DOCX structural boundaries:

- Inline range within a paragraph
- Complete paragraph(s)
- Complete table row(s)

Blocks that cross unsupported boundaries produce `RenderError::UnsupportedBlockPlacement` error.

**BR-053: XML Well-Formedness**  
Generated DOCX XML MUST remain well-formed after rendering. Malformed output is a bug, not a user error.

---

## 4. Technical Architecture

### 4.1 Layer Responsibilities

#### Public API

**Responsibility:** the surface a caller uses  
**Modules:** `template`, `context`, `options`, `rendered`, `error`

**Capabilities:**

- Load a template from a path, a reader, bytes, or any `PackageSource`
- Accept a `Context`, a `serde_json::Value`, or any borrowed `serde::Serialize` value
- Render a resolved plan into a new DOCX package
- Report structured errors that name the failing part

**Key Types:**

- `Template<S = ZipPackageSource>` - a loaded template, rendered many times
- `Context` - the data a template is rendered against
- `IntoContext` - the conversion `Template::render` and the free `render` use
- `RenderedDocument` - the rendered package bytes
- `TemplateOptions` - policies for rendering
- `Error` - the top-level error enum

---

#### Adapters

**Responsibility:** translate between DOCX bytes and the domain model  
**Modules:** `adapters::docx`, `adapters::package`, `package/`, `docx/`

**Capabilities:**

- Parse a WordprocessingML part into the lossless document tree
- Serialize the tree back, preserving untouched markup byte for byte
- Read and write the ZIP/OPC package
- Validate required parts and reject unsafe entry names

**Key Types:**

- `Document` - one parsed part: prolog, root and epilogue
- `Element`, `Node`, `TextNode` - the typed tree
- `PackageSource`, `PackageWriter` - package traits
- `ZipPackageSource`, `ZipPackageWriter`, `InMemoryPackageSource`

**Note:** `adapters::docx` and `adapters::package` are crate private. The
package traits and the part name helpers stay public because callers implement
and use them.

---

#### Domain

**Responsibility:** the document and template model, with no IO  
**Modules:** `domain::document`, `domain::template`, `domain::binding`, `domain::placement`, `domain::plan`, `domain::engine`

**Capabilities:**

- Hold a lossless tree where unknown elements pass through untouched
- Project runs into logical text so a placeholder split across runs is seen whole
- Bind template tags to positions in that text
- Classify whether a block aligns with a paragraph, a row, or an inline range
- Evaluate the bound template against a context into a resolved plan
- Apply the plan to a copy of the tree

**Key Types:**

- `Document`, `Element`, `Role` - the tree
- `BoundTemplate`, `BoundParagraph`, `Block` - template positions
- `Plan`, `Edit` - the resolved edits
- `BindingError`, `PlanError`, `RenderError` - domain errors

**Design Decision:** Evaluation produces a resolved plan, and every loop
iteration carries its own nested plan. The renderer only applies edits. This
keeps evaluation testable without XML and keeps DOCX structure knowledge out of
the evaluator.

---

#### Template Syntax Parser

**Responsibility:** Template language processing  
**Modules:** `syntax/`

**Capabilities:**

- Tokenize template syntax
- Parse tokens into an AST
- Validate block structure (matching tags, nesting)
- Report syntax errors with precise spans
- No dependency on DOCX concepts (testable with plain strings)

**Key Types:**

- `Node` enum - AST node (Text, Variable, If, For, Comment)
- `Expression` enum - Path or Not(Path)
- `Span` - source location inside one part
- `SyntaxError` - parse failure with a span and a message

**Note:** `syntax` is crate private. The binding layer calls it and turns a
`SyntaxError` into `BindingError::Syntax`, which carries the part name.

---

### 4.2 Data Flow

```
1. Load
   ├─ Read the ZIP archive (package adapter)
   ├─ Validate required parts exist (docx validation)
   ├─ Read word/document.xml
   └─ Keep the headers, footers, footnotes and endnotes as bytes

2. Bind
   ├─ Parse the part into the lossless tree (docx adapter)
   ├─ Project runs into logical text (domain)
   ├─ Bind tags to positions, reject unsupported placements (domain)
   └─ Repeat per secondary part when an option enables it

3. Render
   ├─ Evaluate the bound template against the context (domain engine)
   ├─ Produce a resolved plan with a nested plan per loop iteration (domain)
   ├─ Apply the plan to a copy of the tree (domain plan)
   └─ Serialize the rendered part (docx adapter)

4. Write
   ├─ Write the rendered parts (package adapter)
   └─ Copy every other part verbatim (package adapter)
```

---

### 4.3 Module Dependency Rules

**Allowed Dependencies:**

- Public API → Domain and Adapters
- Adapters → Domain
- Domain → `std` and the template syntax parser

**Forbidden Dependencies:**

- Domain MUST NOT depend on `quick_xml`, `zip`, the filesystem, IO, or the adapters
- Adapters MUST NOT depend on the public API
- The syntax parser MUST NOT depend on DOCX concepts

**Rationale:** the domain is testable with plain data, and the adapter boundary
is the only place that knows DOCX is XML inside a ZIP. `tests/architecture.rs`
enforces the first two rules on every test run.

---

### 4.4 Error Handling Architecture

**Top-Level Error:**

```rust
pub enum Error {
    Io(std::io::Error),
    Package(PackageError),
    Xml(XmlError),
    Placement(BindingError),
    Plan(PlanError),
    Render(RenderError),
    Context(ContextError),
}
```

**Error Propagation:**

- Low-level modules return specific error types
- `From` implementations convert to the top-level `Error`
- All public API returns `Result<T, Error>`
- `Error::is_missing_value()` tells a missing field apart from a malformed
  template

**Error Quality Requirements:**

- Include context (part name, span, path)
- Provide actionable messages
- Use `thiserror` for Display implementations
- Never panic on invalid user input

---

### 4.5 SOLID Principles Application

**Single Responsibility:**

- `domain::document` changes only for the tree model
- `domain::engine` changes only for evaluation
- `domain::plan` changes only for plan construction and application
- `adapters::docx` changes only for WordprocessingML parsing and serialization
- `package/` changes only for ZIP handling
- Each module has one reason to change

**Open/Closed:**

- Extend via traits (`PackageSource`, `PackageWriter`)
- No need to modify core `Template` for new sources

**Liskov Substitution:**

- Any `PackageSource` implementation is substitutable
- `ZipPackageSource` and `InMemoryPackageSource` behave identically from caller perspective

**Interface Segregation:**

- Small, focused traits (not one large trait)
- `PackageSource` separate from `PackageWriter`

**Dependency Inversion:**

- High-level `Template` depends on the `PackageSource` trait
- Not on the concrete `ZipPackageSource`
- The domain depends on its own types, not on XML or ZIP
- Enables testing with mock implementations

---

## 5. Quality Requirements

### 5.1 Testing Strategy

#### Test Pyramid

```
        E2E Tests               # Full Template::render() workflows
     Fixture Tests              # Real DOCX with golden outputs
   Integration Tests            # Multi-module interactions
 Unit Tests                     # Isolated functions/modules
```

**Target Distribution:**

- Unit tests: 70% of test count
- Integration tests: 20%
- Fixture/E2E tests: 10%

---

#### Test Categories

**Unit Tests:**

- Parser with plain strings (no DOCX dependency)
- Path resolution against JSON values
- Truthiness rules
- XML escaping
- Text projection across split runs
- Loop scope behavior

**Integration Tests:**

- Parser + Context together
- Document tree + plan application
- Package + Rendering

**Fixture Tests:**

- Real `.docx` files in `tests/fixtures/`
- Each fixture includes:
  - Input template DOCX
  - Input context JSON
  - Expected output (normalized XML or verification criteria)

**Golden Tests:**

- Snapshot testing with `insta` crate
- Compare normalized XML output against saved snapshots
- Normalize before comparison (whitespace, attribute order)

---

#### Phase-Specific Test Requirements

Each development phase has explicit test requirements:

**Phase 1 (Package):**

- Valid/invalid DOCX loading
- Part validation
- Path traversal rejection
- Unchanged part copying

**Phase 2 (XML):**

- Text plane from split runs
- Whitespace preservation
- Escaping correctness
- XML well-formedness

**Phase 3 (Parser):**

- AST generation
- Syntax error reporting with spans
- Block nesting validation

**Phase 4 (Context):**

- Path resolution (fields, arrays, nested)
- Truthiness rules
- Serialization from Rust structs

**Phase 5 (Inline Replacement):**

- End-to-end rendering
- Missing value policies
- Format preservation
- Split placeholder handling

**Phases 6-8 (Conditionals, Loops, Tables):**

- Block rendering
- Scope management
- Structure validation
- Edge cases (empty arrays, nested blocks)

---

### 5.2 Code Quality Standards

#### Linting Requirements

**Must Pass:**

```bash
cargo clippy --all-targets --all-features -- -D warnings
```

No clippy warnings allowed in CI.

**Key Clippy Rules:**

- No `unwrap()` or `expect()` in library code (except internal invariants)
- No panic paths on user input
- Prefer `?` for error propagation
- Use `#[must_use]` on `Result` types

---

#### Formatting Requirements

**Must Pass:**

```bash
cargo fmt --check
```

All code must be formatted with `rustfmt` defaults.

---

#### Documentation Requirements

**Public API:**

- All public items require rustdoc comments
- Include example code blocks
- Document error cases
- Link related types

**Modules:**

- Module-level documentation explaining purpose
- High-level architecture notes for complex modules

**Complex Logic:**

- Inline comments explaining "why", not "what"
- Cite relevant blueprint sections for design decisions

---

### 5.3 Definition of Done

A feature is complete when:

**Functional:**

- ✓ Implementation works as specified
- ✓ Edge cases handled explicitly
- ✓ Errors returned as `Result`, not panics
- ✓ Unsupported cases return clear errors

**Testing:**

- ✓ Unit tests exist for new logic
- ✓ Integration tests exist for user-visible behavior
- ✓ Fixture tests exist for DOCX-specific behavior
- ✓ Regression tests exist for every fixed bug
- ✓ All tests pass in CI

**Quality:**

- ✓ No clippy warnings
- ✓ Code is formatted
- ✓ No new unsafe code (unless justified)
- ✓ Public API reviewed for naming/design

**Documentation:**

- ✓ Public API has rustdoc
- ✓ Examples updated if needed
- ✓ CHANGELOG.md updated
- ✓ Known limitations documented

**CI:**

- ✓ All CI checks pass
- ✓ No failing tests
- ✓ Documentation builds successfully

---

### 5.4 Regression Prevention

**Every bug fix must include:**

1. A failing test that reproduces the bug
2. The fix implementation
3. Verification that the test now passes
4. Addition of test to regression suite

**Fixture-based bugs:**

- Add problematic DOCX to `tests/fixtures/regression/`
- Include context JSON
- Document expected behavior
- Add to CI suite

---

## 6. Performance & Reliability

### 6.1 Performance Targets

#### Version 1.0 Targets

**Document Size:**

- Support documents up to 100MB
- Support up to 10,000 placeholders per document
- Support up to 1,000 loop iterations per loop

**Memory:**

- Peak memory usage < 3x input document size
- No memory leaks (verify with Valgrind/sanitizers)
- Reuse allocations where possible (XML buffers)

**Throughput:**

- Process 1MB document with 100 placeholders in < 100ms (release build)
- Process 10MB document with 1,000 placeholders in < 500ms
- Baseline: modern desktop CPU (no specific hardware assumptions)

**Note:** These are targets, not guarantees. Version 1.0 prioritizes correctness over performance.

---

#### Performance Anti-Patterns to Avoid

**❌ Don't:**

- Decompress unchanged ZIP entries
- Parse entire XML into DOM when streaming suffices
- Clone context data unnecessarily
- Re-serialize user data multiple times

**✅ Do:**

- Stream unchanged ZIP entries directly to output
- Use event-based XML parsing with `quick-xml`
- Borrow into `serde_json::Value` during evaluation
- Buffer structural units (paragraphs, rows) only as needed

---

### 6.2 Scalability Considerations

#### Large Documents

**Challenges:**

- Memory pressure from large XML parts
- Many placeholders increase parsing time
- Deep nesting increases evaluation overhead

**Mitigation Strategies (Future):**

- Streaming API: `render_to_writer()` already provides foundation
- Chunk processing: process document in logical sections
- Lazy evaluation: defer context lookups until needed

**Version 1.0 Scope:**

- Focus on correct handling of medium-sized documents
- Document known limits
- Provide clear error messages on resource exhaustion

---

#### Large Arrays

**Challenges:**

- Looping over 10,000 items duplicates paragraph/row 10,000 times
- Memory allocation for duplicated XML

**Mitigation Strategies:**

- Use buffered writes instead of building entire output in memory
- Consider pagination recommendation in documentation
- Warn users about potential performance impact of large loops

---

### 6.3 Reliability Requirements

#### No Panics

**Requirement:** Library code MUST NOT panic on any user-provided input.

**Allowed Panics:**

- Internal invariant violations (use `debug_assert!` for checks)
- Panics in test code are acceptable

**Testing Strategy:**

- Fuzz testing with malformed inputs
- Property-based testing with arbitrary JSON
- Fixture tests with real-world DOCX files

---

#### Resource Cleanup

**Requirement:** All resources must be properly released.

**Resources to Track:**

- File handles (ZIP archives)
- Memory allocations
- Temporary buffers

**Testing Strategy:**

- Manual testing under resource constraints
- Verify no file handle leaks
- Run tests under sanitizers (LeakSanitizer)

---

#### Error Recovery

**Requirement:** Errors must leave the system in a clean state.

**Guarantees:**

- No partial writes (output is written atomically where possible)
- Failed renders do not corrupt input templates
- Clear error messages guide user to fix

---

### 6.4 Observability

#### Error Context

Every error must include sufficient context for debugging:

**Package Errors:**

- Part name that failed
- Expected vs. actual structure

**Syntax Errors:**

- Exact span (part, start, end)
- Offending text
- Suggestion for fix (when possible)

**Render Errors:**

- Template location (part, span)
- Data path that failed
- Expected vs. actual value type

**Example Error Output:**

```
Render error in word/document.xml:
  expected iterable value at `items`, found object

  Template location:
    word/document.xml:142-178
    {% for item in items %}

  Context path:
    items: {"type": "object"}

  Suggestion:
    Ensure `items` is an array, not an object
```

---

#### Logging

**Version 1.0 Scope:**

- No built-in logging (library should be silent by default)
- Errors contain all necessary information
- Future versions may add opt-in tracing with `tracing` crate

**Rationale:** Libraries should not force logging dependencies on users. Error types provide sufficient debugging information.

---

## 7. Security Requirements

### 7.1 Input Validation

#### ZIP Archive Validation

**Threat:** Malicious ZIP archives (zip bombs, path traversal)

**Mitigations:**

- **Path Traversal:** Reject entries with `../` or absolute paths
- **Size Limits:** Configurable maximum decompressed entry size
- **Entry Count:** Reasonable limit on number of entries
- **Compression Ratio:** Detect decompression bombs (high compression ratios)

**Implementation:**

- Validate all entry names before extraction
- Check decompressed size against limit
- Return `PackageError::UnsupportedEntry` for violations

---

#### XML Validation

**Threat:** Malformed XML causing parser vulnerabilities

**Mitigations:**

- Use well-tested parser (`quick-xml`)
- Fail gracefully on malformed XML
- Don't expose raw XML parsing errors to users (wrap in `XmlError`)

**Testing:**

- Fuzz XML parser with malformed inputs
- Test with real-world malformed DOCX files

---

### 7.2 XML Safety

#### Mandatory Escaping

**Requirement:** ALL user-provided text MUST be XML-escaped.

**Characters to Escape:**

```
< → &lt;
> → &gt;
& → &amp;
" → &quot;
' → &apos;
```

**Implementation:**

- Use `quick-xml::escape::escape()` for text content
- Use `quick-xml::escape::escape_attribute()` for attributes
- Never construct XML via string concatenation

**Testing:**

- Test with special characters: `<script>`, `& Co`, `"quotes"`
- Property-based tests with arbitrary strings
- Verify output XML remains well-formed

---

#### No Raw XML Injection

**Decision:** Version 1.0 does NOT support raw XML injection.

**Rationale:**

- Prevents accidental XML injection vulnerabilities
- Simplifies security model
- Users who need this can use future opt-in `RawXml` type

**Future Consideration:**

```rust
pub struct RawXml(String);  // Opt-in for advanced users
```

With explicit documentation warning about security implications.

---

### 7.3 Data Privacy

#### No Data Exfiltration

**Guarantee:** Library makes no network requests.

**Implementation:**

- No network dependencies
- No telemetry or analytics
- All processing is local

---

#### No Data Logging

**Guarantee:** Library does not log user context data.

**Implementation:**

- Error messages may reference paths/types but not values
- No `Debug` implementation on `Context` that exposes data
- Test fixtures use synthetic data only

---

### 7.4 Supply Chain Security

#### Dependency Auditing

**Requirement:** All dependencies must be audited regularly.

**Tools:**

```bash
cargo audit          # Check for known vulnerabilities
cargo deny check     # Check licenses and security advisories
```

**Policy:**

- Run `cargo audit` in CI
- Update dependencies on security advisories
- Prefer well-maintained crates from trusted authors

---

#### Minimal Dependencies

**Principle:** Depend on as few crates as possible.

**Core Dependencies (v1.0):**

- `zip` - ZIP archive handling
- `quick-xml` - XML parsing
- `serde` / `serde_json` - Data serialization
- `thiserror` - Error derivation
- `winnow` - Parser combinators

**Rationale:** Each dependency is a potential security risk. Keep the tree small and auditable.

---

### 7.5 Unsafe Code Policy

#### Default Position: No Unsafe

**Requirement:** Version 1.0 contains ZERO `unsafe` blocks.

**Rationale:**

- No compelling performance reason for unsafe in this domain
- Reduces audit surface
- Simplifies security review

**Future Exceptions:**
If future performance optimization requires unsafe:

- Must be isolated in private module
- Must be justified in design review
- Must document safety invariants
- Must be covered by targeted tests
- Ideally behind feature flag

---

### 7.6 Threat Model

#### In Scope

**Threats Library Defends Against:**

- Malicious ZIP archives (path traversal, bombs)
- XML injection via user data
- Malformed DOCX causing panics
- Resource exhaustion (memory, CPU)

#### Out of Scope

**Threats Library Does NOT Defend Against:**

- Physical access to machine running library
- Compromised Rust compiler/toolchain
- Side-channel attacks (timing, cache)
- Malicious code in user application

**Rationale:** Library focuses on data-level security. Infrastructure security is user's responsibility.

---

### 7.7 Security Testing

#### Fuzz Testing

**Targets:**

- Template parser with malformed syntax
- XML parser with malformed XML
- Context with arbitrary JSON
- ZIP reader with malicious archives

**Tools:**

- `cargo fuzz` with libFuzzer
- Property-based testing with `proptest`

**Goals:**

- No panics on arbitrary input
- No memory unsafety detected
- Graceful error handling

---

#### Adversarial Testing

**Test Cases:**

- Extremely deep nesting (10,000 levels)
- Very long strings (1GB)
- Huge arrays (1 million elements)
- Pathological regex patterns (if regex used)
- Unicode edge cases (emoji, RTL, combining characters)

**Expected Behavior:**

- Clear error messages
- No panics
- Bounded resource usage

---

## 8. Implementation Roadmap

### 8.1 Phased Delivery Strategy

**Guiding Principles:**

1. Each phase produces testable, usable increment
2. No phase builds on unstable foundation
3. Vertical slices over horizontal layers
4. Early phases deliver end-to-end value

---

### 8.2 Phase Breakdown

#### Phase 0: Engineering Baseline

**Goal:** Create healthy repository foundation

**Deliverables:**

- Cargo library scaffold
- CI pipeline (format, lint, test, docs)
- Test harness and fixture system
- Module layout skeleton
- Error type definitions

**Exit Criteria:**

- CI runs successfully
- Placeholder tests pass
- Team can add features without infrastructure changes

**Estimated Duration:** 1-2 days

---

#### Phase 1: Package Foundation

**Goal:** DOCX package reading/writing without templating

**Deliverables:**

- `PackageSource` trait
- `PackageWriter` trait
- ZIP-backed implementations
- In-memory package source (testing)
- DOCX validation
- Path traversal protection

**Key Test:** Open minimal DOCX, write it back, verify unchanged

**Exit Criteria:**

- Load valid DOCX from file/reader/bytes
- Reject invalid/malicious packages
- Write valid DOCX output
- All package tests pass

**Estimated Duration:** 1 week

---

#### Phase 2: XML Text Normalization

**Goal:** Extract and map DOCX text across split runs

**Deliverables:**

- Text projection across split runs
- Text span to node mapping
- XML escaping
- Basic text replacement (no template syntax yet)

**Key Challenge:** Handle `{{na` and `me}}` split across runs

**Exit Criteria:**

- Build logical text from XML
- Replace text spanning multiple nodes
- Preserve formatting and whitespace
- XML output remains well-formed

**Estimated Duration:** 1-2 weeks

---

#### Phase 3: Template Syntax Parser

**Goal:** Parse template syntax into AST

**Deliverables:**

- Lexer
- Parser
- AST types
- Span tracking
- Syntax error reporting

**Key Test:** Parse `"Hello {{name}}! {% if x %}Y{% endif %}"` correctly

**Exit Criteria:**

- Parse variables, conditionals, loops
- Report syntax errors with precise spans
- No dependency on DOCX (testable with strings)
- All parser tests pass

**Estimated Duration:** 1 week

---

#### Phase 4: Context and Data Lookup

**Goal:** Resolve template paths against data

**Deliverables:**

- `Context` type wrapping JSON
- Path resolution (dots, indices)
- Truthiness rules
- Serialization from Rust structs

**Key Test:** Resolve `user.items.0.name` against nested JSON

**Exit Criteria:**

- Resolve top-level, nested, array-indexed paths
- Implement truthiness rules
- Handle missing values per policy
- Create context from `serde::Serialize`

**Estimated Duration:** 1 week

---

#### Phase 5: Inline Variable Replacement (MVP)

**Goal:** First end-to-end feature - replace `{{variable}}`

**Deliverables:**

- Template orchestration
- Inline rendering
- Missing value policies
- End-to-end integration

**Key Test:** Load DOCX, render with context, write valid output

**Exit Criteria:**

- Complete example works end-to-end
- Split placeholders handled correctly
- Missing values handled per policy
- Generated DOCX opens in Word

**Version:** v0.1.0 (First Public Release)

**Estimated Duration:** 1-2 weeks

---

#### Phase 6: Conditionals

**Goal:** Support `{% if %}` blocks

**Deliverables:**

- Conditional evaluation
- Else branch support
- Paragraph-level block rendering
- Unsupported placement detection

**Key Test:** Show/hide paragraph based on boolean value

**Exit Criteria:**

- If/else rendering works
- Nested conditionals work
- Invalid placement returns error
- Generated XML remains valid

**Version:** v0.2.0

**Estimated Duration:** 1 week

---

#### Phase 7: Paragraph Loops

**Goal:** Support `{% for %}` over paragraphs

**Deliverables:**

- Loop evaluation
- Scope stack management
- Paragraph duplication
- Empty array handling

**Key Test:** Generate N paragraphs from N-element array

**Exit Criteria:**

- Paragraph loops work
- Empty arrays remove template paragraph
- Loop variables shadow outer scope
- Nested loops work (basic cases)

**Version:** v0.3.0

**Estimated Duration:** 1-2 weeks

---

#### Phase 8: Table Loops and Nested Blocks

**Goal:** Support table-row duplication

**Deliverables:**

- Table row detection
- Row duplication for loops
- Conditional rows
- Nested block validation

**Key Test:** Generate dynamic table from array

**Exit Criteria:**

- Table row loops work
- Cell formatting preserved
- Nested blocks work where structurally valid
- Invalid nesting returns error

**Version:** v0.4.0

**Estimated Duration:** 2 weeks

---

#### Phase 9: Multi-Part Support

**Goal:** Process headers, footers, footnotes

**Deliverables:**

- Part selection configuration
- Header/footer processing
- Footnote processing
- Options integration

**Key Test:** Replace placeholders in header and footer

**Exit Criteria:**

- Configurable part processing
- Headers and footers templated correctly
- Optional footnote processing works
- Main document + multi-part together

**Version:** v0.5.0

**Estimated Duration:** 1 week

---

#### Phase 10: Hardening and Performance

**Goal:** Production readiness

**Deliverables:**

- Fuzz testing
- Large document testing
- Performance benchmarks
- Error message improvements
- Dependency audit

**Key Activities:**

- Fuzz parser, XML handler, context
- Test with 100MB documents
- Benchmark rendering throughput
- Improve error context
- Remove all panics

**Exit Criteria:**

- No panics on fuzzed inputs
- Large documents handled gracefully
- Performance targets met or documented
- All errors have clear messages
- Security audit complete

**Version:** v0.8.0

**Estimated Duration:** 2 weeks

---

#### Phase 11: Release Candidate

**Goal:** API freeze and final polish

**Deliverables:**

- API review and stabilization
- Complete documentation
- Migration guide
- Example collection
- Final dependency updates

**Key Activities:**

- Review all public types for naming/design
- Write comprehensive examples
- Document limitations clearly
- Prepare docs.rs content
- Tag release candidate

**Exit Criteria:**

- No breaking API changes planned
- Documentation complete
- Examples all work
- No critical bugs
- Ready for early adopters

**Version:** v1.0.0-rc.1

**Estimated Duration:** 1 week

---

#### Phase 12: Stable 1.0 Release

**Goal:** Production-ready stable release

**Deliverables:**

- Final bug fixes
- Semantic versioning commitment
- Changelog finalization
- Publication to crates.io

**Post-Release Policy:**

- Patch releases for bug fixes (v1.0.x)
- Minor releases for backward-compatible features (v1.x.0)
- Major releases only for breaking changes (v2.0.0)

**Version:** v1.0.0

**Estimated Duration:** Final release milestone

---

### 8.3 Dependency Graph

```
Phase 0 (Baseline)
  ↓
Phase 1 (Package)
  ↓
Phase 2 (XML) ← Foundation for rendering
  ↓
  ├─→ Phase 3 (Parser)   ← Can develop in parallel
  └─→ Phase 4 (Context)  ← Can develop in parallel
       ↓
       Phase 5 (Inline Replacement) ← First MVP
         ↓
         Phase 6 (Conditionals)
           ↓
           Phase 7 (Paragraph Loops)
             ↓
             Phase 8 (Table Loops)
               ↓
               Phase 9 (Multi-Part)
                 ↓
                 Phase 10 (Hardening)
                   ↓
                   Phase 11 (RC)
                     ↓
                     Phase 12 (v1.0)
```

---

### 8.4 Milestone Timeline

**Single Developer (Full-Time):**

- MVP (Phase 5): 4-6 weeks
- Conditionals + Loops (Phase 7): 7-9 weeks
- Full Feature Set (Phase 9): 12-14 weeks
- Production Ready (Phase 12): 16-20 weeks

**Small Team (2-3 Developers):**

- MVP: 3-4 weeks
- Full Feature Set: 8-10 weeks
- Production Ready: 12-16 weeks

**Parallelization Opportunities:**

- Phases 3 & 4 can develop simultaneously
- Fixture creation can happen during any phase
- Documentation can progress alongside implementation

---

### 8.5 Risk Management

#### High-Risk Areas

**1. Split Placeholders**

- **Risk:** Word splits text unpredictably
- **Mitigation:** Extensive fixture testing, logical text projection, golden tests

**2. Invalid DOCX Generation**

- **Risk:** Generated XML doesn't open in Word
- **Mitigation:** Constrained block model, validation, real Word testing

**3. Table Loops**

- **Risk:** Complex table structure duplication
- **Mitigation:** Start with simple row cases, reject ambiguous cases

**4. Performance**

- **Risk:** Large documents slow or memory-intensive
- **Mitigation:** Stream unchanged entries, benchmark early, document limits

---

## 9. Open Questions

### 9.1 Design Decisions Still Under Consideration

#### Q1: Arithmetic Expressions

**Question:** Should version 1.0 support arithmetic in templates?

```
{{item.price * item.quantity}}
```

**Pros:**

- Useful for invoices, calculations
- Common feature in template engines

**Cons:**

- Increases parser complexity
- Opens questions about operator precedence
- What about floating-point precision?

**Current Decision:** Implemented. Templates support `+`, `-`, `*`, `/`, `%` and unary minus with the usual precedence, as in `{{item.price * item.quantity}}` and `{% if subtotal - discount > 0 %}`. Both operands must be numbers, division by zero is a typed error, and integer results stay integers. Floating point follows `f64`, so a caller that needs decimal currency rounding should format the result with `fixed` or `round`.

---

#### Q2: Custom Filters/Helpers

**Question:** Should templates support filters like `{{name | uppercase}}`?

**Pros:**

- Common in templating languages (Liquid, Jinja2)
- Useful for formatting (dates, currency, case)

**Cons:**

- Requires plugin system
- Increases API surface area
- What's the standard library of filters?

**Current Decision:** Implemented. Templates support `{{name | upper}}` and custom filters registered on `TemplateOptions`. The built in filters are the text filters `upper`, `lower`, `trim`, `default`, `len` and `join`, the number filters `round`, `fixed`, `thousands` and `percent`, and the date filters `date` and `timezone` behind the default `dates` feature. A filter is a closure over the current value and its optional argument, so no separate trait object is required:

```rust
let options = TemplateOptions::default().filter("shout", |value, _| {
    // transform value
});
```

**Future Consideration:** A currency filter and locale aware formatting can be added without changing the syntax. A filter that produces text for a specific locale can be registered by the caller today.

---

#### Q3: Image Replacement

**Question:** Should placeholders support image replacement?

```
{{company_logo}}  → Replace with image file
```

**Pros:**

- Common use case (letterheads, reports)
- Other libraries support this

**Cons:**

- Requires relationship management (complex)
- Needs image format validation
- Different API from text replacement

**Current Decision:** NOT in v1.0. Focus on text templating first.

**Future Consideration:** v2.0 feature with explicit API:

```rust
context.insert_image("logo", ImageData::from_path("logo.png")?);
```

---

#### Q4: Streaming API

**Question:** Should library support streaming for very large documents?

**Pros:**

- Handles documents larger than RAM
- Lower memory footprint

**Cons:**

- More complex API
- May not align with parse-early philosophy
- Limits what can be validated upfront

**Current Decision:** v1.0 focuses on in-memory processing up to 100MB.

**Future Path:** `render_to_writer()` already exists as foundation for streaming in v2.0.

---

#### Q5: Dynamic Part Creation

**Question:** Should library support adding new parts (headers, images, etc.)?

**Pros:**

- Maximum flexibility
- Could support dynamic header generation

**Cons:**

- Very complex (relationships, content types)
- Easy to generate invalid DOCX
- Out of scope for "templating"

**Current Decision:** NOT in v1.0. Library templates existing parts only.

---

### 9.2 Implementation Questions

#### Q6: Parser Choice

**Question:** Use parser combinators (winnow) or hand-written parser?

**Considerations:**

- Parser combinators: maintainable, testable, but learning curve
- Hand-written: full control, potentially faster, more code

**Current Decision:** Use `winnow` (parser combinators) for:

- Maintainability
- Good error messages
- Community-standard approach

---

#### Q7: AST Representation

**Question:** Should AST be public or private?

**Pros of Public:**

- Advanced users can inspect parsed templates
- Enables analysis tools

**Cons of Public:**

- Locks in AST structure (semver commitment)
- May change between versions

**Current Decision:** PRIVATE in v1.0. Can expose in v2.0 if demand exists.

**Rationale:** Maintain flexibility to refactor AST without breaking changes.

---

#### Q8: Span Representation

**Question:** Should spans use byte offsets or line/column?

**Considerations:**

- Byte offsets: precise, compact
- Line/column: human-readable

**Current Decision:** Byte offsets internally, display as line/column in errors.

**Implementation:**

```rust
pub struct Span {
    part: String,   // "word/document.xml"
    start: usize,   // Byte offset
    end: usize,     // Byte offset
}

impl Display for Span {
    // Convert to "word/document.xml:L42:C10-L42:C25"
}
```

---

### 9.3 Testing Questions

#### Q9: Fixture Coverage

**Question:** How many fixture DOCX files are sufficient?

**Current Plan:**

- Minimal (5-10 fixtures per feature)
- Focus on common cases and edge cases
- Real-world templates preferred over synthetic

**Categories:**

- Package: valid, invalid, corrupt (3-5 files)
- Inline: simple, split-run, special-chars (5-7 files)
- Conditional: if, if-else, nested (4-6 files)
- Loop: paragraph, table, empty, nested (6-8 files)

**Total Target:** 30-50 fixture DOCX files

---

#### Q10: Property Testing

**Question:** What properties should be tested?

**Candidates:**

- Parser: arbitrary safe strings don't panic
- Context: arbitrary JSON doesn't panic
- Escaping: escaped text is always valid XML
- Rendering: output DOCX is always valid ZIP

**Current Plan:**

- Start with parser and context (high ROI)
- Add escaping properties
- Add rendering properties in Phase 10

---

### 9.4 Performance Questions

#### Q11: Optimization Priority

**Question:** When should performance optimization begin?

**Current Decision:** After Phase 9 (multi-part support).

**Rationale:**

- Premature optimization risks
- Need stable API before optimizing
- Phase 10 dedicated to performance

**Benchmark Targets:**

- 1MB document, 100 placeholders: < 100ms
- 10MB document, 1000 placeholders: < 500ms

---

### 9.5 Documentation Questions

#### Q12: Example Depth

**Question:** How comprehensive should examples be?

**Current Plan:**

- README: Quick start (5-10 lines)
- Examples folder: 5-7 complete examples
  - Basic variable replacement
  - Invoice with table loop
  - Conditional sections
  - Nested loops
  - Multi-part (header/footer)
  - Error handling
  - Custom source/writer

**Each Example Includes:**

- Commented code
- Sample template DOCX
- Sample context JSON
- Expected output description

---

### 9.6 API Design Questions

#### Q13: Builder Pattern Depth

**Question:** How much builder-style chaining should API support?

**Current Design:**

```rust
Template::from_path("template.docx")?
    .with_options(
        TemplateOptions::default()
            .missing_value(MissingValuePolicy::Fail)
            .headers_and_footers(true)
    )
    .render(context)?
    .write_to_file("output.docx")?;
```

**Acceptable or too much chaining?**

**Current Decision:** This level is acceptable. Balances readability and convenience.

---

#### Q14: Error Granularity

**Question:** How fine-grained should error types be?

**Too Coarse:**

```rust
enum Error {
    TemplateError(String),  // Not helpful
}
```

**Too Fine:**

```rust
enum PackageError {
    MissingContentTypes,
    MissingRels,
    MissingDocument,
    MissingDocumentRels,
    // ... 20 more variants
}
```

**Current Decision:** Mid-level granularity with context fields:

```rust
enum PackageError {
    MissingRequiredPart(String),  // Part name in field
    UnsupportedEntry(String),     // Entry name in field
    // ...
}
```

---

### 9.7 Future Feature Considerations

#### Features Explicitly Deferred

**Not in v1.0, maybe v2.0+:**

- Image replacement
- Dynamic relationship management
- Chart data binding
- Content controls templating
- VBA macro support (likely never)
- Streaming very large documents
- Incremental rendering
- Template inheritance
- Partial templates
- Localization/i18n helpers

**Rationale:** Keep v1.0 focused on core text templating. Add features based on user demand.

---

## 10. Success Criteria

### 10.1 Version 1.0 Success Metrics

**Functional Completeness:**

- ✓ Load DOCX from file/reader/bytes
- ✓ Replace `{{variable}}` with nested path support
- ✓ Support `{% if %}` conditionals with `{% else %}`
- ✓ Support `{% for %}` loops over arrays
- ✓ Duplicate paragraphs and table rows
- ✓ Process headers and footers (optional)
- ✓ Safe XML escaping
- ✓ Clear error messages

**Quality Metrics:**

- ✓ 100% of public API documented
- ✓ 80%+ code coverage by tests
- ✓ Zero clippy warnings
- ✓ Zero unsafe code
- ✓ All CI checks pass
- ✓ No known panics on valid inputs

**Usability Metrics:**

- ✓ Examples compile and run
- ✓ Quick start works in < 10 lines
- ✓ Generated DOCX opens in Microsoft Word
- ✓ Error messages are actionable

**Performance Metrics:**

- ✓ Process 1MB/100 placeholders in < 100ms
- ✓ No memory leaks
- ✓ Reasonable memory usage (< 3x input size)

---

### 10.2 Post-Release Success

**Community Adoption:**

- Published on crates.io
- Documentation on docs.rs
- Example templates available
- Issue tracker active

**Maintenance Commitment:**

- Security patches within 48 hours
- Bug fixes in patch releases
- Feature requests triaged
- Semantic versioning respected

---

## 11. References

**External References:**

- DOCX Standard: ISO/IEC 29500 (Office Open XML)
- ZIP Format: PKWARE .ZIP File Format Specification
- Node.js docxtemplater: https://docxtemplater.com/

**Rust Crate Documentation:**

- `zip`: https://docs.rs/zip/
- `quick-xml`: https://docs.rs/quick-xml/
- `serde`: https://docs.rs/serde/
- `winnow`: https://docs.rs/winnow/
- `thiserror`: https://docs.rs/thiserror/

---

## Document History

| Version | Date       | Author | Changes                        |
| ------- | ---------- | ------ | ------------------------------ |
| 0.1.0   | 2026-08-13 | AI     | Initial specification creation |

---

**End of Specification**