-
Notifications
You must be signed in to change notification settings - Fork 73
/
index.js
141 lines (125 loc) Β· 2.72 KB
/
index.js
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
import list from '../list.json'
import { amend } from '../amend/index.js'
amend(list)
const flags = 'i'
/**
* Test user agents for matching patterns
*/
export class Isbot {
/**
* @type {string[]}
*/
#list
/**
* @type {RegExp}
*/
#pattern
constructor (patterns) {
this.#list = patterns || list.slice()
this.#update()
const isbot = ua => this.test(ua)
return Object.defineProperties(
isbot,
Object.getOwnPropertyNames(Isbot.prototype).filter(
prop => !['constructor'].includes(prop)
).reduce(
(accumulator, prop) => Object.assign(
accumulator,
{ [prop]: { get: () => this[prop].bind(this) } }
),
{}
)
)
}
/**
* Recreate the pattern from rules list
*/
#update () {
this.#pattern = new RegExp(
this.#list.join('|'),
flags
)
}
/**
* Find the first index of an existing rule or -1 if not found
* @param {string} rule
* @returns {number}
*/
#index (rule) {
return this.#list.indexOf(rule.toLowerCase())
}
/**
* Match given string against out pattern
* @param {string} ua User Agent string
* @returns {boolean}
*/
test (ua) {
return Boolean(ua) && this.#pattern.test(ua)
}
/**
* Get the match for strings' known crawler pattern
* @param {string} ua User Agent string
* @returns {string|null}
*/
find (ua = '') {
const match = ua.match(this.#pattern)
return match && match[0]
}
/**
* Get the patterns that match user agent string if any
* @param {string} ua User Agent string
* @returns {string[]}
*/
matches (ua = '') {
return this.#list.filter(
entry => new RegExp(entry, flags).test(ua)
)
}
/**
* Clear all patterns that match user agent
* @param {string} ua User Agent string
* @returns {void}
*/
clear (ua = '') {
this.exclude(this.matches(ua))
}
/**
* Extent patterns for known crawlers
* @param {string[]} filters
* @returns {void}
*/
extend (filters = []) {
[].push.apply(
this.#list,
filters.filter(
rule => this.#index(rule) === -1
).map(
filter => filter.toLowerCase()
)
)
this.#update()
}
/**
* Exclude patterns from bot pattern rule
* @param {string[]} filters
* @returns {void}
*/
exclude (filters = []) {
let { length } = filters
while (length--) {
const index = this.#index(filters[length])
if (index > -1) {
this.#list.splice(index, 1)
}
}
this.#update()
}
/**
* Create a new Isbot instance using given list or self's list
* @param {string[]} [list]
* @returns {Isbot}
*/
spawn (list) {
return new Isbot(list || this.#list)
}
}