Skip to content
Myr

utils.js

This file

Path

lib/utils.js

407 lines · 8.1 KiB · JavaScript

Last changed by

Use etag module to generate ETag headersDouglas Christopher Wilsonbefore adoption4d1ee23

History of this file

Take it

The walk stopped after 200 commits: lines older than 766b3ae point at it.

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption766b3ae

lines 1–5why, one step back
1
2/**3 * Module dependencies.4 */5

Use etag module to generate ETag headersDouglas Christopher Wilsonbefore adoption4d1ee23

lines 6–8why, one step back
6var etag = require('etag');
7var mime = require('connect').mime;8var proxyaddr = require('proxy-addr');

Use media-typer to alter content-type charsetDouglas Christopher Wilsonbefore adoptione66667e

line 9why, one step back
9var typer = require('media-typer');

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption766b3ae

lines 10–17why, one step back
10
11/**12 * toString ref.13 */1415var toString = {}.toString;1617/**

improve etag control for res.sendDouglas Christopher Wilsonbefore adoptionc21226a

line 18why, one step back
18 * Return strong ETag for `body`.

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption766b3ae

lines 19–25why, one step back
19 *
20 * @param {String|Buffer} body21 * @param {String} [encoding]22 * @return {String}23 * @api private24 */25

Use etag module to generate ETag headersDouglas Christopher Wilsonbefore adoption4d1ee23

lines 26–29why, one step back
26exports.etag = function (body, encoding) {
27 var buf = !Buffer.isBuffer(body)28 ? new Buffer(body, encoding)29 : body;

improve etag control for res.sendDouglas Christopher Wilsonbefore adoptionc21226a

line 30why, one step back
30

Use etag module to generate ETag headersDouglas Christopher Wilsonbefore adoption4d1ee23

line 31why, one step back
31 return etag(buf, {weak: false});

improve etag control for res.sendDouglas Christopher Wilsonbefore adoptionc21226a

lines 32–43why, one step back
32};
3334/**35 * Return weak ETag for `body`.36 *37 * @param {String|Buffer} body38 * @param {String} [encoding]39 * @return {String}40 * @api private41 */4243exports.wetag = function wetag(body, encoding){

Use etag module to generate ETag headersDouglas Christopher Wilsonbefore adoption4d1ee23

lines 44–46why, one step back
44 var buf = !Buffer.isBuffer(body)
45 ? new Buffer(body, encoding)46 : body;

improve etag control for res.sendDouglas Christopher Wilsonbefore adoptionc21226a

line 47why, one step back
47

Use etag module to generate ETag headersDouglas Christopher Wilsonbefore adoption4d1ee23

line 48why, one step back
48 return etag(buf, {weak: true});

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption766b3ae

lines 49–321why, one step back
49};
5051/**52 * Make `locals()` bound to the given `obj`.53 *54 * This is used for `app.locals` and `res.locals`.55 *56 * @param {Object} obj57 * @return {Function}58 * @api private59 */6061exports.locals = function(){62 function locals(obj){63 for (var key in obj) locals[key] = obj[key];64 return obj;65 };6667 return locals;68};6970/**71 * Check if `path` looks absolute.72 *73 * @param {String} path74 * @return {Boolean}75 * @api private76 */7778exports.isAbsolute = function(path){79 if ('/' == path[0]) return true;80 if (':' == path[1] && '\\' == path[2]) return true;81 if ('\\\\' == path.substring(0, 2)) return true; // Microsoft Azure absolute path82};8384/**85 * Flatten the given `arr`.86 *87 * @param {Array} arr88 * @return {Array}89 * @api private90 */9192exports.flatten = function(arr, ret){93 var ret = ret || []94 , len = arr.length;95 for (var i = 0; i < len; ++i) {96 if (Array.isArray(arr[i])) {97 exports.flatten(arr[i], ret);98 } else {99 ret.push(arr[i]);100 }101 }102 return ret;103};104105/**106 * Normalize the given `type`, for example "html" becomes "text/html".107 *108 * @param {String} type109 * @return {Object}110 * @api private111 */112113exports.normalizeType = function(type){114 return ~type.indexOf('/')115 ? acceptParams(type)116 : { value: mime.lookup(type), params: {} };117};118119/**120 * Normalize `types`, for example "html" becomes "text/html".121 *122 * @param {Array} types123 * @return {Array}124 * @api private125 */126127exports.normalizeTypes = function(types){128 var ret = [];129130 for (var i = 0; i < types.length; ++i) {131 ret.push(exports.normalizeType(types[i]));132 }133134 return ret;135};136137/**138 * Return the acceptable type in `types`, if any.139 *140 * @param {Array} types141 * @param {String} str142 * @return {String}143 * @api private144 */145146exports.acceptsArray = function(types, str){147 // accept anything when Accept is not present148 if (!str) return types[0];149150 // parse151 var accepted = exports.parseAccept(str)152 , normalized = exports.normalizeTypes(types)153 , len = accepted.length;154155 for (var i = 0; i < len; ++i) {156 for (var j = 0, jlen = types.length; j < jlen; ++j) {157 if (exports.accept(normalized[j], accepted[i])) {158 return types[j];159 }160 }161 }162};163164/**165 * Check if `type(s)` are acceptable based on166 * the given `str`.167 *168 * @param {String|Array} type(s)169 * @param {String} str170 * @return {Boolean|String}171 * @api private172 */173174exports.accepts = function(type, str){175 if ('string' == typeof type) type = type.split(/ *, */);176 return exports.acceptsArray(type, str);177};178179/**180 * Check if `type` array is acceptable for `other`.181 *182 * @param {Object} type183 * @param {Object} other184 * @return {Boolean}185 * @api private186 */187188exports.accept = function(type, other){189 var t = type.value.split('/');190 return (t[0] == other.type || '*' == other.type)191 && (t[1] == other.subtype || '*' == other.subtype)192 && paramsEqual(type.params, other.params);193};194195/**196 * Check if accept params are equal.197 *198 * @param {Object} a199 * @param {Object} b200 * @return {Boolean}201 * @api private202 */203204function paramsEqual(a, b){205 return !Object.keys(a).some(function(k) {206 return a[k] != b[k];207 });208}209210/**211 * Parse accept `str`, returning212 * an array objects containing213 * `.type` and `.subtype` along214 * with the values provided by215 * `parseQuality()`.216 *217 * @param {Type} name218 * @return {Type}219 * @api private220 */221222exports.parseAccept = function(str){223 return exports224 .parseParams(str)225 .map(function(obj){226 var parts = obj.value.split('/');227 obj.type = parts[0];228 obj.subtype = parts[1];229 return obj;230 });231};232233/**234 * Parse quality `str`, returning an235 * array of objects with `.value`,236 * `.quality` and optional `.params`237 *238 * @param {String} str239 * @return {Array}240 * @api private241 */242243exports.parseParams = function(str){244 return str245 .split(/ *, */)246 .map(acceptParams)247 .filter(function(obj){248 return obj.quality;249 })250 .sort(function(a, b){251 if (a.quality === b.quality) {252 return a.originalIndex - b.originalIndex;253 } else {254 return b.quality - a.quality;255 }256 });257};258259/**260 * Parse accept params `str` returning an261 * object with `.value`, `.quality` and `.params`.262 * also includes `.originalIndex` for stable sorting263 *264 * @param {String} str265 * @return {Object}266 * @api private267 */268269function acceptParams(str, index) {270 var parts = str.split(/ *; */);271 var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index };272273 for (var i = 1; i < parts.length; ++i) {274 var pms = parts[i].split(/ *= */);275 if ('q' == pms[0]) {276 ret.quality = parseFloat(pms[1]);277 } else {278 ret.params[pms[0]] = pms[1];279 }280 }281282 return ret;283}284285/**286 * Normalize the given path string,287 * returning a regular expression.288 *289 * An empty array should be passed,290 * which will contain the placeholder291 * key names. For example "/user/:id" will292 * then contain ["id"].293 *294 * @param {String|RegExp|Array} path295 * @param {Array} keys296 * @param {Boolean} sensitive297 * @param {Boolean} strict298 * @return {RegExp}299 * @api private300 */301302exports.pathRegexp = function(path, keys, sensitive, strict) {303 if (toString.call(path) == '[object RegExp]') return path;304 if (Array.isArray(path)) path = '(' + path.join('|') + ')';305 path = path306 .concat(strict ? '' : '/?')307 .replace(/\/\(/g, '(?:/')308 .replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?(\*)?/g, function(_, slash, format, key, capture, optional, star){309 keys.push({ name: key, optional: !! optional });310 slash = slash || '';311 return ''312 + (optional ? '' : slash)313 + '(?:'314 + (optional ? slash : '')315 + (format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)')) + ')'316 + (optional || '')317 + (star ? '(/*)?' : '');318 })319 .replace(/([\/.])/g, '\\$1')320 .replace(/\*/g, '(.*)');321 return new RegExp('^' + path + '$', sensitive ? '' : 'i');

improve etag control for res.sendDouglas Christopher Wilsonbefore adoptionc21226a

lines 322–355why, one step back
322}
323324/**325 * Compile "etag" value to function.326 *327 * @param {Boolean|String|Function} val328 * @return {Function}329 * @api private330 */331332exports.compileETag = function(val) {333 var fn;334335 if (typeof val === 'function') {336 return val;337 }338339 switch (val) {340 case true:341 fn = exports.wetag;342 break;343 case false:344 break;345 case 'strong':346 fn = exports.etag;347 break;348 case 'weak':349 fn = exports.wetag;350 break;351 default:352 throw new TypeError('unknown value for etag function: ' + val);353 }354355 return fn;

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption766b3ae

lines 356–398why, one step back
356}
357358/**359 * Compile "proxy trust" value to function.360 *361 * @param {Boolean|String|Number|Array|Function} val362 * @return {Function}363 * @api private364 */365366exports.compileTrust = function(val) {367 if (typeof val === 'function') return val;368369 if (val === true) {370 // Support plain true/false371 return function(){ return true };372 }373374 if (typeof val === 'number') {375 // Support trusting hop count376 return function(a, i){ return i < val };377 }378379 if (typeof val === 'string') {380 // Support comma-separated values381 val = val.split(/ *, */);382 }383384 return proxyaddr.compile(val || []);385}386387/**388 * Set the charset in a given Content-Type string.389 *390 * @param {String} type391 * @param {String} charset392 * @return {String}393 * @api private394 */395396exports.setCharset = function(type, charset){397 if (!type || !charset) return type;398

Use media-typer to alter content-type charsetDouglas Christopher Wilsonbefore adoptione66667e

lines 399–400why, one step back
399 // parse type
400 var parsed = typer.parse(type);

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption766b3ae

line 401why, one step back
401

Use media-typer to alter content-type charsetDouglas Christopher Wilsonbefore adoptione66667e

lines 402–403why, one step back
402 // set charset
403 parsed.parameters.charset = charset;

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption766b3ae

line 404why, one step back
404

Use media-typer to alter content-type charsetDouglas Christopher Wilsonbefore adoptione66667e

lines 405–406why, one step back
405 // format type
406 return typer.format(parsed);

deps: update example dependenciesDouglas Christopher Wilsonbefore adoption766b3ae

line 407why, one step back
407};