Skip to content
Myr

utils.js

This file

Path

lib/utils.js

456 lines · 9.1 KiB · JavaScript

Last changed by

replace utils.escape with html-escapeDouglas Christopher Wilsonbefore adoptionf433b7c

History of this file

Take it

12/**3 * Module dependencies.4 */56var mime = require('connect').mime7  , deprecate = require('util').deprecate8  , proxyaddr = require('proxy-addr')9  , crc32 = require('buffer-crc32')10  , crypto = require('crypto');1112/**13 * toString ref.14 */1516var toString = {}.toString;1718/**19 * Simple detection of charset parameter in content-type20 */21var charsetRegExp = /;\s*charset\s*=/;2223/**24 * Deprecate function, like core `util.deprecate`,25 * but with NODE_ENV and color support.26 *27 * @param {Function} fn28 * @param {String} msg29 * @return {Function}30 * @api private31 */3233exports.deprecate = function(fn, msg){34  if (process.env.NODE_ENV === 'test') return fn;3536  // prepend module name37  msg = 'express: ' + msg;3839  if (process.stderr.isTTY) {40    // colorize41    msg = '\x1b[31;1m' + msg + '\x1b[0m';42  }4344  return deprecate(fn, msg);45};4647/**48 * Return strong ETag for `body`.49 *50 * @param {String|Buffer} body51 * @param {String} [encoding]52 * @return {String}53 * @api private54 */5556exports.etag = function etag(body, encoding){57  if (body.length === 0) {58    // fast-path empty body59    return '"1B2M2Y8AsgTpgAmY7PhCfg=="'60  }6162  var hash = crypto63    .createHash('md5')64    .update(body, encoding)65    .digest('base64')66  return '"' + hash + '"'67};6869/**70 * Return weak ETag for `body`.71 *72 * @param {String|Buffer} body73 * @param {String} [encoding]74 * @return {String}75 * @api private76 */7778exports.wetag = function wetag(body, encoding){79  if (body.length === 0) {80    // fast-path empty body81    return 'W/"0-0"'82  }8384  var buf = Buffer.isBuffer(body)85    ? body86    : new Buffer(body, encoding)87  var len = buf.length88  return 'W/"' + len.toString(16) + '-' + crc32.unsigned(buf) + '"'89};9091/**92 * Make `locals()` bound to the given `obj`.93 *94 * This is used for `app.locals` and `res.locals`.95 *96 * @param {Object} obj97 * @return {Function}98 * @api private99 */100101exports.locals = function(){102  function locals(obj){103    for (var key in obj) locals[key] = obj[key];104    return obj;105  };106107  return locals;108};109110/**111 * Check if `path` looks absolute.112 *113 * @param {String} path114 * @return {Boolean}115 * @api private116 */117118exports.isAbsolute = function(path){119  if ('/' == path[0]) return true;120  if (':' == path[1] && '\\' == path[2]) return true;121  if ('\\\\' == path.substring(0, 2)) return true; // Microsoft Azure absolute path122};123124/**125 * Flatten the given `arr`.126 *127 * @param {Array} arr128 * @return {Array}129 * @api private130 */131132exports.flatten = function(arr, ret){133  var ret = ret || []134    , len = arr.length;135  for (var i = 0; i < len; ++i) {136    if (Array.isArray(arr[i])) {137      exports.flatten(arr[i], ret);138    } else {139      ret.push(arr[i]);140    }141  }142  return ret;143};144145/**146 * Normalize the given `type`, for example "html" becomes "text/html".147 *148 * @param {String} type149 * @return {Object}150 * @api private151 */152153exports.normalizeType = function(type){154  return ~type.indexOf('/')155    ? acceptParams(type)156    : { value: mime.lookup(type), params: {} };157};158159/**160 * Normalize `types`, for example "html" becomes "text/html".161 *162 * @param {Array} types163 * @return {Array}164 * @api private165 */166167exports.normalizeTypes = function(types){168  var ret = [];169170  for (var i = 0; i < types.length; ++i) {171    ret.push(exports.normalizeType(types[i]));172  }173174  return ret;175};176177/**178 * Return the acceptable type in `types`, if any.179 *180 * @param {Array} types181 * @param {String} str182 * @return {String}183 * @api private184 */185186exports.acceptsArray = function(types, str){187  // accept anything when Accept is not present188  if (!str) return types[0];189190  // parse191  var accepted = exports.parseAccept(str)192    , normalized = exports.normalizeTypes(types)193    , len = accepted.length;194195  for (var i = 0; i < len; ++i) {196    for (var j = 0, jlen = types.length; j < jlen; ++j) {197      if (exports.accept(normalized[j], accepted[i])) {198        return types[j];199      }200    }201  }202};203204/**205 * Check if `type(s)` are acceptable based on206 * the given `str`.207 *208 * @param {String|Array} type(s)209 * @param {String} str210 * @return {Boolean|String}211 * @api private212 */213214exports.accepts = function(type, str){215  if ('string' == typeof type) type = type.split(/ *, */);216  return exports.acceptsArray(type, str);217};218219/**220 * Check if `type` array is acceptable for `other`.221 *222 * @param {Object} type223 * @param {Object} other224 * @return {Boolean}225 * @api private226 */227228exports.accept = function(type, other){229  var t = type.value.split('/');230  return (t[0] == other.type || '*' == other.type)231    && (t[1] == other.subtype || '*' == other.subtype)232    && paramsEqual(type.params, other.params);233};234235/**236 * Check if accept params are equal.237 *238 * @param {Object} a239 * @param {Object} b240 * @return {Boolean}241 * @api private242 */243244function paramsEqual(a, b){245  return !Object.keys(a).some(function(k) {246    return a[k] != b[k];247  });248}249250/**251 * Parse accept `str`, returning252 * an array objects containing253 * `.type` and `.subtype` along254 * with the values provided by255 * `parseQuality()`.256 *257 * @param {Type} name258 * @return {Type}259 * @api private260 */261262exports.parseAccept = function(str){263  return exports264    .parseParams(str)265    .map(function(obj){266      var parts = obj.value.split('/');267      obj.type = parts[0];268      obj.subtype = parts[1];269      return obj;270    });271};272273/**274 * Parse quality `str`, returning an275 * array of objects with `.value`,276 * `.quality` and optional `.params`277 *278 * @param {String} str279 * @return {Array}280 * @api private281 */282283exports.parseParams = function(str){284  return str285    .split(/ *, */)286    .map(acceptParams)287    .filter(function(obj){288      return obj.quality;289    })290    .sort(function(a, b){291      if (a.quality === b.quality) {292        return a.originalIndex - b.originalIndex;293      } else {294        return b.quality - a.quality;295      }296    });297};298299/**300 * Parse accept params `str` returning an301 * object with `.value`, `.quality` and `.params`.302 * also includes `.originalIndex` for stable sorting303 *304 * @param {String} str305 * @return {Object}306 * @api private307 */308309function acceptParams(str, index) {310  var parts = str.split(/ *; */);311  var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index };312313  for (var i = 1; i < parts.length; ++i) {314    var pms = parts[i].split(/ *= */);315    if ('q' == pms[0]) {316      ret.quality = parseFloat(pms[1]);317    } else {318      ret.params[pms[0]] = pms[1];319    }320  }321322  return ret;323}324325/**326 * Normalize the given path string,327 * returning a regular expression.328 *329 * An empty array should be passed,330 * which will contain the placeholder331 * key names. For example "/user/:id" will332 * then contain ["id"].333 *334 * @param  {String|RegExp|Array} path335 * @param  {Array} keys336 * @param  {Boolean} sensitive337 * @param  {Boolean} strict338 * @return {RegExp}339 * @api private340 */341342exports.pathRegexp = function(path, keys, sensitive, strict) {343  if (toString.call(path) == '[object RegExp]') return path;344  if (Array.isArray(path)) path = '(' + path.join('|') + ')';345  path = path346    .concat(strict ? '' : '/?')347    .replace(/\/\(/g, '(?:/')348    .replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?(\*)?/g, function(_, slash, format, key, capture, optional, star){349      keys.push({ name: key, optional: !! optional });350      slash = slash || '';351      return ''352        + (optional ? '' : slash)353        + '(?:'354        + (optional ? slash : '')355        + (format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)')) + ')'356        + (optional || '')357        + (star ? '(/*)?' : '');358    })359    .replace(/([\/.])/g, '\\$1')360    .replace(/\*/g, '(.*)');361  return new RegExp('^' + path + '$', sensitive ? '' : 'i');362}363364/**365 * Compile "etag" value to function.366 *367 * @param  {Boolean|String|Function} val368 * @return {Function}369 * @api private370 */371372exports.compileETag = function(val) {373  var fn;374375  if (typeof val === 'function') {376    return val;377  }378379  switch (val) {380    case true:381      fn = exports.wetag;382      break;383    case false:384      break;385    case 'strong':386      fn = exports.etag;387      break;388    case 'weak':389      fn = exports.wetag;390      break;391    default:392      throw new TypeError('unknown value for etag function: ' + val);393  }394395  return fn;396}397398/**399 * Compile "proxy trust" value to function.400 *401 * @param  {Boolean|String|Number|Array|Function} val402 * @return {Function}403 * @api private404 */405406exports.compileTrust = function(val) {407  if (typeof val === 'function') return val;408409  if (val === true) {410    // Support plain true/false411    return function(){ return true };412  }413414  if (typeof val === 'number') {415    // Support trusting hop count416    return function(a, i){ return i < val };417  }418419  if (typeof val === 'string') {420    // Support comma-separated values421    val = val.split(/ *, */);422  }423424  return proxyaddr.compile(val || []);425}426427/**428 * Set the charset in a given Content-Type string.429 *430 * @param {String} type431 * @param {String} charset432 * @return {String}433 * @api private434 */435436exports.setCharset = function(type, charset){437  if (!type || !charset) return type;438439  var exists = charsetRegExp.test(type);440441  // removing existing charset442  if (exists) {443    var parts = type.split(';');444445    for (var i = 1; i < parts.length; i++) {446      if (charsetRegExp.test(';' + parts[i])) {447        parts.splice(i, 1);448        break;449      }450    }451452    type = parts.join(';');453  }454455  return type + '; charset=' + charset;456};