@@ -76,35 +76,48 @@ const NullObject = (() => {
7676 * Parse the given cookie header string into an object
7777 * The object has the various cookies as keys(names) => values
7878 */
79- export function parse ( str , options ) {
79+ export function parse ( input , options ) {
8080 const obj = new NullObject ( ) ;
81- const len = str . length ;
82- if ( len < 2 ) return obj ;
8381 const dec = options ?. decode || decode ;
84- let index = 0 ;
85- do {
86- const eqIdx = str . indexOf ( "=" , index ) ;
87- if ( eqIdx === - 1 ) break ;
88- const colonIdx = str . indexOf ( ";" , index ) ;
89- const endIdx = colonIdx === - 1 ? len : colonIdx ;
90- if ( eqIdx > endIdx ) {
91- index = str . lastIndexOf ( ";" , eqIdx - 1 ) + 1 ;
92- continue ;
93- }
94- const keyStartIdx = startIndex ( str , index , eqIdx ) ;
95- const keyEndIdx = endIndex ( str , eqIdx , keyStartIdx ) ;
96- const key = str . slice ( keyStartIdx , keyEndIdx ) ;
97- if ( obj [ key ] === undefined ) {
82+
83+ // If input is an array, process each string
84+ const headers = Array . isArray ( input ) ? input : [ input ] ;
85+
86+ for ( const str of headers ) {
87+ const len = str . length ;
88+ if ( len < 2 ) continue ;
89+
90+ let index = 0 ;
91+ do {
92+ const eqIdx = str . indexOf ( "=" , index ) ;
93+ if ( eqIdx === - 1 ) break ;
94+ const colonIdx = str . indexOf ( ";" , index ) ;
95+ const endIdx = colonIdx === - 1 ? len : colonIdx ;
96+
97+ if ( eqIdx > endIdx ) {
98+ index = str . lastIndexOf ( ";" , eqIdx - 1 ) + 1 ;
99+ continue ;
100+ }
101+
102+ const keyStartIdx = startIndex ( str , index , eqIdx ) ;
103+ const keyEndIdx = endIndex ( str , eqIdx , keyStartIdx ) ;
104+ const key = str . slice ( keyStartIdx , keyEndIdx ) ; // Keep original case
105+
98106 let valStartIdx = startIndex ( str , eqIdx + 1 , endIdx ) ;
99107 let valEndIdx = endIndex ( str , endIdx , valStartIdx ) ;
100108 const value = dec ( str . slice ( valStartIdx , valEndIdx ) ) ;
109+
110+ // Always overwrite with the latest value for the same key
101111 obj [ key ] = value ;
102- }
103- index = endIdx + 1 ;
104- } while ( index < len ) ;
112+
113+ index = endIdx + 1 ;
114+ } while ( index < len ) ;
115+ }
116+
105117 return obj ;
106118}
107119
120+
108121function startIndex ( str , index , max ) {
109122 do {
110123 const code = str . charCodeAt ( index ) ;
@@ -226,6 +239,13 @@ function isDate(val) {
226239 return __toString . call ( val ) === "[object Date]" ;
227240}
228241
242+ export function stringify ( obj , encode = 0 ) {
243+ return Object . entries ( obj )
244+ . map ( ( [ key , value ] ) => encode ? serialize ( key , value ) : decodeURIComponent ( serialize ( key , value ) ) )
245+ . join ( "; " )
246+ }
247+
248+
229249// Export as default object for named and default usage
230- const COOKIE = { parse, serialize, stringify : serialize } ;
250+ const COOKIE = { parse, serialize, stringify} ;
231251export default COOKIE ;
0 commit comments