2022-07-01 20:06:01 +00:00
|
|
|
import type { APIRoute } from 'astro';
|
2022-08-30 21:09:44 +00:00
|
|
|
import mime from 'mime';
|
2022-07-01 20:24:45 +00:00
|
|
|
// @ts-ignore
|
2022-07-01 20:06:01 +00:00
|
|
|
import loader from 'virtual:image-loader';
|
2022-08-30 21:09:44 +00:00
|
|
|
import { etag } from './utils/etag.js';
|
|
|
|
import { isRemoteImage } from './utils/paths.js';
|
|
|
|
|
|
|
|
async function loadRemoteImage(src: URL) {
|
|
|
|
try {
|
|
|
|
const res = await fetch(src);
|
2022-08-30 21:12:45 +00:00
|
|
|
|
2022-08-30 21:09:44 +00:00
|
|
|
if (!res.ok) {
|
|
|
|
return undefined;
|
|
|
|
}
|
|
|
|
|
|
|
|
return Buffer.from(await res.arrayBuffer());
|
|
|
|
} catch {
|
|
|
|
return undefined;
|
|
|
|
}
|
|
|
|
}
|
2022-07-01 15:47:48 +00:00
|
|
|
|
|
|
|
export const get: APIRoute = async ({ request }) => {
|
|
|
|
try {
|
|
|
|
const url = new URL(request.url);
|
|
|
|
const transform = loader.parseTransform(url.searchParams);
|
|
|
|
|
2022-07-22 23:01:56 +00:00
|
|
|
let inputBuffer: Buffer | undefined = undefined;
|
2022-07-01 15:47:48 +00:00
|
|
|
|
2022-08-30 21:09:44 +00:00
|
|
|
// TODO: handle config subpaths?
|
|
|
|
const sourceUrl = isRemoteImage(transform.src)
|
|
|
|
? new URL(transform.src)
|
|
|
|
: new URL(transform.src, url.origin);
|
|
|
|
inputBuffer = await loadRemoteImage(sourceUrl);
|
2022-07-01 15:47:48 +00:00
|
|
|
|
|
|
|
if (!inputBuffer) {
|
2022-08-30 21:09:44 +00:00
|
|
|
return new Response('Not Found', { status: 404 });
|
2022-07-01 15:47:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
const { data, format } = await loader.transform(inputBuffer, transform);
|
|
|
|
|
|
|
|
return new Response(data, {
|
|
|
|
status: 200,
|
|
|
|
headers: {
|
2022-08-30 21:09:44 +00:00
|
|
|
'Content-Type': mime.getType(format) || '',
|
2022-07-01 15:47:48 +00:00
|
|
|
'Cache-Control': 'public, max-age=31536000',
|
2022-08-30 21:09:44 +00:00
|
|
|
ETag: etag(data.toString()),
|
2022-07-01 17:43:26 +00:00
|
|
|
Date: new Date().toUTCString(),
|
|
|
|
},
|
2022-07-01 15:47:48 +00:00
|
|
|
});
|
|
|
|
} catch (err: unknown) {
|
2022-09-22 19:48:14 +00:00
|
|
|
console.error(err);
|
2022-07-01 15:47:48 +00:00
|
|
|
return new Response(`Server Error: ${err}`, { status: 500 });
|
|
|
|
}
|
2022-08-30 21:12:45 +00:00
|
|
|
};
|