Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// SPDX-License-Identifier: 0BSD
const reUrl = /<(?<url>[^>]+)>/;
const reParam = /(?<key>[^\s=]+)(?:\s*=\s*"?(?<value>[^"]+)"?)?/;
export function parseLinkHeader(input: string, baseUrl: string | URL) {
const links = input.split(/,\s*(?=<)/g);
return links.map(link => parseLink(link, baseUrl));
}
function parseLink(input: string, baseUrl: string | URL) {
const [link, ...linkParams] = input.split(/;\s*/g);
const { href } = new URL(
link.match(reUrl)?.groups?.url ?? "",
baseUrl,
);
const paramEntries = linkParams.map(param => {
const { key, value } = param.match(reParam)?.groups ?? {};
return [key, value];
});
const { rel, ...params } = Object.fromEntries(paramEntries) as Record<string, string>;
const rels = rel.split(/\s+/g).filter(Boolean);
return { href, rels, ...params };
}
March 31, 2024