Skip to content

Commit 52bbd4f

Browse files
committed
fix: error when regex is invalid
1 parent 1eea962 commit 52bbd4f

2 files changed

Lines changed: 17 additions & 1 deletion

File tree

src/cli/utils/findRule.js

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,15 @@
1111
* @property {boolean} [urlRegex] - Whether the URL is a regex pattern.
1212
*/
1313

14+
const validRegex = (pattern) => {
15+
try {
16+
new RegExp(pattern);
17+
return true;
18+
} catch {
19+
return false;
20+
}
21+
};
22+
1423
/**
1524
* Find a matching rule based on method and url
1625
* @param {string} method
@@ -22,7 +31,7 @@ export function findRule(method, url, rules) {
2231
return rules.find(
2332
(r) => {
2433
const isMethodMatch = r.method.toLowerCase() === method.toLowerCase();
25-
if (r.urlRegex) {
34+
if (r.urlRegex && validRegex(r.url)) {
2635
const regex = new RegExp(r.url);
2736
return isMethodMatch && regex.test(url);
2837
}

src/tests/cli/findRule.spec.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,13 @@ describe('findRule', () => {
3030
expect(findRule('GET', 'https://bar.com', rules)).toBeUndefined();
3131
});
3232

33+
it('should not throw for invalid regex', () => {
34+
const rules = [
35+
{ method: 'GET', url: '^https://foo\\.com/([.*$', alias: 'a', urlRegex: true },
36+
];
37+
expect(findRule('GET', 'https://foo.com/api', rules)).toBeUndefined();
38+
});
39+
3340
it('matches by regex string (wrapped in /.../)', () => {
3441
const rules = [
3542
{ method: 'GET', url: /users.*/, alias: 'a', urlRegex: true },

0 commit comments

Comments
 (0)