-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.js
1921 lines (1808 loc) · 60.6 KB
/
index.js
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
;`use strict`
/**
* Tagged Template Literal for Error message
* @param {TemplateStringsArray} strings
* @param {...any} keys
* @returns string
*/
function err(strings, ...keys) {
keys = keys.map((key) => {
if (Array.isArray(key)) return JSON.stringify(key)
if (key instanceof Map) return `Map{}`
if (key instanceof Set) return `Set{}`
if (typeof key === `object`) return JSON.stringify(key)
return String(key)
})
const result = strings.map((string, i) => {
return [string, keys.at(i)]
})
return result.flat().join(``)
}
export class Item {
/**
* @param {BareItem} value
* @param {Parameters} params
*/
constructor(value, params = null) {
this.value = value
this.params = params
}
}
export class InnerList {
/**
* @param {ItemList} value
* @param {Parameters} params
*/
constructor(value, params = null) {
this.value = value
this.params = params
}
}
/////////////////////////
// public interface
/////////////////////////
// 4.1. Serializing Structured Fields
//
// 1. If the structure is a Dictionary or List and its value is empty
// (i.e., it has no members), do not serialize the field at all
// (i.e., omit both the field-name and field-value).
//
// 2. If the structure is a List, let output_string be the result of
// running Serializing a List (Section 4.1.1) with the structure.
//
// 3. Else if the structure is a Dictionary, let output_string be the
// result of running Serializing a Dictionary (Section 4.1.2) with
// the structure.
//
// 4. Else if the structure is an Item, let output_string be the result
// of running Serializing an Item (Section 4.1.3) with the
// structure.
//
// 5. Else, fail serialization.
//
// 6. Return output_string converted into an array of bytes, using
// ASCII encoding [RFC0020].
/**
* @param {Item|BareItem} value
* @returns {string}
*/
export function encodeItem(value) {
return serializeItem(value)
}
/**
* @param {MemberList} value
* @returns {string}
*/
export function encodeList(value) {
return serializeList(value)
}
/**
* @param {Dictionary} value
* @returns {string}
*/
export function encodeDict(value) {
return serializeDict(value)
}
// 4.2. Parsing Structured Fields
//
// 1. Convert input_bytes into an ASCII string input_string; if
// conversion fails, fail parsing.
//
// 2. Discard any leading SP characters from input_string.
//
// 3. If field_type is "list", let output be the result of running
// Parsing a List (Section 4.2.1) with input_string.
//
// 4. If field_type is "dictionary", let output be the result of
// running Parsing a Dictionary (Section 4.2.2) with input_string.
//
// 5. If field_type is "item", let output be the result of running
// Parsing an Item (Section 4.2.3) with input_string.
//
// 6. Discard any leading SP characters from input_string.
//
// 7. If input_string is not empty, fail parsing.
//
// 8. Otherwise, return output.
/**
* @param {string} input
* @returns {Item}
*/
export function decodeItem(input) {
try {
// 2. Discard any leading SP characters from input_string.
input = leadingSP(input)
let { input_string, value } = parseItem(input)
// 6. Discard any leading SP characters from input_string.
input_string = leadingSP(input_string)
if (input_string !== ``) throw new Error(err`failed to parse "${input_string}" as Item`)
return value
} catch (cause) {
throw new Error(err`failed to parse "${input}" as Item`, { cause })
}
}
/**
* @param {string} input
* @returns {MemberList}
*/
export function decodeList(input) {
try {
// 2. Discard any leading SP characters from input_string.
input = leadingSP(input)
let { input_string, value } = parseList(input)
// 6. Discard any leading SP characters from input_string.
input_string = leadingSP(input_string)
if (input_string !== ``) throw new Error(err`failed to parse "${input_string}" as List`)
return value
} catch (cause) {
throw new Error(err`failed to parse "${input}" as List`, { cause })
}
}
/**
* @param {string} input
* @returns {Dictionary}
*/
export function decodeDict(input) {
try {
// 2. Discard any leading SP characters from input_string.
input = leadingSP(input)
let { input_string, value } = parseDictionary(input)
// 6. Discard any leading SP characters from input_string.
input_string = leadingSP(input_string)
if (input_string !== ``) throw new Error(err`failed to parse "${input_string}" as Dict`)
return Object.fromEntries(value)
} catch (cause) {
throw new Error(err`failed to parse "${input}" as Dict`, { cause })
}
}
/**
* @param {string} input
* @returns {Dictionary}
*/
export function decodeMap(input) {
try {
// 2. Discard any leading SP characters from input_string.
input = leadingSP(input)
let { input_string, value } = parseDictionary(input)
// 6. Discard any leading SP characters from input_string.
input_string = leadingSP(input_string)
if (input_string !== ``) throw new Error(err`failed to parse "${input_string}" as Dict`)
return new Map(value)
} catch (cause) {
throw new Error(err`failed to parse "${input}" as Dict`, { cause })
}
}
// 4.1.1. Serializing a List
//
// Given an array of (member_value, parameters) tuples as input_list,
// return an ASCII string suitable for use in a HTTP field value.
//
// 1. Let output be an empty string.
//
// 2. For each (member_value, parameters) of input_list:
//
// 1. If member_value is an array, append the result of running
// Serializing an Inner List (Section 4.1.1.1) with
// (member_value, parameters) to output.
//
// 2. Otherwise, append the result of running Serializing an Item
// (Section 4.1.3) with (member_value, parameters) to output.
//
// 3. If more member_values remain in input_list:
//
// 1. Append "," to output.
//
// 2. Append a single SP to output.
//
// 3. Return output.
/**
* @param {MemberList} list
* @return {string}
*/
export function serializeList(list) {
if (Array.isArray(list) === false) throw new Error(err`failed to serialize "${list}" as List`)
return list
.map((item) => {
if (item instanceof Item) {
return serializeItem(item)
}
if (item instanceof InnerList) {
return serializeInnerList(item)
}
if (Array.isArray(item)) {
const innerList = new InnerList(
item.map((_item) => {
if (_item instanceof Item) return _item
return new Item(_item)
})
)
return serializeInnerList(innerList)
}
return serializeItem(new Item(item))
})
.join(`, `)
}
// 4.1.1.1. Serializing an Inner List
//
// Given an array of (member_value, parameters) tuples as inner_list,
// and parameters as list_parameters, return an ASCII string suitable
// for use in a HTTP field value.
//
// 1. Let output be the string "(".
//
// 2. For each (member_value, parameters) of inner_list:
//
// 1. Append the result of running Serializing an Item
// (Section 4.1.3) with (member_value, parameters) to output.
//
// 2. If more values remain in inner_list, append a single SP to
// output.
//
// 3. Append ")" to output.
//
// 4. Append the result of running Serializing Parameters
// (Section 4.1.1.2) with list_parameters to output.
//
// 5. Return output.
/**
* @param {InnerList} value
* @return {string}
*/
export function serializeInnerList(value) {
return `(${value.value.map(serializeItem).join(" ")})${serializeParams(value.params)}`
}
// 4.1.1.2. Serializing Parameters
//
// Given an ordered Dictionary as input_parameters (each member having a
// param_name and a param_value), return an ASCII string suitable for
// use in a HTTP field value.
//
// 1. Let output be an empty string.
//
// 2. For each param_name with a value of param_value in
// input_parameters:
//
// 1. Append ";" to output.
//
// 2. Append the result of running Serializing a Key
// (Section 4.1.1.3) with param_name to output.
//
// 3. If param_value is not Boolean true:
//
// 1. Append "=" to output.
//
// 2. Append the result of running Serializing a bare Item
// (Section 4.1.3.1) with param_value to output.
//
// 3. Return output.
/**
* @param {Parameters} params
* @return {string}
*/
export function serializeParams(params) {
if (params === null) return ``
return Object.entries(params)
.map(([key, value]) => {
if (value === true) return `;${serializeKey(key)}` // omit true
return `;${serializeKey(key)}=${serializeBareItem(value)}`
})
.join(``)
}
// 4.1.1.3. Serializing a Key
//
// Given a key as input_key, return an ASCII string suitable for use in
// a HTTP field value.
//
// 1. Convert input_key into a sequence of ASCII characters; if
// conversion fails, fail serialization.
//
// 2. If input_key contains characters not in lcalpha, DIGIT, "_", "-",
// ".", or "*" fail serialization.
//
// 3. If the first character of input_key is not lcalpha or "*", fail
// serialization.
//
// 4. Let output be an empty string.
//
// 5. Append input_key to output.
//
// 6. Return output.
/**
* @param {string} value
* @return {string}
*/
export function serializeKey(value) {
if (/^[a-z\*][a-z0-9\-\_\.\*]*$/.test(value) === false) {
throw new Error(err`failed to serialize "${value}" as Key`)
}
return value
}
// 4.1.2. Serializing a Dictionary
//
// Given an ordered Dictionary as input_dictionary (each member having a
// member_name and a tuple value of (member_value, parameters)), return
// an ASCII string suitable for use in a HTTP field value.
//
// 1. Let output be an empty string.
//
// 2. For each member_name with a value of (member_value, parameters)
// in input_dictionary:
//
// 1. Append the result of running Serializing a Key
// (Section 4.1.1.3) with member's member_name to output.
//
// 2. If member_value is Boolean true:
//
// 1. Append the result of running Serializing Parameters
// (Section 4.1.1.2) with parameters to output.
//
// 3. Otherwise:
//
// 1. Append "=" to output.
//
// 2. If member_value is an array, append the result of running
// Serializing an Inner List (Section 4.1.1.1) with
// (member_value, parameters) to output.
//
// 3. Otherwise, append the result of running Serializing an
// Item (Section 4.1.3) with (member_value, parameters) to
// output.
//
// 4. If more members remain in input_dictionary:
//
// 1. Append "," to output.
//
// 2. Append a single SP to output.
//
// 3. Return output.
/**
* @param {Dictionary} dict
* @return {string}
*/
export function serializeDict(dict) {
if (typeof dict !== "object") throw new Error(err`failed to serialize "${dict}" as Dict`)
const entries = dict instanceof Map ? dict.entries() : Object.entries(dict)
return Array.from(entries)
.map(([key, item]) => {
let output = serializeKey(key)
if (item instanceof Item) {
if (item.value === true) {
return output + serializeParams(item.params)
}
return output + `=${serializeItem(item)}`
}
if (item instanceof InnerList) {
return output + `=${serializeInnerList(item)}`
}
if (Array.isArray(item)) {
const innerList = new InnerList(
item.map((_item) => {
if (_item instanceof Item) return _item
return new Item(_item)
})
)
return output + `=${serializeInnerList(innerList)}`
}
if (item === true) {
return output
}
return output + `=${serializeItem(new Item(item))}`
})
.join(`, `)
}
// 4.1.3. Serializing an Item
//
// Given an Item as bare_item and Parameters as item_parameters, return
// an ASCII string suitable for use in a HTTP field value.
//
// 1. Let output be an empty string.
//
// 2. Append the result of running Serializing a Bare Item
// Section 4.1.3.1 with bare_item to output.
//
// 3. Append the result of running Serializing Parameters
// Section 4.1.1.2 with item_parameters to output.
//
// 4. Return output.
/**
* @param {Item|BareItem} value
* @return {string}
*/
export function serializeItem(value) {
if (value instanceof Item) {
return `${serializeBareItem(value.value)}${serializeParams(value.params)}`
} else {
return serializeBareItem(value)
}
}
// 4.1.3.1. Serializing a Bare Item
//
// Given an Item as input_item, return an ASCII string suitable for use
// in a HTTP field value.
//
// 1. If input_item is an Integer, return the result of running
// Serializing an Integer (Section 4.1.4) with input_item.
//
// 2. If input_item is a Decimal, return the result of running
// Serializing a Decimal (Section 4.1.5) with input_item.
//
// 3. If input_item is a String, return the result of running
// Serializing a String (Section 4.1.6) with input_item.
//
// 4. If input_item is a Token, return the result of running
// Serializing a Token (Section 4.1.7) with input_item.
//
// 5. If input_item is a Boolean, return the result of running
// Serializing a Boolean (Section 4.1.9) with input_item.
//
// 6. If input_item is a Byte Sequence, return the result of running
// Serializing a Byte Sequence (Section 4.1.8) with input_item.
//
// 7. If input_item is a Date, return the result of running Serializing
// a Date (Section 4.1.10) with input_item.
//
// 8. Otherwise, fail serialization.
/**
* @param {BareItem} value
* @return {string}
*/
export function serializeBareItem(value) {
switch (typeof value) {
case "number":
if (!Number.isFinite(value)) {
throw new Error(err`failed to serialize "${value}" as Bare Item`)
}
if (Number.isInteger(value)) {
return serializeInteger(value)
}
return serializeDecimal(value)
case "string":
if (/^[\x00-\x7F]*$/.test(value)) {
return serializeString(value)
} else {
return serializeDisplayString(value)
}
case "symbol":
return serializeToken(value)
case "boolean":
return serializeBoolean(value)
case "object":
if (value instanceof Date) {
return serializeDate(value)
}
if (value instanceof Uint8Array) {
return serializeByteSequence(value)
}
default:
// fail
throw new Error(err`failed to serialize "${value}" as Bare Item`)
}
}
// 4.1.4. Serializing an Integer
//
// Given an Integer as input_integer, return an ASCII string suitable
// for use in a HTTP field value.
//
// 1. If input_integer is not an integer in the range of
// -999,999,999,999,999 to 999,999,999,999,999 inclusive, fail
// serialization.
//
// 2. Let output be an empty string.
//
// 3. If input_integer is less than (but not equal to) 0, append "-" to
// output.
//
// 4. Append input_integer's numeric value represented in base 10 using
// only decimal digits to output.
//
// 5. Return output.
/**
* @param {number} value
* @return {string}
*/
export function serializeInteger(value) {
if (value < -999_999_999_999_999n || 999_999_999_999_999n < value) throw new Error(err`failed to serialize "${value}" as Integer`)
return value.toString()
}
// 4.1.5. Serializing a Decimal
//
// Given a decimal number as input_decimal, return an ASCII string
// suitable for use in a HTTP field value.
//
// 1. If input_decimal is not a decimal number, fail serialization.
//
// 2. If input_decimal has more than three significant digits to the
// right of the decimal point, round it to three decimal places,
// rounding the final digit to the nearest value, or to the even
// value if it is equidistant.
//
// 3. If input_decimal has more than 12 significant digits to the left
// of the decimal point after rounding, fail serialization.
//
// 4. Let output be an empty string.
//
// 5. If input_decimal is less than (but not equal to) 0, append "-"
// to output.
//
// 6. Append input_decimal's integer component represented in base 10
// (using only decimal digits) to output; if it is zero, append
// "0".
//
// 7. Append "." to output.
//
// 8. If input_decimal's fractional component is zero, append "0" to
// output.
//
// 9. Otherwise, append the significant digits of input_decimal's
// fractional component represented in base 10 (using only decimal
// digits) to output.
//
// 10. Return output.
/**
* @param {number} value
* @return {string}
*/
export function serializeDecimal(value) {
const roundedValue = roundToEven(value, 3) // round to 3 decimal places
if (Math.floor(Math.abs(roundedValue)).toString().length > 12) throw new Error(err`failed to serialize "${value}" as Decimal`)
const stringValue = roundedValue.toString()
return stringValue.includes(`.`) ? stringValue : `${stringValue}.0`
}
/**
* This implements the rounding procedure described in step 2 of the "Serializing a Decimal" specification.
* This rounding style is known as "even rounding", "banker's rounding", or "commercial rounding".
*
* @param {number} value
* @param {number} precision - decimal places to round to
* @return {number}
*/
function roundToEven(value, precision) {
if (value < 0) {
return -roundToEven(-value, precision)
}
const decimalShift = Math.pow(10, precision)
const isEquidistant = Math.abs(((value * decimalShift) % 1) - 0.5) < Number.EPSILON
if (isEquidistant) {
// If the tail of the decimal place is 'equidistant' we round to the nearest even value
const flooredValue = Math.floor(value * decimalShift)
return (flooredValue % 2 === 0 ? flooredValue : flooredValue + 1) / decimalShift
} else {
// Otherwise, proceed as normal
return Math.round(value * decimalShift) / decimalShift
}
}
// 4.1.6. Serializing a String
//
// Given a String as input_string, return an ASCII string suitable for
// use in a HTTP field value.
//
// 1. Convert input_string into a sequence of ASCII characters; if
// conversion fails, fail serialization.
//
// 2. If input_string contains characters in the range %x00-1f or %x7f
// (i.e., not in VCHAR or SP), fail serialization.
//
// 3. Let output be the string DQUOTE.
//
// 4. For each character char in input_string:
//
// 1. If char is "\" or DQUOTE:
//
// 1. Append "\" to output.
//
// 2. Append char to output.
//
// 5. Append DQUOTE to output.
//
// 6. Return output.
/**
* @param {string} value
* @return {string}
*/
export function serializeString(value) {
if (/[\x00-\x1f\x7f]+/.test(value)) throw new Error(err`failed to serialize "${value}" as string`)
return `"${value.replace(/\\/g, `\\\\`).replace(/"/g, `\\\"`)}"`
}
// 4.1.7. Serializing a Token
//
// Given a Token as input_token, return an ASCII string suitable for use
// in a HTTP field value.
//
// 1. Convert input_token into a sequence of ASCII characters; if
// conversion fails, fail serialization.
//
// 2. If the first character of input_token is not ALPHA or "*", or the
// remaining portion contains a character not in tchar, ":" or "/",
// fail serialization.
//
// 3. Let output be an empty string.
//
// 4. Append input_token to output.
//
// 5. Return output.
//
// tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" /
// "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" /
// DIGIT / ALPHA
// ; any VCHAR, except delimiters
/**
* @param {symbol} token
* @return {string}
*/
export function serializeToken(token) {
/** @type {string} */
const value = Symbol.keyFor(token)
if (/^([a-zA-Z\*])([0-9a-zA-Z\!\#\$\%\&\'\*\+\-\.\^\_\`\|\~\:\/]*)$/.test(value) === false) {
throw new Error(err`failed to serialize "${value}" as token`)
}
return value
}
// 4.1.8. Serializing a Byte Sequence
//
// Given a Byte Sequence as input_bytes, return an ASCII string suitable
// for use in a HTTP field value.
//
// 1. If input_bytes is not a sequence of bytes, fail serialization.
//
// 2. Let output be an empty string.
//
// 3. Append ":" to output.
//
// 4. Append the result of base64-encoding input_bytes as per
// [RFC4648], Section 4, taking account of the requirements below.
//
// 5. Append ":" to output.
//
// 6. Return output.
//
// The encoded data is required to be padded with "=", as per [RFC4648],
// Section 3.2.
//
// Likewise, encoded data SHOULD have pad bits set to zero, as per
// [RFC4648], Section 3.5, unless it is not possible to do so due to
// implementation constraints.
/**
* @param {Uint8Array} value
* @return {string}
*/
export function serializeByteSequence(value) {
if (ArrayBuffer.isView(value) === false) throw new Error(err`failed to serialize "${value}" as Byte Sequence`)
return `:${base64encode(value)}:`
}
// 4.1.9. Serializing a Boolean
//
// Given a Boolean as input_boolean, return an ASCII string suitable for
// use in a HTTP field value.
//
// 1. If input_boolean is not a boolean, fail serialization.
//
// 2. Let output be an empty string.
//
// 3. Append "?" to output.
//
// 4. If input_boolean is true, append "1" to output.
//
// 5. If input_boolean is false, append "0" to output.
//
// 6. Return output.
/**
* @param {boolean} value
* @return {string}
*/
export function serializeBoolean(value) {
if (typeof value !== "boolean") throw new Error(err`failed to serialize "${value}" as boolean`)
return value ? "?1" : "?0"
}
// 4.1.10. Serializing a Date
//
// Given a Date as input_integer, return an ASCII string suitable for
// use in an HTTP field value.
// 1. Let output be "@".
// 2. Append to output the result of running Serializing an Integer
// with input_date (Section 4.1.4).
// 3. Return output.
/**
* @param {Date} value
* @return {string}
*/
export function serializeDate(value) {
const input_date = value.getTime() / 1000
return `@${serializeInteger(input_date)}`
}
// 4.1.11. Serializing a Display String
//
// Given a sequence of Unicode codepoints as input_sequence, return an
// ASCII string suitable for use in an HTTP field value.
//
// 1. If input_sequence is not a sequence of Unicode codepoints, fail serialization.
//
// 2. Let byte_array be the result of applying UTF-8 encoding
// (Section 3 of [UTF8]) to input_sequence. If encoding fails, fail
// serialization.
//
// 3. Let encoded_string be a string containing "%" followed by DQUOTE.
//
// 4. For each byte in byte_array:
//
// 1. If byte is %x25 ("%"), %x22 (DQUOTE), or in the ranges
// %x00-1f or %x7f-ff:
//
// 1. Append "%" to encoded_string.
//
// 2. Let encoded_byte be the result of applying base16
// encoding (Section 8 of [RFC4648]) to byte, with any
// alphabetic characters converted to lowercase.
//
// 3. Append encoded_byte to encoded_string.
//
// 2. Otherwise, decode byte as an ASCII character and append the
// result to encoded_string.
//
// 5. Append DQUOTE to encoded_string.
//
// 6. Return encoded_string.
//
// Note that [UTF8] prohibits the encoding of codepoints between U+D800
// and U+DFFF (surrogates); if they occur in input_sequence,
// serialization will fail.
/**
* @param {string} input_sequence
* @return {string}
*/
export function serializeDisplayString(input_sequence) {
// 2. Let byte_array be the result of applying UTF-8 encoding
// (Section 3 of [UTF8]) to input_sequence. If encoding fails, fail
// serialization.
const textEncoder = new TextEncoder()
const byte_array = textEncoder.encode(input_sequence)
// 3. Let encoded_string be a string containing "%" followed by DQUOTE.
let encoded_string = `%"`
// 4. For each byte in byte_array:
for (const byte of byte_array) {
// 1. If byte is %x25 ("%"), %x22 (DQUOTE), or in the ranges %x00-1f or %x7f-ff:
if (byte === 0x25 || byte === 0x22 || byte <= 0x1f || 0x7f <= byte) {
// 1. Append "%" to encoded_string.
// 2. Let encoded_byte be the result of applying base16 encoding (Section 8 of [RFC4648]) to byte,
// with any alphabetic characters converted to lowercase.
// 3. Append encoded_byte to encoded_string.
encoded_string += `%${byte.toString(16)}`
} else {
// 2. Otherwise, decode byte as an ASCII character and append the result to encoded_string.
encoded_string += String.fromCodePoint(byte)
}
}
// 5. Append DQUOTE to encoded_string.
// 6. Return encoded_string.
return encoded_string + `"`
}
// 4.2.1. Parsing a List
//
// Given an ASCII string as input_string, return an array of
// (item_or_inner_list, parameters) tuples. input_string is modified to
// remove the parsed value.
//
// 1. Let members be an empty array.
//
// 2. While input_string is not empty:
//
// 1. Append the result of running Parsing an Item or Inner List
// (Section 4.2.1.1) with input_string to members.
//
// 2. Discard any leading OWS characters from input_string.
//
// 3. If input_string is empty, return members.
//
// 4. Consume the first character of input_string; if it is not
// ",", fail parsing.
//
// 5. Discard any leading OWS characters from input_string.
//
// 6. If input_string is empty, there is a trailing comma; fail
// parsing.
//
// 3. No structured data has been found; return members (which is
// empty).
/**
* allow BareItem (JS Primitives) for usability
* @typedef {Array.<Item|InnerList|BareItem|Array<BareItem>>} MemberList
*
* @typedef {Object} ParsedList
* @property {MemberList} value
* @property {string} input_string
*
* @param {string} input_string
* @return {ParsedList}
*/
export function parseList(input_string) {
// 1. Let members be an empty array.
/** @type {MemberList} */
const members = []
// 2. While input_string is not empty:
while (input_string.length > 0) {
// 1. Append the result of running Parsing an Item or Inner List (Section 4.2.1.1) with input_string to members.
/** @type {ParsedItemOrInnerList} */
const parsedItemOrInnerList = parseItemOrInnerList(input_string)
members.push(parsedItemOrInnerList.value)
// 2. Discard any leading OWS characters from input_string.
input_string = leadingOWS(parsedItemOrInnerList.input_string)
// 3. If input_string is empty, return members.
if (input_string.length === 0) return { input_string, value: members }
// 4. Consume the first character of input_string; if it is not ",", fail parsing.
if (input_string[0] !== `,`) throw new Error(err`failed to parse "${input_string}" as List`)
// 5. Discard any leading OWS characters from input_string.
input_string = leadingOWS(input_string.substring(1))
// 6. If input_string is empty, there is a trailing comma; fail parsing.
if (input_string.length === 0 || input_string[0] === `,`) throw new Error(err`failed to parse "${input_string}" as List`)
}
// 3. No structured data has been found; return members (which is empty).
return {
value: members,
input_string
}
}
// 4.2.1.1. Parsing an Item or Inner List
//
// Given an ASCII string as input_string, return the tuple
// (item_or_inner_list, parameters), where item_or_inner_list can be
// either a single bare item, or an array of (bare_item, parameters)
// tuples. input_string is modified to remove the parsed value.
//
// 1. If the first character of input_string is "(", return the result
// of running Parsing an Inner List (Section 4.2.1.2) with
// input_string.
//
// 2. Return the result of running Parsing an Item (Section 4.2.3) with
// input_string.
/**
* @typedef {ParsedItem|ParsedInnerList} ParsedItemOrInnerList
*
* @param {string} input_string
* @return {ParsedItemOrInnerList}
*/
export function parseItemOrInnerList(input_string) {
if (input_string[0] === `(`) {
return parseInnerList(input_string)
}
return parseItem(input_string)
}
// 4.2.1.2. Parsing an Inner List
//
// Given an ASCII string as input_string, return the tuple (inner_list,
// parameters), where inner_list is an array of (bare_item, parameters)
// tuples. input_string is modified to remove the parsed value.
//
// 1. Consume the first character of input_string; if it is not "(",
// fail parsing.
//
// 2. Let inner_list be an empty array.
//
// 3. While input_string is not empty:
//
// 1. Discard any leading SP characters from input_string.
//
// 2. If the first character of input_string is ")":
//
// 1. Consume the first character of input_string.
//
// 2. Let parameters be the result of running Parsing
// Parameters (Section 4.2.3.2) with input_string.
//
// 3. Return the tuple (inner_list, parameters).
//
// 3. Let item be the result of running Parsing an Item
// (Section 4.2.3) with input_string.
//
// 4. Append item to inner_list.
//
// 5. If the first character of input_string is not SP or ")", fail
// parsing.
//
// 4. The end of the inner list was not found; fail parsing.
/**
* @typedef {Array.<Item>} ItemList
*
* @typedef {Object} ParsedInnerList
* @property {InnerList} value
* @property {string} input_string
*
* @param {string} input_string
* @return {ParsedInnerList}
*/
export function parseInnerList(input_string) {
// 1. Consume the first character of input_string; if it is not "(", fail parsing.
if (input_string[0] !== `(`) throw new Error(err`failed to parse "${input_string}" as Inner List`)
input_string = input_string.substring(1)
// 2. Let inner_list be an empty array.
const /** @type {ItemList} */ inner_list = []
// 3. While input_string is not empty:
while (input_string.length > 0) {
// 1. Discard any leading SP characters from input_string.
input_string = leadingSP(input_string)
// 2. If the first character of input_string is ")":
if (input_string[0] === `)`) {
// 1. Consume the first character of input_string.
input_string = input_string.substring(1)
// 2. Let parameters be the result of running Parsing Parameters (Section 4.2.3.2) with input_string.
const parsedParameters = parseParameters(input_string)
// 3. Return the tuple (inner_list, parameters).
const innerList = new InnerList(inner_list, parsedParameters.value)
return {
value: innerList,
input_string: parsedParameters.input_string
}
}
// 3. Let item be the result of running Parsing an Item (Section 4.2.3) with input_string.
const /** @type {ParsedItem} */ parsedItem = parseItem(input_string)
// 4. Append item to inner_list.
inner_list.push(parsedItem.value)
// 5. If the first character of input_string is not SP or ")", fail parsing.
input_string = parsedItem.input_string
if (input_string[0] !== ` ` && input_string[0] !== `)`) throw new Error(err`failed to parse "${input_string}" as Inner List`)