mirror of
https://github.com/snapotter-hq/SnapOtter.git
synced 2026-08-03 07:46:42 +02:00
feat: add Optimize for Web tool (#68)
* feat(image-engine): add OptimizeForWebOptions type * feat(image-engine): add optimizeForWeb operation * feat(shared): add optimize-for-web tool definition and i18n * feat(api): add optimize-for-web route with preview endpoint * feat(web): add optimize-for-web settings component with live preview * feat(web): register optimize-for-web in tool registry * fix(web): align toggle switch translate with codebase pattern --------- Co-authored-by: stirling-image <stirling-image@users.noreply.github.com>
This commit is contained in:
co-authored by
stirling-image
parent
c2c104e887
commit
5be8be3dc3
@@ -28,6 +28,7 @@ import { registerImageToPdf } from "./image-to-pdf.js";
|
||||
import { registerInfo } from "./info.js";
|
||||
import { registerNoiseRemoval } from "./noise-removal.js";
|
||||
import { registerOcr } from "./ocr.js";
|
||||
import { registerOptimizeForWeb } from "./optimize-for-web.js";
|
||||
import { registerPassportPhoto } from "./passport-photo.js";
|
||||
import { registerPdfToImage } from "./pdf-to-image.js";
|
||||
import { registerQrGenerate } from "./qr-generate.js";
|
||||
@@ -125,6 +126,7 @@ export async function registerToolRoutes(app: FastifyInstance): Promise<void> {
|
||||
{ id: "bulk-rename", register: registerBulkRename },
|
||||
{ id: "favicon", register: registerFavicon },
|
||||
{ id: "image-to-pdf", register: registerImageToPdf },
|
||||
{ id: "optimize-for-web", register: registerOptimizeForWeb },
|
||||
|
||||
// Adjustments extra
|
||||
{ id: "replace-color", register: registerReplaceColor },
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
import { extname } from "node:path";
|
||||
import { optimizeForWeb } from "@stirling-image/image-engine";
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
|
||||
import sharp from "sharp";
|
||||
import { z } from "zod";
|
||||
import { autoOrient } from "../../lib/auto-orient.js";
|
||||
import { validateImageBuffer } from "../../lib/file-validation.js";
|
||||
import { sanitizeFilename } from "../../lib/filename.js";
|
||||
import { decodeHeic } from "../../lib/heic-converter.js";
|
||||
import { sanitizeSvg } from "../../lib/svg-sanitize.js";
|
||||
import { createToolRoute } from "../tool-factory.js";
|
||||
|
||||
const FORMAT_CONTENT_TYPES: Record<string, string> = {
|
||||
webp: "image/webp",
|
||||
jpeg: "image/jpeg",
|
||||
avif: "image/avif",
|
||||
png: "image/png",
|
||||
};
|
||||
|
||||
const FORMAT_EXTENSIONS: Record<string, string> = {
|
||||
webp: "webp",
|
||||
jpeg: "jpg",
|
||||
avif: "avif",
|
||||
png: "png",
|
||||
};
|
||||
|
||||
const settingsSchema = z.object({
|
||||
format: z.enum(["webp", "jpeg", "avif", "png"]).default("webp"),
|
||||
quality: z.number().min(1).max(100).default(80),
|
||||
maxWidth: z.number().positive().optional(),
|
||||
maxHeight: z.number().positive().optional(),
|
||||
progressive: z.boolean().default(true),
|
||||
stripMetadata: z.boolean().default(true),
|
||||
});
|
||||
|
||||
type Settings = z.infer<typeof settingsSchema>;
|
||||
|
||||
async function processImage(inputBuffer: Buffer, settings: Settings, filename: string) {
|
||||
const image = sharp(inputBuffer);
|
||||
const result = await optimizeForWeb(image, settings);
|
||||
const buffer = await result.toBuffer();
|
||||
|
||||
const ext = extname(filename);
|
||||
const baseName = ext ? filename.slice(0, -ext.length) : filename;
|
||||
const outputFilename = `${baseName}.${FORMAT_EXTENSIONS[settings.format]}`;
|
||||
const contentType = FORMAT_CONTENT_TYPES[settings.format];
|
||||
|
||||
return { buffer, filename: outputFilename, contentType };
|
||||
}
|
||||
|
||||
export function registerOptimizeForWeb(app: FastifyInstance) {
|
||||
// Lightweight preview route for live parameter tuning
|
||||
app.post(
|
||||
"/api/v1/tools/optimize-for-web/preview",
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
let fileBuffer: Buffer | null = null;
|
||||
let filename = "image";
|
||||
let settingsRaw: string | null = null;
|
||||
|
||||
try {
|
||||
const parts = request.parts();
|
||||
for await (const part of parts) {
|
||||
if (part.type === "file") {
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of part.file) {
|
||||
chunks.push(chunk);
|
||||
}
|
||||
fileBuffer = Buffer.concat(chunks);
|
||||
filename = sanitizeFilename(part.filename ?? "image");
|
||||
} else if (part.fieldname === "settings") {
|
||||
settingsRaw = part.value as string;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
return reply.status(400).send({
|
||||
error: "Failed to parse multipart request",
|
||||
details: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
}
|
||||
|
||||
if (!fileBuffer || fileBuffer.length === 0) {
|
||||
return reply.status(400).send({ error: "No image file provided" });
|
||||
}
|
||||
|
||||
const validation = await validateImageBuffer(fileBuffer);
|
||||
if (!validation.valid) {
|
||||
return reply.status(400).send({ error: `Invalid image: ${validation.reason}` });
|
||||
}
|
||||
|
||||
// Decode HEIC/HEIF
|
||||
if (validation.format === "heif") {
|
||||
try {
|
||||
fileBuffer = await decodeHeic(fileBuffer);
|
||||
} catch (err) {
|
||||
return reply.status(422).send({
|
||||
error: "Failed to decode HEIC file",
|
||||
details: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Sanitize SVG
|
||||
if (validation.format === "svg") {
|
||||
try {
|
||||
fileBuffer = sanitizeSvg(fileBuffer);
|
||||
} catch (err) {
|
||||
return reply.status(400).send({
|
||||
error: err instanceof Error ? err.message : "Invalid SVG",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let settings: Settings;
|
||||
try {
|
||||
const parsed = settingsRaw ? JSON.parse(settingsRaw) : {};
|
||||
const result = settingsSchema.safeParse(parsed);
|
||||
if (!result.success) {
|
||||
return reply.status(400).send({
|
||||
error: "Invalid settings",
|
||||
details: result.error.issues.map((i) => ({
|
||||
path: i.path.join("."),
|
||||
message: i.message,
|
||||
})),
|
||||
});
|
||||
}
|
||||
settings = result.data;
|
||||
} catch {
|
||||
return reply.status(400).send({ error: "Settings must be valid JSON" });
|
||||
}
|
||||
|
||||
try {
|
||||
const processBuffer =
|
||||
validation.format === "svg" ? fileBuffer : await autoOrient(fileBuffer);
|
||||
const result = await processImage(processBuffer, settings, filename);
|
||||
|
||||
// Return the optimized image directly as binary with size headers.
|
||||
// This avoids workspace creation for ephemeral previews.
|
||||
reply.header("Content-Type", result.contentType);
|
||||
reply.header("X-Original-Size", String(fileBuffer.length));
|
||||
reply.header("X-Processed-Size", String(result.buffer.length));
|
||||
reply.header("X-Output-Filename", result.filename);
|
||||
return reply.send(result.buffer);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : "Preview processing failed";
|
||||
request.log.error({ err }, "Optimize preview failed");
|
||||
return reply.status(422).send({ error: "Preview failed", details: message });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Standard processing route via tool factory
|
||||
createToolRoute(app, {
|
||||
toolId: "optimize-for-web",
|
||||
settingsSchema,
|
||||
process: processImage,
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user