headers.js
6.23 KB
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
'use strict'
const invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/
const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/
const validateName = name => {
name = `${name}`
if (invalidTokenRegex.test(name) || name === '')
throw new TypeError(`${name} is not a legal HTTP header name`)
}
const validateValue = value => {
value = `${value}`
if (invalidHeaderCharRegex.test(value))
throw new TypeError(`${value} is not a legal HTTP header value`)
}
const find = (map, name) => {
name = name.toLowerCase()
for (const key in map) {
if (key.toLowerCase() === name)
return key
}
return undefined
}
const MAP = Symbol('map')
class Headers {
constructor (init = undefined) {
this[MAP] = Object.create(null)
if (init instanceof Headers) {
const rawHeaders = init.raw()
const headerNames = Object.keys(rawHeaders)
for (const headerName of headerNames) {
for (const value of rawHeaders[headerName]) {
this.append(headerName, value)
}
}
return
}
// no-op
if (init === undefined || init === null)
return
if (typeof init === 'object') {
const method = init[Symbol.iterator]
if (method !== null && method !== undefined) {
if (typeof method !== 'function')
throw new TypeError('Header pairs must be iterable')
// sequence<sequence<ByteString>>
// Note: per spec we have to first exhaust the lists then process them
const pairs = []
for (const pair of init) {
if (typeof pair !== 'object' ||
typeof pair[Symbol.iterator] !== 'function')
throw new TypeError('Each header pair must be iterable')
const arrPair = Array.from(pair)
if (arrPair.length !== 2)
throw new TypeError('Each header pair must be a name/value tuple')
pairs.push(arrPair)
}
for (const pair of pairs) {
this.append(pair[0], pair[1])
}
} else {
// record<ByteString, ByteString>
for (const key of Object.keys(init)) {
this.append(key, init[key])
}
}
} else
throw new TypeError('Provided initializer must be an object')
}
get (name) {
name = `${name}`
validateName(name)
const key = find(this[MAP], name)
if (key === undefined)
return null
return this[MAP][key].join(', ')
}
forEach (callback, thisArg = undefined) {
let pairs = getHeaders(this)
for (let i = 0; i < pairs.length; i++) {
const [name, value] = pairs[i]
callback.call(thisArg, value, name, this)
// refresh in case the callback added more headers
pairs = getHeaders(this)
}
}
set (name, value) {
name = `${name}`
value = `${value}`
validateName(name)
validateValue(value)
const key = find(this[MAP], name)
this[MAP][key !== undefined ? key : name] = [value]
}
append (name, value) {
name = `${name}`
value = `${value}`
validateName(name)
validateValue(value)
const key = find(this[MAP], name)
if (key !== undefined)
this[MAP][key].push(value)
else
this[MAP][name] = [value]
}
has (name) {
name = `${name}`
validateName(name)
return find(this[MAP], name) !== undefined
}
delete (name) {
name = `${name}`
validateName(name)
const key = find(this[MAP], name)
if (key !== undefined)
delete this[MAP][key]
}
raw () {
return this[MAP]
}
keys () {
return new HeadersIterator(this, 'key')
}
values () {
return new HeadersIterator(this, 'value')
}
[Symbol.iterator]() {
return new HeadersIterator(this, 'key+value')
}
entries () {
return new HeadersIterator(this, 'key+value')
}
get [Symbol.toStringTag] () {
return 'Headers'
}
static exportNodeCompatibleHeaders (headers) {
const obj = Object.assign(Object.create(null), headers[MAP])
// http.request() only supports string as Host header. This hack makes
// specifying custom Host header possible.
const hostHeaderKey = find(headers[MAP], 'Host')
if (hostHeaderKey !== undefined)
obj[hostHeaderKey] = obj[hostHeaderKey][0]
return obj
}
static createHeadersLenient (obj) {
const headers = new Headers()
for (const name of Object.keys(obj)) {
if (invalidTokenRegex.test(name))
continue
if (Array.isArray(obj[name])) {
for (const val of obj[name]) {
if (invalidHeaderCharRegex.test(val))
continue
if (headers[MAP][name] === undefined)
headers[MAP][name] = [val]
else
headers[MAP][name].push(val)
}
} else if (!invalidHeaderCharRegex.test(obj[name]))
headers[MAP][name] = [obj[name]]
}
return headers
}
}
Object.defineProperties(Headers.prototype, {
get: { enumerable: true },
forEach: { enumerable: true },
set: { enumerable: true },
append: { enumerable: true },
has: { enumerable: true },
delete: { enumerable: true },
keys: { enumerable: true },
values: { enumerable: true },
entries: { enumerable: true },
})
const getHeaders = (headers, kind = 'key+value') =>
Object.keys(headers[MAP]).sort().map(
kind === 'key' ? k => k.toLowerCase()
: kind === 'value' ? k => headers[MAP][k].join(', ')
: k => [k.toLowerCase(), headers[MAP][k].join(', ')]
)
const INTERNAL = Symbol('internal')
class HeadersIterator {
constructor (target, kind) {
this[INTERNAL] = {
target,
kind,
index: 0,
}
}
get [Symbol.toStringTag] () {
return 'HeadersIterator'
}
next () {
/* istanbul ignore if: should be impossible */
if (!this || Object.getPrototypeOf(this) !== HeadersIterator.prototype)
throw new TypeError('Value of `this` is not a HeadersIterator')
const { target, kind, index } = this[INTERNAL]
const values = getHeaders(target, kind)
const len = values.length
if (index >= len) {
return {
value: undefined,
done: true,
}
}
this[INTERNAL].index++
return { value: values[index], done: false }
}
}
// manually extend because 'extends' requires a ctor
Object.setPrototypeOf(HeadersIterator.prototype,
Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())))
module.exports = Headers