Skip to content

Commit 7894e72

Browse files
committed
Improved header link extraction
1 parent d791c93 commit 7894e72

1 file changed

Lines changed: 27 additions & 15 deletions

File tree

links/HeaderLinkExtractor.ts

Lines changed: 27 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -15,29 +15,41 @@ export class HeaderLinkExtractor implements LinkExtractor {
1515
?? [];
1616
}
1717

18-
1918
private parseLink(value: string) {
20-
const split = value.split(">");
21-
const href = split[0].substring(1);
19+
const split = this.split(value, ">");
20+
const href = split.left.substring(1);
2221
let rel: string | undefined;
2322
let title: string | undefined;
2423
let templated = false;
2524

26-
split[1].match(/[^\(\)<>@,;:"\/\[\]\?={} \t]+=(([^\(\)<>@,;:"\/\[\]\?={} \t]+)|("[^"]*"))/g)?.forEach(param => {
27-
const paramSplit = param.split("=");
28-
if (paramSplit[0] === "rel")
29-
rel = paramSplit[1];
30-
else if (paramSplit[0] === "title")
31-
title = paramSplit[1];
32-
else if (paramSplit[0] === "templated" && paramSplit[1])
25+
split.right.match(/[^\(\)<>@,;:"\/\[\]\?={} \t]+=(([^\(\)<>@,;:"\/\[\]\?={} \t]+)|("[^"]*"))/g)?.forEach(param => {
26+
const paramSplit = this.split(param, "=");
27+
if (paramSplit.left === "rel") {
28+
rel = paramSplit.right;
29+
} else if (paramSplit.left === "title") {
30+
title = paramSplit.right;
31+
if (title.startsWith('"') && title.endsWith('"')) {
32+
title = title.substring(1, title.length - 1);
33+
}
34+
} else if (paramSplit.left === "templated" && paramSplit.right === "true") {
3335
templated = true;
36+
}
3437
});
3538

36-
if (!href)
37-
throw new Error("The link header is lacking the mandatory 'href' field.");
38-
if (!rel)
39-
throw new Error("The link header is lacking the mandatory 'rel' field.");
40-
39+
if (!rel) throw new Error("The link header is lacking the mandatory 'rel' field.");
4140
return new Link(rel, href, title, templated);
4241
}
42+
43+
private split(str: string, separator: string): { left: string, right: string } {
44+
const result = str.split(separator, 2);
45+
return (result.length === 2)
46+
? {
47+
left: result[0],
48+
right: result[1] + str.substr(result.join(separator).length)
49+
}
50+
: {
51+
left: result[0],
52+
right: ''
53+
};
54+
}
4355
}

0 commit comments

Comments
 (0)