-
Notifications
You must be signed in to change notification settings - Fork 298
/
UrlChecker.js
144 lines (97 loc) · 2.24 KB
/
UrlChecker.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
142
143
144
import checkLink from "../internal/checkLink";
import {END_EVENT, LINK_EVENT, QUEUE_EVENT} from "../internal/events";
import isURL from "isurl";
import Link, {REBASED_URL} from "../internal/Link";
import parseOptions from "../internal/parseOptions";
import RequestQueue, {ITEM_EVENT, END_EVENT as REQUEST_QUEUE_END_EVENT} from "limited-request-queue";
import SafeEventEmitter from "../internal/SafeEventEmitter";
import URLCache from "urlcache";
export default class UrlChecker extends SafeEventEmitter
{
#cache;
#linkQueue;
constructor(options)
{
super();
options = parseOptions(options);
this.#cache = new URLCache({ maxAge:options.cacheMaxAge });
this.#linkQueue = new RequestQueue(
{
maxSockets: options.maxSockets,
maxSocketsPerHost: options.maxSocketsPerHost,
rateLimit: options.rateLimit
})
.on(ITEM_EVENT, async (url, {auth, customData, link}, done) =>
{
const result = await checkLink(link, auth, this.#cache, options);
this.emit(LINK_EVENT, result, customData);
// Auto-starts next queue item, if any
// Emits REQUEST_QUEUE_END_EVENT, if not
done();
})
.on(REQUEST_QUEUE_END_EVENT, () => this.emit(END_EVENT));
}
clearCache()
{
this.#cache.clear();
return this;
}
dequeue(id)
{
const success = this.#linkQueue.dequeue(id);
this.emit(QUEUE_EVENT);
return success;
}
// `auth` is undocumented and for internal use only
enqueue(url, customData, auth={})
{
let link;
// Undocumented internal use: `enqueue(Link)`
if (url instanceof Link)
{
link = url;
}
// Documented use: `enqueue(URL)`
else if (isURL.lenient(url))
{
link = new Link().resolve(url);
}
else
{
throw new TypeError("Invalid URL");
}
const id = this.#linkQueue.enqueue(link.get(REBASED_URL), { auth, customData, link });
this.emit(QUEUE_EVENT);
return id;
}
has(id)
{
return this.#linkQueue.has(id);
}
get isPaused()
{
return this.#linkQueue.isPaused;
}
get numActiveLinks()
{
return this.#linkQueue.numActive;
}
get numQueuedLinks()
{
return this.#linkQueue.numQueued;
}
pause()
{
this.#linkQueue.pause();
return this;
}
resume()
{
this.#linkQueue.resume();
return this;
}
get __cache()
{
return this.#cache;
}
}