jmap-server 0.5.0

Backend-agnostic JMAP server framework (RFC 8620): parsing, ResultReference resolution, and Dispatcher
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
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
//! Shared helper utilities for JMAP method handlers.

use std::borrow::Cow;
use std::collections::BTreeSet;

pub use jmap_types::json_type_name;
use jmap_types::{GetObject, Id, JmapError, SetObject, UTCDate};

use crate::backend::{JmapBackend, SetError, SetErrorType};
use crate::handlers::server_fail_value_from_backend;
use serde_json::{Map, Value};

/// Serialize any [`serde::Serialize`] type to a [`serde_json::Value`],
/// mapping serialization errors to [`JmapError::server_fail`].
///
/// Used by every `*-server` handler to project a typed domain object
/// (e.g. `Email`, `Mailbox`, `Chat`) into the wire-format `list` /
/// `created` payload.
pub fn serialize_value<T: serde::Serialize>(val: T) -> Result<serde_json::Value, JmapError> {
    serde_json::to_value(val).map_err(|e| JmapError::server_fail(e.to_string()))
}

/// Convert a slice of [`Id`]s to a JSON `notFound` value.
///
/// RFC 8620 §5.1 specifies `notFound` as `Id[]` — always an array, never
/// `null`. Returns an empty array when all requested ids were found.
///
/// Equivalent to `serde_json::to_value(ids)` but threads through
/// `Value::Array` directly so the call site is infallible (bd:JMAP-wlip.28).
pub fn not_found_json(ids: &[Id]) -> Value {
    Value::Array(
        ids.iter()
            .map(|id| Value::String(id.as_ref().to_owned()))
            .collect(),
    )
}

/// Extract an optional, deserializable argument from a method-arguments
/// envelope (bd:JMAP-wlip.32).
///
/// Looks up `name` in `args`, removing it. The result is:
///
/// - `Ok(None)` if the key is absent OR is present with `Value::Null`
///   (RFC 8620 §3.3 treats absent and explicit-null the same for
///   optional fields).
/// - `Ok(Some(value))` if the key is present and the value
///   deserializes successfully into `T`.
/// - `Err(invalid_arguments_with(name))` if the value is present but
///   fails to deserialize. The error message is built by the caller-
///   supplied `invalid_arguments_with` so the resulting `JmapError`
///   carries a domain-specific description ("ids must be an Id
///   array", "filter must be a Filter object", etc.).
///
/// Collapses six near-identical
/// `match args.remove(...).unwrap_or(Value::Null) { Value::Null => None,
/// v => Some(serde_json::from_value(v)...) }` blocks in `handlers.rs`
/// into one-liners.
///
/// # Interaction with `ResultReference` resolution (bd:JMAP-jfia.15)
///
/// [`crate::parse::resolve_args`] replaces a `#key` with the value
/// produced by walking the JSON Pointer path against a prior
/// response. RFC 6901 §4 makes no distinction between "key absent"
/// and "key present with `null`", so the resolved value CAN be
/// `Value::Null`. This function then treats that resolved-null
/// identically to "key was not sent". The behaviour is
/// RFC-compliant — both are "optional argument not provided" — but
/// the asymmetry between an explicit `null` argument and a
/// `#key`-resolved `null` argument may surprise a handler author
/// who expects "I asked for the value via a ResultReference, so it
/// must have been there". If a handler needs to distinguish
/// resolved-null from unsent, it has to read the raw `args` map
/// before calling this helper.
pub fn optional_arg<T>(
    args: &mut Map<String, Value>,
    name: &str,
    invalid_arguments_with: impl FnOnce() -> JmapError,
) -> Result<Option<T>, JmapError>
where
    T: serde::de::DeserializeOwned,
{
    match args.remove(name).unwrap_or(Value::Null) {
        Value::Null => Ok(None),
        v => Ok(Some(
            serde_json::from_value(v).map_err(|_| invalid_arguments_with())?,
        )),
    }
}

/// Remove and decode the optional `filter` argument of a hand-written
/// `/query` or `/queryChanges` handler (RFC 8620 §5.5).
///
/// Absent or `null` yields `None`. A value that is not a JSON object is
/// not a filter at all and yields `invalidArguments`. An object that does
/// not decode as `T` yields `unsupportedFilter` ("The "filter" is
/// syntactically valid, but the server cannot process it") with the serde
/// message as its description. With `deny_unknown_fields` on the filter
/// types, that covers an unknown or misspelt condition property at any
/// depth and an operator tree sent to an object whose filter is a bare
/// condition.
pub fn filter_arg<T>(args: &mut Map<String, Value>) -> Result<Option<T>, JmapError>
where
    T: serde::de::DeserializeOwned,
{
    match args.remove("filter").unwrap_or(Value::Null) {
        Value::Null => Ok(None),
        v @ Value::Object(_) => serde_json::from_value(v).map(Some).map_err(|e| {
            let mut err = JmapError::unsupported_filter();
            err.description = Some(format!("filter: {e}"));
            err
        }),
        v => Err(JmapError::invalid_arguments(format!(
            "filter: expected an object, got {}",
            json_type_name(&v)
        ))),
    }
}

/// Read an optional boolean argument from a method-arguments envelope without
/// removing it (bd:JMAP-ic0j.39).
///
/// Returns `default` if `key` is absent, if the value is not a boolean, or if
/// the value is `Value::Null`. This is the canonical workspace helper for
/// JMAP's "permissive parsing" convention on optional boolean controls
/// (RFC 8620 §3.6.1 — unknown / non-typed values coerce to the spec default).
///
/// Use [`take_bool_arg`] if the caller wants to consume the entry as part of
/// a "walk the args map removing as we go" pattern.
///
/// Collapses ~50 near-identical
/// `args.get(K).and_then(|v| v.as_bool()).unwrap_or(default)` blocks across
/// the extension-server family into single-line calls.
pub fn bool_arg(args: &Map<String, Value>, key: &str, default: bool) -> bool {
    args.get(key).and_then(|v| v.as_bool()).unwrap_or(default)
}

/// Read an optional boolean argument from a method-arguments envelope,
/// removing it from the map (bd:JMAP-ic0j.39).
///
/// Returns `default` if `key` is absent, if the value is not a boolean, or if
/// the value is `Value::Null`. Mirrors the semantics of [`bool_arg`] but
/// consumes the entry from `args`. Matches the canonical mail-server
/// "remove-as-we-go" parsing pattern.
pub fn take_bool_arg(args: &mut Map<String, Value>, key: &str, default: bool) -> bool {
    args.remove(key)
        .and_then(|v| v.as_bool())
        .unwrap_or(default)
}

/// Extract `accountId` from a JMAP method arguments envelope and return both
/// the extracted [`Id`] and the remaining argument map.
///
/// The caller passes the full `args: Value` from the method invocation by
/// value; this function destructures it once, so handlers do not have to
/// repeat the `let Value::Object(mut args) = args else { ... }` pattern after
/// every call.
///
/// # Errors
///
/// Returns `invalidArguments` with:
///
/// - `"arguments must be an object containing accountId"` when `args` is
///   not a JSON object.
/// - `"accountId is required"` when the field is missing or not a string.
/// - `"accountId is not a valid Id: <reason>"` when the field is a string
///   but does not satisfy the RFC 8620 §1.2 Id grammar
///   (`Id::new_validated`). Catches empty strings, strings longer than
///   255 bytes, and strings containing characters outside the SAFE-CHAR
///   set (`%x21 / %x23-7E` — visible ASCII excluding `"`).
///   bd:JMAP-wlip.5 closed the previous silent-pass-through behaviour
///   where a malformed accountId reached the backend's `account_exists`
///   call and surfaced as either `notFound` or a storage-layer parse
///   error, depending on the backend.
pub fn extract_account_id(args: Value) -> Result<(Id, Map<String, Value>), JmapError> {
    let Value::Object(mut args) = args else {
        return Err(JmapError::invalid_arguments(
            "arguments must be an object containing accountId",
        ));
    };
    // Remove (not get) the accountId entry so the returned args map no
    // longer carries it (bd:JMAP-jfia.9). This matches optional_arg's
    // remove-and-consume semantics and prevents downstream handlers
    // from re-parsing the validated id or seeing it as an unexpected
    // residual key.
    let raw = args
        .remove("accountId")
        .ok_or_else(|| JmapError::invalid_arguments("accountId is required"))?;
    let s = raw
        .as_str()
        .ok_or_else(|| JmapError::invalid_arguments("accountId is required"))?;
    let id = Id::new_validated(s)
        .map_err(|e| JmapError::invalid_arguments(format!("accountId is not a valid Id: {e}")))?;
    Ok((id, args))
}

/// Parse the optional `maxChanges` argument of `/changes` and
/// `/queryChanges`. RFC 8620 §5.2: "If supplied by the client, the value
/// MUST be a positive integer greater than 0. If a value outside of this
/// range is given, the server MUST reject the call with an
/// "invalidArguments" error." §5.6 gives no range of its own, so the same
/// rule applies to `/queryChanges`.
///
/// Pass the raw argument as taken from the args map (`args.get(..)` or
/// `args.remove(..).as_ref()`). Absent or `null` yields `Ok(None)`.
///
/// # Errors
///
/// Returns `invalidArguments` (`"maxChanges must be a positive integer"`)
/// for `0`, negative numbers, non-integers, and non-number values.
pub fn parse_max_changes(value: Option<&Value>) -> Result<Option<u64>, JmapError> {
    match value {
        None | Some(Value::Null) => Ok(None),
        Some(v) => {
            v.as_u64().filter(|&n| n > 0).map(Some).ok_or_else(|| {
                JmapError::invalid_arguments("maxChanges must be a positive integer")
            })
        }
    }
}

/// Return the current UTC instant as an [`UTCDate`] (RFC 3339,
/// millisecond precision, format `YYYY-MM-DDTHH:MM:SS.mmmZ`, or
/// `YYYY-MM-DDTHH:MM:SSZ` when the milliseconds are zero because
/// RFC 8620 §1.4 says the "time-secfrac" "MUST always be omitted if
/// zero"). For years `0000..=9999` the value passes
/// [`UTCDate::new_validated`].
///
/// Uses `std::time::SystemTime` so no external dependency is needed.
///
/// Returns a typed [`UTCDate`] rather than a `String` (bd:JMAP-wlip.20)
/// so callers do not need to wrap the result in
/// `UTCDate::from(now_utc_string().as_str())`. The function name is
/// retained for back-compat across the workspace's many call sites.
///
/// Pre-epoch handling: `SystemTime::now().duration_since(UNIX_EPOCH)`
/// fails on clocks drifted before the epoch. The function uses
/// `Err::duration()` to recover the magnitude and negates the seconds
/// before formatting; the result is a correct RFC 3339 timestamp
/// anywhere from the BCE proleptic Gregorian range up to
/// `1970-01-01T00:00:00Z`. The rem_euclid / div_euclid math at
/// the format step handles arbitrarily-large negative offsets, not
/// only sub-day drifts. Pre-epoch correctness is best-effort —
/// `SystemTime` is non-monotonic and the JMAP spec does not require
/// pre-epoch timestamps. (bd:JMAP-wlip.11 corrected the previous
/// docstring's incorrect "1969-12-31T… through 1970-01-01T00:00:00Z"
/// range claim.)
///
/// Clock-overflow handling: on a corrupted clock (system clock
/// reporting a Duration whose `as_secs()` exceeds `i64::MAX`,
/// `civil_from_days` reporting a year outside `i32`, or any other
/// `SystemTime` failure mode), this function **panics**. The
/// previous sentinel-string behaviour (`UTCDate::from("clock-out-of-range")`)
/// was an idiom-grade defect (bd:JMAP-jfia.30): the sentinel was not a
/// valid wire-format timestamp, had no in-band signal to distinguish
/// it from a real value, and could silently propagate into JSON
/// responses, audit logs, and database rows.
///
/// Callers that need to handle clock failure without panicking MUST
/// use [`now_utc_string_checked`], which returns `Option<UTCDate>`.
/// Long-running daemons, schedulers, and persistence layers SHOULD
/// prefer the checked variant; one-shot tools and request handlers
/// MAY accept the panic since clock corruption is unrecoverable and
/// the dispatcher's `task::spawn` isolation already converts the
/// panic into a `serverFail` invocation rather than crashing the
/// process.
///
/// # Panics
///
/// Panics if `SystemTime::now()` cannot be expressed as an RFC 3339
/// timestamp — the same conditions under which
/// [`now_utc_string_checked`] returns `None`.
pub fn now_utc_string() -> UTCDate {
    now_utc_string_checked().expect("system clock returned an out-of-range value (bd:JMAP-jfia.30)")
}

/// Return the current UTC instant as an [`UTCDate`] in the same
/// format as [`now_utc_string`], or `None` if the system clock cannot be expressed as an RFC 3339
/// timestamp.
///
/// Added in bd:JMAP-jfia.30 to replace the previous sentinel-string
/// failure mode of [`now_utc_string`] with a typed `Option` shape.
/// Callers that want to react to a clock fault (audit-log
/// timestamps, last-seen markers, retention sweeps) SHOULD use this
/// variant; callers for whom a panic at the first sign of clock
/// corruption is acceptable MAY use [`now_utc_string`] directly.
///
/// Returns `None` when:
/// - `SystemTime::now().duration_since(UNIX_EPOCH).as_secs()`
///   exceeds `i64::MAX` (only reachable on a corrupted clock —
///   approx ±292 billion years from epoch).
/// - The negation of a pre-epoch duration overflows `i64`
///   (unreachable on a `try_from`-validated input but checked
///   defensively).
/// - `civil_from_days` reports a year outside `i32`
///   (bd:JMAP-jfia.2 — between the i32-year boundary and the
///   i64::MAX-secs cap).
///
/// # Why `Option<UTCDate>` and not `Result<UTCDate, ClockError>` (bd:JMAP-jfia.38)
///
/// The three failure modes are all "corrupted clock" — each one is
/// physically unreachable on a sane host (years 5.7M-to-292B,
/// `try_from`-impossible negation, `i32`-overflowing year). A caller
/// that wants to branch on which physical mechanism fired would be
/// branching on states that don't happen. The shapes the workspace
/// uses elsewhere for typed-variant-per-mode (`SetError`,
/// `BackendChangesError`, `BackendSetError`, `MergePatchError`) all
/// carry failure modes that DO occur in normal operation —
/// `notFound`, `tooManyChanges`, `invalidPatch`, `depthExceeded`.
/// The clock-corruption modes are different in kind. Erasing the
/// discriminator here trades a hypothetical observability win for a
/// cleaner contract: "the clock is unusable for RFC 3339, abandon
/// timestamping." A future need for per-mode telemetry can be added
/// non-breakingly as a parallel helper (e.g. `now_utc_string_diagnose
/// -> Result<UTCDate, ClockError>`) without disturbing this shape.
pub fn now_utc_string_checked() -> Option<UTCDate> {
    use std::time::SystemTime;

    let (secs, millis) = signed_seconds_since_epoch(SystemTime::now())?;
    utc_date_from_epoch_millis(secs, millis)
}

/// Format `secs` seconds plus `millis` milliseconds since the Unix epoch
/// in the [`now_utc_string`] format, or `None` if the year does not fit
/// in `i32`.
fn utc_date_from_epoch_millis(secs: i64, millis: u32) -> Option<UTCDate> {
    let time_of_day = secs.rem_euclid(86400);
    let (h, m, s) = (
        time_of_day / 3600,
        time_of_day % 3600 / 60,
        time_of_day % 60,
    );
    let (year, month, day) = civil_from_days(secs.div_euclid(86400))?;

    // RFC 8620 §1.4: a zero time-secfrac MUST be omitted.
    let frac = if millis == 0 {
        String::new()
    } else {
        format!(".{millis:03}")
    };
    Some(UTCDate::from(format!(
        "{year:04}-{month:02}-{day:02}T{h:02}:{m:02}:{s:02}{frac}Z"
    )))
}

/// Convert a [`SystemTime`] into `(signed_seconds_since_epoch, millis)`,
/// returning `None` when the system clock cannot be expressed as an
/// `i64` second count.
///
/// Extracted from [`now_utc_string_checked`] in bd:JMAP-jfia.11 to
/// flatten the previous three-level nested match
/// (`duration_since` → `try_from` → `checked_neg`) into one
/// linear function the reader can scan top-to-bottom. The
/// `.checked_neg()` branch is unreachable on a `try_from`-validated
/// input (its output is `[0, i64::MAX]` so negation cannot underflow)
/// but is kept for defence in depth — the failure path stays total.
pub(crate) fn signed_seconds_since_epoch(now: std::time::SystemTime) -> Option<(i64, u32)> {
    use std::time::UNIX_EPOCH;
    match now.duration_since(UNIX_EPOCH) {
        Ok(d) => {
            let s = i64::try_from(d.as_secs()).ok()?;
            Some((s, d.subsec_millis()))
        }
        Err(e) => {
            // Pre-epoch clock: the instant is -d. Floor it to whole
            // milliseconds (as truncation does post-epoch), then split
            // it so `millis` counts forward from the floored second:
            // -1.2 s is (-2, 800), not (-1, 200) (bd:JMAP-yt1w.46).
            let d = e.duration();
            let s = i64::try_from(d.as_secs()).ok()?;
            match d.subsec_nanos() {
                0 => Some((s.checked_neg()?, 0)),
                nanos => Some((
                    s.checked_add(1)?.checked_neg()?,
                    (1_000_000_000 - nanos) / 1_000_000,
                )),
            }
        }
    }
}

/// Format `secs` seconds since the Unix epoch as a seconds-precision
/// [`UTCDate`] (`YYYY-MM-DDTHH:MM:SSZ`, RFC 8620 §1.4), or `None` if the
/// year falls outside `0000..=9999`, which that four-digit form cannot
/// express.
///
/// This is the inverse of [`UTCDate::to_epoch_seconds`], which truncates
/// the milliseconds that [`now_utc_string`] may add.
pub fn utc_date_from_epoch_seconds(secs: i64) -> Option<UTCDate> {
    let time_of_day = secs.rem_euclid(86400);
    let (h, m, s) = (
        time_of_day / 3600,
        time_of_day % 3600 / 60,
        time_of_day % 60,
    );
    let (year, month, day) = civil_from_days(secs.div_euclid(86400))?;
    if !(0..=9999).contains(&year) {
        return None;
    }
    Some(UTCDate::from(format!(
        "{year:04}-{month:02}-{day:02}T{h:02}:{m:02}:{s:02}Z"
    )))
}

/// Convert a count of days since the Unix epoch (1970-01-01) to a proleptic
/// Gregorian (year, month, day) triple, or `None` if the resulting year
/// does not fit in `i32`.
///
/// Algorithm by Howard Hinnant (public domain):
/// <https://howardhinnant.github.io/date_algorithms.html>
///
/// The year-narrowing cast is fallible because the algorithm's intermediate
/// `y` value is bounded by `i64::MAX / 146_097 ≈ ±6.3e13`, only a subset
/// of which fits in `i32` (~±2.1e9 years). For a sane `SystemTime`-derived
/// input we stay well inside `i32::MIN..=i32::MAX`, but the outer
/// `now_utc_string` only rejects `u64` seconds exceeding `i64::MAX`
/// (bd:JMAP-wlip.27 sentinel) — inputs between the i32-year boundary
/// (~5.7e6 years from epoch) and that sentinel reach this function and
/// previously panicked the dispatcher worker (bd:JMAP-jfia.2). Returning
/// `None` lets the caller fall through to its own sentinel rather than
/// taking down the task.
///
/// Month and day cannot fail: the algorithm's modular structure pins them
/// to `[1, 12]` and `[1, 31]` respectively, narrow casts handled with
/// `try_from(...).expect(...)` documenting the invariant.
fn civil_from_days(z: i64) -> Option<(i32, u8, u8)> {
    let z = z + 719_468;
    let era: i64 = if z >= 0 { z } else { z - 146_096 } / 146_097;
    let doe = z - era * 146_097; // [0, 146096]
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; // [0, 399]
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365]
    let mp = (5 * doy + 2) / 153; // [0, 11]
    let d = doy - (153 * mp + 2) / 5 + 1; // [1, 31]
    let mo = if mp < 10 { mp + 3 } else { mp - 9 }; // [1, 12]
    let yr = if mo <= 2 { y + 1 } else { y };
    Some((
        i32::try_from(yr).ok()?,
        u8::try_from(mo).expect("month bounded by algorithm to [1, 12]"),
        u8::try_from(d).expect("day bounded by algorithm to [1, 31]"),
    ))
}

/// Maximum recursion depth for [`json_merge_patch`] application.
///
/// Beyond this depth [`json_merge_patch`] returns
/// [`MergePatchError::DepthExceeded`] without applying any further levels.
/// Mitigates stack DoS from adversarial `PatchObject` values
/// (bd:JMAP-sc1b.97). 32 levels comfortably exceeds any legitimate JMAP
/// `/set update` shape — the deepest standard JMAP `/set update` shape
/// (Email with nested `bodyStructure`) tops out around 6 levels, so the
/// cap fires only on adversarial input.
///
/// Crate-private (bd:JMAP-wlip.4): consumers see the cap-exceeded
/// behaviour via [`MergePatchError::DepthExceeded`], not by reading the
/// constant directly. The crate reserves the right to tighten the
/// value (e.g. 32 → 16) without a major-version bump because the
/// contract is "the function may return DepthExceeded", not "the cap
/// is exactly N".
pub(crate) const MAX_MERGE_PATCH_DEPTH: usize = 32;

/// Error returned by [`json_merge_patch`] when a patch cannot be applied.
///
/// Marked `#[non_exhaustive]` so future RFC 7396 failure modes (e.g. a
/// size cap in addition to the depth cap) can be added without an API
/// break.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MergePatchError {
    /// The patch nests deeper than the crate's `MAX_MERGE_PATCH_DEPTH`
    /// DoS-guard cap.
    ///
    /// Callers SHOULD map this to
    /// [`SetError`](crate::SetError) with
    /// [`SetErrorType::InvalidPatch`](crate::SetErrorType::InvalidPatch)
    /// and MUST discard any partially-mutated `target` rather than
    /// persisting it — see the contract on [`json_merge_patch`].
    ///
    /// # Why no `reached` / `max` payload (bd:JMAP-jfia.39)
    ///
    /// The variant is intentionally unit-shaped. The cap value is
    /// available in the `Display` impl (which interpolates
    /// `MAX_MERGE_PATCH_DEPTH`) for log-line and user-message use.
    /// A typed payload `{ reached: usize, max: usize }` was
    /// considered and rejected for now because (a) no current
    /// consumer in the workspace destructures the reached depth or
    /// the cap programmatically — all 6 call sites map to
    /// `SetErrorType::InvalidPatch` with a generic description; and
    /// (b) changing a unit variant to a struct variant is a breaking
    /// pattern-match change even on a `#[non_exhaustive]` enum (the
    /// existing `if let Err(MergePatchError::DepthExceeded)` pattern
    /// would stop compiling). If a future consumer needs
    /// programmatic access to the depth, the additive evolution is
    /// to add a new variant alongside (e.g.
    /// `DepthExceededDetail { reached: usize, max: usize }`) and
    /// emit the new variant from `json_merge_patch`. The unit
    /// variant would then become unreachable but remain valid
    /// pattern syntax for any pinned-version consumer.
    DepthExceeded,
}

impl std::fmt::Display for MergePatchError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::DepthExceeded => write!(
                f,
                "merge patch nesting exceeds {MAX_MERGE_PATCH_DEPTH} levels"
            ),
        }
    }
}

impl std::error::Error for MergePatchError {}

/// Apply a JSON Merge Patch (RFC 7396) to `target` in-place.
///
/// Used by every `*-server` backend's `update_object` implementation
/// to merge a sparse `/set update` patch into the stored serialized
/// object. Extracted from per-crate copies in bd:JMAP-sc1b.103 — keep
/// edits here so all five reference backends stay byte-identical.
///
/// # Errors
///
/// Returns [`MergePatchError::DepthExceeded`] when the patch nests
/// deeper than the crate's internal `MAX_MERGE_PATCH_DEPTH` DoS-guard
/// cap (added in bd:JMAP-sc1b.97, made non-silent in bd:JMAP-wlip.1).
/// The exact value is intentionally not exposed; consumers see the
/// behaviour via the typed error rather than reading the constant.
/// Below the cap the behaviour is exactly RFC 7396 and the call always
/// returns `Ok(())`.
///
/// # Partial-mutation contract
///
/// On `Err(DepthExceeded)`, `target` may have been mutated up to the
/// level where the cap fired — RFC 7396 merging is applied recursively
/// in place and the function does not roll back on error. Callers MUST
/// discard `target` rather than persist it. The standard pattern in
/// every `*-server` `update_object` impl is to operate on a `.clone()`
/// of the stored value and only `insert(...)` it back on `Ok(())`; that
/// pattern is naturally safe because the stored value is left untouched
/// on error.
pub fn json_merge_patch(target: &mut Value, patch: Value) -> Result<(), MergePatchError> {
    json_merge_patch_inner(target, patch, 0)
}

fn json_merge_patch_inner(
    target: &mut Value,
    patch: Value,
    depth: usize,
) -> Result<(), MergePatchError> {
    if depth > MAX_MERGE_PATCH_DEPTH {
        return Err(MergePatchError::DepthExceeded);
    }
    match patch {
        Value::Object(patch_map) => {
            // Per RFC 7396 §2: "If the target value is not a JSON object,
            // the resulting value will be the merge patch." We therefore
            // reset a non-Object target to an empty Object before merging
            // — this is reachable when a Patch creates a nested field that
            // is absent from the target (the parent recursion frame inserted
            // Value::Null as a placeholder).
            if !target.is_object() {
                *target = Value::Object(Map::new());
            }
            let target_map = target
                .as_object_mut()
                .expect("target was just set to Value::Object above");
            for (key, patch_val) in patch_map {
                if patch_val.is_null() {
                    target_map.remove(&key);
                } else {
                    let entry = target_map.entry(key).or_insert(Value::Null);
                    json_merge_patch_inner(entry, patch_val, depth + 1)?;
                }
            }
        }
        other => *target = other,
    }
    Ok(())
}

/// Error returned by [`apply_jmap_patch`] and [`apply_patch_object`] when
/// a PatchObject cannot be applied.
///
/// Every variant is an RFC 8620 §5.3 violation for which "the update
/// MUST be rejected with an "invalidPatch" error". Callers SHOULD map
/// any variant to [`SetError`](crate::SetError) with
/// [`SetErrorType::InvalidPatch`](crate::SetErrorType::InvalidPatch);
/// the `Display` form is suitable as its description.
///
/// Marked `#[non_exhaustive]` so further §5.3 checks can be added
/// without an API break.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PatchPathError {
    /// A part before the last does not exist on the patched object.
    ParentMissing,
    /// A part before the last names an array, so the pointer would
    /// reference inside an array.
    InsideArray,
    /// A part before the last names a value that is neither an object nor
    /// an array (string, number, boolean or null), which has no members.
    ParentNotObject,
    /// A `~` in the path is not followed by `0` or `1`, so the path is
    /// not a valid RFC 6901 JSON Pointer.
    InvalidEscape,
    /// The pointer of one patch is a prefix of the pointer of another in
    /// the same PatchObject (e.g. `"alerts/1/offset"` and `"alerts"`).
    PrefixConflict,
    /// The path's segment count plus the value's object/array nesting
    /// exceeds the crate's `MAX_MERGE_PATCH_DEPTH` DoS-guard cap.
    ///
    /// Not an RFC 8620 §5.3 rule: it is this crate's server limit
    /// (RFC 8620 §3.6.1 lets a server reject requests that exceed its
    /// limits), so repeated path patches cannot grow a stored value's
    /// depth without bound. It is still reported as invalidPatch.
    DepthExceeded,
    /// A part before the last is a Binary value inside a `metadata` or
    /// `privateMetadata` namespace value: draft-ietf-jmap-metadata-05
    /// §3.2, "a path that traverses an array or a Binary value (Section
    /// 2.1.1) is rejected with an "invalidPatch" SetError".
    InsideBinary,
}

impl std::fmt::Display for PatchPathError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::ParentMissing => f.write_str("patch path parent does not exist"),
            Self::InsideArray => f.write_str("patch path references inside an array"),
            Self::ParentNotObject => f.write_str("patch path parent is not an object"),
            Self::InvalidEscape => f.write_str("patch path has a '~' not followed by '0' or '1'"),
            Self::PrefixConflict => {
                f.write_str("patch has a path that is a prefix of another path")
            }
            Self::DepthExceeded => {
                write!(f, "patch nesting exceeds {MAX_MERGE_PATCH_DEPTH} levels")
            }
            Self::InsideBinary => {
                f.write_str("patch path references inside a metadata Binary value")
            }
        }
    }
}

impl std::error::Error for PatchPathError {}

/// Apply one RFC 8620 §5.3 PatchObject entry (`path` → `value`) to
/// `target` in-place.
///
/// `path` is a PatchObject key: an RFC 6901 JSON Pointer with the
/// implicit leading `/` omitted (e.g. `"mailboxIds/abc123"`). Each
/// `/`-separated reference token is decoded per RFC 6901 §4 (`~1` → `/`,
/// then `~0` → `~`). Every token before the last must name an existing
/// object member; the last token names the member to set. A `null`
/// `value` removes that member (a no-op when it is absent); any other
/// value inserts or replaces it.
///
/// Extracted from per-crate copies in bd:JMAP-j6ab. Extension servers
/// MUST call this rather than reimplement it.
///
/// Empty tokens are legal: RFC 6901 §3 allows a zero-length
/// `reference-token`, and its §5 example evaluates `"/"` to the member
/// named `""`. The RFC 8620 §5.3 "null sets the property default" rule
/// is type-specific and left to the caller. The rule that no two pointers
/// in one PatchObject may be prefixes of each other is checked by
/// [`apply_patch_object`].
///
/// # Errors
///
/// Returns [`PatchPathError`] when a part before the last does not exist
/// ([`ParentMissing`](PatchPathError::ParentMissing)), is an array
/// ([`InsideArray`](PatchPathError::InsideArray)) or is another
/// non-object value ([`ParentNotObject`](PatchPathError::ParentNotObject))
/// or is a Binary value below a `metadata/<namespace>` or
/// `privateMetadata/<namespace>` prefix
/// ([`InsideBinary`](PatchPathError::InsideBinary); an object with
/// `"@type": "Binary"`, draft-ietf-jmap-metadata-05 §2.1.1),
/// when `path` contains an invalid escape
/// ([`InvalidEscape`](PatchPathError::InvalidEscape)), or when the
/// number of `/`-separated segments in `path` plus the object/array
/// nesting of `value` (a scalar nests 0 levels) exceeds the crate's
/// `MAX_MERGE_PATCH_DEPTH` DoS-guard cap
/// ([`DepthExceeded`](PatchPathError::DepthExceeded)).
///
/// # Mutation contract
///
/// A single call is all-or-nothing: on `Err`, `target` is unchanged.
/// A PatchObject has several entries, and an error on a later entry
/// does not undo earlier ones, so callers applying a whole PatchObject
/// MUST use [`apply_patch_object`].
pub fn apply_jmap_patch(
    target: &mut Map<String, Value>,
    path: &str,
    value: Value,
) -> Result<(), PatchPathError> {
    let segments = path.split('/').count();
    if segments > MAX_MERGE_PATCH_DEPTH
        || nests_deeper_than(&value, MAX_MERGE_PATCH_DEPTH - segments)
    {
        return Err(PatchPathError::DepthExceeded);
    }
    let (parents, leaf) = match path.rsplit_once('/') {
        Some((parents, leaf)) => (Some(parents), leaf),
        None => (None, path),
    };
    let leaf = decode_pointer_token(leaf)?;
    let in_metadata = matches!(path.split('/').next(), Some("metadata" | "privateMetadata"));
    let mut parent = target;
    for (i, token) in parents.into_iter().flat_map(|p| p.split('/')).enumerate() {
        parent = match parent.get_mut(decode_pointer_token(token)?.as_ref()) {
            // Token 0 is the property and token 1 the namespace; a Binary
            // is an object within the namespace value.
            Some(Value::Object(map))
                if in_metadata
                    && i >= 2
                    && map.get("@type").and_then(Value::as_str) == Some("Binary") =>
            {
                return Err(PatchPathError::InsideBinary);
            }
            Some(Value::Object(map)) => map,
            Some(Value::Array(_)) => return Err(PatchPathError::InsideArray),
            Some(_) => return Err(PatchPathError::ParentNotObject),
            None => return Err(PatchPathError::ParentMissing),
        };
    }
    if value.is_null() {
        parent.remove(leaf.as_ref());
    } else {
        parent.insert(leaf.into_owned(), value);
    }
    Ok(())
}

/// Check the RFC 8620 §5.3 PatchObject errors that `patch` alone
/// determines, without the object it applies to.
///
/// A server whose spec orders these before other checks calls this
/// first; draft-ietf-jmap-metadata-05 §3.2 says "Patch errors that can
/// be determined from the request alone (for example, two paths where
/// one is a prefix of the other) MUST be reported with "invalidPatch"
/// before rule 1 is evaluated". [`apply_patch_object`] runs the same
/// check, so calling both is redundant but harmless.
///
/// # Errors
///
/// Returns [`PatchPathError::InvalidEscape`] for a key with a `~` not
/// followed by `0` or `1`, [`PatchPathError::DepthExceeded`] for an
/// entry over the `MAX_MERGE_PATCH_DEPTH` cap, and
/// [`PatchPathError::PrefixConflict`] when the decoded pointer of one key
/// is a whole-segment prefix of another (`"alerts"` and
/// `"alerts/1/offset"` conflict; `"alert"` and `"alerts/x"` do not).
pub fn check_patch_paths(patch: &Map<String, Value>) -> Result<(), PatchPathError> {
    let mut pointers = patch
        .iter()
        .map(|(k, v)| {
            let segments = k
                .split('/')
                .map(decode_pointer_token)
                .collect::<Result<Vec<_>, _>>()?;
            if segments.len() > MAX_MERGE_PATCH_DEPTH
                || nests_deeper_than(v, MAX_MERGE_PATCH_DEPTH - segments.len())
            {
                return Err(PatchPathError::DepthExceeded);
            }
            Ok(segments)
        })
        .collect::<Result<Vec<_>, _>>()?;
    // Sorted, a pointer that prefixes any other also prefixes its successor.
    pointers.sort_unstable();
    if pointers.windows(2).any(|w| w[1].starts_with(&w[0])) {
        return Err(PatchPathError::PrefixConflict);
    }
    Ok(())
}

/// Apply a whole RFC 8620 §5.3 PatchObject to `target`.
///
/// Each entry is applied with [`apply_jmap_patch`]. The value at each
/// pointer is set as given: a top-level key such as `"name"` replaces that
/// property wholesale, with no nested merge of object values (RFC 8620
/// §5.3: "The value to set for this property").
///
/// # Errors
///
/// Returns any error [`check_patch_paths`] returns for `patch`, and
/// otherwise any error [`apply_jmap_patch`] returns for an entry.
///
/// # Mutation contract
///
/// All-or-nothing: on `Err`, `target` is unchanged.
pub fn apply_patch_object(
    target: &mut Map<String, Value>,
    patch: &Map<String, Value>,
) -> Result<(), PatchPathError> {
    check_patch_paths(patch)?;
    let mut patched = target.clone();
    for (path, value) in patch {
        apply_jmap_patch(&mut patched, path, value.clone())?;
    }
    *target = patched;
    Ok(())
}

/// Whether `value` nests objects or arrays more than `limit` levels deep
/// (a scalar nests 0 levels). Recursion is bounded by `limit`, not by the
/// input.
fn nests_deeper_than(value: &Value, limit: usize) -> bool {
    match value {
        Value::Object(map) => limit == 0 || map.values().any(|v| nests_deeper_than(v, limit - 1)),
        Value::Array(items) => limit == 0 || items.iter().any(|v| nests_deeper_than(v, limit - 1)),
        _ => false,
    }
}

/// Decode one RFC 6901 reference token: `~1` → `/`, then `~0` → `~`
/// (RFC 6901 §4 order, so `~01` becomes `~1`, not `/`).
fn decode_pointer_token(token: &str) -> Result<Cow<'_, str>, PatchPathError> {
    if !token.contains('~') {
        return Ok(Cow::Borrowed(token));
    }
    let escapes_valid = token
        .match_indices('~')
        .all(|(i, _)| matches!(token.as_bytes().get(i + 1), Some(b'0' | b'1')));
    if !escapes_valid {
        return Err(PatchPathError::InvalidEscape);
    }
    Ok(Cow::Owned(token.replace("~1", "/").replace("~0", "~")))
}

/// Resolve a request-side `position` argument (RFC 8620 §5.5) into a
/// 0-based start index suitable for slicing the full ordered result
/// list (bd:JMAP-qz9v.48).
///
/// `position` is the signed offset from the `/query` request. The
/// foundation handler at [`handle_query`](crate::handle_query) parses it
/// via [`serde_json::Value::as_i64`], so the value reaching the
/// backend is any `i64` (including `i64::MIN`). Non-negative values
/// are absolute offsets from the start of the result list; negative
/// values are end-relative offsets per RFC 8620 §5.5 ("`-1` represents
/// the last entry, `-2` the second to last, and so on").
///
/// Returns a `usize` clamped to `[0, total]`. The clamp at the high
/// end matches the slice-safety property: `all_ids[start..]` is
/// guaranteed not to panic regardless of the input `position`.
///
/// # Edge cases this helper exists to centralize
///
/// 1. `position == 0` → `0`.
/// 2. `position > total` → `total` (yields an empty page, matching
///    the RFC's silent-clamp semantics — `/query` does not error on
///    out-of-range positions).
/// 3. `position == i64::MIN` → handled via [`i64::saturating_neg`],
///    which returns `i64::MAX` rather than overflowing. The resulting
///    `usize::MAX`-magnitude offset is then absorbed by
///    [`usize::saturating_sub`].
/// 4. `position` exceeding `usize::MAX` on a 32-bit target (`i64`
///    values above `2^32 - 1`) → clamped to `total` rather than
///    truncated. The previous workspace idiom (`position as usize`)
///    silently wrapped the high bits on 32-bit, returning a small
///    `start` index that did not match the caller's intent.
///
/// # Why this lives in the foundation
///
/// The pattern is identical across every extension server's `/query`
/// backend impl. Centralizing it eliminates the per-crate
/// `(position as usize)` / `(position.saturating_neg() as usize)`
/// idiom that clippy::pedantic flags as `cast_possible_truncation` +
/// `cast_sign_loss`, and prevents future siblings from re-introducing
/// the strictly-worse `(-position) as usize` variant (which panics on
/// `i64::MIN` in debug builds and wraps in release).
///
/// # Example
///
/// ```
/// use jmap_server::resolve_query_offset;
///
/// // Absolute offset.
/// assert_eq!(resolve_query_offset(0, 100), 0);
/// assert_eq!(resolve_query_offset(25, 100), 25);
///
/// // End-relative offset.
/// assert_eq!(resolve_query_offset(-1, 100), 99);
/// assert_eq!(resolve_query_offset(-100, 100), 0);
///
/// // Out-of-range clamps to total.
/// assert_eq!(resolve_query_offset(1_000, 100), 100);
/// assert_eq!(resolve_query_offset(-1_000, 100), 0);
///
/// // i64::MIN does not overflow.
/// assert_eq!(resolve_query_offset(i64::MIN, 100), 0);
/// ```
#[must_use]
pub fn resolve_query_offset(position: i64, total: usize) -> usize {
    if position >= 0 {
        // `i64 >= 0` → fits in `u64`. `usize::try_from` returns the
        // value on 64-bit targets and `Err` on 32-bit targets only
        // when the magnitude exceeds `usize::MAX`; saturating to
        // `usize::MAX` is then clamped to `total` by `.min`.
        usize::try_from(position).unwrap_or(usize::MAX).min(total)
    } else {
        // `saturating_neg` maps `i64::MIN` to `i64::MAX` instead of
        // overflowing. Every other negative `i64` negates exactly.
        let neg = usize::try_from(position.saturating_neg()).unwrap_or(usize::MAX);
        total.saturating_sub(neg)
    }
}

/// Convert an RFC 8620 `limit` / `maxChanges` argument (`UnsignedInt|null`)
/// to a `usize` item count for [`Iterator::take`] (bd:JMAP-pgj7).
///
/// RFC 8620 §5.5: "The maximum number of results to return. If null, no
/// limit presumed." `None` therefore maps to `usize::MAX`. A `Some(n)`
/// larger than `usize::MAX` (only possible on 32-bit targets) saturates
/// to `usize::MAX` instead of truncating, which is the same "take
/// everything" outcome, since no in-memory list can exceed `usize::MAX`.
///
/// This replaces the per-crate `n as usize` idiom, which silently drops
/// the high bits on 32-bit targets (a `limit` of `2^32` became `0`).
///
/// # Example
///
/// ```
/// use jmap_server::limit_or_max;
///
/// assert_eq!(limit_or_max(None), usize::MAX);
/// assert_eq!(limit_or_max(Some(0)), 0);
/// assert_eq!(limit_or_max(Some(25)), 25);
/// ```
#[must_use]
pub fn limit_or_max(limit: Option<u64>) -> usize {
    limit.map_or(usize::MAX, |n| usize::try_from(n).unwrap_or(usize::MAX))
}

/// Parse the RFC 8620 §5.5 `/query` arguments `anchor` (`Id|null`) and
/// `anchorOffset` (`Int`, default `0`) from `args`.
///
/// # Errors
///
/// `invalidArguments` when `anchor` is neither a string nor `null`, is a
/// string that is not an RFC 8620 §1.2 Id, or `anchorOffset` is neither an
/// integer nor `null`.
pub fn query_anchor_args(args: &Map<String, Value>) -> Result<(Option<Id>, i64), JmapError> {
    let anchor = match args.get("anchor") {
        None | Some(Value::Null) => None,
        Some(Value::String(s)) => Some(
            Id::new_validated(s.as_str())
                .map_err(|e| JmapError::invalid_arguments(format!("anchor: {e}")))?,
        ),
        Some(v) => {
            return Err(JmapError::invalid_arguments(format!(
                "anchor: expected an Id string or null, got {}",
                json_type_name(v)
            )));
        }
    };
    let anchor_offset = match args.get("anchorOffset") {
        None | Some(Value::Null) => 0,
        Some(v) => v.as_i64().ok_or_else(|| {
            JmapError::invalid_arguments(format!(
                "anchorOffset: expected an integer, got {}",
                json_type_name(v)
            ))
        })?,
    };
    Ok((anchor, anchor_offset))
}

/// Start index of a `/query` page within the filtered, sorted `ids`
/// (RFC 8620 §5.5), for [`JmapBackend::query_objects`] implementations.
///
/// With an `anchor`, `position` is ignored and the start is the
/// anchor's index plus `anchor_offset`, clamped to `0..=ids.len()`.
/// Without one, `anchor_offset` is ignored and the start is
/// [`resolve_query_offset`]`(position, ids.len())`.
///
/// # Errors
///
/// [`JmapError::anchor_not_found`] when `anchor` is not in `ids`.
///
/// [`JmapBackend::query_objects`]: crate::JmapBackend::query_objects
pub fn resolve_query_start(
    ids: &[Id],
    position: i64,
    anchor: Option<&Id>,
    anchor_offset: i64,
) -> Result<usize, JmapError> {
    let Some(anchor) = anchor else {
        return Ok(resolve_query_offset(position, ids.len()));
    };
    let index = ids
        .iter()
        .position(|id| id == anchor)
        .ok_or_else(JmapError::anchor_not_found)?;
    let start = i64::try_from(index)
        .unwrap_or(i64::MAX)
        .saturating_add(anchor_offset)
        .max(0);
    Ok(resolve_query_offset(start, ids.len()))
}

/// Enforce RFC 8620 §5.3 `maxObjectsInSet` cap at the top of a `/set`
/// handler (bd:JMAP-ayoz.41.1).
///
/// Counts entries in the wire `create` (object), `update` (object), and
/// `destroy` (array) arguments. Returns the method-level error
/// [`JmapError::request_too_large`] (wire `type: "requestTooLarge"`,
/// `description: "maxObjectsInSet"`) when the sum exceeds `max`. Per
/// RFC 8620 §5.3 it is returned instead of the `Foo/set` response, so
/// the dispatcher emits an `error` invocation and later method calls
/// in the same request still run (bd:JMAP-yt1w.30).
///
/// Call at the top of every `handle_*_set` after the `account_exists`
/// gate and before any per-entry processing. A request carrying
/// megabytes of `/set` ops is rejected before the handler touches the
/// storage layer:
///
/// ```ignore
/// let (account_id, args) = extract_account_id(args)?;
/// if !backend.account_exists(caller, &account_id).await
///     .map_err(|e| server_fail_from_backend(&e))?
/// {
///     return Err(JmapError::account_not_found());
/// }
/// jmap_server::helpers::enforce_max_objects_in_set(
///     &args,
///     backend.max_objects_in_set(caller, &account_id),
/// )?;
/// ```
///
/// # Why this lives in the foundation
///
/// `maxObjectsInSet` is a RFC 8620 §5.3 base-protocol cap, not an
/// extension concept. Every `jmap-*-server` extension's `handle_*_set`
/// needs the same check; the helper is the single source of truth so a
/// future revision (different error shape, additional counting rule,
/// alternate semantics for non-object `create` / `update`) lands in one
/// place instead of being propagated through 28 handler sites.
///
/// # Counting rules
///
/// - `create` is counted as `args["create"].as_object()?.len()` —
///   missing key, `null`, or non-object types count as 0.
/// - `update` is counted the same way (RFC 8620 §5.3 `update` is
///   `Id[PatchObject]`).
/// - `destroy` is counted as `args["destroy"].as_array()?.len()` —
///   missing key, `null`, or non-array types count as 0.
///
/// Wire-shape validation of the individual `create` / `update` /
/// `destroy` arguments belongs to the per-handler argument parsing,
/// not to this cap-enforcement helper. A non-object `create` survives
/// the cap check (counts as 0) and is rejected by the handler's
/// downstream `args.remove("create")` match arm. Conversely, a
/// well-formed but over-limit `create` is rejected here before the
/// handler runs.
///
/// # Errors
///
/// Returns `JmapError::request_too_large()` with description
/// `"maxObjectsInSet"` when the sum exceeds `max` (RFC 8620 §5.3).
pub fn enforce_max_objects_in_set(args: &Map<String, Value>, max: u64) -> Result<(), JmapError> {
    let create_count = args
        .get("create")
        .and_then(|v| v.as_object())
        .map_or(0u64, |m| m.len() as u64);
    let update_count = args
        .get("update")
        .and_then(|v| v.as_object())
        .map_or(0u64, |m| m.len() as u64);
    let destroy_count = args
        .get("destroy")
        .and_then(|v| v.as_array())
        .map_or(0u64, |a| a.len() as u64);
    // u64 saturation: each count is bounded by serde_json's body parse
    // (Map::len / Vec::len are usize; on 64-bit targets usize == u64,
    // on 32-bit targets usize < u64). The sum cannot exceed
    // 3 * u32::MAX even on 32-bit hosts, well within u64 range.
    let count = create_count
        .saturating_add(update_count)
        .saturating_add(destroy_count);
    if count > max {
        let mut err = JmapError::request_too_large();
        err.description = Some("maxObjectsInSet".into());
        return Err(err);
    }
    Ok(())
}

/// Enforce RFC 8620 §5.1 `maxObjectsInGet` at the top of a `/get`
/// handler (bd:JMAP-yt1w.31).
///
/// Counts the entries in the wire `ids` argument. Returns the
/// method-level error [`JmapError::request_too_large`] (wire
/// `type: "requestTooLarge"`, `description: "maxObjectsInGet"`) when the
/// count exceeds `max`. Per RFC 8620 §5.1 it is returned instead of the
/// `Foo/get` response.
///
/// Call after the `account_exists` gate and before parsing `ids`:
///
/// ```ignore
/// jmap_server::helpers::enforce_max_objects_in_get(
///     &args,
///     backend.max_objects_in_get(caller, &account_id),
/// )?;
/// ```
///
/// # Counting rules
///
/// `ids` is counted as `args["ids"].as_array()?.len()`. A missing key,
/// `null` (fetch all), or a non-array value counts as 0: RFC 8620 §5.1
/// bounds "the number of ids requested by the client", and a null `ids`
/// requests none. Bounding a fetch-all by the number of records is the
/// backend's job, since only it knows how many records exist. Wire-shape
/// validation of `ids` belongs to the handler's argument parsing.
///
/// # Errors
///
/// Returns `JmapError::request_too_large()` with description
/// `"maxObjectsInGet"` when the count exceeds `max` (RFC 8620 §5.1).
pub fn enforce_max_objects_in_get(args: &Map<String, Value>, max: u64) -> Result<(), JmapError> {
    let count = args
        .get("ids")
        .and_then(|v| v.as_array())
        .map_or(0u64, |a| a.len() as u64);
    if count > max {
        let mut err = JmapError::request_too_large();
        err.description = Some("maxObjectsInGet".into());
        return Err(err);
    }
    Ok(())
}

/// Reject a `/set` create object that carries a DID-bearing property, or
/// an update PatchObject that changes one (draft-atwood-jmap-did-00
/// §The `did` Property).
///
/// `entry` is one value from the `create` or `update` argument and
/// `did_properties` names the data type's DID-bearing properties, which the
/// consuming specification defines. `current` is `None` for a create and
/// the stored object for an update.
///
/// "Clients omit DID-bearing properties when creating objects, as
/// {{RFC8620}} Section 1.1 requires for server-set properties; an update
/// can include one only with its current value ({{RFC8620}} Section 5.3).
/// Servers MUST reject a create that includes a DID-bearing property, or an
/// update that changes one, with a SetError of type `invalidProperties`"
/// (draft-atwood-jmap-did-00 L247). So a create that names the property is
/// rejected whatever the value, even `null`. An update key equal to the
/// property name passes when its value equals the stored value, where an
/// absent stored property counts as `null`, the value's other type. A
/// PatchObject key is a path, and a key whose first segment is the property
/// name but has further segments always changes it, so it is rejected.
/// Keeping the value unchanged on the server side, including across a DID
/// migration, is the backend's job.
///
/// Returns `None` when `entry` is acceptable. Otherwise returns an
/// `invalidProperties` [`SetError`] whose `properties` lists every rejected
/// DID-bearing property, in `did_properties` order.
#[must_use]
pub fn reject_did_bearing_properties(
    entry: &Map<String, Value>,
    did_properties: &[&str],
    current: Option<&Map<String, Value>>,
) -> Option<SetError> {
    // ponytail: compares the raw first segment, without RFC 6901 `~0`/`~1`
    // decoding. That is exact for property names with no `~` or `/`, which
    // covers every DID-bearing name in the drafts.
    let rejected: Vec<&str> = did_properties
        .iter()
        .copied()
        .filter(|prop| {
            entry.iter().any(|(k, v)| {
                k.split('/').next() == Some(*prop)
                    && !(k == prop
                        && current
                            .is_some_and(|stored| stored.get(*prop).unwrap_or(&Value::Null) == v))
            })
        })
        .collect();
    (!rejected.is_empty())
        .then(|| SetError::new(SetErrorType::InvalidProperties).with_properties(rejected))
}

/// Reject a `/set` create that carries a server-set property of `O`.
///
/// RFC 8620 §1.1: for a "server-set" property, "The client MUST NOT send
/// this property when creating a new object of this type."; RFC 8620 §5.3
/// makes such a record `invalidProperties`.
///
/// A `null` value asserts nothing and is treated as absent.
///
/// Returns `None` when `create` carries none of [`SetObject::SERVER_SET`]
/// with a non-null value. Otherwise returns an `invalidProperties`
/// [`SetError`] whose `properties` lists each one carried, in `SERVER_SET`
/// order.
#[must_use]
pub fn reject_server_set<O: SetObject>(create: &Map<String, Value>) -> Option<SetError> {
    let rejected: Vec<&str> = O::SERVER_SET
        .iter()
        .copied()
        .filter(|prop| create.get(*prop).is_some_and(|v| !v.is_null()))
        .collect();
    (!rejected.is_empty())
        .then(|| SetError::new(SetErrorType::InvalidProperties).with_properties(rejected))
}

/// Reject a `/set` update patch that names a server-set or immutable
/// property of `O`.
///
/// A patch key names a property when it equals the property name or starts
/// with `"<name>/"`, a JSON Pointer inside it (RFC 8620 §5.3). Changing a
/// [`SetObject::SERVER_SET`] property is `invalidProperties` (RFC 8620
/// §5.3), and a [`SetObject::IMMUTABLE`] value "MUST NOT change after the
/// object is created" (RFC 8620 §1.1).
///
/// `current` is the stored object, when the handler has it. RFC 8620 §5.3:
/// "Any server-set properties MAY be included in the patch if their value is
/// identical to the current server value", so a key that names the whole
/// property with its stored value passes. A key with further segments always
/// changes the property and is rejected.
///
/// Returns `None` when the patch names none. Otherwise returns an
/// `invalidProperties` [`SetError`] whose `properties` lists each property
/// named, `SERVER_SET` first, then `IMMUTABLE`, each in list order.
///
/// ponytail: compares the raw first segment, without RFC 6901 `~0`/`~1`
/// decoding, which is exact for property names with no `~` or `/`. With
/// `current` `None` an unchanged value is rejected too; a handler that can
/// fetch the stored object passes it.
#[must_use]
pub fn reject_read_only_patch<O: SetObject>(
    patch: &Map<String, Value>,
    current: Option<&Map<String, Value>>,
) -> Option<SetError> {
    let rejected: Vec<&str> = O::SERVER_SET
        .iter()
        .chain(O::IMMUTABLE)
        .copied()
        .filter(|prop| {
            patch.iter().any(|(k, v)| {
                k.split('/').next() == Some(*prop)
                    && !(k == prop
                        && current
                            .is_some_and(|stored| stored.get(*prop).unwrap_or(&Value::Null) == v))
            })
        })
        .collect();
    (!rejected.is_empty())
        .then(|| SetError::new(SetErrorType::InvalidProperties).with_properties(rejected))
}

/// Whether patch key `key` names a [`SetObject::SERVER_SET`] or
/// [`SetObject::IMMUTABLE`] property of `O`: its first JSON Pointer segment
/// is the property name (RFC 8620 §5.3).
fn names_read_only<O: SetObject>(key: &str) -> bool {
    let prop = key.split('/').next().unwrap_or(key);
    O::SERVER_SET.contains(&prop) || O::IMMUTABLE.contains(&prop)
}

/// Reject a `/set` update `patch` that changes a server-set or immutable
/// property of `O`, then drop the keys that repeat the stored value.
///
/// Runs [`reject_read_only_patch`] with `current`, the stored object. When
/// that passes, every key naming such a property holds its stored value
/// (RFC 8620 §5.3) and is removed, leaving only the client changes. An
/// empty result is a no-op update.
///
/// # Errors
///
/// The `invalidProperties` [`SetError`] from [`reject_read_only_patch`].
pub fn strip_read_only_patch<O: SetObject>(
    patch: &mut Map<String, Value>,
    current: Option<&Map<String, Value>>,
) -> Result<(), Box<SetError>> {
    if let Some(err) = reject_read_only_patch::<O>(patch, current) {
        return Err(Box::new(err));
    }
    patch.retain(|k, _| !names_read_only::<O>(k));
    Ok(())
}

/// Check a `/set` update `patch` of the stored object `id` against the
/// server-set and immutable properties of `O`, and report a no-op.
///
/// RFC 8620 §5.3: "Any server-set properties MAY be included in the patch
/// if their value is identical to the current server value (before
/// applying the patches to the object).  Otherwise, the update MUST be
/// rejected with an "invalidProperties" SetError." The stored object is
/// fetched only when the patch names such a property or is empty; then
/// [`strip_read_only_patch`] rejects a changed value and drops the
/// identical ones, leaving only the client changes for the handler's own
/// checks.
///
/// Returns `Ok(true)` when nothing is left to apply, for a literal `{}` or
/// a patch of identical server-set values: the update succeeds as a no-op,
/// with no write, `updated` mapping `id` to `null`, and the state unchanged.
/// A missing object leaves nothing to compare, so a read-only key is
/// rejected as `invalidProperties`, and an empty patch is `notFound`.
///
/// # Errors
///
/// The `notUpdated` value: `notFound` for an empty patch of a missing
/// object, the `invalidProperties` SetError, or `serverFail` when the fetch
/// fails.
pub async fn check_read_only_patch<B, O>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    id: &Id,
    patch: &mut Map<String, Value>,
) -> Result<bool, Value>
where
    B: JmapBackend,
    O: GetObject + SetObject + serde::Serialize + Send + Sync,
{
    if !patch.is_empty() && !patch.keys().any(|k| names_read_only::<O>(k)) {
        return Ok(false);
    }
    let (found, _) = backend
        .get_objects::<O>(caller, account_id, Some(std::slice::from_ref(id)), None)
        .await
        .map_err(|e| server_fail_value_from_backend(&e))?;
    let current = match found.first().map(serde_json::to_value).transpose() {
        Ok(Some(Value::Object(m))) => Some(m),
        Ok(Some(_)) => {
            return Err(server_fail_value_from_backend(
                "stored object is not a JSON object",
            ));
        }
        Ok(None) => None,
        Err(e) => return Err(server_fail_value_from_backend(&e)),
    };
    if patch.is_empty() {
        return current
            .map(|_| true)
            .ok_or_else(|| Value::from(&SetError::new(SetErrorType::NotFound)));
    }
    strip_read_only_patch::<O>(patch, current.as_ref()).map_err(|e| Value::from(&*e))?;
    Ok(patch.is_empty())
}

/// Whether a client may change `prop` of `O` in a `/set` update: it is in
/// [`SetObject::CLIENT_SETTABLE`] and not in [`SetObject::IMMUTABLE`].
///
/// For a handler whose spec lists the update keys it supports, so that any
/// other property is rejected rather than checked against the read-only
/// lists.
#[must_use]
pub fn is_client_updatable<O: SetObject>(prop: &str) -> bool {
    O::CLIENT_SETTABLE.contains(&prop) && !O::IMMUTABLE.contains(&prop)
}

/// Resolve an Id-typed value that may be a creation-id reference
/// (RFC 8620 §5.3).
///
/// A value starting with `#` names a record created earlier in the same
/// request; it resolves to that record's server-assigned id from
/// `created_ids` (pass [`crate::CallContext::created_ids`]). Any other
/// value is a literal id and is returned as is. `None` means a `#`
/// reference with no matching creation; the caller rejects the
/// create/update, typically with an `invalidProperties` SetError naming
/// the property.
///
/// References to creates in the *same* `/set` call are not in
/// `created_ids` yet; the handler orders and resolves those itself
/// (RFC 8620 §5.3).
pub fn resolve_creation_ref(
    raw: &str,
    created_ids: &std::collections::BTreeMap<Id, Id>,
) -> Option<Id> {
    match raw.strip_prefix('#') {
        Some(creation_id) => created_ids.get(&Id::from(creation_id)).cloned(),
        None => Some(Id::from(raw)),
    }
}

/// The `id` a `/set` create handler fills in before parsing the create
/// object into its typed struct, whose `id` is required.
///
/// The builder passed to the backend overwrites it with the minted id, so
/// it never reaches storage or the wire. It must still satisfy RFC 8620
/// §1.2 (at least 1 octet, URL-safe base64 alphabet) because deserializing
/// an [`Id`] validates it.
pub const CREATE_ID_PLACEHOLDER: &str = "pending";

/// Parse a client-supplied id: a `/set` `update` key, a `destroy` element
/// or an Id-typed property value.
///
/// RFC 8620 §1.2: an Id "MUST be at least 1 and a maximum of 255 octets in
/// size, and it MUST only contain characters from the 'URL and Filename
/// Safe' base64 alphabet". [`Id::from`] does not check this, so every
/// handler routes wire ids through here instead.
///
/// # Errors
///
/// A boxed `invalidProperties` [`SetError`] naming `property` (`"id"` for an
/// `update` key or `destroy` element) whose description says why the
/// value is not an Id. The caller records it in `notCreated`,
/// `notUpdated` or `notDestroyed` for that entry.
pub fn parse_wire_id(raw: &str, property: &str) -> Result<Id, Box<SetError>> {
    Id::new_validated(raw).map_err(|e| {
        Box::new(
            SetError::new(SetErrorType::InvalidProperties)
                .with_properties([property])
                .with_description(e.to_string()),
        )
    })
}

/// `true` if `using` includes `urn:ietf:params:jmap:metadata`
/// (draft-ietf-jmap-metadata-05 §3: the extensions "apply to requests
/// whose using includes urn:ietf:params:jmap:metadata").
pub fn uses_metadata(using: &[String]) -> bool {
    using
        .iter()
        .any(|u| u == jmap_metadata_types::JMAP_METADATA_URI)
}

/// draft-ietf-jmap-metadata-05 §3: the §3.6 filter conditions extend
/// `Foo/query` only for "requests whose using includes
/// urn:ietf:params:jmap:metadata". Without it a metadata leaf anywhere in
/// `filter`, as `is_metadata` judges a condition, is `unsupportedFilter`
/// (RFC 8620 §5.5: "The filter is syntactically valid, but the server
/// cannot process it"). `Foo/query` and `Foo/queryChanges` handlers call
/// it once the filter is decoded.
///
/// # Errors
///
/// `unsupportedFilter` as above.
pub fn reject_metadata_filter_without_capability<T>(
    filter: Option<&jmap_types::Filter<T>>,
    is_metadata: fn(&T) -> bool,
    using: &[String],
) -> Result<(), JmapError> {
    fn any_leaf<T>(f: &jmap_types::Filter<T>, is_metadata: fn(&T) -> bool) -> bool {
        match f {
            jmap_types::Filter::Condition(c) => is_metadata(c),
            jmap_types::Filter::Operator(op) => {
                op.conditions.iter().any(|f| any_leaf(f, is_metadata))
            }
            _ => false,
        }
    }
    if uses_metadata(using) || !filter.is_some_and(|f| any_leaf(f, is_metadata)) {
        return Ok(());
    }
    let mut err = JmapError::unsupported_filter();
    err.description = Some(
        "metadata filter conditions require urn:ietf:params:jmap:metadata in using".to_owned(),
    );
    Err(err)
}

/// [`reject_metadata_filter_without_capability`] on the undecoded
/// `filter` argument of a `Foo/query` or `Foo/queryChanges` request, for
/// handlers that pass `args` on to [`handle_query`](crate::handle_query)
/// or [`handle_query_changes`](crate::handle_query_changes) and so never
/// hold the decoded filter. A `filter` that does not decode is left for
/// that handler to report.
///
/// # Errors
///
/// `unsupportedFilter` for a -05 §3.6 condition without
/// `urn:ietf:params:jmap:metadata` in `using` (-05 §3).
pub fn reject_metadata_filter_arg<T: serde::de::DeserializeOwned>(
    args: &Value,
    is_metadata: fn(&T) -> bool,
    using: &[String],
) -> Result<(), JmapError> {
    if uses_metadata(using) {
        return Ok(());
    }
    let Some(raw) = args.get("filter").filter(|v| !v.is_null()) else {
        return Ok(());
    };
    match serde_json::from_value::<jmap_types::Filter<T>>(raw.clone()) {
        Ok(filter) => reject_metadata_filter_without_capability(Some(&filter), is_metadata, using),
        Err(_) => Ok(()),
    }
}

/// Which part of one metadata property a `Foo/get` returns.
#[derive(Debug, Default)]
enum Selection {
    /// Not returned.
    #[default]
    Omit,
    /// The whole stored object.
    All,
    /// Only these namespaces (-05 §3.1 subselectors, combined by union).
    Namespaces(BTreeSet<String>),
}

impl Selection {
    fn add_namespace(&mut self, ns: &str) {
        match self {
            Self::All => {}
            Self::Omit => *self = Self::Namespaces(BTreeSet::from([ns.to_owned()])),
            Self::Namespaces(set) => {
                set.insert(ns.to_owned());
            }
        }
    }

    /// The value to return for a property stored as `stored`; absent and
    /// `null` are `{}` (-05 §2: "When returned, its value MUST be an
    /// object ({} when no metadata is set), never null").
    fn select(&self, stored: Option<&Value>) -> Option<Value> {
        let stored = stored.and_then(Value::as_object);
        match self {
            Self::Omit => None,
            Self::All => Some(Value::Object(stored.cloned().unwrap_or_default())),
            Self::Namespaces(set) => Some(Value::Object(
                stored
                    .into_iter()
                    .flatten()
                    .filter(|(k, _)| set.contains(k.as_str()))
                    .map(|(k, v)| (k.clone(), v.clone()))
                    .collect(),
            )),
        }
    }
}

/// How a `Foo/get` handler returns `metadata` and `privateMetadata`
/// (draft-ietf-jmap-metadata-05 §2 and §3.1).
///
/// Build one per request with [`MetadataProjection::new`], then call
/// [`MetadataProjection::apply`] on every returned object.
#[derive(Debug, Default)]
pub struct MetadataProjection {
    metadata: Selection,
    private_metadata: Selection,
}

impl MetadataProjection {
    /// Build the projection for one `Foo/get` request.
    ///
    /// `properties` is the request's `properties` (`None` for the default
    /// list), `default_includes` is `false` for `Email/get`, whose
    /// "default property list ... is unchanged" (-05 §3.1), and `true` for
    /// every other type; `info` is the type's DataTypeMetadataInfo
    /// ([`JmapBackend::metadata_info`](crate::JmapBackend::metadata_info)),
    /// `None` when the type is not listed and so "does not gain the
    /// metadata or privateMetadata properties" (-05 §1.2.1). The rules:
    ///
    /// - Default list: both properties with the capability in `using`
    ///   ("the server MUST include metadata and, where supportsPrivate is
    ///   true, privateMetadata"), neither without it ("not default
    ///   properties of Foo/get") (-05 §3, §3.1).
    /// - A root name returns the whole property, with or without the
    ///   capability ("still returned when requested by name").
    /// - With the capability, `metadata/<namespace>` and
    ///   `privateMetadata/<namespace>` return only the stored namespaces
    ///   named; several combine by union and a root entry supersedes them.
    ///   A namespace with no stored data is left out, which covers "A
    ///   subselector naming a namespace that is not supported ... MUST be
    ///   silently omitted ... unless the object has data stored under that
    ///   namespace". Without the capability these entries are ignored like
    ///   any other unknown property.
    /// - `privateMetadata` is never returned when `supportsPrivate` is
    ///   false (-05 §2: "this property MUST NOT be returned").
    ///
    /// # Errors
    ///
    /// `invalidArguments` for an entry that begins with `metadata/` or
    /// `privateMetadata/` and is not followed by a namespace identifier
    /// (-05 §3.1: "Any other properties entry beginning with metadata/ or
    /// privateMetadata/ MUST be rejected with an "invalidArguments"
    /// method-level error").
    pub fn new(
        properties: Option<&[String]>,
        default_includes: bool,
        using: &[String],
        info: Option<&jmap_metadata_types::DataTypeMetadataInfo>,
    ) -> Result<Self, JmapError> {
        let Some(info) = info else {
            return Ok(Self::default());
        };
        let uses = uses_metadata(using);
        let mut projection = Self::default();
        match properties {
            None if uses && default_includes => {
                projection.metadata = Selection::All;
                projection.private_metadata = Selection::All;
            }
            None => {}
            Some(props) => {
                for p in props {
                    let (root, ns) = p
                        .split_once('/')
                        .map_or((p.as_str(), None), |(r, n)| (r, Some(n)));
                    let sel = match root {
                        "metadata" => &mut projection.metadata,
                        "privateMetadata" => &mut projection.private_metadata,
                        _ => continue,
                    };
                    match ns {
                        None => *sel = Selection::All,
                        Some(_) if !uses => {}
                        // A subselector names one namespace: nothing below
                        // it ("metadata/<namespace>/<key>" is an error).
                        // is_valid_namespace alone accepts '/' in a domain
                        // label.
                        Some(ns)
                            if !ns.contains('/') && jmap_metadata_types::is_valid_namespace(ns) =>
                        {
                            sel.add_namespace(ns);
                        }
                        Some(_) => {
                            return Err(JmapError::invalid_arguments(format!(
                                "properties: {p:?} is not a metadata subselector"
                            )));
                        }
                    }
                }
            }
        }
        if !info.supports_private {
            projection.private_metadata = Selection::Omit;
        }
        Ok(projection)
    }

    /// Set or remove `metadata` and `privateMetadata` on the response
    /// object `target` from the stored object `source`.
    pub fn apply(&self, source: &Value, target: &mut Value) {
        let Value::Object(target) = target else {
            return;
        };
        for (root, sel) in [
            ("metadata", &self.metadata),
            ("privateMetadata", &self.private_metadata),
        ] {
            match sel.select(source.get(root)) {
                Some(v) => {
                    target.insert(root.to_owned(), v);
                }
                None => {
                    target.remove(root);
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{
        MAX_MERGE_PATCH_DEPTH, MergePatchError, PatchPathError, apply_jmap_patch,
        apply_patch_object, civil_from_days, enforce_max_objects_in_set, extract_account_id,
        filter_arg, is_client_updatable, json_merge_patch, json_type_name, limit_or_max,
        now_utc_string, parse_max_changes, parse_wire_id, query_anchor_args,
        reject_did_bearing_properties, reject_read_only_patch, reject_server_set,
        resolve_creation_ref, resolve_query_offset, resolve_query_start,
        signed_seconds_since_epoch, utc_date_from_epoch_millis, utc_date_from_epoch_seconds,
    };
    use jmap_types::{Id, PushSubscription, UTCDate};
    use serde_json::json;

    fn props(e: Option<crate::backend::SetError>) -> Option<Vec<String>> {
        e.map(|e| {
            serde_json::from_value(serde_json::to_value(e).unwrap()["properties"].clone()).unwrap()
        })
    }

    /// Oracle: RFC 8620 §7.2, `id` is "(immutable; server-set)" and the
    /// other properties are client-sent. RFC 8620 §1.1: "The client MUST
    /// NOT send this property when creating". A null `id` is treated as
    /// absent.
    #[test]
    fn reject_server_set_names_server_set_create_properties() {
        let ok = json!({"id": null, "deviceClientId": "d", "url": "https://x.example/"});
        assert_eq!(
            props(reject_server_set::<PushSubscription>(
                ok.as_object().unwrap()
            )),
            None
        );
        let bad = json!({"id": "p1", "deviceClientId": "d"});
        assert_eq!(
            props(reject_server_set::<PushSubscription>(
                bad.as_object().unwrap()
            )),
            Some(vec!["id".to_owned()])
        );
    }

    /// Oracle: RFC 8620 §7.2, `id` is server-set, `deviceClientId`, `url`
    /// and `keys` are "(immutable)", `expires` and `types` carry no
    /// attribute. `keys/auth` points inside `keys`; `urlX` is another name.
    #[test]
    fn reject_read_only_patch_names_server_set_and_immutable_keys() {
        let ok = json!({"expires": null, "types": ["Email"], "urlX": 1});
        assert_eq!(
            props(reject_read_only_patch::<PushSubscription>(
                ok.as_object().unwrap(),
                None
            )),
            None
        );
        let bad = json!({"keys/auth": "a", "id": "p2", "url": "https://y.example/"});
        assert_eq!(
            props(reject_read_only_patch::<PushSubscription>(
                bad.as_object().unwrap(),
                None
            )),
            Some(vec!["id".to_owned(), "url".to_owned(), "keys".to_owned()])
        );
    }

    /// Oracle: RFC 8620 §7.2: `id` is "(immutable; server-set)",
    /// `deviceClientId` is "(immutable)", `expires` carries no attribute;
    /// `nope` is not a PushSubscription property.
    #[test]
    fn is_client_updatable_excludes_server_set_immutable_and_unknown() {
        assert!(is_client_updatable::<PushSubscription>("expires"));
        assert!(!is_client_updatable::<PushSubscription>("id"));
        assert!(!is_client_updatable::<PushSubscription>("deviceClientId"));
        assert!(!is_client_updatable::<PushSubscription>("nope"));
    }

    /// Oracle: RFC 8620 §5.3, "Any server-set properties MAY be included in
    /// the patch if their value is identical to the current server value
    /// ... Otherwise, the update MUST be rejected with an
    /// "invalidProperties" SetError." `keys/auth` points inside `keys`, so
    /// it changes it even when the leaf value matches.
    #[test]
    fn reject_read_only_patch_allows_unchanged_whole_values() {
        let stored = json!({"id": "p1", "url": "https://x.example/", "keys": {"auth": "a"}});
        let stored = stored.as_object().unwrap();
        let same = json!({"id": "p1", "url": "https://x.example/"});
        assert_eq!(
            props(reject_read_only_patch::<PushSubscription>(
                same.as_object().unwrap(),
                Some(stored)
            )),
            None
        );
        let changed = json!({"id": "p1", "url": "https://y.example/", "keys/auth": "a"});
        assert_eq!(
            props(reject_read_only_patch::<PushSubscription>(
                changed.as_object().unwrap(),
                Some(stored)
            )),
            Some(vec!["url".to_owned(), "keys".to_owned()])
        );
    }

    /// Oracle: RFC 8620 §5.3 — "the client refers to the new record
    /// using its creation id prefixed with a '#'"; the RFC 8620 §5.3
    /// example request sets `"subTodoIds": [ "#k15" ]` after creating
    /// `k15`. A bare value is an ordinary id.
    #[test]
    fn resolve_creation_ref_maps_hash_refs_and_passes_literals() {
        let created = std::collections::BTreeMap::from([(Id::from("k15"), Id::from("T15"))]);
        assert_eq!(
            resolve_creation_ref("#k15", &created),
            Some(Id::from("T15"))
        );
        assert_eq!(resolve_creation_ref("k15", &created), Some(Id::from("k15")));
        assert_eq!(resolve_creation_ref("#k16", &created), None);
    }

    /// RFC 8620 §1.2: 1 to 255 octets from `A-Za-z0-9`, `-` and `_`.
    #[test]
    fn parse_wire_id_enforces_rfc8620_id_syntax() {
        assert_eq!(parse_wire_id("aZ09-_", "id"), Ok(Id::from("aZ09-_")));
        assert!(parse_wire_id(&"a".repeat(255), "id").is_ok());
        for bad in [
            "",
            "has space",
            "line\nbreak",
            "#c1",
            "a=",
            &"a".repeat(256),
        ] {
            let err = parse_wire_id(bad, "mailboxId").unwrap_err();
            assert_eq!(
                serde_json::to_value(&err).unwrap()["type"],
                "invalidProperties",
                "{bad:?}"
            );
            assert_eq!(
                err.properties.as_deref(),
                Some(&["mailboxId".to_owned()][..])
            );
        }
    }

    #[test]
    fn query_anchor_args_rejects_non_id_anchor() {
        let args = serde_json::json!({ "anchor": "not an id" });
        let err = query_anchor_args(args.as_object().unwrap()).unwrap_err();
        assert_eq!(
            err.error_type,
            jmap_types::MethodErrorType::InvalidArguments
        );
        let args = serde_json::json!({ "anchor": "m1", "anchorOffset": -1 });
        assert_eq!(
            query_anchor_args(args.as_object().unwrap()).unwrap(),
            (Some(Id::from("m1")), -1)
        );
    }

    #[derive(Debug, serde::Deserialize)]
    #[serde(rename_all = "camelCase", deny_unknown_fields)]
    struct NameCond {
        name: Option<String>,
    }

    // draft-atwood-jmap-did-00 L247 (jmap-chat-spec 6bcd9d8): "Clients omit
    // DID-bearing properties when creating objects, as {{RFC8620}} Section
    // 1.1 requires for server-set properties; an update can include one only
    // with its current value ({{RFC8620}} Section 5.3). Servers MUST reject a
    // create that includes a DID-bearing property, or an update that changes
    // one, with a SetError of type `invalidProperties`, listing the
    // DID-bearing property name in the `properties` array."
    fn did_entry(v: serde_json::Value) -> serde_json::Map<String, serde_json::Value> {
        v.as_object().cloned().expect("object")
    }

    fn invalid_did() -> serde_json::Value {
        json!({ "type": "invalidProperties", "properties": ["did"] })
    }

    #[test]
    fn did_create_with_did_property_is_invalid_properties() {
        let entry = did_entry(json!({
            "name": "x",
            "did": "did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK"
        }));
        let err = reject_did_bearing_properties(&entry, &["did"], None).expect("L247: MUST reject");
        assert_eq!(
            serde_json::to_value(&err).expect("serialize"),
            invalid_did()
        );
    }

    #[test]
    fn did_create_with_null_did_is_still_rejected() {
        // L247: "a create that includes a DID-bearing property"; null is included.
        let entry = did_entry(json!({ "did": null }));
        assert!(reject_did_bearing_properties(&entry, &["did"], None).is_some());
    }

    #[test]
    fn did_lists_every_did_bearing_property_named() {
        // L247 rejects each included DID-bearing property. The two names
        // here are arbitrary DID-bearing names the caller declares; the
        // `properties` array follows `did_properties` order, not key order.
        let entry = did_entry(json!({
            "ownerDid": "did:web:example.com",
            "did": "did:web:example.org"
        }));
        let err = reject_did_bearing_properties(&entry, &["did", "ownerDid"], None)
            .expect("L247: MUST reject");
        assert_eq!(
            err.properties,
            Some(vec!["did".to_owned(), "ownerDid".to_owned()])
        );
    }

    #[test]
    fn did_update_with_current_value_passes() {
        // L247: "an update can include one only with its current value".
        let stored = did_entry(json!({ "id": "a", "did": "did:web:example.com" }));
        let entry = did_entry(json!({ "name": "y", "did": "did:web:example.com" }));
        assert_eq!(
            reject_did_bearing_properties(&entry, &["did"], Some(&stored)),
            None
        );

        let stored_null = did_entry(json!({ "id": "a", "did": null }));
        let entry_null = did_entry(json!({ "did": null }));
        assert_eq!(
            reject_did_bearing_properties(&entry_null, &["did"], Some(&stored_null)),
            None
        );
    }

    #[test]
    fn did_update_with_null_over_absent_did_passes() {
        // L247: "an update can include one only with its current value".
        // RFC 8620 §5.3: "null ... to remove it (or reset it to its
        // default value)", so an absent property's current value is null.
        let stored = did_entry(json!({ "id": "a" }));
        let entry = did_entry(json!({ "did": null }));
        assert_eq!(
            reject_did_bearing_properties(&entry, &["did"], Some(&stored)),
            None
        );
    }

    #[test]
    fn did_update_that_changes_did_is_rejected() {
        // L247: "Servers MUST reject ... an update that changes one". A
        // different value, null over a stored DID, and a path under the
        // property ("did/x", RFC 8620 §5.3 PatchObject path) all change it.
        let stored = did_entry(json!({ "id": "a", "did": "did:web:example.com" }));
        for entry in [
            did_entry(json!({ "did": "did:web:example.org" })),
            did_entry(json!({ "did": null })),
            did_entry(json!({ "did/x": 1 })),
        ] {
            let err = reject_did_bearing_properties(&entry, &["did"], Some(&stored))
                .expect("L247: update that changes one");
            assert_eq!(
                serde_json::to_value(&err).expect("serialize"),
                invalid_did()
            );
        }
    }

    #[test]
    fn did_entry_without_did_bearing_property_passes() {
        // A property whose name merely starts with "did" is not "did".
        let entry = did_entry(json!({ "name": "x", "didx": 1, "keywords/did": true }));
        assert_eq!(reject_did_bearing_properties(&entry, &["did"], None), None);
    }

    fn filter_of(v: serde_json::Value) -> Result<Option<NameCond>, jmap_types::JmapError> {
        let mut args = json!({ "filter": v }).as_object().cloned().expect("object");
        filter_arg::<NameCond>(&mut args)
    }

    /// Oracle: RFC 8620 §5.5 — "unsupportedFilter: The "filter" is
    /// syntactically valid, but the server cannot process it"; RFC 8620
    /// §3.6.2 — invalidArguments for an argument of the wrong type.
    /// Hand-written JSON inputs.
    #[test]
    fn filter_arg_maps_object_and_non_object_failures() {
        assert!(filter_of(json!(null)).expect("null").is_none());
        let cond = filter_of(json!({ "name": "x" })).expect("known key");
        assert_eq!(cond.and_then(|c| c.name).as_deref(), Some("x"));
        let err = filter_of(json!({ "label": "x" })).expect_err("unknown key");
        assert_eq!(err.error_type.to_string(), "unsupportedFilter");
        assert!(
            err.description
                .as_deref()
                .is_some_and(|d| d.contains("label")),
            "{err:?}"
        );
        let err = filter_of(json!(42)).expect_err("scalar");
        assert_eq!(err.error_type.to_string(), "invalidArguments");
    }

    /// Oracle (bd:JMAP-wlip.5): a malformed accountId — empty string,
    /// containing forbidden ASCII characters, or exceeding 255 bytes —
    /// MUST surface as `invalidArguments`, not silently pass through to
    /// the backend's `account_exists` call.
    ///
    /// Test vectors hand-built from RFC 8620 §1.2's Id grammar
    /// (SAFE-CHAR = `%x21 / %x23-7E`).
    #[test]
    fn extract_account_id_rejects_malformed_id() {
        // Empty string.
        let err = extract_account_id(json!({ "accountId": "" }))
            .expect_err("empty accountId must fail validation");
        assert_eq!(err.error_type.to_string(), "invalidArguments");

        // Contains a space (0x20 — outside SAFE-CHAR's 0x21+ lower bound).
        let err = extract_account_id(json!({ "accountId": "my account" }))
            .expect_err("space in accountId must fail validation");
        assert_eq!(err.error_type.to_string(), "invalidArguments");

        // Contains a DQUOTE (0x22 — explicitly excluded by SAFE-CHAR).
        let err = extract_account_id(json!({ "accountId": "a\"b" }))
            .expect_err("DQUOTE in accountId must fail validation");
        assert_eq!(err.error_type.to_string(), "invalidArguments");

        // 256 bytes — exceeds the 255 cap.
        let long: String = "a".repeat(256);
        let err = extract_account_id(json!({ "accountId": long }))
            .expect_err("over-long accountId must fail validation");
        assert_eq!(err.error_type.to_string(), "invalidArguments");
    }

    /// Oracle (bd:JMAP-wlip.5): a well-formed accountId passes
    /// validation and is returned intact. Positive control paired with
    /// the rejection test above.
    ///
    /// Also pins (bd:JMAP-jfia.9): the returned args map MUST NOT
    /// contain accountId. The helper consumes the field rather than
    /// leaving it as a residual key for downstream handlers to
    /// re-parse or surface as "unexpected key".
    #[test]
    fn extract_account_id_accepts_well_formed_id() {
        let (id, rest) = extract_account_id(json!({
            "accountId": "u123-abc_DEF",
            "ids": ["e1", "e2"]
        }))
        .expect("well-formed accountId must pass validation");
        assert_eq!(id.as_ref(), "u123-abc_DEF");
        // Remaining args still contain the unrelated keys.
        assert!(rest.contains_key("ids"));
        // accountId MUST have been removed from the args map
        // (bd:JMAP-jfia.9). matches optional_arg's consume semantics.
        assert!(
            !rest.contains_key("accountId"),
            "accountId must be removed from args after extraction"
        );
    }

    /// Test vectors derived independently with Python's `datetime.date` module.
    /// `days` is the count of days since 1970-01-01.
    #[test]
    fn civil_from_days_known_dates() {
        let cases: &[(i64, (i32, u8, u8))] = &[
            (0, (1970, 1, 1)),       // Unix epoch
            (365, (1971, 1, 1)),     // one year later (1970 is not a leap year)
            (10957, (2000, 1, 1)),   // Y2K
            (11016, (2000, 2, 29)),  // leap day in a century-divisible leap year
            (11017, (2000, 3, 1)),   // day after the leap day (era boundary in algorithm)
            (19358, (2023, 1, 1)),   // a recent non-leap year start
            (19722, (2023, 12, 31)), // end of 2023
            (19782, (2024, 2, 29)),  // leap day in 2024
            (19783, (2024, 3, 1)),   // day after 2024 leap day
        ];

        for &(days, expected) in cases {
            assert_eq!(
                civil_from_days(days),
                Some(expected),
                "civil_from_days({days}) mismatch"
            );
        }
    }

    /// Oracle (bd:JMAP-jfia.2): civil_from_days MUST return None rather
    /// than panic on inputs whose computed year overflows i32. The
    /// Hinnant algorithm's intermediate `y = yoe + era * 400` value is
    /// bounded by `i64::MAX / 146_097 ≈ ±6.3e13`, only a thin slice of
    /// which fits in i32. The outer `now_utc_string_checked`
    /// u64→i64 sentinel only catches u64 seconds exceeding `i64::MAX`,
    /// so corrupted-clock inputs between the i32-year boundary and
    /// i64::MAX reach this function. A panic here would surface as
    /// serverFail under dispatcher task::spawn isolation — degraded,
    /// but a contract violation versus the function's "fallible
    /// without panicking" contract.
    ///
    /// Test vectors: the maximum days-from-epoch derived from
    /// i64::MAX seconds (the regime that reaches civil_from_days
    /// after passing the outer u64→i64 sentinel), and the symmetric
    /// negative case. These years are deep enough into the i64
    /// algorithm range to definitely overflow i32. Plus a
    /// non-overflowing positive control just below the threshold to
    /// prove the boundary check fires only when warranted.
    #[test]
    fn civil_from_days_returns_none_on_year_overflow() {
        // i64::MAX / 86400 ≈ 1.07e14 days → year ≈ 2.92e11, well past i32::MAX (~2.15e9).
        let max_days = i64::MAX / 86400;
        assert_eq!(
            civil_from_days(max_days),
            None,
            "i64::MAX / 86400 days must overflow i32 year"
        );

        // i64::MIN / 86400 ≈ -1.07e14 days — symmetric negative case.
        let min_days = i64::MIN / 86400;
        assert_eq!(
            civil_from_days(min_days),
            None,
            "i64::MIN / 86400 days must overflow i32 year"
        );

        // Positive control: a far-future but i32-fitting year should
        // still succeed. Year ~58_798_075 (from 10 * i32::MAX days)
        // fits in i32 with room to spare, so this MUST return Some.
        let year_58m_days = 10_i64 * i64::from(i32::MAX);
        let result = civil_from_days(year_58m_days);
        assert!(
            result.is_some(),
            "i32-fitting year must return Some; got {result:?}"
        );
    }

    /// Oracle (bd:JMAP-jfia.30): now_utc_string_checked MUST return
    /// `Some(UTCDate)` on a sane clock (every host the test runs on
    /// in practice). The civil_from_days_returns_none_on_year_overflow
    /// test above pins the underlying None-on-corrupted-clock
    /// behaviour at the algorithm level; this test pins the
    /// happy-path contract: a sane clock yields the typed wire format,
    /// not a sentinel string.
    #[test]
    fn now_utc_string_checked_returns_some_on_sane_clock() {
        use super::now_utc_string_checked;
        let dt = now_utc_string_checked().expect(
            "test host clock must be reasonable enough for now_utc_string_checked to succeed",
        );
        let s: &str = dt.as_ref();
        assert!(
            UTCDate::new_validated(s).is_ok(),
            "must be an RFC 8620 §1.4 UTCDate: {s:?}"
        );
    }

    /// Oracle (bd:JMAP-jfia.30): now_utc_string (the panicking variant)
    /// MUST agree with now_utc_string_checked on a sane clock — i.e.
    /// the .expect() in now_utc_string does not introduce a wire-format
    /// discrepancy versus the Option-returning variant.
    #[test]
    fn now_utc_string_matches_checked_variant_on_sane_clock() {
        use super::now_utc_string_checked;
        let panicky = now_utc_string();
        let checked = now_utc_string_checked().expect("test host clock must be reasonable");
        // Both calls observe SystemTime::now() at slightly different
        // instants; the seconds part can differ if the test runs across
        // a second boundary. Compare the prefix up to the seconds
        // resolution.
        let panicky_s: &str = panicky.as_ref();
        let checked_s: &str = checked.as_ref();
        // Compare the date portion only (YYYY-MM-DD, 10 chars).
        assert_eq!(
            &panicky_s[..10],
            &checked_s[..10],
            "date portions must match: panicky={panicky_s:?} checked={checked_s:?}"
        );
    }

    /// Oracle: GNU `date -u -d @<secs> +%FT%TZ` (coreutils), plus the
    /// RFC 8620 §7.2.3 example expiry (rfc8620.txt:3879) and the RFC 8620
    /// §1.4 example date. -62167219200 is 0000-01-01T00:00:00Z; one second
    /// earlier is year -1, which the four-digit form cannot express.
    #[test]
    fn utc_date_from_epoch_seconds_known_values() {
        for (secs, expected) in [
            (0, Some("1970-01-01T00:00:00Z")),
            (-1, Some("1969-12-31T23:59:59Z")),
            (1_414_649_520, Some("2014-10-30T06:12:00Z")),
            (1_531_448_069, Some("2018-07-13T02:14:29Z")),
            (253_402_300_799, Some("9999-12-31T23:59:59Z")),
            (253_402_300_800, None),
            (-62_167_219_200, Some("0000-01-01T00:00:00Z")),
            (-62_167_219_201, None),
        ] {
            assert_eq!(
                utc_date_from_epoch_seconds(secs)
                    .as_ref()
                    .map(AsRef::as_ref),
                expected,
                "secs = {secs}"
            );
        }
    }

    /// Oracle: GNU `date -u -d @1414649520 +%FT%TZ` gives
    /// 2014-10-30T06:12:00Z (also the RFC 8620 §1.4 example). RFC 8620
    /// §1.4: "the "time-secfrac" MUST always be omitted if zero"
    /// (rfc8620.txt:346-347), so zero millis yield the 20-char form.
    #[test]
    fn utc_date_from_epoch_millis_omits_zero_secfrac() {
        for (millis, expected) in [
            (0, "2014-10-30T06:12:00Z"),
            (1, "2014-10-30T06:12:00.001Z"),
            (120, "2014-10-30T06:12:00.120Z"),
            (999, "2014-10-30T06:12:00.999Z"),
        ] {
            let d = utc_date_from_epoch_millis(1_414_649_520, millis).unwrap();
            assert_eq!(d.as_ref(), expected, "millis = {millis}");
            assert!(UTCDate::new_validated(expected).is_ok(), "{expected}");
        }
    }

    /// Oracle: GNU `date -u -d @<secs> +%FT%TZ` (coreutils). Pre-epoch
    /// seconds must take the time of day from the floored day, not from
    /// truncating division (bd:JMAP-yt1w.40: -1 used to yield 00:00:59).
    #[test]
    fn utc_date_from_epoch_millis_pre_epoch_time_of_day() {
        for (secs, expected) in [
            (-1, "1969-12-31T23:59:59Z"),
            (-61, "1969-12-31T23:58:59Z"),
            (-3601, "1969-12-31T22:59:59Z"),
            (-86401, "1969-12-30T23:59:59Z"),
            (-90061, "1969-12-30T22:58:59Z"),
        ] {
            let d = utc_date_from_epoch_millis(secs, 0).unwrap();
            assert_eq!(d.as_ref(), expected, "secs = {secs}");
        }
    }

    /// Oracle: GNU `date -u -d @<secs> +%FT%T.%3NZ` (coreutils), which
    /// floors to the millisecond. Pre-epoch sub-second clocks used to
    /// format as -s + millis instead of -s - millis (bd:JMAP-yt1w.46).
    #[test]
    fn signed_seconds_since_epoch_pre_epoch_subsec() {
        use std::time::{Duration, UNIX_EPOCH};
        for (before, expected) in [
            (Duration::from_millis(1200), "1969-12-31T23:59:58.800Z"),
            (Duration::from_millis(500), "1969-12-31T23:59:59.500Z"),
            (Duration::from_micros(1_200_500), "1969-12-31T23:59:58.799Z"),
            (
                Duration::from_millis(86_400_001),
                "1969-12-30T23:59:59.999Z",
            ),
            (Duration::from_secs(1), "1969-12-31T23:59:59Z"),
        ] {
            let (secs, millis) = signed_seconds_since_epoch(UNIX_EPOCH - before).unwrap();
            let d = utc_date_from_epoch_millis(secs, millis).unwrap();
            assert_eq!(d.as_ref(), expected, "before = {before:?}");
        }
    }

    #[test]
    fn now_utc_string_format() {
        // bd:JMAP-wlip.20 — return type is UTCDate; AsRef<str> gives
        // the underlying wire-format string for shape assertions.
        let dt = now_utc_string();
        let s: &str = dt.as_ref();
        // YYYY-MM-DDTHH:MM:SS.mmmZ (24 chars), or YYYY-MM-DDTHH:MM:SSZ
        // (20 chars) when the milliseconds are zero (RFC 8620 §1.4).
        assert!(s.len() == 24 || s.len() == 20, "unexpected length: {s}");
        assert!(s.ends_with('Z'), "must end with Z: {s}");
        assert_eq!(&s[4..5], "-", "missing year-month separator: {s}");
        assert_eq!(&s[7..8], "-", "missing month-day separator: {s}");
        assert_eq!(&s[10..11], "T", "missing date-time separator: {s}");
        assert_eq!(&s[13..14], ":", "missing hour-minute separator: {s}");
        assert_eq!(&s[16..17], ":", "missing minute-second separator: {s}");
        if s.len() == 24 {
            assert_eq!(&s[19..20], ".", "missing decimal point before millis: {s}");
            assert!(
                s[20..23].chars().all(|c| c.is_ascii_digit()),
                "milliseconds must be 3 digits: {s}"
            );
        }
        assert!(
            s.starts_with("20"),
            "year should start with 20 in 21st century: {s}"
        );
    }

    // -----------------------------------------------------------------------
    // json_merge_patch (RFC 7396)
    //
    // Test oracles are hand-built JSON values derived from RFC 7396 §2 and §3
    // examples, plus the regression case from bd:JMAP-sc1b.87. No oracle is
    // computed by the function under test (test-integrity rule from
    // workspace AGENTS.md).
    // -----------------------------------------------------------------------

    /// Oracle: bd:JMAP-sc1b.97 — a 1000-deep merge patch must NOT crash
    /// via stack overflow. The depth cap returns
    /// [`MergePatchError::DepthExceeded`] beyond [`MAX_MERGE_PATCH_DEPTH`]
    /// rather than recursing further.
    ///
    /// The test does not use the function as its own oracle: the input
    /// is hand-built (a 1000-deep `{ "a": { "a": ... { "a": {} } } }`
    /// chain where every level is Object, matching the structural
    /// shape of a real PatchObject — the documented latent panic from
    /// bd:JMAP-sc1b.87 only fires on non-Object leaves, which a typed
    /// PatchObject cannot produce). The assertion checks that the
    /// call completes without panicking AND that it surfaces the
    /// depth-exceeded error rather than silently succeeding (the
    /// pre-bd:JMAP-wlip.1 silent-truncation bug).
    #[test]
    fn json_merge_patch_does_not_stack_overflow() {
        const DEPTH: usize = 1000;
        let mut target = serde_json::json!({});
        for _ in 0..DEPTH {
            target = serde_json::json!({ "a": target });
        }
        let mut patch = serde_json::json!({});
        for _ in 0..DEPTH {
            patch = serde_json::json!({ "a": patch });
        }
        let err = json_merge_patch(&mut target, patch)
            .expect_err("deep patch must surface DepthExceeded, not silently truncate");
        assert_eq!(
            err,
            MergePatchError::DepthExceeded,
            "deep patch must return MergePatchError::DepthExceeded"
        );
    }

    /// Oracle: bd:JMAP-wlip.1 — a patch at exactly [`MAX_MERGE_PATCH_DEPTH`]
    /// levels (the deepest legal patch) MUST apply successfully. The cap
    /// fires only when the patch tries to recurse one level beyond. The
    /// expected target shape is hand-built level-by-level from the same
    /// counter the patch uses, so the oracle is independent of the
    /// recursion under test.
    #[test]
    fn json_merge_patch_at_exact_cap_applies() {
        // Build a patch nested exactly MAX_MERGE_PATCH_DEPTH levels deep.
        // Outermost level is depth=1; innermost leaf-Object is at depth
        // MAX_MERGE_PATCH_DEPTH. The first depth-cap check fires at
        // depth == MAX_MERGE_PATCH_DEPTH + 1, so this is the deepest
        // patch that still applies.
        let mut patch = serde_json::json!({ "leaf": "value" });
        for _ in 0..(MAX_MERGE_PATCH_DEPTH - 1) {
            patch = serde_json::json!({ "a": patch });
        }
        let mut target = serde_json::json!({});
        json_merge_patch(&mut target, patch).expect("patch at the cap must apply");
        // Walk the resulting target down its 'a' chain to verify the
        // leaf field landed.
        let mut cursor = &target;
        for _ in 0..(MAX_MERGE_PATCH_DEPTH - 1) {
            cursor = cursor.get("a").expect("each level must have 'a'");
        }
        assert_eq!(
            cursor.get("leaf"),
            Some(&serde_json::Value::String("value".to_owned())),
            "the leaf field at exactly MAX_MERGE_PATCH_DEPTH must be applied"
        );
    }

    /// Oracle: a shallow merge patch under the cap still applies
    /// normally. Positive control paired with the stack-overflow test
    /// above to prove the depth cap only fires at the boundary, not on
    /// every call.
    #[test]
    fn json_merge_patch_shallow_applies_normally() {
        let mut target = serde_json::json!({ "a": 1, "b": { "c": 2 } });
        let patch = serde_json::json!({ "b": { "c": 99, "d": 7 }, "e": null });
        json_merge_patch(&mut target, patch).expect("shallow patch must succeed");
        assert_eq!(
            target,
            serde_json::json!({ "a": 1, "b": { "c": 99, "d": 7 } }),
            "RFC 7396 merge semantics broken at shallow depth"
        );
    }

    /// Regression: a Patch that adds a nested Object to a previously-
    /// absent field used to panic with `expect("merge patch target
    /// must be an object")` because the parent recursion frame
    /// inserted Value::Null as the placeholder, then recursed into
    /// Null with an Object patch.
    ///
    /// Per RFC 7396 §2 the correct behaviour is to reset the non-Object
    /// target to an empty Object and merge into it. Oracle is hand-
    /// derived from RFC 7396 §2's pseudocode:
    /// `Target[Name] = MergePatch(Target[Name], Value)` where
    /// MergePatch resets a non-Object target to `{}`.
    #[test]
    fn json_merge_patch_adds_nested_object_to_absent_field() {
        let mut target = serde_json::json!({ "a": 1 });
        let patch = serde_json::json!({ "b": { "c": 2 } });
        json_merge_patch(&mut target, patch).expect("nested-add patch must succeed");
        assert_eq!(
            target,
            serde_json::json!({ "a": 1, "b": { "c": 2 } }),
            "patch must add the nested object at the previously-absent field"
        );
    }

    /// Oracle: [`MergePatchError`] implements [`std::error::Error`] and
    /// has a stable Display form referencing the cap value. Pinning the
    /// Display string keeps the error message stable across refactors;
    /// the cap value is interpolated from the public constant so this
    /// test does not need updating if the cap changes.
    #[test]
    fn merge_patch_error_display() {
        let err = MergePatchError::DepthExceeded;
        let s = err.to_string();
        assert!(
            s.contains(&MAX_MERGE_PATCH_DEPTH.to_string()),
            "Display must mention the cap value; got {s:?}"
        );
        assert!(
            s.contains("merge patch"),
            "Display must identify the error source; got {s:?}"
        );
    }

    // ------------------------------------------------------------------
    // apply_jmap_patch (RFC 8620 §5.3 PatchObject paths, RFC 6901)
    //
    // Oracles are hand-built JSON values derived from the quoted RFC
    // text; the function under test is never its own oracle.
    // ------------------------------------------------------------------

    /// Build a `Map` from a JSON object literal.
    fn obj(v: serde_json::Value) -> serde_json::Map<String, serde_json::Value> {
        match v {
            serde_json::Value::Object(m) => m,
            other => panic!("fixture must be a JSON object, got {other}"),
        }
    }

    /// Apply `path` → `value` to `before` and assert it fails with `want`
    /// and leaves the object unchanged.
    fn assert_patch_rejected(
        before: serde_json::Value,
        path: &str,
        value: serde_json::Value,
        want: PatchPathError,
    ) {
        let mut target = obj(before.clone());
        let err = apply_jmap_patch(&mut target, path, value).expect_err("patch must be rejected");
        assert_eq!(err, want, "wrong error for path {path:?}");
        assert_eq!(
            serde_json::Value::Object(target),
            before,
            "rejected patch {path:?} must leave the object unchanged"
        );
    }

    /// Oracle: RFC 8620 §5.3 — "Anything else: The value to set for this
    /// property (this may be a replacement or addition to the object
    /// being patched)."
    #[test]
    fn apply_jmap_patch_non_null_adds_or_replaces() {
        let mut target = obj(json!({ "a": 1 }));
        apply_jmap_patch(&mut target, "a", json!(2)).expect("replace");
        apply_jmap_patch(&mut target, "b", json!("x")).expect("add");
        assert_eq!(
            serde_json::Value::Object(target),
            json!({ "a": 2, "b": "x" })
        );
    }

    /// Oracle: RFC 8620 §5.3 — "If null, ... remove the property from the
    /// patched object.  If the key is not present in the parent, this a
    /// no-op."
    #[test]
    fn apply_jmap_patch_null_removes_and_absent_is_noop() {
        let mut target = obj(json!({ "a": 1, "m": { "k": true } }));
        apply_jmap_patch(&mut target, "a", serde_json::Value::Null).expect("remove");
        apply_jmap_patch(&mut target, "m/k", serde_json::Value::Null).expect("nested remove");
        apply_jmap_patch(&mut target, "m/absent", serde_json::Value::Null).expect("no-op");
        assert_eq!(serde_json::Value::Object(target), json!({ "m": {} }));
    }

    /// Oracle: RFC 8620 §5.3 — "The keys are a path in JSON Pointer
    /// format [RFC6901], with an implicit leading "/"". `mailboxIds/abc`
    /// sets member `abc` of the existing `mailboxIds` object and leaves
    /// its siblings alone.
    #[test]
    fn apply_jmap_patch_nested_path_sets_member_of_existing_object() {
        let mut target = obj(json!({ "mailboxIds": { "inbox": true }, "x": { "y": { "z": 1 } } }));
        apply_jmap_patch(&mut target, "mailboxIds/abc", json!(true)).expect("set");
        apply_jmap_patch(&mut target, "x/y/w", json!(2)).expect("deep set");
        assert_eq!(
            serde_json::Value::Object(target),
            json!({ "mailboxIds": { "inbox": true, "abc": true }, "x": { "y": { "z": 1, "w": 2 } } })
        );
    }

    /// Oracle: RFC 8620 §5.3 — "All parts prior to the last (i.e., the
    /// value after the final slash) MUST already exist on the object
    /// being patched." A missing parent is rejected, never created, for
    /// both non-null and null values.
    #[test]
    fn apply_jmap_patch_missing_parent_is_rejected() {
        let before = json!({ "a": { "b": {} } });
        for value in [json!("v"), serde_json::Value::Null] {
            assert_patch_rejected(
                before.clone(),
                "x/y",
                value.clone(),
                PatchPathError::ParentMissing,
            );
            assert_patch_rejected(
                before.clone(),
                "a/c/d",
                value,
                PatchPathError::ParentMissing,
            );
        }
    }

    /// Oracle: RFC 8620 §5.3 — "All parts prior to the last ... MUST
    /// already exist on the object being patched." A string, number,
    /// boolean or null has no members, so a part beneath one does not
    /// exist; the existing value must not be clobbered.
    #[test]
    fn apply_jmap_patch_non_object_parent_is_rejected() {
        let before = json!({ "s": "text", "n": 42, "b": true, "z": null });
        for parent in ["s", "n", "b", "z"] {
            assert_patch_rejected(
                before.clone(),
                &format!("{parent}/sub"),
                json!("would-clobber"),
                PatchPathError::ParentNotObject,
            );
        }
    }

    /// Oracle: RFC 8620 §5.3 — "The pointer MUST NOT reference inside an
    /// array (i.e., you MUST NOT insert/delete from an array; the array
    /// MUST be replaced in its entirety instead)." Applies to numeric
    /// tokens and to paths that would descend through an array element.
    #[test]
    fn apply_jmap_patch_inside_array_is_rejected() {
        let before = json!({ "list": ["a", { "k": 1 }] });
        assert_patch_rejected(
            before.clone(),
            "list/0",
            json!("x"),
            PatchPathError::InsideArray,
        );
        assert_patch_rejected(
            before.clone(),
            "list/1/k",
            json!(2),
            PatchPathError::InsideArray,
        );
        assert_patch_rejected(
            before,
            "list/0",
            serde_json::Value::Null,
            PatchPathError::InsideArray,
        );
    }

    /// Oracle: draft-ietf-jmap-metadata-05 §3.2 — "a path that traverses
    /// an array or a Binary value (Section 2.1.1) is rejected with an
    /// "invalidPatch" SetError"; §2.1.1 — "a patch path ... cannot address
    /// its members". Fixture is the §2.1.1 example. The Binary itself can
    /// still be replaced or removed, since the path then ends at it.
    #[test]
    fn apply_jmap_patch_through_metadata_binary_is_rejected() {
        let before = json!({ "metadata": { "acme.example.com": {
            "label": "draft copy",
            "thumbprint": {
                "@type": "Binary",
                "base64": "VEVYVHR0eHQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
            }
        } } });
        for (path, value) in [
            ("metadata/acme.example.com/thumbprint/base64", json!("AA==")),
            (
                "metadata/acme.example.com/thumbprint/base64",
                serde_json::Value::Null,
            ),
            ("metadata/acme.example.com/thumbprint/x", json!(1)),
        ] {
            assert_patch_rejected(before.clone(), path, value, PatchPathError::InsideBinary);
        }
        let private = json!({ "privateMetadata": { "x.example": {
            "b": { "@type": "Binary", "base64": "" }
        } } });
        assert_patch_rejected(
            private,
            "privateMetadata/x.example/b/base64",
            json!("Zg=="),
            PatchPathError::InsideBinary,
        );

        let mut target = obj(before);
        let bin = json!({ "@type": "Binary", "base64": "Zg==" });
        apply_jmap_patch(
            &mut target,
            "metadata/acme.example.com/thumbprint",
            bin.clone(),
        )
        .expect("replace whole Binary");
        assert_eq!(target["metadata"]["acme.example.com"]["thumbprint"], bin);
    }

    /// Oracle: RFC 8620 §5.3 — a path through an existing object is
    /// allowed. -05 §2.1.1 defines a Binary only "within a namespace
    /// value", so an `@type: "Binary"` object elsewhere is an ordinary
    /// object.
    #[test]
    fn apply_jmap_patch_binary_outside_metadata_is_ordinary() {
        let mut target = obj(json!({ "other": { "x": { "@type": "Binary", "base64": "" } } }));
        apply_jmap_patch(&mut target, "other/x/base64", json!("Zg==")).expect("plain object");
        assert_eq!(target["other"]["x"]["base64"], json!("Zg=="));
    }

    /// Oracle: RFC 8620 §5.3 — "the array MUST be replaced in its entirety
    /// instead": setting the array-valued property itself is allowed.
    #[test]
    fn apply_jmap_patch_replaces_whole_array() {
        let mut target = obj(json!({ "list": ["a"] }));
        apply_jmap_patch(&mut target, "list", json!(["b", "c"])).expect("replace array");
        assert_eq!(
            serde_json::Value::Object(target),
            json!({ "list": ["b", "c"] })
        );
    }

    /// Oracle: RFC 6901 §4 — "first transforming any occurrence of the
    /// sequence '~1' to '/', and then transforming any occurrence of the
    /// sequence '~0' to '~' ... (the string '~01' correctly becomes '~1'
    /// after transformation)." Decoding is per token, after splitting on
    /// `/`, so `a~1b/c` addresses member `c` of member `a/b`.
    #[test]
    fn apply_jmap_patch_decodes_rfc6901_escapes() {
        let mut target = obj(json!({ "a/b": {}, "m~n": {} }));
        apply_jmap_patch(&mut target, "foo~1bar", json!(1)).expect("~1");
        apply_jmap_patch(&mut target, "foo~0bar", json!(2)).expect("~0");
        apply_jmap_patch(&mut target, "~01", json!(3)).expect("~01");
        apply_jmap_patch(&mut target, "a~1b/c", json!(4)).expect("escaped parent");
        apply_jmap_patch(&mut target, "m~0n/~1", json!(5)).expect("escaped parent and leaf");
        assert_eq!(
            serde_json::Value::Object(target),
            json!({
                "foo/bar": 1,
                "foo~bar": 2,
                "~1": 3,
                "a/b": { "c": 4 },
                "m~n": { "/": 5 }
            })
        );
    }

    /// Oracle: RFC 6901 §3 — `escaped = "~" ( "0" / "1" )` and "It is an
    /// error condition if a JSON Pointer value does not conform to this
    /// syntax". RFC 8620 §5.3 requires keys in JSON Pointer format, so a
    /// malformed escape in any token is rejected.
    #[test]
    fn apply_jmap_patch_invalid_escape_is_rejected() {
        let before = json!({ "a": {} });
        for path in ["~2", "x~", "a/~", "~x/b", "a/b~"] {
            assert_patch_rejected(
                before.clone(),
                path,
                json!(1),
                PatchPathError::InvalidEscape,
            );
        }
    }

    /// Oracle: RFC 6901 §3 — `reference-token = *( unescaped / escaped )`
    /// permits an empty token, and the §5 example evaluates `"/"` to the
    /// member named `""` (`"" : 0`). The PatchObject key `""` is the
    /// pointer `"/"`; `"a/"` is the pointer `"/a/"`.
    #[test]
    fn apply_jmap_patch_empty_token_names_empty_member() {
        let mut target = obj(json!({ "a": {} }));
        apply_jmap_patch(&mut target, "", json!(0)).expect("empty top-level token");
        apply_jmap_patch(&mut target, "a/", json!(1)).expect("empty nested token");
        assert_eq!(
            serde_json::Value::Object(target),
            json!({ "": 0, "a": { "": 1 } })
        );
    }

    /// Oracle: an empty token is an ordinary member name, so a missing
    /// empty-named parent is rejected like any other missing parent
    /// (RFC 8620 §5.3 "All parts prior to the last ... MUST already
    /// exist").
    #[test]
    fn apply_jmap_patch_missing_empty_parent_is_rejected() {
        assert_patch_rejected(
            json!({ "a": {} }),
            "a//b",
            json!(1),
            PatchPathError::ParentMissing,
        );
    }

    // ------------------------------------------------------------------
    // apply_patch_object (RFC 8620 §5.3 whole PatchObject)
    // ------------------------------------------------------------------

    /// Oracle: RFC 8620 §5.3 — "There MUST NOT be two patches in the
    /// PatchObject where the pointer of one is the prefix of the pointer
    /// of the other, e.g., "alerts/1/offset" and "alerts""; on violation
    /// "the update MUST be rejected with an "invalidPatch" error".
    #[test]
    fn apply_patch_object_prefix_conflict_is_rejected() {
        let before = json!({ "alerts": { "1": { "offset": 0 } } });
        let mut target = obj(before.clone());
        let patch = obj(json!({ "alerts/1/offset": 5, "alerts": {} }));
        let err = apply_patch_object(&mut target, &patch).expect_err("must be rejected");
        assert_eq!(err, PatchPathError::PrefixConflict);
        assert_eq!(serde_json::Value::Object(target), before);
    }

    /// Oracle: RFC 8620 §5.3 forbids only a pointer that is "the prefix of
    /// the pointer of the other"; JSON Pointers are compared by reference
    /// token (RFC 6901 §3), so "alert" is not a prefix of "alerts/x".
    #[test]
    fn apply_patch_object_near_prefix_is_accepted() {
        let mut target = obj(json!({ "alerts": {} }));
        let patch = obj(json!({ "alert": 1, "alerts/x": 2 }));
        apply_patch_object(&mut target, &patch).expect("no prefix conflict");
        assert_eq!(
            serde_json::Value::Object(target),
            json!({ "alert": 1, "alerts": { "x": 2 } })
        );
    }

    /// Oracle: RFC 8620 §5.3 — "if there is any violation, the update MUST
    /// be rejected"; the valid entry "a" must not be applied either.
    #[test]
    fn apply_patch_object_partial_failure_leaves_target_unchanged() {
        let before = json!({ "a": 1 });
        let mut target = obj(before.clone());
        let patch = obj(json!({ "a": 2, "m/k": 1 }));
        let err = apply_patch_object(&mut target, &patch).expect_err("must be rejected");
        assert_eq!(err, PatchPathError::ParentMissing);
        assert_eq!(serde_json::Value::Object(target), before);
    }

    /// A value nesting `levels` objects deep (`0` is the scalar `1`).
    fn nested(levels: usize) -> serde_json::Value {
        (0..levels).fold(json!(1), |inner, _| json!({ "k": inner }))
    }

    /// Oracle: this crate's DoS guard, not an RFC 8620 §5.3 rule (RFC 8620
    /// §3.6.1 lets a server reject requests beyond its limits). Path
    /// segments plus value nesting may not exceed `MAX_MERGE_PATCH_DEPTH`
    /// (32): 3 + 30 = 33 is rejected before any entry is applied.
    #[test]
    fn apply_patch_object_path_plus_value_over_depth_cap_is_rejected() {
        let before = json!({ "x": 1, "a": { "b": {} } });
        let mut target = obj(before.clone());
        let patch = obj(json!({ "x": 2, "a/b/c": nested(30) }));
        let err = apply_patch_object(&mut target, &patch).expect_err("must be rejected");
        assert_eq!(err, PatchPathError::DepthExceeded);
        assert_eq!(serde_json::Value::Object(target), before);
    }

    /// Oracle: the crate's DoS guard rejects only depth beyond
    /// `MAX_MERGE_PATCH_DEPTH`; exactly 3 segments + 29 levels = 32 applies.
    #[test]
    fn apply_patch_object_path_plus_value_at_depth_cap_applies() {
        let mut target = obj(json!({ "a": { "b": {} } }));
        let patch = obj(json!({ "a/b/c": nested(29) }));
        apply_patch_object(&mut target, &patch).expect("at the cap must apply");
        assert_eq!(
            serde_json::Value::Object(target),
            json!({ "a": { "b": { "c": nested(29) } } })
        );
    }

    /// Oracle: the crate's DoS guard; a key of 33 segments exceeds
    /// `MAX_MERGE_PATCH_DEPTH` even with a scalar value.
    #[test]
    fn apply_patch_object_path_over_depth_cap_is_rejected() {
        let before = json!({ "a": {} });
        let mut target = obj(before.clone());
        let path = format!("a{}", "/k".repeat(32));
        let patch = obj(json!({ path: 1 }));
        let err = apply_patch_object(&mut target, &patch).expect_err("must be rejected");
        assert_eq!(err, PatchPathError::DepthExceeded);
        assert_eq!(serde_json::Value::Object(target), before);
    }

    // ------------------------------------------------------------------
    // enforce_max_objects_in_set (bd:JMAP-ayoz.41.1) — RFC 8620 §5.3
    //
    // Oracles for all tests below are hand-built JmapError comparisons
    // and hand-built JSON args; the helper itself is never the oracle.
    // ------------------------------------------------------------------

    /// Oracle (RFC 8620 §5.3): an empty `/set` args envelope (no
    /// `create` / `update` / `destroy` keys) MUST pass any positive cap.
    #[test]
    fn enforce_max_objects_in_set_empty_args_is_ok() {
        let args = json!({}).as_object().unwrap().clone();
        enforce_max_objects_in_set(&args, 500).expect("empty args must be under any positive cap");
    }

    /// Oracle (RFC 8620 §5.3): at the exact boundary count == max, the
    /// helper MUST return Ok. The cap is enforced as strictly-greater
    /// (`count > max`), not greater-or-equal.
    #[test]
    fn enforce_max_objects_in_set_at_limit_is_ok() {
        // 5 + 5 + 5 = 15 entries against max=15 must pass.
        let mut create = serde_json::Map::new();
        let mut update = serde_json::Map::new();
        let mut destroy = Vec::new();
        for i in 0..5 {
            create.insert(format!("c{i}"), json!({}));
            update.insert(format!("u{i}"), json!({}));
            destroy.push(json!(format!("d{i}")));
        }
        let args = json!({
            "create": create,
            "update": update,
            "destroy": destroy,
        })
        .as_object()
        .unwrap()
        .clone();
        enforce_max_objects_in_set(&args, 15).expect("exact-boundary count must be allowed");
    }

    /// Oracle (RFC 8620 §5.3, bd:JMAP-yt1w.30): one entry over the cap
    /// MUST return the method error "requestTooLarge" — "The total number
    /// of objects to create, update, or destroy exceeds the maximum number
    /// the server is willing to process in a single method call." — with
    /// description "maxObjectsInSet". The wire shape is verified by
    /// hand-building the expected JmapError independently of the helper.
    #[test]
    fn enforce_max_objects_in_set_over_limit_returns_limit_error() {
        // 5 + 5 + 6 = 16 entries against max=15 must fail.
        let mut create = serde_json::Map::new();
        let mut update = serde_json::Map::new();
        let mut destroy = Vec::new();
        for i in 0..5 {
            create.insert(format!("c{i}"), json!({}));
            update.insert(format!("u{i}"), json!({}));
        }
        for i in 0..6 {
            destroy.push(json!(format!("d{i}")));
        }
        let args = json!({
            "create": create,
            "update": update,
            "destroy": destroy,
        })
        .as_object()
        .unwrap()
        .clone();
        let err = enforce_max_objects_in_set(&args, 15)
            .expect_err("16-entry args against max=15 must fail");
        // Independent oracle — hand-built JmapError, not derived from
        // the function under test.
        let expected = jmap_types::JmapError::request_too_large();
        assert_eq!(
            err.error_type.to_string(),
            expected.error_type.to_string(),
            "type must be \"requestTooLarge\""
        );
        assert_eq!(
            err.description.as_deref(),
            Some("maxObjectsInSet"),
            "description must name the exceeded cap"
        );
    }

    /// Oracle (bd:JMAP-yt1w.30): RFC 8620 §5.3 (rfc8620.txt L2166-2170):
    /// "The following additional errors may be returned instead of the
    /// "Foo/set" response: "requestTooLarge": The total number of objects
    /// to create, update, or destroy exceeds the maximum number the server
    /// is willing to process in a single method call." Exceeding
    /// maxObjectsInSet is therefore the method-level error
    /// `requestTooLarge`, not the request-level `limit` error.
    #[test]
    fn enforce_max_objects_in_set_over_limit_returns_request_too_large() {
        let mut create = serde_json::Map::new();
        for i in 0..3 {
            create.insert(format!("c{i}"), json!({}));
        }
        let args = json!({
            "create": create,
            "destroy": ["d0"],
        })
        .as_object()
        .unwrap()
        .clone();
        let err =
            enforce_max_objects_in_set(&args, 3).expect_err("4-entry args against max=3 must fail");
        assert_eq!(
            err.error_type.to_string(),
            "requestTooLarge",
            "RFC 8620 §5.3: over-cap /set must yield method error requestTooLarge"
        );
    }

    /// Oracle (RFC 8620 §5.3): a non-object `create` argument (e.g.
    /// `null` or a string) counts as 0 — wire-shape validation belongs
    /// to the per-handler argument parsing, not this cap helper. The
    /// handler will reject the malformed `create` downstream; this
    /// helper only counts well-formed entries.
    #[test]
    fn enforce_max_objects_in_set_ignores_non_object_create() {
        let args = json!({
            "create": null,
            "update": null,
            "destroy": ["id1"],
        })
        .as_object()
        .unwrap()
        .clone();
        // Only the 1 destroy entry counts.
        enforce_max_objects_in_set(&args, 1).expect("non-object create/update count as 0");
    }

    /// Oracle (RFC 8620 §5.3): a non-array `destroy` argument counts
    /// as 0. Same rationale as the create/update test above.
    #[test]
    fn enforce_max_objects_in_set_ignores_non_array_destroy() {
        let args = json!({
            "create": { "c0": {} },
            "destroy": "not-an-array",
        })
        .as_object()
        .unwrap()
        .clone();
        // Only the 1 create entry counts.
        enforce_max_objects_in_set(&args, 1).expect("non-array destroy counts as 0");
    }

    /// Oracle (RFC 8620 §5.3): the cap counts the SUM of all three
    /// sources. A request whose individual create/update/destroy
    /// counts are each below the cap can still trip the cap when
    /// summed.
    #[test]
    fn enforce_max_objects_in_set_sums_all_three() {
        // 3 + 3 + 3 = 9; against max=5, must fail because the SUM > max
        // even though each individual count <= max.
        let args = json!({
            "create": { "c0": {}, "c1": {}, "c2": {} },
            "update": { "u0": {}, "u1": {}, "u2": {} },
            "destroy": ["d0", "d1", "d2"],
        })
        .as_object()
        .unwrap()
        .clone();
        let err =
            enforce_max_objects_in_set(&args, 5).expect_err("sum-of-all-three must trip the cap");
        assert_eq!(err.error_type.to_string(), "requestTooLarge");
        assert_eq!(err.description.as_deref(), Some("maxObjectsInSet"));
    }

    /// Oracle (RFC 8620 §5.5 + bd:JMAP-qz9v.48): `position` is a signed
    /// offset where non-negative is absolute and negative is
    /// end-relative. All hand-computed values below come from reading
    /// the spec text, NOT from the implementation under test.
    #[test]
    fn resolve_query_offset_absolute() {
        // Non-negative position: absolute offset, clamped at total.
        assert_eq!(resolve_query_offset(0, 100), 0);
        assert_eq!(resolve_query_offset(1, 100), 1);
        assert_eq!(resolve_query_offset(50, 100), 50);
        assert_eq!(resolve_query_offset(99, 100), 99);
        assert_eq!(resolve_query_offset(100, 100), 100);
        // Past-the-end → clamped to total (RFC 8620 §5.5 silent-clamp).
        assert_eq!(resolve_query_offset(101, 100), 100);
        assert_eq!(resolve_query_offset(10_000, 100), 100);
        assert_eq!(resolve_query_offset(i64::MAX, 100), 100);
    }

    #[test]
    fn resolve_query_offset_end_relative() {
        // RFC 8620 §5.5: "-1 represents the last entry, -2 the second
        // to last". Implemented as `total - |position|`, saturating at
        // 0 from below.
        assert_eq!(resolve_query_offset(-1, 100), 99);
        assert_eq!(resolve_query_offset(-2, 100), 98);
        assert_eq!(resolve_query_offset(-99, 100), 1);
        assert_eq!(resolve_query_offset(-100, 100), 0);
        // Past-the-start → clamped to 0.
        assert_eq!(resolve_query_offset(-101, 100), 0);
        assert_eq!(resolve_query_offset(-10_000, 100), 0);
    }

    /// Oracle: with total=0 (empty result list), every position
    /// resolves to 0 (the only valid index, and a no-op slice).
    #[test]
    fn resolve_query_offset_empty_total() {
        assert_eq!(resolve_query_offset(0, 0), 0);
        assert_eq!(resolve_query_offset(1, 0), 0);
        assert_eq!(resolve_query_offset(-1, 0), 0);
        assert_eq!(resolve_query_offset(i64::MAX, 0), 0);
        assert_eq!(resolve_query_offset(i64::MIN, 0), 0);
    }

    /// Oracle: `i64::MIN` would overflow `-position` (the previous
    /// workspace idiom at mail-server `memory/mod.rs:980`) but
    /// `saturating_neg` returns `i64::MAX`. The resulting end-relative
    /// offset of `i64::MAX` is well past any realistic `total`, so for
    /// any realistic total the result is 0.
    ///
    /// For the synthetic case `total == usize::MAX`, the offset stays
    /// within the saturation range and the result is
    /// `usize::MAX - i64::MAX`, which on a 64-bit target is exactly
    /// `0x8000_0000_0000_0000`. The point of the regression guard is
    /// that the call does NOT panic (which it would under the prior
    /// `(-position) as usize` idiom in debug builds).
    /// Oracle: RFC 8620 §5.5 `limit` -- "If null, no limit presumed" --
    /// so `None` is unbounded; `Some(n)` is exactly `n` items.
    #[test]
    fn limit_or_max_follows_rfc8620_limit_semantics() {
        let items = [1u8, 2, 3, 4, 5];
        assert_eq!(items.iter().take(limit_or_max(None)).count(), 5);
        assert_eq!(items.iter().take(limit_or_max(Some(0))).count(), 0);
        assert_eq!(items.iter().take(limit_or_max(Some(2))).count(), 2);
        // u64::MAX never truncates to a small count: on 64-bit it is
        // exactly usize::MAX, on 32-bit it saturates to usize::MAX.
        assert_eq!(limit_or_max(Some(u64::MAX)), usize::MAX);
    }

    #[test]
    fn resolve_query_offset_i64_min_does_not_overflow() {
        assert_eq!(resolve_query_offset(i64::MIN, 1), 0);
        assert_eq!(resolve_query_offset(i64::MIN, 100), 0);
        assert_eq!(resolve_query_offset(i64::MIN, i64::MAX as usize), 0);
        // Synthetic upper bound: the answer is computable but not 0.
        // What matters is no overflow / no panic, and start <= total.
        let start = resolve_query_offset(i64::MIN, usize::MAX);
        assert_eq!(start, usize::MAX - (i64::MAX as usize));
        // And `i64::MAX` on the positive side is also handled.
        assert_eq!(resolve_query_offset(i64::MAX, 0), 0);
        assert_eq!(resolve_query_offset(i64::MAX, 1), 1);
    }

    /// Oracle: the bead's specific concern was that `position as usize`
    /// truncates on 32-bit targets. On 64-bit (this test host) the
    /// `i64`-to-`usize` conversion is lossless within `[0, i64::MAX]`,
    /// so the truncation cannot be directly demonstrated; what we CAN
    /// verify is that the helper uses `usize::try_from` semantics, so
    /// a value above `i64::MAX` (only reachable here via direct cast
    /// from an unsigned constant) clamps to `total` rather than
    /// wrapping. The `i64::MIN` case in the prior test is the real
    /// regression guard.
    #[test]
    fn resolve_query_offset_truncation_resistant() {
        // The slice-safety property: `total..=total` is always a valid
        // start index for `slice[start..]` (yields empty slice). The
        // helper MUST return a value in `0..=total`.
        for &pos in &[i64::MIN, -1_000_000, -1, 0, 1, 1_000_000, i64::MAX] {
            for &total in &[0usize, 1, 100, 10_000] {
                let start = resolve_query_offset(pos, total);
                assert!(
                    start <= total,
                    "resolve_query_offset({pos}, {total}) = {start} violates start <= total"
                );
            }
        }
    }
    /// Oracle: RFC 8620 §5.5 (https://www.rfc-editor.org/rfc/rfc8620.txt):
    /// "If found, the "anchorOffset" is then added to its index.  If the
    /// resulting index is now negative, it is clamped to 0. ... If the
    /// anchor is not found, the call is rejected with an "anchorNotFound"
    /// error.  If an "anchor" is specified, any position argument supplied
    /// by the client MUST be ignored.  If no "anchor" is supplied, any
    /// "anchorOffset" argument MUST be ignored."
    ///
    /// `ids` is `[a, b, c, d]`, so anchor `c` is index 2.
    #[test]
    fn resolve_query_start_follows_rfc8620_anchor_rules() {
        let ids: Vec<jmap_types::Id> = ["a", "b", "c", "d"].map(jmap_types::Id::from).to_vec();
        let c = jmap_types::Id::from("c");
        let start = |position, anchor, offset| resolve_query_start(&ids, position, anchor, offset);
        assert_eq!(start(0, Some(&c), 1), Ok(3));
        assert_eq!(start(0, Some(&c), -1), Ok(1));
        assert_eq!(start(0, Some(&c), -5), Ok(0));
        assert_eq!(start(3, Some(&c), 0), Ok(2));
        assert_eq!(start(1, None, 2), Ok(1));
        let missing = jmap_types::Id::from("z");
        assert_eq!(
            start(0, Some(&missing), 0).map_err(|e| e.error_type.to_string()),
            Err("anchorNotFound".to_owned())
        );
    }

    /// RFC 8620 §5.2: "the value MUST be a positive integer greater than
    /// 0. If a value outside of this range is given, the server MUST
    /// reject the call with an "invalidArguments" error." The argument is
    /// `UnsignedInt|null`, so absent and `null` mean "not given".
    #[test]
    fn parse_max_changes_follows_rfc8620_5_2() {
        assert_eq!(parse_max_changes(None).ok(), Some(None));
        assert_eq!(parse_max_changes(Some(&json!(null))).ok(), Some(None));
        assert_eq!(parse_max_changes(Some(&json!(1))).ok(), Some(Some(1)));
        assert_eq!(parse_max_changes(Some(&json!(50))).ok(), Some(Some(50)));
        for bad in [json!(0), json!(-1), json!(1.5), json!("5"), json!(true)] {
            assert_eq!(
                parse_max_changes(Some(&bad)).map_err(|e| e.error_type.to_string()),
                Err("invalidArguments".to_owned()),
                "maxChanges = {bad} must be rejected"
            );
        }
    }

    /// Oracle: the six JSON value kinds of RFC 8259 §3 ("object, array,
    /// number, string ... false, null, true"), with `true`/`false` named
    /// "boolean", written out by hand.
    #[test]
    fn json_type_name_names_each_json_kind() {
        let cases = [
            (json!(null), "null"),
            (json!(true), "boolean"),
            (json!(false), "boolean"),
            (json!(-1.5), "number"),
            (json!("CANARY-zegc"), "string"),
            (json!([1, 2]), "array"),
            (json!({ "note": "CANARY-zegc" }), "object"),
        ];
        for (value, want) in cases {
            assert_eq!(json_type_name(&value), want, "{value}");
        }
    }

    /// RFC 8620 §5.5 types `anchor` as "Id|null" and `anchorOffset` as
    /// "Int"; wrong types are `invalidArguments` (§3.6.2). The description
    /// names only the JSON type and never echoes the client value
    /// (§3.6.1: "unstructured English text"; bd JMAP-zegc).
    #[test]
    fn query_anchor_args_does_not_echo_wrongly_typed_value() {
        for (name, args) in [
            ("anchor", json!({ "anchor": { "note": "CANARY-zegc" } })),
            (
                "anchorOffset",
                json!({ "anchorOffset": { "note": "CANARY-zegc" } }),
            ),
        ] {
            let err = query_anchor_args(args.as_object().expect("object"))
                .expect_err("wrongly typed argument must be rejected");
            assert_eq!(err.error_type.to_string(), "invalidArguments", "{name}");
            let desc = err.description.as_deref().unwrap_or_default();
            assert!(desc.starts_with(name), "{desc}");
            assert!(desc.contains("got object"), "{desc}");
            assert!(!desc.contains("CANARY"), "{desc}");
        }
    }
}