-
Notifications
You must be signed in to change notification settings - Fork 30
/
astro.ts
75 lines (67 loc) · 2.2 KB
/
astro.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
import { ShouldDelegateUrl, UrlParser, UrlTransformer } from "../types.ts";
import {
getNumericParam,
setParamIfDefined,
toCanonicalUrlString,
toUrl,
} from "../utils.ts";
import { getImageCdnForUrlByDomain } from "../detect.ts";
export interface AstroParams {
href: string;
quality?: string | number;
}
export const delegateUrl: ShouldDelegateUrl = (url) => {
const parsedUrl = toUrl(url);
const searchParamHref = parsedUrl.searchParams.get("href");
const decodedHref = typeof searchParamHref === "string"
? decodeURIComponent(searchParamHref)
: new URL(parsedUrl.pathname, parsedUrl.origin).toString();
const source = toCanonicalUrlString(toUrl(decodedHref));
if (!source || !source.startsWith("http")) {
return false;
}
const cdn = getImageCdnForUrlByDomain(source);
if (!cdn) {
return false;
}
return {
cdn,
url: source,
};
};
export const parse: UrlParser<AstroParams> = (url) => {
const parsedUrl = toUrl(url);
const searchParamHref = parsedUrl.searchParams.get("href");
const decodedHref = typeof searchParamHref === "string"
? decodeURIComponent(searchParamHref)
: new URL(parsedUrl.pathname, parsedUrl.origin).toString();
const encodedHref = encodeURIComponent(
toCanonicalUrlString(toUrl(decodedHref)),
);
const width = getNumericParam(parsedUrl, "w") || undefined;
const height = getNumericParam(parsedUrl, "h") || undefined;
const format = parsedUrl.searchParams.get("f") || undefined;
const quality = parsedUrl.searchParams.get("q") || undefined;
return {
width,
height,
format,
base: `/_image?href=${encodedHref}`,
params: { quality, href: encodedHref },
cdn: "astro",
};
};
export const transform: UrlTransformer = (
{ url: originalUrl, width, height, format },
) => {
const parsedUrl = toUrl(originalUrl);
const href = toCanonicalUrlString(
new URL(parsedUrl.pathname, parsedUrl.origin),
);
const url = { searchParams: new URLSearchParams() } as URL;
setParamIfDefined(url, "href", href, true, true);
setParamIfDefined(url, "w", width, true, true);
setParamIfDefined(url, "h", height, true, true);
setParamIfDefined(url, "f", format);
return `/_image?${url.searchParams.toString()}`;
};