Name: js-handler/node_modules/restify/node_modules/negotiator/lib/mediaType.js
| 1: | module.exports = preferredMediaTypes; |
| 2: | preferredMediaTypes.preferredMediaTypes = preferredMediaTypes; |
| 3: | |
| 4: | function parseAccept(accept) { |
| 5: | return accept.split(',').map(function(e) { |
| 6: | return parseMediaType(e.trim()); |
| 7: | }).filter(function(e) { |
| 8: | return e && e.q > 0; |
| 9: | }); |
| 10: | }; |
| 11: | |
| 12: | function parseMediaType(s) { |
| 13: | var match = s.match(/\s*(\S+)\/([^;\s]+)\s*(?:;(.*))?/); |
| 14: | if (!match) return null; |
| 15: | |
| 16: | var type = match[1], |
| 17: | subtype = match[2], |
| 18: | full = "" + type + "/" + subtype, |
| 19: | params = {}, |
| 20: | q = 1; |
| 21: | |
| 22: | if (match[3]) { |
| 23: | params = match[3].split(';').map(function(s) { |
| 24: | return s.trim().split('='); |
| 25: | }).reduce(function (set, p) { |
| 26: | set[p[0]] = p[1]; |
| 27: | return set |
| 28: | }, params); |
| 29: | |
| 30: | if (params.q != null) { |
| 31: | q = parseFloat(params.q); |
| 32: | delete params.q; |
| 33: | } |
| 34: | } |
| 35: | |
| 36: | return { |
| 37: | type: type, |
| 38: | subtype: subtype, |
| 39: | params: params, |
| 40: | q: q, |
| 41: | full: full |
| 42: | }; |
| 43: | } |
| 44: | |
| 45: | function getMediaTypePriority(type, accepted) { |
| 46: | return (accepted.filter(function(a) { |
| 47: | return specify(type, a); |
| 48: | }).sort(function (a, b) { |
| 49: | // revsort |
| 50: | return a.q > b.q ? -1 : 1; |
| 51: | })[0] || {q:0}).q; |
| 52: | } |
| 53: | |
| 54: | function specifies(spec, type) { |
| 55: | return spec === '*' || spec === type; |
| 56: | } |
| 57: | |
| 58: | function specify(type, spec) { |
| 59: | var p = parseMediaType(type); |
| 60: | |
| 61: | if (spec.params) { |
| 62: | var keys = Object.keys(spec.params); |
| 63: | if (keys.some(function (k) { |
| 64: | return !specifies(spec.params[k], p.params[k]); |
| 65: | })) { |
| 66: | // some didn't specify. |
| 67: | return null; |
| 68: | } |
| 69: | } |
| 70: | |
| 71: | if (specifies(spec.type, p.type) && |
| 72: | specifies(spec.subtype, p.subtype)) { |
| 73: | return spec; |
| 74: | } |
| 75: | } |
| 76: | |
| 77: | function preferredMediaTypes(accept, provided) { |
| 78: | accept = parseAccept(accept || ''); |
| 79: | if (provided) { |
| 80: | return provided.map(function(type) { |
| 81: | return [type, getMediaTypePriority(type, accept)]; |
| 82: | }).filter(function(pair) { |
| 83: | return pair[1] > 0; |
| 84: | }).sort(function(a, b) { |
| 85: | // revsort |
| 86: | return a[1] === b[1] ? 0 : a[1] > b[1] ? -1 : 1; |
| 87: | }).map(function(pair) { |
| 88: | return pair[0]; |
| 89: | }); |
| 90: | |
| 91: | } else { |
| 92: | return accept.map(function(type) { |
| 93: | return type.full; |
| 94: | }); |
| 95: | } |
| 96: | } |
