path-to-regexp 3.1.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/Readme.md CHANGED
@@ -21,6 +21,7 @@ npm install path-to-regexp --save
21
21
  const pathToRegexp = require('path-to-regexp')
22
22
 
23
23
  // pathToRegexp(path, keys?, options?)
24
+ // pathToRegexp.match(path)
24
25
  // pathToRegexp.parse(path)
25
26
  // pathToRegexp.compile(path)
26
27
  ```
@@ -150,9 +151,20 @@ regexpWord.exec('/users')
150
151
 
151
152
  **Tip:** Backslashes need to be escaped with another backslash in JavaScript strings.
152
153
 
154
+ ### Match
155
+
156
+ The `match` function will return a function for transforming paths into parameters:
157
+
158
+ ```js
159
+ const match = pathToRegexp.match('/user/:id')
160
+
161
+ match('/user/123') //=> { path: '/user/123', index: 0, params: { id: '123' } }
162
+ match('/invalid') //=> false
163
+ ```
164
+
153
165
  ### Parse
154
166
 
155
- The parse function is exposed via `pathToRegexp.parse`. This will return an array of strings and keys.
167
+ The `parse` function will return a list of strings and keys from a path string:
156
168
 
157
169
  ```js
158
170
  const tokens = pathToRegexp.parse('/route/:foo/(.*)')
@@ -171,7 +183,7 @@ console.log(tokens[2])
171
183
 
172
184
  ### Compile ("Reverse" Path-To-RegExp)
173
185
 
174
- Path-To-RegExp exposes a compile function for transforming a string into a valid path.
186
+ The `compile` function will return a function for transforming parameters into a valid path:
175
187
 
176
188
  ```js
177
189
  const toPath = pathToRegexp.compile('/user/:id')
@@ -181,7 +193,7 @@ toPath({ id: 'café' }) //=> "/user/caf%C3%A9"
181
193
  toPath({ id: '/' }) //=> "/user/%2F"
182
194
 
183
195
  toPath({ id: ':/' }) //=> "/user/%3A%2F"
184
- toPath({ id: ':/' }, { encode: (value, token) => value }) //=> "/user/:/"
196
+ toPath({ id: ':/' }, { encode: (value, token) => value, validate: false }) //=> "/user/:/"
185
197
 
186
198
  const toPathRepeated = pathToRegexp.compile('/:segment+')
187
199
 
@@ -193,7 +205,7 @@ const toPathRegexp = pathToRegexp.compile('/user/:id(\\d+)')
193
205
  toPathRegexp({ id: 123 }) //=> "/user/123"
194
206
  toPathRegexp({ id: '123' }) //=> "/user/123"
195
207
  toPathRegexp({ id: 'abc' }) //=> Throws `TypeError`.
196
- toPathRegexp({ id: 'abc' }, { validate: true }) //=> "/user/abc"
208
+ toPathRegexp({ id: 'abc' }, { validate: false }) //=> "/user/abc"
197
209
  ```
198
210
 
199
211
  **Note:** The generated function will throw on invalid input. It will do all necessary checks to ensure the generated path is valid. This method only works with strings.
package/index.d.ts CHANGED
@@ -51,6 +51,16 @@ declare namespace pathToRegexp {
51
51
  */
52
52
  export function parse (path: string, options?: ParseOptions): Token[];
53
53
 
54
+ /**
55
+ * Create path match function from `path-to-regexp` spec.
56
+ */
57
+ export function match <P extends object = object> (path: string, options?: ParseOptions): MatchFunction<P>;
58
+
59
+ /**
60
+ * Create a path match function from `path-to-regexp` output.
61
+ */
62
+ export function regexpToFunction <P extends object = object> (re: RegExp, keys: Key[]): MatchFunction<P>;
63
+
54
64
  /**
55
65
  * Transforming an Express-style path into a valid path.
56
66
  */
@@ -86,9 +96,25 @@ declare namespace pathToRegexp {
86
96
  validate?: boolean;
87
97
  }
88
98
 
99
+ interface MatchFunctionOptions {
100
+ /**
101
+ * Function for decoding strings for params.
102
+ */
103
+ decode?: (value: string, token: Key) => string;
104
+ }
105
+
106
+ interface MatchResult <P extends object = object> {
107
+ path: string;
108
+ index: number;
109
+ params: P;
110
+ }
111
+
112
+ type Match <P extends object = object> = false | MatchResult<P>;
113
+
89
114
  export type Token = string | Key;
90
115
  export type Path = string | RegExp | Array<string | RegExp>;
91
116
  export type PathFunction <P extends object = object> = (data?: P, options?: PathFunctionOptions) => string;
117
+ export type MatchFunction <P extends object = object> = (path: string, options?: MatchFunctionOptions) => Match<P>;
92
118
  }
93
119
 
94
120
  export = pathToRegexp;
package/index.js CHANGED
@@ -2,6 +2,8 @@
2
2
  * Expose `pathToRegexp`.
3
3
  */
4
4
  module.exports = pathToRegexp
5
+ module.exports.match = match
6
+ module.exports.regexpToFunction = regexpToFunction
5
7
  module.exports.parse = parse
6
8
  module.exports.compile = compile
7
9
  module.exports.tokensToFunction = tokensToFunction
@@ -88,6 +90,7 @@ function parse (str, options) {
88
90
  var optional = modifier === '?' || modifier === '*'
89
91
  var pattern = capture || group
90
92
  var delimiter = prev || defaultDelimiter
93
+ var prevText = prev || (typeof tokens[tokens.length - 1] === 'string' ? tokens[tokens.length - 1] : '')
91
94
 
92
95
  tokens.push({
93
96
  name: name || key++,
@@ -97,7 +100,7 @@ function parse (str, options) {
97
100
  repeat: repeat,
98
101
  pattern: pattern
99
102
  ? escapeGroup(pattern)
100
- : '[^' + escapeString(delimiter === defaultDelimiter ? delimiter : (delimiter + defaultDelimiter)) + ']+?'
103
+ : restrictBacktrack(delimiter, defaultDelimiter, prevText)
101
104
  })
102
105
  }
103
106
 
@@ -109,6 +112,16 @@ function parse (str, options) {
109
112
  return tokens
110
113
  }
111
114
 
115
+ function restrictBacktrack (delimiter, defaultDelimiter, prevText) {
116
+ var charGroup = '[^' + escapeString(delimiter === defaultDelimiter ? delimiter : (delimiter + defaultDelimiter)) + ']'
117
+
118
+ if (!prevText || prevText.indexOf(delimiter) > -1 || prevText.indexOf(defaultDelimiter) > -1) {
119
+ return charGroup + '+?'
120
+ }
121
+
122
+ return escapeString(prevText) + '|(?:(?!' + escapeString(prevText) + ')' + charGroup + ')+?'
123
+ }
124
+
112
125
  /**
113
126
  * Compile a string to a template function for the path.
114
127
  *
@@ -120,6 +133,46 @@ function compile (str, options) {
120
133
  return tokensToFunction(parse(str, options), options)
121
134
  }
122
135
 
136
+ /**
137
+ * Create path match function from `path-to-regexp` spec.
138
+ */
139
+ function match (str, options) {
140
+ var keys = []
141
+ var re = pathToRegexp(str, keys, options)
142
+ return regexpToFunction(re, keys)
143
+ }
144
+
145
+ /**
146
+ * Create a path match function from `path-to-regexp` output.
147
+ */
148
+ function regexpToFunction (re, keys) {
149
+ return function (pathname, options) {
150
+ var m = re.exec(pathname)
151
+ if (!m) return false
152
+
153
+ var path = m[0]
154
+ var index = m.index
155
+ var params = {}
156
+ var decode = (options && options.decode) || decodeURIComponent
157
+
158
+ for (var i = 1; i < m.length; i++) {
159
+ if (m[i] === undefined) continue
160
+
161
+ var key = keys[i - 1]
162
+
163
+ if (key.repeat) {
164
+ params[key.name] = m[i].split(key.delimiter).map(function (value) {
165
+ return decode(value, key)
166
+ })
167
+ } else {
168
+ params[key.name] = decode(m[i], key)
169
+ }
170
+ }
171
+
172
+ return { path: path, index: index, params: params }
173
+ }
174
+ }
175
+
123
176
  /**
124
177
  * Expose a method for transforming tokens into the path function.
125
178
  */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "path-to-regexp",
3
3
  "description": "Express style path to RegExp utility",
4
- "version": "3.1.0",
4
+ "version": "3.3.0",
5
5
  "main": "index.js",
6
6
  "typings": "index.d.ts",
7
7
  "files": [
@@ -12,7 +12,8 @@
12
12
  "scripts": {
13
13
  "lint": "standard",
14
14
  "test-spec": "mocha --require ts-node/register -R spec --bail test.ts",
15
- "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --require ts-node/register -R spec test.ts",
15
+ "test-cov": "nyc --reporter=lcov mocha -- --require ts-node/register -R spec test.ts",
16
+ "coverage": "nyc report --reporter=text-lcov",
16
17
  "test": "npm run lint && npm run test-cov"
17
18
  },
18
19
  "keywords": [
@@ -36,10 +37,10 @@
36
37
  "@types/mocha": "^5.2.5",
37
38
  "@types/node": "^12.7.3",
38
39
  "chai": "^4.1.1",
39
- "istanbul": "^0.4.5",
40
40
  "mocha": "^6.2.0",
41
+ "nyc": "^14.1.1",
41
42
  "standard": "^14.1.0",
42
43
  "ts-node": "^8.3.0",
43
- "typescript": "^3.0.1"
44
+ "typescript": "^3.7.2"
44
45
  }
45
46
  }
package/History.md DELETED
@@ -1,202 +0,0 @@
1
- 3.0.0 / 2019-01-13
2
- ==================
3
-
4
- * Always use prefix character as delimiter token, allowing any character to be a delimiter (e.g. `/:att1-:att2-:att3-:att4-:att5`)
5
- * Remove `partial` support, prefer escaping the prefix delimiter explicitly (e.g. `\\/(apple-)?icon-:res(\\d+).png`)
6
-
7
- 2.4.0 / 2018-08-26
8
- ==================
9
-
10
- * Support `start` option to disable anchoring from beginning of the string
11
-
12
- 2.3.0 / 2018-08-20
13
- ==================
14
-
15
- * Use `delimiter` when processing repeated matching groups (e.g. `foo/bar` has no prefix, but has a delimiter)
16
-
17
- 2.2.1 / 2018-04-24
18
- ==================
19
-
20
- * Allow empty string with `end: false` to match both relative and absolute paths
21
-
22
- 2.2.0 / 2018-03-06
23
- ==================
24
-
25
- * Pass `token` as second argument to `encode` option (e.g. `encode(value, token)`)
26
-
27
- 2.1.0 / 2017-10-20
28
- ==================
29
-
30
- * Handle non-ending paths where the final character is a delimiter
31
- * E.g. `/foo/` before required either `/foo/` or `/foo//` to match in non-ending mode
32
-
33
- 2.0.0 / 2017-08-23
34
- ==================
35
-
36
- * New option! Ability to set `endsWith` to match paths like `/test?query=string` up to the query string
37
- * New option! Set `delimiters` for specific characters to be treated as parameter prefixes (e.g. `/:test`)
38
- * Remove `isarray` dependency
39
- * Explicitly handle trailing delimiters instead of trimming them (e.g. `/test/` is now treated as `/test/` instead of `/test` when matching)
40
- * Remove overloaded `keys` argument that accepted `options`
41
- * Remove `keys` list attached to the `RegExp` output
42
- * Remove asterisk functionality (it's a real pain to properly encode)
43
- * Change `tokensToFunction` (e.g. `compile`) to accept an `encode` function for pretty encoding (e.g. pass your own implementation)
44
-
45
- 1.7.0 / 2016-11-08
46
- ==================
47
-
48
- * Allow a `delimiter` option to be passed in with `tokensToRegExp` which will be used for "non-ending" token match situations
49
-
50
- 1.6.0 / 2016-10-03
51
- ==================
52
-
53
- * Populate `RegExp.keys` when using the `tokensToRegExp` method (making it consistent with the main export)
54
- * Allow a `delimiter` option to be passed in with `parse`
55
- * Updated TypeScript definition with `Keys` and `Options` updated
56
-
57
- 1.5.3 / 2016-06-15
58
- ==================
59
-
60
- * Add `\\` to the ignore character group to avoid backtracking on mismatched parens
61
-
62
- 1.5.2 / 2016-06-15
63
- ==================
64
-
65
- * Escape `\\` in string segments of regexp
66
-
67
- 1.5.1 / 2016-06-08
68
- ==================
69
-
70
- * Add `index.d.ts` to NPM package
71
-
72
- 1.5.0 / 2016-05-20
73
- ==================
74
-
75
- * Handle partial token segments (better)
76
- * Allow compile to handle asterisk token segments
77
-
78
- 1.4.0 / 2016-05-18
79
- ==================
80
-
81
- * Handle RegExp unions in path matching groups
82
-
83
- 1.3.0 / 2016-05-08
84
- ==================
85
-
86
- * Clarify README language and named parameter token support
87
- * Support advanced Closure Compiler with type annotations
88
- * Add pretty paths options to compiled function output
89
- * Add TypeScript definition to project
90
- * Improved prefix handling with non-complete segment parameters (E.g. `/:foo?-bar`)
91
-
92
- 1.2.1 / 2015-08-17
93
- ==================
94
-
95
- * Encode values before validation with path compilation function
96
- * More examples of using compilation in README
97
-
98
- 1.2.0 / 2015-05-20
99
- ==================
100
-
101
- * Add support for matching an asterisk (`*`) as an unnamed match everything group (`(.*)`)
102
-
103
- 1.1.1 / 2015-05-11
104
- ==================
105
-
106
- * Expose methods for working with path tokens
107
-
108
- 1.1.0 / 2015-05-09
109
- ==================
110
-
111
- * Expose the parser implementation to consumers
112
- * Implement a compiler function to generate valid strings
113
- * Huge refactor of tests to be more DRY and cover new parse and compile functions
114
- * Use chai in tests
115
- * Add .editorconfig
116
-
117
- 1.0.3 / 2015-01-17
118
- ==================
119
-
120
- * Optimised function runtime
121
- * Added `files` to `package.json`
122
-
123
- 1.0.2 / 2014-12-17
124
- ==================
125
-
126
- * Use `Array.isArray` shim
127
- * Remove ES5 incompatible code
128
- * Fixed repository path
129
- * Added new readme badges
130
-
131
- 1.0.1 / 2014-08-27
132
- ==================
133
-
134
- * Ensure installation works correctly on 0.8
135
-
136
- 1.0.0 / 2014-08-17
137
- ==================
138
-
139
- * No more API changes
140
-
141
- 0.2.5 / 2014-08-07
142
- ==================
143
-
144
- * Allow keys parameter to be omitted
145
-
146
- 0.2.4 / 2014-08-02
147
- ==================
148
-
149
- * Code coverage badge
150
- * Updated readme
151
- * Attach keys to the generated regexp
152
-
153
- 0.2.3 / 2014-07-09
154
- ==================
155
-
156
- * Add MIT license
157
-
158
- 0.2.2 / 2014-07-06
159
- ==================
160
-
161
- * A passed in trailing slash in non-strict mode will become optional
162
- * In non-end mode, the optional trailing slash will only match at the end
163
-
164
- 0.2.1 / 2014-06-11
165
- ==================
166
-
167
- * Fixed a major capturing group regexp regression
168
-
169
- 0.2.0 / 2014-06-09
170
- ==================
171
-
172
- * Improved support for arrays
173
- * Improved support for regexps
174
- * Better support for non-ending strict mode matches with a trailing slash
175
- * Travis CI support
176
- * Block using regexp special characters in the path
177
- * Removed support for the asterisk to match all
178
- * New support for parameter suffixes - `*`, `+` and `?`
179
- * Updated readme
180
- * Provide delimiter information with keys array
181
-
182
- 0.1.2 / 2014-03-10
183
- ==================
184
-
185
- * Move testing dependencies to `devDependencies`
186
-
187
- 0.1.1 / 2014-03-10
188
- ==================
189
-
190
- * Match entire substring with `options.end`
191
- * Properly handle ending and non-ending matches
192
-
193
- 0.1.0 / 2014-03-06
194
- ==================
195
-
196
- * Add `options.end`
197
-
198
- 0.0.2 / 2013-02-10
199
- ==================
200
-
201
- * Update to match current express
202
- * Add .license property to component.json