Skip to content
Myr

utils.js

This file

Path

lib/utils.js

418 lines · 8.3 KiB · JavaScript

Last changed by

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

History of this file

Take it

The walk stopped after 200 commits: lines older than 297fb4e point at it.

update connectTJ Holowaychukbefore adoption297fb4e

lines 1–6why, one step back
1
2/**3 * Module dependencies.4 */56var mime = require('connect').mime

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

line 7why, one step back
7 , proxyaddr = require('proxy-addr')

improve etag control for res.sendDouglas Christopher Wilsonbefore adoptionc21226a

lines 8–9why, one step back
8 , crc32 = require('buffer-crc32')
9 , crypto = require('crypto');

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

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

update connectTJ Holowaychukbefore adoption297fb4e

lines 11–16why, one step back
11
12/**13 * toString ref.14 */1516var toString = {}.toString;

Add standard deprecation utilityDouglas Christopher Wilsonbefore adoption8dc4ff2

lines 17–18why, one step back
17
18/**

improve etag control for res.sendDouglas Christopher Wilsonbefore adoptionc21226a

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

update connectTJ Holowaychukbefore adoption297fb4e

lines 20–21why, one step back
20 *
21 * @param {String|Buffer} body

mark res.send ETag as weak and reduce collisionsDouglas Christopher Wilsonbefore adoption8ab96ab

line 22why, one step back
22 * @param {String} [encoding]

update connectTJ Holowaychukbefore adoption297fb4e

lines 23–26why, one step back
23 * @return {String}
24 * @api private25 */26

improve etag control for res.sendDouglas Christopher Wilsonbefore adoptionc21226a

lines 27–54why, one step back
27exports.etag = function etag(body, encoding){
28 if (body.length === 0) {29 // fast-path empty body30 return '"1B2M2Y8AsgTpgAmY7PhCfg=="'31 }3233 var hash = crypto34 .createHash('md5')35 .update(body, encoding)36 .digest('base64')37 return '"' + hash + '"'38};3940/**41 * Return weak ETag for `body`.42 *43 * @param {String|Buffer} body44 * @param {String} [encoding]45 * @return {String}46 * @api private47 */4849exports.wetag = function wetag(body, encoding){50 if (body.length === 0) {51 // fast-path empty body52 return 'W/"0-0"'53 }54

mark res.send ETag as weak and reduce collisionsDouglas Christopher Wilsonbefore adoption8ab96ab

lines 55–59why, one step back
55 var buf = Buffer.isBuffer(body)
56 ? body57 : new Buffer(body, encoding)58 var len = buf.length59 return 'W/"' + len.toString(16) + '-' + crc32.unsigned(buf) + '"'

update connectTJ Holowaychukbefore adoption297fb4e

lines 60–71why, one step back
60};
6162/**63 * Make `locals()` bound to the given `obj`.64 *65 * This is used for `app.locals` and `res.locals`.66 *67 * @param {Object} obj68 * @return {Function}69 * @api private70 */71

lint: remove unused stuffJonathan Ongbefore adoption9bed2b8

line 72why, one step back
72exports.locals = function(){

update connectTJ Holowaychukbefore adoption297fb4e

lines 73–91why, one step back
73 function locals(obj){
74 for (var key in obj) locals[key] = obj[key];75 return obj;76 };7778 return locals;79};8081/**82 * Check if `path` looks absolute.83 *84 * @param {String} path85 * @return {Boolean}86 * @api private87 */8889exports.isAbsolute = function(path){90 if ('/' == path[0]) return true;91 if (':' == path[1] && '\\' == path[2]) return true;

Merge pull request #1740 from superic/masterTJ Holowaychukbefore adoptione43ff07

line 92why, one step back
92 if ('\\\\' == path.substring(0, 2)) return true; // Microsoft Azure absolute path

update connectTJ Holowaychukbefore adoption297fb4e

lines 93–332why, one step back
93};
9495/**96 * Flatten the given `arr`.97 *98 * @param {Array} arr99 * @return {Array}100 * @api private101 */102103exports.flatten = function(arr, ret){104 var ret = ret || []105 , len = arr.length;106 for (var i = 0; i < len; ++i) {107 if (Array.isArray(arr[i])) {108 exports.flatten(arr[i], ret);109 } else {110 ret.push(arr[i]);111 }112 }113 return ret;114};115116/**117 * Normalize the given `type`, for example "html" becomes "text/html".118 *119 * @param {String} type120 * @return {Object}121 * @api private122 */123124exports.normalizeType = function(type){125 return ~type.indexOf('/')126 ? acceptParams(type)127 : { value: mime.lookup(type), params: {} };128};129130/**131 * Normalize `types`, for example "html" becomes "text/html".132 *133 * @param {Array} types134 * @return {Array}135 * @api private136 */137138exports.normalizeTypes = function(types){139 var ret = [];140141 for (var i = 0; i < types.length; ++i) {142 ret.push(exports.normalizeType(types[i]));143 }144145 return ret;146};147148/**149 * Return the acceptable type in `types`, if any.150 *151 * @param {Array} types152 * @param {String} str153 * @return {String}154 * @api private155 */156157exports.acceptsArray = function(types, str){158 // accept anything when Accept is not present159 if (!str) return types[0];160161 // parse162 var accepted = exports.parseAccept(str)163 , normalized = exports.normalizeTypes(types)164 , len = accepted.length;165166 for (var i = 0; i < len; ++i) {167 for (var j = 0, jlen = types.length; j < jlen; ++j) {168 if (exports.accept(normalized[j], accepted[i])) {169 return types[j];170 }171 }172 }173};174175/**176 * Check if `type(s)` are acceptable based on177 * the given `str`.178 *179 * @param {String|Array} type(s)180 * @param {String} str181 * @return {Boolean|String}182 * @api private183 */184185exports.accepts = function(type, str){186 if ('string' == typeof type) type = type.split(/ *, */);187 return exports.acceptsArray(type, str);188};189190/**191 * Check if `type` array is acceptable for `other`.192 *193 * @param {Object} type194 * @param {Object} other195 * @return {Boolean}196 * @api private197 */198199exports.accept = function(type, other){200 var t = type.value.split('/');201 return (t[0] == other.type || '*' == other.type)202 && (t[1] == other.subtype || '*' == other.subtype)203 && paramsEqual(type.params, other.params);204};205206/**207 * Check if accept params are equal.208 *209 * @param {Object} a210 * @param {Object} b211 * @return {Boolean}212 * @api private213 */214215function paramsEqual(a, b){216 return !Object.keys(a).some(function(k) {217 return a[k] != b[k];218 });219}220221/**222 * Parse accept `str`, returning223 * an array objects containing224 * `.type` and `.subtype` along225 * with the values provided by226 * `parseQuality()`.227 *228 * @param {Type} name229 * @return {Type}230 * @api private231 */232233exports.parseAccept = function(str){234 return exports235 .parseParams(str)236 .map(function(obj){237 var parts = obj.value.split('/');238 obj.type = parts[0];239 obj.subtype = parts[1];240 return obj;241 });242};243244/**245 * Parse quality `str`, returning an246 * array of objects with `.value`,247 * `.quality` and optional `.params`248 *249 * @param {String} str250 * @return {Array}251 * @api private252 */253254exports.parseParams = function(str){255 return str256 .split(/ *, */)257 .map(acceptParams)258 .filter(function(obj){259 return obj.quality;260 })261 .sort(function(a, b){262 if (a.quality === b.quality) {263 return a.originalIndex - b.originalIndex;264 } else {265 return b.quality - a.quality;266 }267 });268};269270/**271 * Parse accept params `str` returning an272 * object with `.value`, `.quality` and `.params`.273 * also includes `.originalIndex` for stable sorting274 *275 * @param {String} str276 * @return {Object}277 * @api private278 */279280function acceptParams(str, index) {281 var parts = str.split(/ *; */);282 var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index };283284 for (var i = 1; i < parts.length; ++i) {285 var pms = parts[i].split(/ *= */);286 if ('q' == pms[0]) {287 ret.quality = parseFloat(pms[1]);288 } else {289 ret.params[pms[0]] = pms[1];290 }291 }292293 return ret;294}295296/**297 * Normalize the given path string,298 * returning a regular expression.299 *300 * An empty array should be passed,301 * which will contain the placeholder302 * key names. For example "/user/:id" will303 * then contain ["id"].304 *305 * @param {String|RegExp|Array} path306 * @param {Array} keys307 * @param {Boolean} sensitive308 * @param {Boolean} strict309 * @return {RegExp}310 * @api private311 */312313exports.pathRegexp = function(path, keys, sensitive, strict) {314 if (toString.call(path) == '[object RegExp]') return path;315 if (Array.isArray(path)) path = '(' + path.join('|') + ')';316 path = path317 .concat(strict ? '' : '/?')318 .replace(/\/\(/g, '(?:/')319 .replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?(\*)?/g, function(_, slash, format, key, capture, optional, star){320 keys.push({ name: key, optional: !! optional });321 slash = slash || '';322 return ''323 + (optional ? '' : slash)324 + '(?:'325 + (optional ? slash : '')326 + (format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)')) + ')'327 + (optional || '')328 + (star ? '(/*)?' : '');329 })330 .replace(/([\/.])/g, '\\$1')331 .replace(/\*/g, '(.*)');332 return new RegExp('^' + path + '$', sensitive ? '' : 'i');

improve etag control for res.sendDouglas Christopher Wilsonbefore adoptionc21226a

lines 333–366why, one step back
333}
334335/**336 * Compile "etag" value to function.337 *338 * @param {Boolean|String|Function} val339 * @return {Function}340 * @api private341 */342343exports.compileETag = function(val) {344 var fn;345346 if (typeof val === 'function') {347 return val;348 }349350 switch (val) {351 case true:352 fn = exports.wetag;353 break;354 case false:355 break;356 case 'strong':357 fn = exports.etag;358 break;359 case 'weak':360 fn = exports.wetag;361 break;362 default:363 throw new TypeError('unknown value for etag function: ' + val);364 }365366 return fn;

improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b

lines 367–395why, one step back
367}
368369/**370 * Compile "proxy trust" value to function.371 *372 * @param {Boolean|String|Number|Array|Function} val373 * @return {Function}374 * @api private375 */376377exports.compileTrust = function(val) {378 if (typeof val === 'function') return val;379380 if (val === true) {381 // Support plain true/false382 return function(){ return true };383 }384385 if (typeof val === 'number') {386 // Support trusting hop count387 return function(a, i){ return i < val };388 }389390 if (typeof val === 'string') {391 // Support comma-separated values392 val = val.split(/ *, */);393 }394395 return proxyaddr.compile(val || []);

update connectTJ Holowaychukbefore adoption297fb4e

line 396why, one step back
396}

set proper charset in content-type for res.sendDouglas Christopher Wilsonbefore adoptionf14e39d

lines 397–409why, one step back
397
398/**399 * Set the charset in a given Content-Type string.400 *401 * @param {String} type402 * @param {String} charset403 * @return {String}404 * @api private405 */406407exports.setCharset = function(type, charset){408 if (!type || !charset) return type;409

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

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

set proper charset in content-type for res.sendDouglas Christopher Wilsonbefore adoptionf14e39d

line 412why, one step back
412

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

lines 413–414why, one step back
413 // set charset
414 parsed.parameters.charset = charset;

set proper charset in content-type for res.sendDouglas Christopher Wilsonbefore adoptionf14e39d

line 415why, one step back
415

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

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

set proper charset in content-type for res.sendDouglas Christopher Wilsonbefore adoptionf14e39d

line 418why, one step back
418};