-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
213 lines (194 loc) · 5.63 KB
/
index.ts
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
import puppeteer, { Browser, Page } from "puppeteer";
export interface Options {
/** Check existence of fragment links on same page. */
samePage: boolean;
/** Check links on same origin. */
sameSite: boolean;
/** Check external site links. */
offSite: boolean;
/** Check existence of fragment links outside the current page. */
fragments: boolean;
/** How many links to check at a time? */
concurrency: number;
puppeteer: {
timeout: puppeteer.DirectNavigationOptions["timeout"];
waitUntil: puppeteer.DirectNavigationOptions["waitUntil"];
};
}
const defaults: Options = {
samePage: true,
sameSite: true,
offSite: true,
fragments: true,
concurrency: 5,
puppeteer: {
timeout: 20_000,
waitUntil: "load",
},
};
export interface Entry {
input: { link: string; count: number };
output: Partial<{
pageExists: boolean;
status: number;
fragExists: boolean;
error: Error;
}>;
type: "samePage" | "sameSite" | "offSite";
}
export async function* checkLinks(
url: URL,
options: Partial<Options> = {},
): AsyncGenerator<Entry, void, void> {
const opts = { ...defaults, ...options };
opts.puppeteer = { ...defaults.puppeteer, ...options.puppeteer };
if (opts.concurrency < 1 || opts.concurrency > 100) {
throw new Error(
`options.concurrency must be between 1-100, got ${opts.concurrency}.`,
);
}
let caughtError;
const browser = await puppeteer.launch();
try {
const page = await browser.newPage();
const response = await page.goto(url.href, opts.puppeteer);
if (!response || !response.ok()) {
const reason = response ? `. HTTP ${response.status()}` : "";
throw new Error(`Failed to navigate to ${url}${reason}`);
}
const links = await getAllLinks(page, opts);
for await (const res of checkSamePageLinks(links.samePage, page)) {
yield { ...res, type: "samePage" };
}
for await (const res of checkOffPageLinks(links.sameSite, browser, opts)) {
yield { ...res, type: "sameSite" };
}
for await (const res of checkOffPageLinks(links.offSite, browser, opts)) {
yield { ...res, type: "offSite" };
}
} catch (error) {
caughtError = error;
} finally {
await browser.close();
if (caughtError) throw caughtError;
}
}
export async function getAllLinks(page: Page, options: Options) {
return {
samePage: count(options.samePage ? await getSamePageLinks(page) : []),
sameSite: count(options.sameSite ? await getSameSiteLinks(page) : []),
offSite: count(options.offSite ? await getExternalLinks(page) : []),
};
}
function getExternalLinks(page: Page) {
return page.$$eval("a[href]", elems => {
return (elems as HTMLAnchorElement[])
.filter(a => /https?:/.test(a.protocol) && a.origin !== location.origin)
.map(a => a.href);
});
}
function getSameSiteLinks(page: Page) {
return page.$$eval("a[href]:not([href^='#'])", elems => {
return (elems as HTMLAnchorElement[])
.filter(a => a.origin === location.origin)
.map(a => a.href);
});
}
function getSamePageLinks(page: Page) {
return page.$$eval("a[href^='#']", elems => {
return (elems as HTMLAnchorElement[]).map(a => a.hash);
});
}
async function* checkSamePageLinks(links: Map<string, number>, page: Page) {
for (const [link, count] of links) {
if (link.length <= 1) continue;
const fragExists = await isFragmentValid(link, page);
yield { input: { link, count }, output: { pageExists: true, fragExists } };
}
}
async function* checkOffPageLinks(
links: Map<string, number>,
browser: Browser,
options: Options,
) {
const uniqueLinks = [...links.keys()];
// TODO: retry on TimeoutError
const resultIterator = pmap(
link => isLinkValid(link, options, browser),
uniqueLinks,
options.concurrency,
);
for await (const { input: link, output } of resultIterator) {
yield { input: { link, count: links.get(link)! }, output };
}
}
async function isFragmentValid(hash: string, page: Page) {
const id = hash.replace(/^#/, "");
const selector = `[id='${id}'], [name='${id}']`;
try {
return await page.$eval(selector, el => !!el);
} catch {
return false;
}
}
async function isLinkValid(
link: string,
options: Options,
browser: Browser,
): Promise<
| { error: Error }
| { pageExists: boolean; fragExists?: boolean; status?: number }
> {
const url = new URL(link);
const page = await browser.newPage();
try {
const response = await page.goto(link, options.puppeteer);
const pageExists = !response || response.ok();
let fragExists;
if (options.fragments && pageExists && url.hash && url.hash.length > 1) {
fragExists = await isFragmentValid(url.hash, page);
}
const status = response ? response.status() : undefined;
return { pageExists, fragExists, status };
} catch (error) {
return { error };
} finally {
await page.close();
}
}
function count<T>(items: T[]) {
const counts = new Map<T, number>();
for (const item of items) {
const count = counts.get(item) || 0;
counts.set(item, count + 1);
}
return counts;
}
async function* pmap<InputType, OutputType>(
fn: (input: InputType) => Promise<OutputType>,
inputs: InputType[],
concurrency: number,
) {
type Output = { input: InputType; output: OutputType };
concurrency = Math.min(concurrency, inputs.length);
const promises = [];
const next = (state: { value: number }): Promise<Output> => {
return new Promise(async resolve => {
const input = inputs[state.value];
const output = await fn(input);
resolve({ input, output });
state.value += 1;
if (state.value < inputs.length) {
const newPromise = next(state);
promises.push(newPromise);
}
});
};
const state = { value: 0 }; // "shared memory"
for (; state.value < concurrency; state.value += 1) {
promises.push(next(state));
}
for (const promise of promises) {
yield await promise;
}
}