-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathindex.js
More file actions
75 lines (64 loc) · 1.77 KB
/
index.js
File metadata and controls
75 lines (64 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
'use strict'
const parse = require('ret')
const { types } = require('ret')
/**
* @param {*} node
* @param {object} opts
* @param {number} opts.reps - The number of repetitions encountered
* @param {number} opts.limit - The maximum number of repetitions allowed
* @param {number} starHeight - The current height of the star in the regex tree
* @returns {boolean}
*/
function walk (node, opts, starHeight) {
let i
let ok
let len
if (node.type === types.REPETITION) {
starHeight++
opts.reps++
if (starHeight > 1) return false
if (opts.reps > opts.limit) return false
}
if (node.options) {
for (i = 0, len = node.options.length; i < len; i++) {
ok = walk({ stack: node.options[i] }, opts, starHeight)
if (!ok) return false
}
}
const stack = node.stack || node.value?.stack
if (!stack) return true
for (i = 0, len = stack.length; i < len; i++) {
ok = walk(stack[i], opts, starHeight)
if (!ok) return false
}
return true
}
/**
* @param {string|RegExp} re - The regular expression to check, can be a string or RegExp object
* @param {object} [options]
* @param {number} [options.limit=25] - The maximum number of repetitions allowed
* @returns {boolean} - Returns true if the regex is safe, false if it is unsafe or invalid
*/
function safeRegex (re, options) {
const opts = {
reps: 0,
limit: options?.limit ?? 25
}
if (isRegExp(re)) re = re.source
else if (typeof re !== 'string') re = String(re)
try {
return walk(parse(re), opts, 0)
} catch {
return false
}
}
/**
* @param {*} x
* @returns {x is RegExp}
*/
function isRegExp (x) {
return Object.prototype.toString.call(x) === '[object RegExp]'
}
module.exports = safeRegex
module.exports.default = safeRegex
module.exports.safeRegex = safeRegex