-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
44 lines (40 loc) · 1.14 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
const reParamSplit = /\s*;\s*/
const reHeaderSplit = /\s*:\s*/
const rePropertySplit = /\s*=\s*(.+)/
const reEncodingSplit = /\s*'[^']*'\s*(.*)/
const reQuotesTrim = /(?:^["'\s]*)|(?:["'\s]*$)/g
const parser = (data) => {
if (!(data && typeof data === 'string')) {
return
}
const headerSplit = data.split(reParamSplit)
.map(item => item.trim())
.filter(item => !!item)
let type = headerSplit.shift()
if (!type) {
return
}
type = type.toLowerCase().split(reHeaderSplit)
type = type[1] || type[0]
return headerSplit
.map(prop => prop.split(rePropertySplit))
.reduce((o, [key, value]) => {
if (!value) {
o[key] = true
} else if (key.slice(-1) === '*') {
let encoding
[encoding, value] = value.split(reEncodingSplit)
if (value) {
try {
value = decodeURIComponent(value)
} catch (e) { }
o[key.slice(0, -1).toLowerCase()] = value
}
o.encoding = encoding.toLowerCase()
} else if (!(key in o)) {
o[key.toLowerCase()] = value.replace(reQuotesTrim, '')
}
return o
}, { type })
}
module.exports = parser