utils.js
This file
Path
lib/utils.js
282 lines · 5.6 KiB · JavaScript
Last changed by
mergeTJ Holowaychukbefore adoptione2ad0d3
History of this fileTake it
The walk stopped after 200 commits: lines older than 64aac19 point at it.
any engineTJ Holowaychukbefore adoption64aac19
lines 1–5why, one step back12/**3 * Module dependencies.4 */5add etag utilTJ Holowaychukbefore adoptionf2f0976
line 6why, one step back6var mime = require('connect').mimemergeTJ Holowaychukbefore adoptione2ad0d3
line 7why, one step back7 , crc32 = require('buffer-crc32');add etag utilTJ Holowaychukbefore adoptionf2f0976
lines 8–17why, one step back89/**10 * Return ETag for `body`.11 *12 * @param {String|Buffer} body13 * @return {String}14 * @api private15 */1617exports.etag = function(body){mergeTJ Holowaychukbefore adoptione2ad0d3
line 18why, one step back18 return '"' + crc32.signed(body) + '"';add etag utilTJ Holowaychukbefore adoptionf2f0976
line 19why, one step back19};any engineTJ Holowaychukbefore adoption64aac19
lines 20–267why, one step back2021/**22 * Make `locals()` bound to the given `obj`.23 * 24 * This is used for `app.locals` and `res.locals`. 25 *26 * @param {Object} obj27 * @return {Function}28 * @api private29 */3031exports.locals = function(obj){32 obj.viewCallbacks = obj.viewCallbacks || [];3334 function locals(obj){35 for (var key in obj) locals[key] = obj[key];36 return obj;37 };3839 return locals;40};4142/**43 * Check if `path` looks absolute.44 *45 * @param {String} path46 * @return {Boolean}47 * @api private48 */4950exports.isAbsolute = function(path){51 if ('/' == path[0]) return true;52 if (':' == path[1] && '\\' == path[2]) return true;53};5455/**56 * Flatten the given `arr`.57 *58 * @param {Array} arr59 * @return {Array}60 * @api private61 */6263exports.flatten = function(arr, ret){64 var ret = ret || []65 , len = arr.length;66 for (var i = 0; i < len; ++i) {67 if (Array.isArray(arr[i])) {68 exports.flatten(arr[i], ret);69 } else {70 ret.push(arr[i]);71 }72 }73 return ret;74};7576/**77 * Normalize the given `type`, for example "html" becomes "text/html".78 *79 * @param {String} type80 * @return {String}81 * @api private82 */8384exports.normalizeType = function(type){85 return ~type.indexOf('/') ? type : mime.lookup(type);86};8788/**89 * Normalize `types`, for example "html" becomes "text/html".90 *91 * @param {Array} types92 * @return {Array}93 * @api private94 */9596exports.normalizeTypes = function(types){97 var ret = [];9899 for (var i = 0; i < types.length; ++i) {100 ret.push(~types[i].indexOf('/')101 ? types[i]102 : mime.lookup(types[i]));103 }104105 return ret;106};107108/**109 * Return the acceptable type in `types`, if any.110 *111 * @param {Array} types112 * @param {String} str113 * @return {String}114 * @api private115 */116117exports.acceptsArray = function(types, str){118 // accept anything when Accept is not present119 if (!str) return types[0];120121 // parse122 var accepted = exports.parseAccept(str)123 , normalized = exports.normalizeTypes(types)124 , len = accepted.length;125126 for (var i = 0; i < len; ++i) {127 for (var j = 0, jlen = types.length; j < jlen; ++j) {128 if (exports.accept(normalized[j].split('/'), accepted[i])) {129 return types[j];130 }131 }132 }133};134135/**136 * Check if `type(s)` are acceptable based on137 * the given `str`.138 *139 * @param {String|Array} type(s)140 * @param {String} str141 * @return {Boolean|String}142 * @api private143 */144145exports.accepts = function(type, str){146 if ('string' == typeof type) type = type.split(/ *, */);147 return exports.acceptsArray(type, str);148};149150/**151 * Check if `type` array is acceptable for `other`.152 *153 * @param {Array} type154 * @param {Object} other155 * @return {Boolean}156 * @api private157 */158159exports.accept = function(type, other){160 return (type[0] == other.type || '*' == other.type)161 && (type[1] == other.subtype || '*' == other.subtype);162};163164/**165 * Parse accept `str`, returning166 * an array objects containing167 * `.type` and `.subtype` along168 * with the values provided by169 * `parseQuality()`.170 *171 * @param {Type} name172 * @return {Type}173 * @api private174 */175176exports.parseAccept = function(str){177 return exports178 .parseQuality(str)179 .map(function(obj){180 var parts = obj.value.split('/');181 obj.type = parts[0];182 obj.subtype = parts[1];183 return obj;184 });185};186187/**188 * Parse quality `str`, returning an189 * array of objects with `.value` and190 * `.quality`.191 *192 * @param {Type} name193 * @return {Type}194 * @api private195 */196197exports.parseQuality = function(str){198 return str199 .split(/ *, */)200 .map(quality)201 .filter(function(obj){202 return obj.quality;203 })204 .sort(function(a, b){205 return b.quality - a.quality;206 });207};208209/**210 * Parse quality `str` returning an211 * object with `.value` and `.quality`.212 *213 * @param {String} str214 * @return {Object}215 * @api private216 */217218function quality(str) {219 var parts = str.split(/ *; */)220 , val = parts[0];221222 var q = parts[1]223 ? parseFloat(parts[1].split(/ *= */)[1])224 : 1;225226 return { value: val, quality: q };227}228229/**230 * Escape special characters in the given string of html.231 *232 * @param {String} html233 * @return {String}234 * @api private235 */236237exports.escape = function(html) {238 return String(html)239 .replace(/&/g, '&')240 .replace(/"/g, '"')241 .replace(/</g, '<')242 .replace(/>/g, '>');243};244245/**246 * Normalize the given path string,247 * returning a regular expression.248 *249 * An empty array should be passed,250 * which will contain the placeholder251 * key names. For example "/user/:id" will252 * then contain ["id"].253 *254 * @param {String|RegExp|Array} path255 * @param {Array} keys256 * @param {Boolean} sensitive257 * @param {Boolean} strict258 * @return {RegExp}259 * @api private260 */261262exports.pathRegexp = function(path, keys, sensitive, strict) {263 if (path instanceof RegExp) return path;264 if (Array.isArray(path)) path = '(' + path.join('|') + ')';265 path = path266 .concat(strict ? '' : '/?')267 .replace(/\/\(/g, '(?:/')* immediately after :param would become not greedyriadhbefore adoption73bed61
line 268why, one step back268 .replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?(\*)?/g, function(_, slash, format, key, capture, optional, star){any engineTJ Holowaychukbefore adoption64aac19
lines 269–275why, one step back269 keys.push({ name: key, optional: !! optional });270 slash = slash || '';271 return ''272 + (optional ? '' : slash)273 + '(?:'274 + (optional ? slash : '')275 + (format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)')) + ')'* immediately after :param would become not greedyriadhbefore adoption73bed61
line 276why, one step back276 + (optional || '')tests for issues 1115 fix for utilsriadhbefore adoption3827f5e
line 277why, one step back277 + (star ? '(/*)?' : '');any engineTJ Holowaychukbefore adoption64aac19
lines 278–282why, one step back278 })279 .replace(/([\/.])/g, '\\$1')280 .replace(/\*/g, '(.*)');281 return new RegExp('^' + path + '$', sensitive ? '' : 'i');282}