All files / http / unstable_structured_fields.ts

97.29% Branches 395/406
100.00% Functions 59/59
93.97% Lines 670/713
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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x21
 
x21
x21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x21
x142
x142
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x21
x27
x27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x21
x31
x31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x21
x61
x61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x21
x21
 
x9
x9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x21
x21
 
x35
x35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x21
x11
x11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x21
x21
 
x9
x9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x21
x21
x21
 
x59
x59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x21
x21
x21
 
x6
x6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x21
x7
x7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x21
x21
 
x6
x6
 
 
 
 
 
 
 
 
 
 
 
 
x21
x21
x21
x21
x21
x21
 
 
x21
x21
x21
x21
x21
 
 
x21
x184
x184
x184
x184
 
 
x21
x1437
x1437
x1437
 
 
x21
x577
x577
x577
 
 
x21
x258
x258
 
 
x21
x319
x319
x319
 
 
 
 
x21
x21
x21
x21
x21
x1617
x1617
x21
x21
 
 
x21
x21
x21
x21
x21
x21
x21
x21
x21
x21
 
 
x21
x154
x154
x154
 
 
x21
x48
x48
x48
x48
 
 
x21
x462
x462
x462
 
 
x21
x2410
x2410
 
 
x21
x4287
x4287
 
 
x21
x714
x714
 
 
x21
x261
x91
x91
x261
 
 
x21
x509
x70
x70
x509
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x21
x51
x51
x51
x51
 
 
 
 
 
x38
x51
 
x51
x51
 
x51
x90
x90
x90
x90
x36
x36
x90
x3
x3
 
x3
x43
x43
x90
x2
x2
 
x2
x90
 
x2
x51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x21
x54
x54
x54
x54
 
 
 
 
 
x41
x54
 
x54
x54
 
x54
x96
x96
 
x96
x79
x79
x96
 
x13
x13
x13
x13
x13
x13
 
x90
x90
x96
x39
x39
x94
x5
x5
 
x5
x46
x46
x94
x2
x2
 
x2
x96
 
x2
x54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x21
x124
x124
x124
x124
x124
x6
x6
 
x6
x58
x124
 
x169
x169
x27
x27
x142
x169
 
x27
 
 
 
 
 
 
x27
 
x27
x65
x65
x24
x24
x24
x24
x41
x41
 
x41
x65
x2
x2
 
x2
x65
 
x1
x1
 
x27
 
x307
x307
x307
x307
x307
 
x364
x364
 
x364
x193
x193
x355
x35
x35
x353
x16
x16
x353
x15
x15
x353
x8
x8
x353
x19
x19
x364
x68
x68
 
x10
x10
 
x364
 
x201
x201
x201
x201
x15
x15
x15
 
x201
x4
x4
 
x4
 
x197
x201
x424
x424
x197
x201
x3
x3
 
x3
 
x201
x34
x34
x2
x2
 
x2
 
x32
x34
x49
x49
x32
x34
x2
x2
 
x2
 
x34
x3
x3
 
x3
 
x27
x27
x27
 
x160
 
 
 
 
 
 
 
x160
x201
 
x35
 
 
 
 
 
 
x35
x35
 
 
x35
x35
x501
x501
 
x470
x501
x3
x3
 
x3
x467
x467
 
 
x35
x1
x1
 
 
x35
x26
x26
x26
 
 
x5
x5
 
x33
x17
 
x17
x7
x7
x2
x2
x2
x2
 
x2
x5
x17
x1
x10
 
x9
x9
x1
x1
x1
x1
 
x1
x8
x8
x17
 
x1
x1
 
x35
 
x68
x68
 
 
 
 
 
 
x68
x68
x68
x351
x351
x298
x351
x53
x53
x351
 
x68
x68
 
x16
 
 
 
 
 
 
x16
x16
 
 
x16
x154
x6
x6
 
x6
x148
x148
 
x16
x2
x2
 
x2
 
x8
x8
 
x8
x8
x8
x16
x2
x2
 
x2
x16
 
x15
 
 
 
 
 
 
x15
x15
x3
x3
x15
x3
x3
 
x9
x9
x9
x9
 
x15
 
x8
 
 
 
 
 
 
x8
x8
x1
x1
 
x1
 
x7
x7
x8
 
x19
 
 
 
 
 
x19
x3
x3
 
x3
 
x16
x19
x165
 
x165
 
x9
x9
x9
x9
x4
x4
 
x4
x165
 
x25
x25
x25
x3
x3
x3
x3
 
x3
x22
x156
 
 
 
 
 
x131
x131
x131
x131
x131
x131
x3
x3
x3
x3
 
x3
x128
x128
x165
 
x1
x1
 
x19
 
x168
x168
x5
x5
 
x5
 
x163
x163
x168
x106
x106
 
x163
x168
 
x280
x280
 
x280
x72
x72
x72
 
x72
x72
x57
x57
x72
x14
x14
 
x69
x69
 
x277
x280
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x21
x20
 
x20
x35
x6
x35
x29
x29
x35
 
x20
x20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x21
x28
 
x28
x47
 
x47
 
x4
x47
 
x40
 
x5
x40
x35
x35
x40
x47
 
x25
x28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x21
x43
x43
 
x10
x10
x10
x10
 
x125
x125
x125
 
x162
x162
x162
x84
x162
x16
x162
x13
x162
x39
x162
x1
x162
x5
x162
x2
x162
x2
x162
x162
 
x84
x84
x1
x1
x84
x2
x2
x81
x84
 
x16
x16
x2
x2
 
 
x14
x14
 
 
x14
x16
x2
x2
 
 
x12
 
 
x12
x16
x25
x25
 
x12
x16
x3
x3
 
x12
x16
 
x13
 
x13
x13
x105
x105
x2
x2
x105
x3
x3
x105
 
 
x13
x9
x9
 
 
x2
x2
x13
 
x39
x39
x1
x1
 
x38
x39
x1
x1
 
x39
x111
x111
x1
x1
x111
 
x36
x39
 
x1
x1
x1
 
x5
x5
x5
 
x2
x2
x2
x1
x1
 
 
 
x1
x2
 
x2
x2
 
x2
x2
x19
 
x1
x19
 
x1
x18
 
x15
x17
 
x2
x2
x19
x2
 
x2
x2
 
x127
x127
 
x127
x44
x44
x44
 
x44
x37
x37
x37
x44
 
x126
x127
 
x91
x91
x1
x1
 
x91
x2
x2
 
x91
x60
x1
x1
x60
x91





























































































































































































































































































































































































































































































































































































I



























































I

























































































I


























































































































I









I










































































I




















I






































I





















I

















I

















































































































































































































































































































































I




























































// Copyright 2018-2026 the Deno authors. MIT license.
// This module is browser compatible.

/**
 * Utilities for parsing and serializing
 * {@link https://www.rfc-editor.org/rfc/rfc9651 | RFC 9651} Structured Field Values for HTTP.
 *
 * Structured Fields provide a standardized way to define HTTP header and trailer
 * field values using common data types (Lists, Dictionaries, Items) with strict
 * parsing and serialization rules.
 *
 * @example Parsing a Dictionary (e.g., UCP-Agent header)
 * ```ts
 * import { isItem, parseDictionary } from "@std/http/unstable-structured-fields";
 * import { assertEquals } from "@std/assert";
 *
 * const header = 'profile="https://example.com/profile.json"';
 * const dict = parseDictionary(header);
 * const profile = dict.get("profile");
 *
 * if (profile && isItem(profile)) {
 *   assertEquals(profile.value, {
 *     type: "string",
 *     value: "https://example.com/profile.json",
 *   });
 * }
 * ```
 *
 * @example Serializing a Dictionary
 * ```ts
 * import { item, serializeDictionary, string } from "@std/http/unstable-structured-fields";
 * import { assertEquals } from "@std/assert";
 *
 * const dict = new Map([
 *   ["profile", item(string("https://example.com/profile.json"))],
 * ]);
 *
 * assertEquals(
 *   serializeDictionary(dict),
 *   'profile="https://example.com/profile.json"'
 * );
 * ```
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @module
 */

import { decodeBase64, encodeBase64 } from "@std/encoding/base64";

const UTF8_DECODER = new TextDecoder("utf-8", { fatal: true });
const UTF8_ENCODER = new TextEncoder();

// =============================================================================
// Type Definitions (RFC 9651 Section 3)
// =============================================================================

/**
 * A Bare Item value in a Structured Field.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @see {@link https://www.rfc-editor.org/rfc/rfc9651#section-3.3}
 */
export type BareItem =
  | { type: "integer"; value: number }
  | { type: "decimal"; value: number }
  | { type: "string"; value: string }
  | { type: "token"; value: string }
  | { type: "binary"; value: Uint8Array }
  | { type: "boolean"; value: boolean }
  | { type: "date"; value: Date }
  | { type: "displaystring"; value: string };

/**
 * Parameters attached to an Item or Inner List.
 *
 * Returned parameters are immutable. When building parameters for serialization,
 * you can pass a mutable `Map` as it is assignable to `ReadonlyMap`.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @see {@link https://www.rfc-editor.org/rfc/rfc9651#section-3.1.2}
 */
export type Parameters = ReadonlyMap<string, BareItem>;

/**
 * An Item in a Structured Field, consisting of a Bare Item and Parameters.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @see {@link https://www.rfc-editor.org/rfc/rfc9651#section-3.3}
 */
export interface Item {
  /** The bare item value. */
  value: BareItem;
  /** Parameters associated with this item. */
  parameters: Parameters;
}

/**
 * An Inner List in a Structured Field.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @see {@link https://www.rfc-editor.org/rfc/rfc9651#section-3.1.1}
 */
export interface InnerList {
  /** The items in the inner list. */
  items: Item[];
  /** Parameters associated with the inner list. */
  parameters: Parameters;
}

/**
 * A List Structured Field value.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @see {@link https://www.rfc-editor.org/rfc/rfc9651#section-3.1}
 */
export type List = Array<Item | InnerList>;

/**
 * A Dictionary Structured Field value.
 *
 * Returned dictionaries are immutable. When building dictionaries for serialization,
 * you can pass a mutable `Map` as it is assignable to `ReadonlyMap`.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @see {@link https://www.rfc-editor.org/rfc/rfc9651#section-3.2}
 */
export type Dictionary = ReadonlyMap<string, Item | InnerList>;

// =============================================================================
// Convenience Builders
// =============================================================================

/**
 * Creates an integer Bare Item.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @param value The integer value. Must be in the range -999999999999999 to
 * 999999999999999; validated during serialization.
 * @returns A Bare Item of type integer.
 *
 * @example Usage
 * ```ts
 * import { integer } from "@std/http/unstable-structured-fields";
 * import { assertEquals } from "@std/assert";
 *
 * assertEquals(integer(42), { type: "integer", value: 42 });
 * ```
 */
export function integer(value: number): Extract<BareItem, { type: "integer" }> {
  return { type: "integer", value };
}

/**
 * Creates a decimal Bare Item.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @param value The decimal value. Must be finite with an integer part of at
 * most 12 digits; validated during serialization.
 * @returns A Bare Item of type decimal.
 *
 * @example Usage
 * ```ts
 * import { decimal } from "@std/http/unstable-structured-fields";
 * import { assertEquals } from "@std/assert";
 *
 * assertEquals(decimal(3.14), { type: "decimal", value: 3.14 });
 * ```
 */
export function decimal(value: number): Extract<BareItem, { type: "decimal" }> {
  return { type: "decimal", value };
}

/**
 * Creates a string Bare Item.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @param value The string value. Must contain only ASCII printable characters
 * (0x20-0x7E); validated during serialization.
 * @returns A Bare Item of type string.
 *
 * @example Usage
 * ```ts
 * import { string } from "@std/http/unstable-structured-fields";
 * import { assertEquals } from "@std/assert";
 *
 * assertEquals(string("hello"), { type: "string", value: "hello" });
 * ```
 */
export function string(value: string): Extract<BareItem, { type: "string" }> {
  return { type: "string", value };
}

/**
 * Creates a token Bare Item.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @param value The token value. Must start with ALPHA or '*' and contain only
 * token characters; validated during serialization.
 * @returns A Bare Item of type token.
 *
 * @example Usage
 * ```ts
 * import { token } from "@std/http/unstable-structured-fields";
 * import { assertEquals } from "@std/assert";
 *
 * assertEquals(token("foo"), { type: "token", value: "foo" });
 * ```
 */
export function token(value: string): Extract<BareItem, { type: "token" }> {
  return { type: "token", value };
}

/**
 * Creates a binary Bare Item.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @param value The binary value as a Uint8Array.
 * @returns A Bare Item of type binary.
 *
 * @example Usage
 * ```ts
 * import { binary } from "@std/http/unstable-structured-fields";
 * import { assertEquals } from "@std/assert";
 *
 * const result = binary(new Uint8Array([1, 2, 3]));
 * assertEquals(result.type, "binary");
 * ```
 */
export function binary(
  value: Uint8Array,
): Extract<BareItem, { type: "binary" }> {
  return { type: "binary", value };
}

/**
 * Creates a boolean Bare Item.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @param value The boolean value.
 * @returns A Bare Item of type boolean.
 *
 * @example Usage
 * ```ts
 * import { boolean } from "@std/http/unstable-structured-fields";
 * import { assertEquals } from "@std/assert";
 *
 * assertEquals(boolean(true), { type: "boolean", value: true });
 * ```
 */
export function boolean(
  value: boolean,
): Extract<BareItem, { type: "boolean" }> {
  return { type: "boolean", value };
}

/**
 * Creates a date Bare Item.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @param value The date value. Must represent a valid date whose Unix timestamp
 * is in the integer range; validated during serialization.
 * @returns A Bare Item of type date.
 *
 * @example Usage
 * ```ts
 * import { date } from "@std/http/unstable-structured-fields";
 * import { assertEquals } from "@std/assert";
 *
 * const d = new Date("2022-08-04T00:00:00Z");
 * assertEquals(date(d), { type: "date", value: d });
 * ```
 */
export function date(value: Date): Extract<BareItem, { type: "date" }> {
  return { type: "date", value };
}

/**
 * Creates a display string Bare Item.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @param value The display string value (can contain Unicode).
 * @returns A Bare Item of type displaystring.
 *
 * @example Usage
 * ```ts
 * import { displayString } from "@std/http/unstable-structured-fields";
 * import { assertEquals } from "@std/assert";
 *
 * assertEquals(displayString("héllo"), { type: "displaystring", value: "héllo" });
 * ```
 */
export function displayString(
  value: string,
): Extract<BareItem, { type: "displaystring" }> {
  return { type: "displaystring", value };
}

/**
 * Creates an Item from a Bare Item and optional Parameters.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @param value The Bare Item value.
 * @param parameters Optional parameters as a `Map` or iterable of key-value pairs.
 * @returns An Item with the given value and parameters.
 *
 * @example Usage
 * ```ts
 * import { item, integer, token } from "@std/http/unstable-structured-fields";
 * import { assertEquals } from "@std/assert";
 *
 * assertEquals(item(integer(42)), {
 *   value: { type: "integer", value: 42 },
 *   parameters: new Map(),
 * });
 *
 * assertEquals(item(integer(42), [["q", token("fast")]]), {
 *   value: { type: "integer", value: 42 },
 *   parameters: new Map([["q", token("fast")]]),
 * });
 * ```
 */
export function item(
  value: BareItem,
  parameters?: Iterable<[string, BareItem]>,
): Item {
  return { value, parameters: new Map(parameters) };
}

/**
 * Creates an Inner List from Items and optional Parameters.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @param items The items in the inner list.
 * @param parameters Optional parameters as a `Map` or iterable of key-value pairs.
 * @returns An InnerList with the given items and parameters.
 *
 * @example Usage
 * ```ts
 * import { innerList, item, integer } from "@std/http/unstable-structured-fields";
 * import { assertEquals } from "@std/assert";
 *
 * const list = innerList([item(integer(1)), item(integer(2))]);
 *
 * assertEquals(list.items.length, 2);
 * assertEquals(list.parameters.size, 0);
 * ```
 */
export function innerList(
  items: Item[],
  parameters?: Iterable<[string, BareItem]>,
): InnerList {
  return { items, parameters: new Map(parameters) };
}

// =============================================================================
// Type Guards
// =============================================================================

/**
 * Checks if a list member is an Item (not an Inner List).
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @param member The list member to check.
 * @returns `true` if the member is an Item, `false` if it's an Inner List.
 *
 * @example Usage
 * ```ts
 * import { parseList, isItem } from "@std/http/unstable-structured-fields";
 * import { assert } from "@std/assert";
 *
 * const list = parseList("1, (2 3)");
 * assert(isItem(list[0]!));   // true - integer item
 * assert(!isItem(list[1]!));  // false - inner list
 * ```
 */
export function isItem(member: Item | InnerList): member is Item {
  return !("items" in member);
}

/**
 * Checks if a list member is an Inner List.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @param member The list member to check.
 * @returns `true` if the member is an Inner List, `false` if it's an Item.
 *
 * @example Usage
 * ```ts
 * import { parseList, isInnerList } from "@std/http/unstable-structured-fields";
 * import { assert } from "@std/assert";
 *
 * const list = parseList("1, (2 3)");
 * assert(!isInnerList(list[0]!)); // false - integer item
 * assert(isInnerList(list[1]!));  // true - inner list
 * ```
 */
export function isInnerList(
  member: Item | InnerList,
): member is InnerList {
  return "items" in member;
}

// =============================================================================
// Parsing (RFC 9651 Section 4.2)
// =============================================================================

/** Parser state holding input string and current position. */
interface ParserState {
  input: string;
  pos: number;
}

// Character code constants for ASCII ranges
const CHAR_CODE_0 = 48; // '0'
const CHAR_CODE_9 = 57; // '9'
const CHAR_CODE_UPPER_A = 65; // 'A'
const CHAR_CODE_UPPER_Z = 90; // 'Z'
const CHAR_CODE_LOWER_A = 97; // 'a'
const CHAR_CODE_LOWER_Z = 122; // 'z'

// RFC 9651 numeric limits
const MAX_INTEGER_DIGITS = 15;
const MAX_INTEGER = 999_999_999_999_999;
const MAX_DECIMAL_INTEGER_DIGITS = 12;
const MAX_DECIMAL_FRACTIONAL_DIGITS = 3;
const MAX_DECIMAL_INTEGER_PART = 999_999_999_999;

/** Check if character is alphabetic (A-Z or a-z) */
function isAlpha(c: string): boolean {
  const code = c.charCodeAt(0);
  return (code >= CHAR_CODE_UPPER_A && code <= CHAR_CODE_UPPER_Z) ||
    (code >= CHAR_CODE_LOWER_A && code <= CHAR_CODE_LOWER_Z);
}

/** Check if character is a digit (0-9) */
function isDigit(c: string): boolean {
  const code = c.charCodeAt(0);
  return code >= CHAR_CODE_0 && code <= CHAR_CODE_9;
}

/** Check if character is lowercase alphabetic (a-z) */
function isLcalpha(c: string): boolean {
  const code = c.charCodeAt(0);
  return code >= CHAR_CODE_LOWER_A && code <= CHAR_CODE_LOWER_Z;
}

/** Check if character is valid at the start of a key (lcalpha or "*") */
function isKeyStart(c: string): boolean {
  return isLcalpha(c) || c === "*";
}

/** Check if character is valid within a key (lcalpha / DIGIT / "_" / "-" / "." / "*") */
function isKeyChar(c: string): boolean {
  return isLcalpha(c) || isDigit(c) || c === "_" || c === "-" || c === "." ||
    c === "*";
}

// Pre-computed lookup table for tchar (RFC 9110 token characters)
// tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." /
//         "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA
const TCHAR_LOOKUP: boolean[] = (() => {
  const table: boolean[] = new Array(128).fill(false);
  const tchars = "!#$%&'*+-.^_`|~0123456789" +
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  for (const c of tchars) {
    table[c.charCodeAt(0)] = true;
  }
  return table;
})();

// Pre-computed lookup table for base64 characters (A-Z, a-z, 0-9, +, /, =)
const BASE64_LOOKUP: boolean[] = (() => {
  const table: boolean[] = new Array(128).fill(false);
  for (let i = CHAR_CODE_UPPER_A; i <= CHAR_CODE_UPPER_Z; i++) table[i] = true;
  for (let i = CHAR_CODE_LOWER_A; i <= CHAR_CODE_LOWER_Z; i++) table[i] = true;
  for (let i = CHAR_CODE_0; i <= CHAR_CODE_9; i++) table[i] = true;
  table[43] = true; // +
  table[47] = true; // /
  table[61] = true; // =
  return table;
})();

/** Check if character is a valid base64 character */
function isBase64Char(c: string): boolean {
  const code = c.charCodeAt(0);
  return code < 128 && BASE64_LOOKUP[code]!;
}

/** Check if character is a lowercase hex digit (0-9, a-f) */
function isLcHexDigit(c: string): boolean {
  const code = c.charCodeAt(0);
  return (code >= CHAR_CODE_0 && code <= CHAR_CODE_9) ||
    (code >= CHAR_CODE_LOWER_A && code <= 102); // 'f' = 102
}

/** RFC 9110 tchar: token characters */
function isTchar(c: string): boolean {
  const code = c.charCodeAt(0);
  return code < 128 && TCHAR_LOOKUP[code]!;
}

/** Check if at end of input */
function isEof(state: ParserState): boolean {
  return state.pos >= state.input.length;
}

/** Peek current character */
function peek(state: ParserState): string {
  return state.input[state.pos] ?? "";
}

/** Consume current character and advance */
function consume(state: ParserState): string {
  return state.input[state.pos++] ?? "";
}

/** Skip optional whitespace (SP or HTAB) */
function skipOWS(state: ParserState): void {
  while (!isEof(state) && (peek(state) === " " || peek(state) === "\t")) {
    state.pos++;
  }
}

/** Skip required whitespace (at least one SP) */
function skipSP(state: ParserState): void {
  while (!isEof(state) && peek(state) === " ") {
    state.pos++;
  }
}

/**
 * Parses a List Structured Field value.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @param input The string to parse.
 * @returns The parsed List.
 * @throws {SyntaxError} If the input is invalid.
 *
 * @see {@link https://www.rfc-editor.org/rfc/rfc9651#section-4.2.1}
 *
 * @example Usage
 * ```ts
 * import { parseList } from "@std/http/unstable-structured-fields";
 * import { assertEquals } from "@std/assert";
 *
 * const list = parseList("1, 42");
 * assertEquals(list.length, 2);
 * ```
 */
export function parseList(input: string): List {
  const state: ParserState = { input, pos: 0 };
  skipSP(state);
  const list = parseListInternal(state);
  skipSP(state);
  if (!isEof(state)) {
    throw new SyntaxError(
      `Invalid structured field: unexpected character at position ${state.pos}`,
    );
  }
  return list;
}

function parseListInternal(state: ParserState): List {
  const members: List = [];

  while (!isEof(state)) {
    const member = parseItemOrInnerList(state);
    members.push(member);
    skipOWS(state);
    if (isEof(state)) {
      return members;
    }
    if (peek(state) !== ",") {
      throw new SyntaxError(
        `Invalid structured field: expected ',' at position ${state.pos}`,
      );
    }
    consume(state); // consume ','
    skipOWS(state);
    if (isEof(state)) {
      throw new SyntaxError(
        "Invalid structured field: trailing comma in list",
      );
    }
  }

  return members;
}

/**
 * Parses a Dictionary Structured Field value.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @param input The string to parse.
 * @returns The parsed Dictionary.
 * @throws {SyntaxError} If the input is invalid.
 *
 * @see {@link https://www.rfc-editor.org/rfc/rfc9651#section-4.2.2}
 *
 * @example Usage
 * ```ts
 * import { parseDictionary } from "@std/http/unstable-structured-fields";
 * import { assertEquals } from "@std/assert";
 *
 * const dict = parseDictionary('profile="https://example.com"');
 * assertEquals(dict.has("profile"), true);
 * ```
 */
export function parseDictionary(input: string): Dictionary {
  const state: ParserState = { input, pos: 0 };
  skipSP(state);
  const dict = parseDictionaryInternal(state);
  skipSP(state);
  if (!isEof(state)) {
    throw new SyntaxError(
      `Invalid structured field: unexpected character at position ${state.pos}`,
    );
  }
  return dict;
}

function parseDictionaryInternal(state: ParserState): Dictionary {
  const dict: Map<string, Item | InnerList> = new Map();

  while (!isEof(state)) {
    const key = parseKey(state);
    let member: Item | InnerList;

    if (peek(state) === "=") {
      consume(state); // consume '='
      member = parseItemOrInnerList(state);
    } else {
      // Bare key means boolean true with parameters
      const parameters = parseParameters(state);
      member = {
        value: { type: "boolean", value: true },
        parameters,
      };
    }

    dict.set(key, member);
    skipOWS(state);
    if (isEof(state)) {
      return dict;
    }
    if (peek(state) !== ",") {
      throw new SyntaxError(
        `Invalid structured field: expected ',' at position ${state.pos}`,
      );
    }
    consume(state); // consume ','
    skipOWS(state);
    if (isEof(state)) {
      throw new SyntaxError(
        "Invalid structured field: trailing comma in dictionary",
      );
    }
  }

  return dict;
}

/**
 * Parses an Item Structured Field value.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @param input The string to parse.
 * @returns The parsed Item.
 * @throws {SyntaxError} If the input is invalid.
 *
 * @see {@link https://www.rfc-editor.org/rfc/rfc9651#section-4.2.3}
 *
 * @example Usage
 * ```ts
 * import { parseItem } from "@std/http/unstable-structured-fields";
 * import { assertEquals } from "@std/assert";
 *
 * const item = parseItem("42");
 * assertEquals(item.value, { type: "integer", value: 42 });
 * ```
 */
export function parseItem(input: string): Item {
  const state: ParserState = { input, pos: 0 };
  skipSP(state);
  const item = parseItemInternal(state);
  skipSP(state);
  if (!isEof(state)) {
    throw new SyntaxError(
      `Invalid structured field: unexpected character at position ${state.pos}`,
    );
  }
  return item;
}

function parseItemOrInnerList(state: ParserState): Item | InnerList {
  if (peek(state) === "(") {
    return parseInnerList(state);
  }
  return parseItemInternal(state);
}

function parseInnerList(state: ParserState): InnerList {
  if (consume(state) !== "(") {
    throw new SyntaxError(
      `Invalid structured field: expected '(' at position ${state.pos - 1}`,
    );
  }

  const items: Item[] = [];

  while (!isEof(state)) {
    skipSP(state);
    if (peek(state) === ")") {
      consume(state);
      const parameters = parseParameters(state);
      return { items, parameters };
    }
    const item = parseItemInternal(state);
    items.push(item);

    const c = peek(state);
    if (c !== " " && c !== ")") {
      throw new SyntaxError(
        `Invalid structured field: expected SP or ')' at position ${state.pos}`,
      );
    }
  }

  throw new SyntaxError(
    "Invalid structured field: unterminated inner list",
  );
}

function parseItemInternal(state: ParserState): Item {
  const value = parseBareItem(state);
  const parameters = parseParameters(state);
  return { value, parameters };
}

function parseBareItem(state: ParserState): BareItem {
  const c = peek(state);

  if (c === "-" || isDigit(c)) {
    return parseIntegerOrDecimal(state);
  }
  if (c === '"') {
    return parseString(state);
  }
  if (c === ":") {
    return parseBinary(state);
  }
  if (c === "?") {
    return parseBoolean(state);
  }
  if (c === "@") {
    return parseDate(state);
  }
  if (c === "%") {
    return parseDisplayString(state);
  }
  if (isAlpha(c) || c === "*") {
    return parseToken(state);
  }

  throw new SyntaxError(
    `Invalid structured field: unexpected character '${c}' at position ${state.pos}`,
  );
}

function parseIntegerOrDecimal(state: ParserState): BareItem {
  const { input } = state;
  let sign = 1;
  if (peek(state) === "-") {
    state.pos++;
    sign = -1;
  }

  if (!isDigit(peek(state))) {
    throw new SyntaxError(
      `Invalid structured field: expected digit at position ${state.pos}`,
    );
  }

  const intStart = state.pos;
  while (isDigit(peek(state))) {
    state.pos++;
  }
  const intLen = state.pos - intStart;
  if (intLen > MAX_INTEGER_DIGITS) {
    throw new SyntaxError(
      "Invalid structured field: integer too long",
    );
  }

  if (peek(state) === ".") {
    state.pos++; // consume '.'
    if (intLen > MAX_DECIMAL_INTEGER_DIGITS) {
      throw new SyntaxError(
        "Invalid structured field: decimal integer part too long",
      );
    }

    const fracStart = state.pos;
    while (isDigit(peek(state))) {
      state.pos++;
    }
    const fracLen = state.pos - fracStart;
    if (fracLen > MAX_DECIMAL_FRACTIONAL_DIGITS) {
      throw new SyntaxError(
        "Invalid structured field: decimal fractional part too long",
      );
    }

    if (fracLen === 0) {
      throw new SyntaxError(
        "Invalid structured field: decimal requires fractional digits",
      );
    }

    const value = sign * parseFloat(input.slice(intStart, state.pos));
    return { type: "decimal", value };
  }

  const value = sign * parseInt(input.slice(intStart, state.pos), 10);

  if (value < -MAX_INTEGER || value > MAX_INTEGER) {
    throw new SyntaxError(
      "Invalid structured field: integer out of range",
    );
  }

  return { type: "integer", value };
}

function parseString(state: ParserState): BareItem {
  if (consume(state) !== '"') {
    throw new SyntaxError(
      `Invalid structured field: expected '"' at position ${state.pos - 1}`,
    );
  }

  const { input } = state;
  const startPos = state.pos;

  // Fast path: find first special character (\ or ")
  let firstSpecial = startPos;
  while (firstSpecial < input.length) {
    const c = input[firstSpecial]!;
    if (c === '"' || c === "\\") break;
    // Validate printable ASCII
    const code = c.charCodeAt(0);
    if (code < 0x20 || code > 0x7e) {
      throw new SyntaxError(
        `Invalid structured field: invalid character in string at position ${firstSpecial}`,
      );
    }
    firstSpecial++;
  }

  // If we hit end of string without finding closing quote
  if (firstSpecial >= input.length) {
    throw new SyntaxError("Invalid structured field: unterminated string");
  }

  // Fast path: no escapes, just a closing quote
  if (input[firstSpecial] === '"') {
    state.pos = firstSpecial + 1;
    return { type: "string", value: input.slice(startPos, firstSpecial) };
  }

  // Slow path: has escapes, need to process character by character
  let value = input.slice(startPos, firstSpecial);
  state.pos = firstSpecial;

  while (!isEof(state)) {
    const c = consume(state);

    if (c === "\\") {
      const escaped = consume(state);
      if (escaped !== '"' && escaped !== "\\") {
        throw new SyntaxError(
          `Invalid structured field: invalid escape sequence at position ${
            state.pos - 1
          }`,
        );
      }
      value += escaped;
    } else if (c === '"') {
      return { type: "string", value };
    } else {
      // Must be printable ASCII (0x20-0x7E) excluding 0x22 (") and 0x5C (\)
      const code = c.charCodeAt(0);
      if (code < 0x20 || code > 0x7e) {
        throw new SyntaxError(
          `Invalid structured field: invalid character in string at position ${
            state.pos - 1
          }`,
        );
      }
      value += c;
    }
  }

  throw new SyntaxError(
    "Invalid structured field: unterminated string",
  );
}

function parseToken(state: ParserState): BareItem {
  const first = peek(state);
  if (!isAlpha(first) && first !== "*") {
    throw new SyntaxError(
      `Invalid structured field: invalid token start at position ${state.pos}`,
    );
  }

  const startPos = state.pos;
  state.pos++; // Skip validated first char
  while (!isEof(state)) {
    const c = peek(state);
    if (isTchar(c) || c === ":" || c === "/") {
      state.pos++;
    } else {
      break;
    }
  }

  return { type: "token", value: state.input.slice(startPos, state.pos) };
}

function parseBinary(state: ParserState): BareItem {
  if (consume(state) !== ":") {
    throw new SyntaxError(
      `Invalid structured field: expected ':' at position ${state.pos - 1}`,
    );
  }

  const { input } = state;
  const startPos = state.pos;

  // Find the closing colon while validating base64 characters
  while (state.pos < input.length && input[state.pos] !== ":") {
    if (!isBase64Char(input[state.pos]!)) {
      throw new SyntaxError(
        `Invalid structured field: invalid base64 character at position ${state.pos}`,
      );
    }
    state.pos++;
  }

  if (state.pos >= input.length) {
    throw new SyntaxError(
      "Invalid structured field: unterminated binary",
    );
  }

  const base64 = input.slice(startPos, state.pos);
  state.pos++; // consume closing ':'

  try {
    const value = decodeBase64(base64);
    return { type: "binary", value };
  } catch {
    throw new SyntaxError(
      "Invalid structured field: invalid base64 encoding",
    );
  }
}

function parseBoolean(state: ParserState): BareItem {
  if (consume(state) !== "?") {
    throw new SyntaxError(
      `Invalid structured field: expected '?' at position ${state.pos - 1}`,
    );
  }

  const c = consume(state);
  if (c === "1") {
    return { type: "boolean", value: true };
  }
  if (c === "0") {
    return { type: "boolean", value: false };
  }

  throw new SyntaxError(
    `Invalid structured field: expected '0' or '1' at position ${
      state.pos - 1
    }`,
  );
}

function parseDate(state: ParserState): BareItem {
  if (consume(state) !== "@") {
    throw new SyntaxError(
      `Invalid structured field: expected '@' at position ${state.pos - 1}`,
    );
  }

  const intItem = parseIntegerOrDecimal(state);
  if (intItem.type !== "integer") {
    throw new SyntaxError(
      "Invalid structured field: date must be an integer",
    );
  }

  const value = new Date(intItem.value * 1000);
  return { type: "date", value };
}

function parseDisplayString(state: ParserState): BareItem {
  if (consume(state) !== "%") {
    throw new SyntaxError(
      `Invalid structured field: expected '%' at position ${state.pos - 1}`,
    );
  }
  if (consume(state) !== '"') {
    throw new SyntaxError(
      `Invalid structured field: expected '"' at position ${state.pos - 1}`,
    );
  }

  const bytes: number[] = [];
  while (!isEof(state)) {
    const c = consume(state);

    if (c === '"') {
      // Decode UTF-8 bytes to string
      try {
        const value = UTF8_DECODER.decode(new Uint8Array(bytes));
        return { type: "displaystring", value };
      } catch {
        throw new SyntaxError(
          "Invalid structured field: invalid UTF-8 in display string",
        );
      }
    } else if (c === "%") {
      // Percent-encoded byte
      const hex1 = consume(state);
      const hex2 = consume(state);
      if (!isLcHexDigit(hex1) || !isLcHexDigit(hex2)) {
        throw new SyntaxError(
          `Invalid structured field: invalid percent encoding at position ${
            state.pos - 2
          }`,
        );
      }
      bytes.push(parseInt(hex1 + hex2, 16));
    } else {
      // Must be allowed unescaped character per RFC 9651:
      // unescaped = %x20-21 / %x23-24 / %x26-5B / %x5D-7E
      // (space, !, #, $, &-[, ]-~)
      // Note: " (0x22) and % (0x25) must be percent-encoded
      // Note: Per conformance tests, \ (0x5C) is also allowed
      const code = c.charCodeAt(0);
      const isAllowed = code === 0x20 || code === 0x21 || // space, !
        code === 0x23 || code === 0x24 || // #, $
        (code >= 0x26 && code <= 0x5b) || // &-[
        (code >= 0x5c && code <= 0x7e); // \-~ (includes \ per conformance tests)
      if (!isAllowed) {
        throw new SyntaxError(
          `Invalid structured field: invalid character in display string at position ${
            state.pos - 1
          }`,
        );
      }
      bytes.push(code);
    }
  }

  throw new SyntaxError(
    "Invalid structured field: unterminated display string",
  );
}

function parseKey(state: ParserState): string {
  if (!isKeyStart(peek(state))) {
    throw new SyntaxError(
      `Invalid structured field: invalid key start at position ${state.pos}`,
    );
  }

  const startPos = state.pos;
  state.pos++; // Skip validated first char
  while (!isEof(state) && isKeyChar(peek(state))) {
    state.pos++;
  }

  return state.input.slice(startPos, state.pos);
}

function parseParameters(state: ParserState): Parameters {
  const parameters: Map<string, BareItem> = new Map();

  while (peek(state) === ";") {
    consume(state); // consume ';'
    skipSP(state);
    const key = parseKey(state);

    let value: BareItem;
    if (peek(state) === "=") {
      consume(state); // consume '='
      value = parseBareItem(state);
    } else {
      value = { type: "boolean", value: true };
    }

    parameters.set(key, value);
  }

  return parameters;
}

// =============================================================================
// Serialization (RFC 9651 Section 4.1)
// =============================================================================

/**
 * Serializes a List to a string.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @param list The List to serialize.
 * @returns The serialized string.
 * @throws {TypeError} If the list contains invalid values.
 *
 * @see {@link https://www.rfc-editor.org/rfc/rfc9651#section-4.1.1}
 *
 * @example Usage
 * ```ts
 * import { item, serializeList, integer } from "@std/http/unstable-structured-fields";
 * import { assertEquals } from "@std/assert";
 *
 * const list = [item(integer(1)), item(integer(42))];
 *
 * assertEquals(serializeList(list), "1, 42");
 * ```
 */
export function serializeList(list: List): string {
  const parts: string[] = [];

  for (const member of list) {
    if ("items" in member) {
      parts.push(serializeInnerList(member));
    } else {
      parts.push(serializeItemInternal(member));
    }
  }

  return parts.join(", ");
}

/**
 * Serializes a Dictionary to a string.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @param dict The Dictionary to serialize.
 * @returns The serialized string.
 * @throws {TypeError} If the dictionary contains invalid values.
 *
 * @see {@link https://www.rfc-editor.org/rfc/rfc9651#section-4.1.2}
 *
 * @example Usage
 * ```ts
 * import { item, serializeDictionary, string } from "@std/http/unstable-structured-fields";
 * import { assertEquals } from "@std/assert";
 *
 * const dict = new Map([
 *   ["key", item(string("value"))],
 * ]);
 *
 * assertEquals(serializeDictionary(dict), 'key="value"');
 * ```
 */
export function serializeDictionary(dict: Dictionary): string {
  const parts: string[] = [];

  for (const [key, member] of dict) {
    validateKey(key);

    if ("items" in member) {
      // Inner list
      parts.push(`${key}=${serializeInnerList(member)}`);
    } else {
      // Item
      if (member.value.type === "boolean" && member.value.value === true) {
        // Omit =?1 for true boolean
        parts.push(key + serializeParameters(member.parameters));
      } else {
        parts.push(`${key}=${serializeItemInternal(member)}`);
      }
    }
  }

  return parts.join(", ");
}

/**
 * Serializes an Item to a string.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @param value The Item to serialize.
 * @returns The serialized string.
 * @throws {TypeError} If the item contains invalid values.
 *
 * @see {@link https://www.rfc-editor.org/rfc/rfc9651#section-4.1.3}
 *
 * @example Usage
 * ```ts
 * import { item, serializeItem, integer } from "@std/http/unstable-structured-fields";
 * import { assertEquals } from "@std/assert";
 *
 * assertEquals(serializeItem(item(integer(42))), "42");
 * ```
 */
export function serializeItem(value: Item): string {
  return serializeItemInternal(value);
}

function serializeInnerList(innerList: InnerList): string {
  const items = innerList.items.map(serializeItemInternal).join(" ");
  return `(${items})${serializeParameters(innerList.parameters)}`;
}

function serializeItemInternal(item: Item): string {
  return serializeBareItem(item.value) + serializeParameters(item.parameters);
}

function serializeBareItem(bareItem: BareItem): string {
  switch (bareItem.type) {
    case "integer":
      return serializeInteger(bareItem.value);
    case "decimal":
      return serializeDecimal(bareItem.value);
    case "string":
      return serializeString(bareItem.value);
    case "token":
      return serializeToken(bareItem.value);
    case "binary":
      return serializeBinary(bareItem.value);
    case "boolean":
      return serializeBoolean(bareItem.value);
    case "date":
      return serializeDate(bareItem.value);
    case "displaystring":
      return serializeDisplayString(bareItem.value);
  }
}

function serializeInteger(value: number): string {
  if (!Number.isInteger(value)) {
    throw new TypeError("Integer must be a whole number");
  }
  if (value < -MAX_INTEGER || value > MAX_INTEGER) {
    throw new TypeError("Integer out of range");
  }
  return String(value);
}

function serializeDecimal(value: number): string {
  if (!Number.isFinite(value)) {
    throw new TypeError("Decimal must be finite");
  }

  // Round to MAX_DECIMAL_FRACTIONAL_DIGITS decimal places
  const scale = 10 ** MAX_DECIMAL_FRACTIONAL_DIGITS;
  const rounded = Math.round(value * scale) / scale;

  // Check integer part (max MAX_DECIMAL_INTEGER_DIGITS digits)
  const intPart = Math.trunc(Math.abs(rounded));
  if (intPart > MAX_DECIMAL_INTEGER_PART) {
    throw new TypeError("Decimal integer part too large");
  }

  // Format with MAX_DECIMAL_FRACTIONAL_DIGITS fractional digits
  const str = rounded.toFixed(MAX_DECIMAL_FRACTIONAL_DIGITS);

  // Remove trailing zeros but keep at least one digit after decimal
  let end = str.length;
  while (end > 0 && str[end - 1] === "0") {
    end--;
  }
  // Keep at least one digit after decimal point
  const dotIndex = str.indexOf(".");
  if (end <= dotIndex + 1) {
    end = dotIndex + 2;
  }

  return str.slice(0, end);
}

function serializeString(value: string): string {
  // Validate ASCII printable and check if escaping needed
  let needsEscape = false;
  for (let i = 0; i < value.length; i++) {
    const code = value.charCodeAt(i);
    if (code < 0x20 || code > 0x7e) {
      throw new TypeError(`Invalid character in string at position ${i}`);
    }
    if (code === 0x22 || code === 0x5c) { // " or \
      needsEscape = true;
    }
  }

  // Fast path: no escaping needed
  if (!needsEscape) {
    return `"${value}"`;
  }

  // Slow path: escape \ and "
  const escaped = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
  return `"${escaped}"`;
}

function serializeToken(value: string): string {
  if (value.length === 0) {
    throw new TypeError("Token cannot be empty");
  }

  const first = value[0]!;
  if (!isAlpha(first) && first !== "*") {
    throw new TypeError("Token must start with ALPHA or '*'");
  }

  for (let i = 1; i < value.length; i++) {
    const c = value[i]!;
    if (!isTchar(c) && c !== ":" && c !== "/") {
      throw new TypeError(`Invalid character in token at position ${i}`);
    }
  }

  return value;
}

function serializeBinary(value: Uint8Array): string {
  return `:${encodeBase64(value)}:`;
}

function serializeBoolean(value: boolean): string {
  return value ? "?1" : "?0";
}

function serializeDate(value: Date): string {
  const timestamp = Math.floor(value.getTime() / 1000);
  if (!Number.isFinite(timestamp)) {
    throw new TypeError("Invalid date");
  }
  if (timestamp < -MAX_INTEGER || timestamp > MAX_INTEGER) {
    throw new TypeError("Date out of range");
  }
  return `@${timestamp}`;
}

function serializeDisplayString(value: string): string {
  const bytes = UTF8_ENCODER.encode(value);

  let result = '%"';
  for (const byte of bytes) {
    if (byte === 0x25) {
      // % -> %25
      result += "%25";
    } else if (byte === 0x22) {
      // " -> %22
      result += "%22";
    } else if (byte >= 0x20 && byte <= 0x7e) {
      // Printable ASCII
      result += String.fromCharCode(byte);
    } else {
      // Percent-encode non-ASCII
      result += "%" + byte.toString(16).padStart(2, "0");
    }
  }
  result += '"';

  return result;
}

function serializeParameters(parameters: Parameters): string {
  let result = "";

  for (const [key, value] of parameters) {
    validateKey(key);
    result += ";";
    result += key;

    if (value.type !== "boolean" || value.value !== true) {
      result += "=";
      result += serializeBareItem(value);
    }
  }

  return result;
}

function validateKey(key: string): void {
  if (key.length === 0) {
    throw new TypeError("Key cannot be empty");
  }

  if (!isKeyStart(key[0]!)) {
    throw new TypeError("Key must start with lowercase letter or '*'");
  }

  for (let i = 1; i < key.length; i++) {
    if (!isKeyChar(key[i]!)) {
      throw new TypeError(`Invalid character in key at position ${i}`);
    }
  }
}