enhance cloudflare image optimization plugin with new options and explain endpoint (#215)

This commit is contained in:
dswbx
2025-07-22 11:48:43 +02:00
committed by GitHub
parent 847c264b35
commit ea372a8125
@@ -1,15 +1,39 @@
import type { App, AppPlugin } from "bknd"; import type { App, AppPlugin } from "bknd";
import { s, jsc } from "bknd/core";
import { mergeObject, pickHeaders2 } from "core/utils";
/**
* check RequestInitCfPropertiesImage
*/
const schema = s.partialObject({
dpr: s.number({ minimum: 1, maximum: 3 }),
fit: s.string({ enum: ["scale-down", "contain", "cover", "crop", "pad"] }),
format: s.string({
enum: ["auto", "avif", "webp", "jpeg", "baseline-jpeg", "json"],
default: "auto",
}),
height: s.number(),
width: s.number(),
metadata: s.string({ enum: ["copyright", "keep", "none"] }),
quality: s.number({ minimum: 1, maximum: 100 }),
});
type ImageOptimizationSchema = s.Static<typeof schema>;
export type CloudflareImageOptimizationOptions = { export type CloudflareImageOptimizationOptions = {
accessUrl?: string; accessUrl?: string;
resolvePath?: string; resolvePath?: string;
autoFormat?: boolean; explain?: boolean;
defaultOptions?: ImageOptimizationSchema;
fixedOptions?: ImageOptimizationSchema;
cacheControl?: string;
}; };
export function cloudflareImageOptimization({ export function cloudflareImageOptimization({
accessUrl = "/_plugin/image/optimize", accessUrl = "/_plugin/image/optimize",
resolvePath = "/api/media/file", resolvePath = "/api/media/file",
autoFormat = true, explain = false,
defaultOptions = {},
fixedOptions = {},
}: CloudflareImageOptimizationOptions = {}): AppPlugin { }: CloudflareImageOptimizationOptions = {}): AppPlugin {
const disallowedAccessUrls = ["/api", "/admin", "/_optimize"]; const disallowedAccessUrls = ["/api", "/admin", "/_optimize"];
if (disallowedAccessUrls.includes(accessUrl) || accessUrl.length < 2) { if (disallowedAccessUrls.includes(accessUrl) || accessUrl.length < 2) {
@@ -19,7 +43,14 @@ export function cloudflareImageOptimization({
return (app: App) => ({ return (app: App) => ({
name: "cf-image-optimization", name: "cf-image-optimization",
onBuilt: () => { onBuilt: () => {
app.server.get(`${accessUrl}/:path{.+$}`, async (c) => { if (explain) {
app.server.get(accessUrl, async (c) => {
return c.json({
searchParams: schema.toJSON(),
});
});
}
app.server.get(`${accessUrl}/:path{.+$}`, jsc("query", schema), async (c) => {
const request = c.req.raw; const request = c.req.raw;
const url = new URL(request.url); const url = new URL(request.url);
@@ -34,26 +65,25 @@ export function cloudflareImageOptimization({
} }
const imageURL = `${url.origin}${resolvePath}/${path}`; const imageURL = `${url.origin}${resolvePath}/${path}`;
const metadata = await storage.objectMetadata(path); //const metadata = await storage.objectMetadata(path);
// Cloudflare-specific options are in the cf object.
const params = Object.fromEntries(url.searchParams.entries());
const options: RequestInitCfPropertiesImage = {};
// Copy parameters from query string to request options. // Copy parameters from query string to request options.
// You can implement various different parameters here. // You can implement various different parameters here.
if ("fit" in params) options.fit = params.fit as any; const options = mergeObject(
if ("width" in params) options.width = Number.parseInt(params.width); structuredClone(defaultOptions),
if ("height" in params) options.height = Number.parseInt(params.height); c.req.valid("query"),
if ("quality" in params) options.quality = Number.parseInt(params.quality); structuredClone(fixedOptions),
);
// Your Worker is responsible for automatic format negotiation. Check the Accept header. // Your Worker is responsible for automatic format negotiation. Check the Accept header.
if (autoFormat) { if (options.format) {
const accept = request.headers.get("Accept")!; if (options.format === "auto") {
if (/image\/avif/.test(accept)) { const accept = request.headers.get("Accept")!;
options.format = "avif"; if (/image\/avif/.test(accept)) {
} else if (/image\/webp/.test(accept)) { options.format = "avif";
options.format = "webp"; } else if (/image\/webp/.test(accept)) {
options.format = "webp";
}
} }
} }
@@ -63,16 +93,20 @@ export function cloudflareImageOptimization({
}); });
// Returning fetch() with resizing options will pass through response with the resized image. // Returning fetch() with resizing options will pass through response with the resized image.
const res = await fetch(imageRequest, { cf: { image: options } }); const res = await fetch(imageRequest, { cf: { image: options as any } });
const headers = pickHeaders2(res.headers, [
"Content-Type",
"Content-Length",
"Age",
"Date",
"Last-Modified",
]);
headers.set("Cache-Control", "public, max-age=31536000, immutable");
return new Response(res.body, { return new Response(res.body, {
status: res.status, status: res.status,
statusText: res.statusText, statusText: res.statusText,
headers: { headers,
"Cache-Control": "public, max-age=600",
"Content-Type": metadata.type,
"Content-Length": metadata.size.toString(),
},
}); });
}); });
}, },