summaryrefslogtreecommitdiff
path: root/deps/undici/src/lib/fetch/headers.js
blob: 0c6e5584d33003510f9c93e0e62f58022904f6f2 (plain)
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
// https://github.com/Ethan-Arrowood/undici-fetch

'use strict'

const { validateHeaderName, validateHeaderValue } = require('http')
const { kHeadersList } = require('../core/symbols')
const { kGuard } = require('./symbols')
const { kEnumerableProperty } = require('../core/util')

const kHeadersMap = Symbol('headers map')
const kHeadersSortedMap = Symbol('headers map sorted')

function normalizeAndValidateHeaderName (name) {
  if (name === undefined) {
    throw new TypeError(`Header name ${name}`)
  }
  const normalizedHeaderName = name.toLocaleLowerCase()
  validateHeaderName(normalizedHeaderName)
  return normalizedHeaderName
}

function normalizeAndValidateHeaderValue (name, value) {
  if (value === undefined) {
    throw new TypeError(value, name)
  }
  const normalizedHeaderValue = `${value}`.replace(
    /^[\n\t\r\x20]+|[\n\t\r\x20]+$/g,
    ''
  )
  validateHeaderValue(name, normalizedHeaderValue)
  return normalizedHeaderValue
}

function fill (headers, object) {
  // To fill a Headers object headers with a given object object, run these steps:

  if (object[Symbol.iterator]) {
    // 1. If object is a sequence, then for each header in object:
    // TODO: How to check if sequence?
    for (let header of object) {
      // 1. If header does not contain exactly two items, then throw a TypeError.
      if (!header[Symbol.iterator]) {
        // TODO: Spec doesn't define what to do here?
        throw new TypeError()
      }

      if (typeof header === 'string') {
        // TODO: Spec doesn't define what to do here?
        throw new TypeError()
      }

      if (!Array.isArray(header)) {
        header = [...header]
      }

      if (header.length !== 2) {
        throw new TypeError()
      }

      // 2. Append header’s first item/header’s second item to headers.
      headers.append(header[0], header[1])
    }
  } else if (object && typeof object === 'object') {
    // Otherwise, object is a record, then for each key → value in object,
    // append key/value to headers.
    // TODO: How to check if record?
    for (const header of Object.entries(object)) {
      headers.append(header[0], header[1])
    }
  } else {
    // TODO: Spec doesn't define what to do here?
    throw TypeError()
  }
}

// https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object
const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))

// https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object
function makeHeadersIterator (iterator) {
  const i = {
    next () {
      if (Object.getPrototypeOf(this) !== i) {
        throw new TypeError(
          '\'next\' called on an object that does not implement interface Headers Iterator.'
        )
      }

      return iterator.next()
    },
    // The class string of an iterator prototype object for a given interface is the
    // result of concatenating the identifier of the interface and the string " Iterator".
    [Symbol.toStringTag]: 'Headers Iterator'
  }

  // The [[Prototype]] internal slot of an iterator prototype object must be %IteratorPrototype%.
  Object.setPrototypeOf(i, esIteratorPrototype)
  // esIteratorPrototype needs to be the prototype of i
  // which is the prototype of an empty object. Yes, it's confusing.
  return Object.setPrototypeOf({}, i)
}

class HeadersList {
  constructor (init) {
    if (init instanceof HeadersList) {
      this[kHeadersMap] = new Map(init[kHeadersMap])
      this[kHeadersSortedMap] = init[kHeadersSortedMap]
    } else {
      this[kHeadersMap] = new Map(init)
      this[kHeadersSortedMap] = null
    }
  }

  clear () {
    this[kHeadersMap].clear()
    this[kHeadersSortedMap] = null
  }

  append (name, value) {
    this[kHeadersSortedMap] = null

    const normalizedName = normalizeAndValidateHeaderName(name)
    const normalizedValue = normalizeAndValidateHeaderValue(name, value)

    const exists = this[kHeadersMap].get(normalizedName)

    if (exists) {
      this[kHeadersMap].set(normalizedName, `${exists}, ${normalizedValue}`)
    } else {
      this[kHeadersMap].set(normalizedName, `${normalizedValue}`)
    }
  }

  set (name, value) {
    this[kHeadersSortedMap] = null

    const normalizedName = normalizeAndValidateHeaderName(name)
    return this[kHeadersMap].set(normalizedName, value)
  }

  delete (name) {
    this[kHeadersSortedMap] = null

    const normalizedName = normalizeAndValidateHeaderName(name)
    return this[kHeadersMap].delete(normalizedName)
  }

  get (name) {
    const normalizedName = normalizeAndValidateHeaderName(name)
    return this[kHeadersMap].get(normalizedName) ?? null
  }

  has (name) {
    const normalizedName = normalizeAndValidateHeaderName(name)
    return this[kHeadersMap].has(normalizedName)
  }

  keys () {
    return this[kHeadersMap].keys()
  }

  values () {
    return this[kHeadersMap].values()
  }

  entries () {
    return this[kHeadersMap].entries()
  }

  [Symbol.iterator] () {
    return this[kHeadersMap][Symbol.iterator]()
  }
}

// https://fetch.spec.whatwg.org/#headers-class
class Headers {
  constructor (...args) {
    if (
      args[0] !== undefined &&
      !(typeof args[0] === 'object' && args[0] != null) &&
      !Array.isArray(args[0])
    ) {
      throw new TypeError(
        "Failed to construct 'Headers': The provided value is not of type '(record<ByteString, ByteString> or sequence<sequence<ByteString>>"
      )
    }
    const init = args.length >= 1 ? args[0] ?? {} : {}
    this[kHeadersList] = new HeadersList()

    // The new Headers(init) constructor steps are:

    // 1. Set this’s guard to "none".
    this[kGuard] = 'none'

    // 2. If init is given, then fill this with init.
    fill(this, init)
  }

  get [Symbol.toStringTag] () {
    return this.constructor.name
  }

  // https://fetch.spec.whatwg.org/#dom-headers-append
  append (name, value) {
    if (!(this instanceof Headers)) {
      throw new TypeError('Illegal invocation')
    }

    if (arguments.length < 2) {
      throw new TypeError(
        `Failed to execute 'append' on 'Headers': 2 arguments required, but only ${arguments.length} present.`
      )
    }

    // Note: undici does not implement forbidden header names
    if (this[kGuard] === 'immutable') {
      throw new TypeError('immutable')
    } else if (this[kGuard] === 'request-no-cors') {
      // TODO
    }

    return this[kHeadersList].append(String(name), String(value))
  }

  // https://fetch.spec.whatwg.org/#dom-headers-delete
  delete (name) {
    if (!(this instanceof Headers)) {
      throw new TypeError('Illegal invocation')
    }

    if (arguments.length < 1) {
      throw new TypeError(
        `Failed to execute 'delete' on 'Headers': 1 argument required, but only ${arguments.length} present.`
      )
    }

    // Note: undici does not implement forbidden header names
    if (this[kGuard] === 'immutable') {
      throw new TypeError('immutable')
    } else if (this[kGuard] === 'request-no-cors') {
      // TODO
    }

    return this[kHeadersList].delete(String(name))
  }

  // https://fetch.spec.whatwg.org/#dom-headers-get
  get (name) {
    if (!(this instanceof Headers)) {
      throw new TypeError('Illegal invocation')
    }

    if (arguments.length < 1) {
      throw new TypeError(
        `Failed to execute 'get' on 'Headers': 1 argument required, but only ${arguments.length} present.`
      )
    }

    return this[kHeadersList].get(String(name))
  }

  // https://fetch.spec.whatwg.org/#dom-headers-has
  has (name) {
    if (!(this instanceof Headers)) {
      throw new TypeError('Illegal invocation')
    }

    if (arguments.length < 1) {
      throw new TypeError(
        `Failed to execute 'has' on 'Headers': 1 argument required, but only ${arguments.length} present.`
      )
    }

    return this[kHeadersList].has(String(name))
  }

  // https://fetch.spec.whatwg.org/#dom-headers-set
  set (name, value) {
    if (!(this instanceof Headers)) {
      throw new TypeError('Illegal invocation')
    }

    if (arguments.length < 2) {
      throw new TypeError(
        `Failed to execute 'set' on 'Headers': 2 arguments required, but only ${arguments.length} present.`
      )
    }

    // Note: undici does not implement forbidden header names
    if (this[kGuard] === 'immutable') {
      throw new TypeError('immutable')
    } else if (this[kGuard] === 'request-no-cors') {
      // TODO
    }

    return this[kHeadersList].set(String(name), String(value))
  }

  get [kHeadersSortedMap] () {
    this[kHeadersList][kHeadersSortedMap] ??= new Map([...this[kHeadersList]].sort((a, b) => a[0] < b[0] ? -1 : 1))
    return this[kHeadersList][kHeadersSortedMap]
  }

  keys () {
    if (!(this instanceof Headers)) {
      throw new TypeError('Illegal invocation')
    }

    return makeHeadersIterator(this[kHeadersSortedMap].keys())
  }

  values () {
    if (!(this instanceof Headers)) {
      throw new TypeError('Illegal invocation')
    }

    return makeHeadersIterator(this[kHeadersSortedMap].values())
  }

  entries () {
    if (!(this instanceof Headers)) {
      throw new TypeError('Illegal invocation')
    }

    return makeHeadersIterator(this[kHeadersSortedMap].entries())
  }

  /**
   * @param {(value: string, key: string, self: Headers) => void} callbackFn
   * @param {unknown} thisArg
   */
  forEach (callbackFn, thisArg = globalThis) {
    if (!(this instanceof Headers)) {
      throw new TypeError('Illegal invocation')
    }

    if (arguments.length < 1) {
      throw new TypeError(
        `Failed to execute 'forEach' on 'Headers': 1 argument required, but only ${arguments.length} present.`
      )
    }

    if (typeof callbackFn !== 'function') {
      throw new TypeError(
        "Failed to execute 'forEach' on 'Headers': parameter 1 is not of type 'Function'."
      )
    }

    for (const [key, value] of this) {
      callbackFn.apply(thisArg, [value, key, this])
    }
  }

  [Symbol.for('nodejs.util.inspect.custom')] () {
    if (!(this instanceof Headers)) {
      throw new TypeError('Illegal invocation')
    }

    return this[kHeadersList]
  }
}

Headers.prototype[Symbol.iterator] = Headers.prototype.entries

Object.defineProperties(Headers.prototype, {
  append: kEnumerableProperty,
  delete: kEnumerableProperty,
  get: kEnumerableProperty,
  has: kEnumerableProperty,
  set: kEnumerableProperty,
  keys: kEnumerableProperty,
  values: kEnumerableProperty,
  entries: kEnumerableProperty,
  forEach: kEnumerableProperty
})

module.exports = {
  fill,
  Headers,
  HeadersList,
  normalizeAndValidateHeaderName,
  normalizeAndValidateHeaderValue
}