UNPKG

22.1 kBJavaScriptView Raw
1/*!
2 * send
3 * Copyright(c) 2012 TJ Holowaychuk
4 * Copyright(c) 2014-2016 Douglas Christopher Wilson
5 * MIT Licensed
6 */
7
8'use strict'
9
10/**
11 * Module dependencies.
12 * @private
13 */
14
15var createError = require('http-errors')
16var debug = require('debug')('send')
17var deprecate = require('depd')('send')
18var destroy = require('destroy')
19var encodeUrl = require('encodeurl')
20var escapeHtml = require('escape-html')
21var etag = require('etag')
22var EventEmitter = require('events').EventEmitter
23var fresh = require('fresh')
24var fs = require('fs')
25var mime = require('mime')
26var ms = require('ms')
27var onFinished = require('on-finished')
28var parseRange = require('range-parser')
29var path = require('path')
30var statuses = require('statuses')
31var Stream = require('stream')
32var util = require('util')
33
34/**
35 * Path function references.
36 * @private
37 */
38
39var extname = path.extname
40var join = path.join
41var normalize = path.normalize
42var resolve = path.resolve
43var sep = path.sep
44
45/**
46 * Regular expression for identifying a bytes Range header.
47 * @private
48 */
49
50var BYTES_RANGE_REGEXP = /^ *bytes=/
51
52/**
53 * Simple expression to split token list.
54 * @private
55 */
56
57var TOKEN_LIST_REGEXP = / *, */
58
59/**
60 * Maximum value allowed for the max age.
61 * @private
62 */
63
64var MAX_MAXAGE = 60 * 60 * 24 * 365 * 1000 // 1 year
65
66/**
67 * Regular expression to match a path with a directory up component.
68 * @private
69 */
70
71var UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/
72
73/**
74 * Module exports.
75 * @public
76 */
77
78module.exports = send
79module.exports.mime = mime
80
81/**
82 * Shim EventEmitter.listenerCount for node.js < 0.10
83 */
84
85/* istanbul ignore next */
86var listenerCount = EventEmitter.listenerCount ||
87 function (emitter, type) { return emitter.listeners(type).length }
88
89/**
90 * Return a `SendStream` for `req` and `path`.
91 *
92 * @param {object} req
93 * @param {string} path
94 * @param {object} [options]
95 * @return {SendStream}
96 * @public
97 */
98
99function send (req, path, options) {
100 return new SendStream(req, path, options)
101}
102
103/**
104 * Initialize a `SendStream` with the given `path`.
105 *
106 * @param {Request} req
107 * @param {String} path
108 * @param {object} [options]
109 * @private
110 */
111
112function SendStream (req, path, options) {
113 Stream.call(this)
114
115 var opts = options || {}
116
117 this.options = opts
118 this.path = path
119 this.req = req
120
121 this._acceptRanges = opts.acceptRanges !== undefined
122 ? Boolean(opts.acceptRanges)
123 : true
124
125 this._cacheControl = opts.cacheControl !== undefined
126 ? Boolean(opts.cacheControl)
127 : true
128
129 this._etag = opts.etag !== undefined
130 ? Boolean(opts.etag)
131 : true
132
133 this._dotfiles = opts.dotfiles !== undefined
134 ? opts.dotfiles
135 : 'ignore'
136
137 if (this._dotfiles !== 'ignore' && this._dotfiles !== 'allow' && this._dotfiles !== 'deny') {
138 throw new TypeError('dotfiles option must be "allow", "deny", or "ignore"')
139 }
140
141 this._hidden = Boolean(opts.hidden)
142
143 if (opts.hidden !== undefined) {
144 deprecate('hidden: use dotfiles: \'' + (this._hidden ? 'allow' : 'ignore') + '\' instead')
145 }
146
147 // legacy support
148 if (opts.dotfiles === undefined) {
149 this._dotfiles = undefined
150 }
151
152 this._extensions = opts.extensions !== undefined
153 ? normalizeList(opts.extensions, 'extensions option')
154 : []
155
156 this._index = opts.index !== undefined
157 ? normalizeList(opts.index, 'index option')
158 : ['index.html']
159
160 this._lastModified = opts.lastModified !== undefined
161 ? Boolean(opts.lastModified)
162 : true
163
164 this._maxage = opts.maxAge || opts.maxage
165 this._maxage = typeof this._maxage === 'string'
166 ? ms(this._maxage)
167 : Number(this._maxage)
168 this._maxage = !isNaN(this._maxage)
169 ? Math.min(Math.max(0, this._maxage), MAX_MAXAGE)
170 : 0
171
172 this._root = opts.root
173 ? resolve(opts.root)
174 : null
175
176 if (!this._root && opts.from) {
177 this.from(opts.from)
178 }
179}
180
181/**
182 * Inherits from `Stream`.
183 */
184
185util.inherits(SendStream, Stream)
186
187/**
188 * Enable or disable etag generation.
189 *
190 * @param {Boolean} val
191 * @return {SendStream}
192 * @api public
193 */
194
195SendStream.prototype.etag = deprecate.function(function etag (val) {
196 this._etag = Boolean(val)
197 debug('etag %s', this._etag)
198 return this
199}, 'send.etag: pass etag as option')
200
201/**
202 * Enable or disable "hidden" (dot) files.
203 *
204 * @param {Boolean} path
205 * @return {SendStream}
206 * @api public
207 */
208
209SendStream.prototype.hidden = deprecate.function(function hidden (val) {
210 this._hidden = Boolean(val)
211 this._dotfiles = undefined
212 debug('hidden %s', this._hidden)
213 return this
214}, 'send.hidden: use dotfiles option')
215
216/**
217 * Set index `paths`, set to a falsy
218 * value to disable index support.
219 *
220 * @param {String|Boolean|Array} paths
221 * @return {SendStream}
222 * @api public
223 */
224
225SendStream.prototype.index = deprecate.function(function index (paths) {
226 var index = !paths ? [] : normalizeList(paths, 'paths argument')
227 debug('index %o', paths)
228 this._index = index
229 return this
230}, 'send.index: pass index as option')
231
232/**
233 * Set root `path`.
234 *
235 * @param {String} path
236 * @return {SendStream}
237 * @api public
238 */
239
240SendStream.prototype.root = function root (path) {
241 this._root = resolve(String(path))
242 debug('root %s', this._root)
243 return this
244}
245
246SendStream.prototype.from = deprecate.function(SendStream.prototype.root,
247 'send.from: pass root as option')
248
249SendStream.prototype.root = deprecate.function(SendStream.prototype.root,
250 'send.root: pass root as option')
251
252/**
253 * Set max-age to `maxAge`.
254 *
255 * @param {Number} maxAge
256 * @return {SendStream}
257 * @api public
258 */
259
260SendStream.prototype.maxage = deprecate.function(function maxage (maxAge) {
261 this._maxage = typeof maxAge === 'string'
262 ? ms(maxAge)
263 : Number(maxAge)
264 this._maxage = !isNaN(this._maxage)
265 ? Math.min(Math.max(0, this._maxage), MAX_MAXAGE)
266 : 0
267 debug('max-age %d', this._maxage)
268 return this
269}, 'send.maxage: pass maxAge as option')
270
271/**
272 * Emit error with `status`.
273 *
274 * @param {number} status
275 * @param {Error} [error]
276 * @private
277 */
278
279SendStream.prototype.error = function error (status, error) {
280 // emit if listeners instead of responding
281 if (listenerCount(this, 'error') !== 0) {
282 return this.emit('error', createError(status, error, {
283 expose: false
284 }))
285 }
286
287 var res = this.res
288 var msg = statuses[status] || String(status)
289 var doc = createHtmlDocument('Error', escapeHtml(msg))
290
291 // clear existing headers
292 clearHeaders(res)
293
294 // add error headers
295 if (error && error.headers) {
296 setHeaders(res, error.headers)
297 }
298
299 // send basic response
300 res.statusCode = status
301 res.setHeader('Content-Type', 'text/html; charset=UTF-8')
302 res.setHeader('Content-Length', Buffer.byteLength(doc))
303 res.setHeader('Content-Security-Policy', "default-src 'self'")
304 res.setHeader('X-Content-Type-Options', 'nosniff')
305 res.end(doc)
306}
307
308/**
309 * Check if the pathname ends with "/".
310 *
311 * @return {boolean}
312 * @private
313 */
314
315SendStream.prototype.hasTrailingSlash = function hasTrailingSlash () {
316 return this.path[this.path.length - 1] === '/'
317}
318
319/**
320 * Check if this is a conditional GET request.
321 *
322 * @return {Boolean}
323 * @api private
324 */
325
326SendStream.prototype.isConditionalGET = function isConditionalGET () {
327 return this.req.headers['if-match'] ||
328 this.req.headers['if-unmodified-since'] ||
329 this.req.headers['if-none-match'] ||
330 this.req.headers['if-modified-since']
331}
332
333/**
334 * Check if the request preconditions failed.
335 *
336 * @return {boolean}
337 * @private
338 */
339
340SendStream.prototype.isPreconditionFailure = function isPreconditionFailure () {
341 var req = this.req
342 var res = this.res
343
344 // if-match
345 var match = req.headers['if-match']
346 if (match) {
347 var etag = res.getHeader('ETag')
348 return !etag || (match !== '*' && match.split(TOKEN_LIST_REGEXP).every(function (match) {
349 return match !== etag && match !== 'W/' + etag && 'W/' + match !== etag
350 }))
351 }
352
353 // if-unmodified-since
354 var unmodifiedSince = Date.parse(req.headers['if-unmodified-since'])
355 if (!isNaN(unmodifiedSince)) {
356 var lastModified = Date.parse(res.getHeader('Last-Modified'))
357 return isNaN(lastModified) || lastModified > unmodifiedSince
358 }
359
360 return false
361}
362
363/**
364 * Strip content-* header fields.
365 *
366 * @private
367 */
368
369SendStream.prototype.removeContentHeaderFields = function removeContentHeaderFields () {
370 var res = this.res
371 var headers = getHeaderNames(res)
372
373 for (var i = 0; i < headers.length; i++) {
374 var header = headers[i]
375 if (header.substr(0, 8) === 'content-' && header !== 'content-location') {
376 res.removeHeader(header)
377 }
378 }
379}
380
381/**
382 * Respond with 304 not modified.
383 *
384 * @api private
385 */
386
387SendStream.prototype.notModified = function notModified () {
388 var res = this.res
389 debug('not modified')
390 this.removeContentHeaderFields()
391 res.statusCode = 304
392 res.end()
393}
394
395/**
396 * Raise error that headers already sent.
397 *
398 * @api private
399 */
400
401SendStream.prototype.headersAlreadySent = function headersAlreadySent () {
402 var err = new Error('Can\'t set headers after they are sent.')
403 debug('headers already sent')
404 this.error(500, err)
405}
406
407/**
408 * Check if the request is cacheable, aka
409 * responded with 2xx or 304 (see RFC 2616 section 14.2{5,6}).
410 *
411 * @return {Boolean}
412 * @api private
413 */
414
415SendStream.prototype.isCachable = function isCachable () {
416 var statusCode = this.res.statusCode
417 return (statusCode >= 200 && statusCode < 300) ||
418 statusCode === 304
419}
420
421/**
422 * Handle stat() error.
423 *
424 * @param {Error} error
425 * @private
426 */
427
428SendStream.prototype.onStatError = function onStatError (error) {
429 switch (error.code) {
430 case 'ENAMETOOLONG':
431 case 'ENOENT':
432 case 'ENOTDIR':
433 this.error(404, error)
434 break
435 default:
436 this.error(500, error)
437 break
438 }
439}
440
441/**
442 * Check if the cache is fresh.
443 *
444 * @return {Boolean}
445 * @api private
446 */
447
448SendStream.prototype.isFresh = function isFresh () {
449 return fresh(this.req.headers, {
450 'etag': this.res.getHeader('ETag'),
451 'last-modified': this.res.getHeader('Last-Modified')
452 })
453}
454
455/**
456 * Check if the range is fresh.
457 *
458 * @return {Boolean}
459 * @api private
460 */
461
462SendStream.prototype.isRangeFresh = function isRangeFresh () {
463 var ifRange = this.req.headers['if-range']
464
465 if (!ifRange) {
466 return true
467 }
468
469 // if-range as etag
470 if (ifRange.indexOf('"') !== -1) {
471 var etag = this.res.getHeader('ETag')
472 return Boolean(etag && ifRange.indexOf(etag) !== -1)
473 }
474
475 // if-range as modified date
476 var lastModified = this.res.getHeader('Last-Modified')
477 return Boolean(lastModified && Date.parse(lastModified) <= Date.parse(ifRange))
478}
479
480/**
481 * Redirect to path.
482 *
483 * @param {string} path
484 * @private
485 */
486
487SendStream.prototype.redirect = function redirect (path) {
488 var res = this.res
489
490 if (listenerCount(this, 'directory') !== 0) {
491 this.emit('directory', res, path)
492 return
493 }
494
495 if (this.hasTrailingSlash()) {
496 this.error(403)
497 return
498 }
499
500 var loc = encodeUrl(collapseLeadingSlashes(this.path + '/'))
501 var doc = createHtmlDocument('Redirecting', 'Redirecting to <a href="' + escapeHtml(loc) + '">' +
502 escapeHtml(loc) + '</a>')
503
504 // redirect
505 res.statusCode = 301
506 res.setHeader('Content-Type', 'text/html; charset=UTF-8')
507 res.setHeader('Content-Length', Buffer.byteLength(doc))
508 res.setHeader('Content-Security-Policy', "default-src 'self'")
509 res.setHeader('X-Content-Type-Options', 'nosniff')
510 res.setHeader('Location', loc)
511 res.end(doc)
512}
513
514/**
515 * Pipe to `res.
516 *
517 * @param {Stream} res
518 * @return {Stream} res
519 * @api public
520 */
521
522SendStream.prototype.pipe = function pipe (res) {
523 // root path
524 var root = this._root
525
526 // references
527 this.res = res
528
529 // decode the path
530 var path = decode(this.path)
531 if (path === -1) {
532 this.error(400)
533 return res
534 }
535
536 // null byte(s)
537 if (~path.indexOf('\0')) {
538 this.error(400)
539 return res
540 }
541
542 var parts
543 if (root !== null) {
544 // malicious path
545 if (UP_PATH_REGEXP.test(normalize('.' + sep + path))) {
546 debug('malicious path "%s"', path)
547 this.error(403)
548 return res
549 }
550
551 // join / normalize from optional root dir
552 path = normalize(join(root, path))
553 root = normalize(root + sep)
554
555 // explode path parts
556 parts = path.substr(root.length).split(sep)
557 } else {
558 // ".." is malicious without "root"
559 if (UP_PATH_REGEXP.test(path)) {
560 debug('malicious path "%s"', path)
561 this.error(403)
562 return res
563 }
564
565 // explode path parts
566 parts = normalize(path).split(sep)
567
568 // resolve the path
569 path = resolve(path)
570 }
571
572 // dotfile handling
573 if (containsDotFile(parts)) {
574 var access = this._dotfiles
575
576 // legacy support
577 if (access === undefined) {
578 access = parts[parts.length - 1][0] === '.'
579 ? (this._hidden ? 'allow' : 'ignore')
580 : 'allow'
581 }
582
583 debug('%s dotfile "%s"', access, path)
584 switch (access) {
585 case 'allow':
586 break
587 case 'deny':
588 this.error(403)
589 return res
590 case 'ignore':
591 default:
592 this.error(404)
593 return res
594 }
595 }
596
597 // index file support
598 if (this._index.length && this.hasTrailingSlash()) {
599 this.sendIndex(path)
600 return res
601 }
602
603 this.sendFile(path)
604 return res
605}
606
607/**
608 * Transfer `path`.
609 *
610 * @param {String} path
611 * @api public
612 */
613
614SendStream.prototype.send = function send (path, stat) {
615 var len = stat.size
616 var options = this.options
617 var opts = {}
618 var res = this.res
619 var req = this.req
620 var ranges = req.headers.range
621 var offset = options.start || 0
622
623 if (headersSent(res)) {
624 // impossible to send now
625 this.headersAlreadySent()
626 return
627 }
628
629 debug('pipe "%s"', path)
630
631 // set header fields
632 this.setHeader(path, stat)
633
634 // set content-type
635 this.type(path)
636
637 // conditional GET support
638 if (this.isConditionalGET()) {
639 if (this.isPreconditionFailure()) {
640 this.error(412)
641 return
642 }
643
644 if (this.isCachable() && this.isFresh()) {
645 this.notModified()
646 return
647 }
648 }
649
650 // adjust len to start/end options
651 len = Math.max(0, len - offset)
652 if (options.end !== undefined) {
653 var bytes = options.end - offset + 1
654 if (len > bytes) len = bytes
655 }
656
657 // Range support
658 if (this._acceptRanges && BYTES_RANGE_REGEXP.test(ranges)) {
659 // parse
660 ranges = parseRange(len, ranges, {
661 combine: true
662 })
663
664 // If-Range support
665 if (!this.isRangeFresh()) {
666 debug('range stale')
667 ranges = -2
668 }
669
670 // unsatisfiable
671 if (ranges === -1) {
672 debug('range unsatisfiable')
673
674 // Content-Range
675 res.setHeader('Content-Range', contentRange('bytes', len))
676
677 // 416 Requested Range Not Satisfiable
678 return this.error(416, {
679 headers: {'Content-Range': res.getHeader('Content-Range')}
680 })
681 }
682
683 // valid (syntactically invalid/multiple ranges are treated as a regular response)
684 if (ranges !== -2 && ranges.length === 1) {
685 debug('range %j', ranges)
686
687 // Content-Range
688 res.statusCode = 206
689 res.setHeader('Content-Range', contentRange('bytes', len, ranges[0]))
690
691 // adjust for requested range
692 offset += ranges[0].start
693 len = ranges[0].end - ranges[0].start + 1
694 }
695 }
696
697 // clone options
698 for (var prop in options) {
699 opts[prop] = options[prop]
700 }
701
702 // set read options
703 opts.start = offset
704 opts.end = Math.max(offset, offset + len - 1)
705
706 // content-length
707 res.setHeader('Content-Length', len)
708
709 // HEAD support
710 if (req.method === 'HEAD') {
711 res.end()
712 return
713 }
714
715 this.stream(path, opts)
716}
717
718/**
719 * Transfer file for `path`.
720 *
721 * @param {String} path
722 * @api private
723 */
724SendStream.prototype.sendFile = function sendFile (path) {
725 var i = 0
726 var self = this
727
728 debug('stat "%s"', path)
729 fs.stat(path, function onstat (err, stat) {
730 if (err && err.code === 'ENOENT' && !extname(path) && path[path.length - 1] !== sep) {
731 // not found, check extensions
732 return next(err)
733 }
734 if (err) return self.onStatError(err)
735 if (stat.isDirectory()) return self.redirect(path)
736 self.emit('file', path, stat)
737 self.send(path, stat)
738 })
739
740 function next (err) {
741 if (self._extensions.length <= i) {
742 return err
743 ? self.onStatError(err)
744 : self.error(404)
745 }
746
747 var p = path + '.' + self._extensions[i++]
748
749 debug('stat "%s"', p)
750 fs.stat(p, function (err, stat) {
751 if (err) return next(err)
752 if (stat.isDirectory()) return next()
753 self.emit('file', p, stat)
754 self.send(p, stat)
755 })
756 }
757}
758
759/**
760 * Transfer index for `path`.
761 *
762 * @param {String} path
763 * @api private
764 */
765SendStream.prototype.sendIndex = function sendIndex (path) {
766 var i = -1
767 var self = this
768
769 function next (err) {
770 if (++i >= self._index.length) {
771 if (err) return self.onStatError(err)
772 return self.error(404)
773 }
774
775 var p = join(path, self._index[i])
776
777 debug('stat "%s"', p)
778 fs.stat(p, function (err, stat) {
779 if (err) return next(err)
780 if (stat.isDirectory()) return next()
781 self.emit('file', p, stat)
782 self.send(p, stat)
783 })
784 }
785
786 next()
787}
788
789/**
790 * Stream `path` to the response.
791 *
792 * @param {String} path
793 * @param {Object} options
794 * @api private
795 */
796
797SendStream.prototype.stream = function stream (path, options) {
798 // TODO: this is all lame, refactor meeee
799 var finished = false
800 var self = this
801 var res = this.res
802
803 // pipe
804 var stream = fs.createReadStream(path, options)
805 this.emit('stream', stream)
806 stream.pipe(res)
807
808 // response finished, done with the fd
809 onFinished(res, function onfinished () {
810 finished = true
811 destroy(stream)
812 })
813
814 // error handling code-smell
815 stream.on('error', function onerror (err) {
816 // request already finished
817 if (finished) return
818
819 // clean up stream
820 finished = true
821 destroy(stream)
822
823 // error
824 self.onStatError(err)
825 })
826
827 // end
828 stream.on('end', function onend () {
829 self.emit('end')
830 })
831}
832
833/**
834 * Set content-type based on `path`
835 * if it hasn't been explicitly set.
836 *
837 * @param {String} path
838 * @api private
839 */
840
841SendStream.prototype.type = function type (path) {
842 var res = this.res
843
844 if (res.getHeader('Content-Type')) return
845
846 var type = mime.lookup(path)
847
848 if (!type) {
849 debug('no content-type')
850 return
851 }
852
853 var charset = mime.charsets.lookup(type)
854
855 debug('content-type %s', type)
856 res.setHeader('Content-Type', type + (charset ? '; charset=' + charset : ''))
857}
858
859/**
860 * Set response header fields, most
861 * fields may be pre-defined.
862 *
863 * @param {String} path
864 * @param {Object} stat
865 * @api private
866 */
867
868SendStream.prototype.setHeader = function setHeader (path, stat) {
869 var res = this.res
870
871 this.emit('headers', res, path, stat)
872
873 if (this._acceptRanges && !res.getHeader('Accept-Ranges')) {
874 debug('accept ranges')
875 res.setHeader('Accept-Ranges', 'bytes')
876 }
877
878 if (this._cacheControl && !res.getHeader('Cache-Control')) {
879 var cacheControl = 'public, max-age=' + Math.floor(this._maxage / 1000)
880 debug('cache-control %s', cacheControl)
881 res.setHeader('Cache-Control', cacheControl)
882 }
883
884 if (this._lastModified && !res.getHeader('Last-Modified')) {
885 var modified = stat.mtime.toUTCString()
886 debug('modified %s', modified)
887 res.setHeader('Last-Modified', modified)
888 }
889
890 if (this._etag && !res.getHeader('ETag')) {
891 var val = etag(stat)
892 debug('etag %s', val)
893 res.setHeader('ETag', val)
894 }
895}
896
897/**
898 * Clear all headers from a response.
899 *
900 * @param {object} res
901 * @private
902 */
903
904function clearHeaders (res) {
905 var headers = getHeaderNames(res)
906
907 for (var i = 0; i < headers.length; i++) {
908 res.removeHeader(headers[i])
909 }
910}
911
912/**
913 * Collapse all leading slashes into a single slash
914 *
915 * @param {string} str
916 * @private
917 */
918function collapseLeadingSlashes (str) {
919 for (var i = 0; i < str.length; i++) {
920 if (str[i] !== '/') {
921 break
922 }
923 }
924
925 return i > 1
926 ? '/' + str.substr(i)
927 : str
928}
929
930/**
931 * Determine if path parts contain a dotfile.
932 *
933 * @api private
934 */
935
936function containsDotFile (parts) {
937 for (var i = 0; i < parts.length; i++) {
938 if (parts[i][0] === '.') {
939 return true
940 }
941 }
942
943 return false
944}
945
946/**
947 * Create a Content-Range header.
948 *
949 * @param {string} type
950 * @param {number} size
951 * @param {array} [range]
952 */
953
954function contentRange (type, size, range) {
955 return type + ' ' + (range ? range.start + '-' + range.end : '*') + '/' + size
956}
957
958/**
959 * Create a minimal HTML document.
960 *
961 * @param {string} title
962 * @param {string} body
963 * @private
964 */
965
966function createHtmlDocument (title, body) {
967 return '<!DOCTYPE html>\n' +
968 '<html lang="en">\n' +
969 '<head>\n' +
970 '<meta charset="utf-8">\n' +
971 '<title>' + title + '</title>\n' +
972 '</head>\n' +
973 '<body>\n' +
974 '<pre>' + body + '</pre>\n' +
975 '</body>\n'
976}
977
978/**
979 * decodeURIComponent.
980 *
981 * Allows V8 to only deoptimize this fn instead of all
982 * of send().
983 *
984 * @param {String} path
985 * @api private
986 */
987
988function decode (path) {
989 try {
990 return decodeURIComponent(path)
991 } catch (err) {
992 return -1
993 }
994}
995
996/**
997 * Get the header names on a respnse.
998 *
999 * @param {object} res
1000 * @returns {array[string]}
1001 * @private
1002 */
1003
1004function getHeaderNames (res) {
1005 return typeof res.getHeaderNames !== 'function'
1006 ? Object.keys(res._headers || {})
1007 : res.getHeaderNames()
1008}
1009
1010/**
1011 * Determine if the response headers have been sent.
1012 *
1013 * @param {object} res
1014 * @returns {boolean}
1015 * @private
1016 */
1017
1018function headersSent (res) {
1019 return typeof res.headersSent !== 'boolean'
1020 ? Boolean(res._header)
1021 : res.headersSent
1022}
1023
1024/**
1025 * Normalize the index option into an array.
1026 *
1027 * @param {boolean|string|array} val
1028 * @param {string} name
1029 * @private
1030 */
1031
1032function normalizeList (val, name) {
1033 var list = [].concat(val || [])
1034
1035 for (var i = 0; i < list.length; i++) {
1036 if (typeof list[i] !== 'string') {
1037 throw new TypeError(name + ' must be array of strings or false')
1038 }
1039 }
1040
1041 return list
1042}
1043
1044/**
1045 * Set an object of headers on a response.
1046 *
1047 * @param {object} res
1048 * @param {object} headers
1049 * @private
1050 */
1051
1052function setHeaders (res, headers) {
1053 var keys = Object.keys(headers)
1054
1055 for (var i = 0; i < keys.length; i++) {
1056 var key = keys[i]
1057 res.setHeader(key, headers[key])
1058 }
1059}