You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
1.9 KiB

7 years ago
  1. /**
  2. * Expose `pathtoRegexp`.
  3. */
  4. module.exports = pathtoRegexp;
  5. /**
  6. * Normalize the given path string,
  7. * returning a regular expression.
  8. *
  9. * An empty array should be passed,
  10. * which will contain the placeholder
  11. * key names. For example "/user/:id" will
  12. * then contain ["id"].
  13. *
  14. * @param {String|RegExp|Array} path
  15. * @param {Array} keys
  16. * @param {Object} options
  17. * @return {RegExp}
  18. * @api private
  19. */
  20. function pathtoRegexp(path, keys, options) {
  21. options = options || {};
  22. var strict = options.strict;
  23. var end = options.end !== false;
  24. var flags = options.sensitive ? '' : 'i';
  25. keys = keys || [];
  26. if (path instanceof RegExp) {
  27. return path;
  28. }
  29. if (Array.isArray(path)) {
  30. // Map array parts into regexps and return their source. We also pass
  31. // the same keys and options instance into every generation to get
  32. // consistent matching groups before we join the sources together.
  33. path = path.map(function (value) {
  34. return pathtoRegexp(value, keys, options).source;
  35. });
  36. return new RegExp('(?:' + path.join('|') + ')', flags);
  37. }
  38. path = ('^' + path + (strict ? '' : path[path.length - 1] === '/' ? '?' : '/?'))
  39. .replace(/\/\(/g, '/(?:')
  40. .replace(/([\/\.])/g, '\\$1')
  41. .replace(/(\\\/)?(\\\.)?:(\w+)(\(.*?\))?(\*)?(\?)?/g, function (match, slash, format, key, capture, star, optional) {
  42. slash = slash || '';
  43. format = format || '';
  44. capture = capture || '([^\\/' + format + ']+?)';
  45. optional = optional || '';
  46. keys.push({ name: key, optional: !!optional });
  47. return ''
  48. + (optional ? '' : slash)
  49. + '(?:'
  50. + format + (optional ? slash : '') + capture
  51. + (star ? '((?:[\\/' + format + '].+?)?)' : '')
  52. + ')'
  53. + optional;
  54. })
  55. .replace(/\*/g, '(.*)');
  56. // If the path is non-ending, match until the end or a slash.
  57. path += (end ? '$' : (path[path.length - 1] === '/' ? '' : '(?=\\/|$)'));
  58. return new RegExp(path, flags);
  59. };