File tree Expand file tree Collapse file tree 4 files changed +45
-3
lines changed Expand file tree Collapse file tree 4 files changed +45
-3
lines changed Original file line number Diff line number Diff line change 1
1
import createBoundary from "./util/createBoundary"
2
- import escape from "./util/escapeName "
2
+ import normalize from "./util/normalizeValue "
3
3
import isFormData from "./util/isFormData"
4
+ import escape from "./util/escapeName"
4
5
import isFile from "./util/isFile"
5
6
6
7
import { FormDataLike } from "./FormDataLike"
@@ -119,7 +120,7 @@ export class FormDataEncoder {
119
120
120
121
length += isFile ( value )
121
122
? value . size
122
- : this . #encoder. encode ( String ( value ) ) . byteLength
123
+ : this . #encoder. encode ( normalize ( value ) ) . byteLength
123
124
124
125
length += this . #CRLF_BYTES_LENGTH
125
126
}
@@ -167,7 +168,7 @@ export class FormDataEncoder {
167
168
for ( const [ name , value ] of this . #form. entries ( ) ) {
168
169
yield this . #getFieldHeader( name , value )
169
170
170
- yield isFile ( value ) ? value : this . #encoder. encode ( String ( value ) )
171
+ yield isFile ( value ) ? value : this . #encoder. encode ( normalize ( value ) )
171
172
172
173
yield this . #CRLF_BYTES
173
174
}
Original file line number Diff line number Diff line change
1
+ /**
2
+ * Escape fieldname following the spec requirements.
3
+ *
4
+ * See: https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#multipart-form-data
5
+ *
6
+ * @param name A fieldname to escape
7
+ */
1
8
const escapeName = ( name : unknown ) => String ( name )
2
9
. replace ( / \r / g, "%0D" ) // CR
3
10
. replace ( / \n / g, "%0A" ) // LF
Original file line number Diff line number Diff line change
1
+ import test from "ava"
2
+
3
+ import normalize from "./normalizeValue"
4
+
5
+ const expected = "First line.\r\nSecond line.\r\nThird line."
6
+
7
+ test ( "Replaces all CR not followed by LF with CRLF" , t => {
8
+ const actual = normalize ( "First line.\rSecond line.\rThird line." )
9
+
10
+ t . is ( actual , expected )
11
+ } )
12
+
13
+ test ( "Replaces all LF not predicessed by CR with CRLF" , t => {
14
+ const actual = normalize ( "First line.\nSecond line.\nThird line." )
15
+
16
+ t . is ( actual , expected )
17
+ } )
18
+
19
+ test ( "Keeps all CRLF without changes" , t => {
20
+ const actual = normalize ( expected )
21
+
22
+ t . is ( actual , expected )
23
+ } )
Original file line number Diff line number Diff line change
1
+ /**
2
+ * Normalize non-File value following the spec requirements.
3
+ *
4
+ * See: https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#multipart-form-data
5
+ *
6
+ * @param value A value to normalize
7
+ */
8
+ const normalizeValue = ( value : unknown ) : string => String ( value )
9
+ . replace ( / \r (? ! \n ) | (?< ! \r ) \n / g, "\r\n" )
10
+
11
+ export default normalizeValue
You can’t perform that action at this time.
0 commit comments