feat(api): add resize, crop, rotate, convert, compress, metadata, and color tool routes

Seven tool route files using the createToolRoute factory, registering 10 API
endpoints total (color adjustments covers 4 tool IDs). Also fixes the tool
factory generic to properly infer Zod output types and clamps the compress
binary-search quality to 1-100.
This commit is contained in:
Siddharth Kumar Sah
2026-03-22 03:56:34 +08:00
parent d53f6733b8
commit 37112af779
10 changed files with 313 additions and 10 deletions
+1 -1
View File
@@ -10,7 +10,7 @@ export interface ToolRouteConfig<T> {
/** Unique tool identifier, used as the URL path segment. */
toolId: string;
/** Zod schema that validates the settings JSON from the request. */
settingsSchema: z.ZodSchema<T>;
settingsSchema: z.ZodType<T, z.ZodTypeDef, unknown>;
/** The processing function: takes input buffer + validated settings, returns output. */
process: (
inputBuffer: Buffer,
@@ -0,0 +1,99 @@
import { z } from "zod";
import { createToolRoute } from "../tool-factory.js";
import {
brightness as adjustBrightness,
contrast as adjustContrast,
saturation as adjustSaturation,
colorChannels,
grayscale,
sepia,
invert,
} from "@stirling-image/image-engine";
import sharp from "sharp";
import type { FastifyInstance } from "fastify";
const settingsSchema = z.object({
brightness: z.number().min(-100).max(100).default(0),
contrast: z.number().min(-100).max(100).default(0),
saturation: z.number().min(-100).max(100).default(0),
red: z.number().min(0).max(200).default(100),
green: z.number().min(0).max(200).default(100),
blue: z.number().min(0).max(200).default(100),
effect: z
.enum(["none", "grayscale", "sepia", "invert"])
.default("none"),
});
/**
* Combined color adjustment route that handles brightness, contrast,
* saturation, color channels, and color effects in a single request.
*
* Serves tool IDs: brightness-contrast, saturation, color-channels, color-effects
*/
export function registerColorAdjustments(app: FastifyInstance) {
// Register the same handler under all four color-related tool IDs
const toolIds = [
"brightness-contrast",
"saturation",
"color-channels",
"color-effects",
];
for (const toolId of toolIds) {
createToolRoute(app, {
toolId,
settingsSchema,
process: async (inputBuffer, settings, filename) => {
let image = sharp(inputBuffer);
// Apply brightness
if (settings.brightness !== 0) {
image = await adjustBrightness(image, {
value: settings.brightness,
});
}
// Apply contrast
if (settings.contrast !== 0) {
image = await adjustContrast(image, { value: settings.contrast });
}
// Apply saturation
if (settings.saturation !== 0) {
image = await adjustSaturation(image, {
value: settings.saturation,
});
}
// Apply color channels (only if not default 100/100/100)
if (
settings.red !== 100 ||
settings.green !== 100 ||
settings.blue !== 100
) {
image = await colorChannels(image, {
red: settings.red,
green: settings.green,
blue: settings.blue,
});
}
// Apply effect
switch (settings.effect) {
case "grayscale":
image = await grayscale(image);
break;
case "sepia":
image = await sepia(image);
break;
case "invert":
image = await invert(image);
break;
}
const buffer = await image.toBuffer();
return { buffer, filename, contentType: "image/png" };
},
});
}
}
+37
View File
@@ -0,0 +1,37 @@
import { z } from "zod";
import { createToolRoute } from "../tool-factory.js";
import { compress } from "@stirling-image/image-engine";
import sharp from "sharp";
import type { FastifyInstance } from "fastify";
const settingsSchema = z.object({
mode: z.enum(["quality", "targetSize"]).default("quality"),
quality: z.number().min(1).max(100).optional(),
targetSizeKb: z.number().positive().optional(),
});
export function registerCompress(app: FastifyInstance) {
createToolRoute(app, {
toolId: "compress",
settingsSchema,
process: async (inputBuffer, settings, filename) => {
const image = sharp(inputBuffer);
const compressOptions: {
quality?: number;
targetSizeBytes?: number;
} = {};
if (settings.mode === "targetSize" && settings.targetSizeKb) {
// Convert KB to bytes for the engine
compressOptions.targetSizeBytes = settings.targetSizeKb * 1024;
} else {
compressOptions.quality = settings.quality ?? 80;
}
const result = await compress(image, compressOptions);
const buffer = await result.toBuffer();
return { buffer, filename, contentType: "image/jpeg" };
},
});
}
+42
View File
@@ -0,0 +1,42 @@
import { z } from "zod";
import { createToolRoute } from "../tool-factory.js";
import { convert } from "@stirling-image/image-engine";
import sharp from "sharp";
import type { FastifyInstance } from "fastify";
import { extname } from "node:path";
const FORMAT_CONTENT_TYPES: Record<string, string> = {
jpg: "image/jpeg",
png: "image/png",
webp: "image/webp",
avif: "image/avif",
tiff: "image/tiff",
gif: "image/gif",
};
const settingsSchema = z.object({
format: z.enum(["jpg", "png", "webp", "avif", "tiff", "gif"]),
quality: z.number().min(1).max(100).optional(),
});
export function registerConvert(app: FastifyInstance) {
createToolRoute(app, {
toolId: "convert",
settingsSchema,
process: async (inputBuffer, settings, filename) => {
const image = sharp(inputBuffer);
const result = await convert(image, settings);
const buffer = await result.toBuffer();
// Change filename extension to match the output format
const ext = extname(filename);
const baseName = ext ? filename.slice(0, -ext.length) : filename;
const outputFilename = `${baseName}.${settings.format}`;
const contentType =
FORMAT_CONTENT_TYPES[settings.format] || "application/octet-stream";
return { buffer, filename: outputFilename, contentType };
},
});
}
+25
View File
@@ -0,0 +1,25 @@
import { z } from "zod";
import { createToolRoute } from "../tool-factory.js";
import { crop } from "@stirling-image/image-engine";
import sharp from "sharp";
import type { FastifyInstance } from "fastify";
const settingsSchema = z.object({
left: z.number().int().min(0),
top: z.number().int().min(0),
width: z.number().int().positive(),
height: z.number().int().positive(),
});
export function registerCrop(app: FastifyInstance) {
createToolRoute(app, {
toolId: "crop",
settingsSchema,
process: async (inputBuffer, settings, filename) => {
const image = sharp(inputBuffer);
const result = await crop(image, settings);
const buffer = await result.toBuffer();
return { buffer, filename, contentType: "image/png" };
},
});
}
+16 -7
View File
@@ -1,15 +1,24 @@
import type { FastifyInstance } from "fastify";
import { registerResize } from "./resize.js";
import { registerCrop } from "./crop.js";
import { registerRotate } from "./rotate.js";
import { registerConvert } from "./convert.js";
import { registerCompress } from "./compress.js";
import { registerStripMetadata } from "./strip-metadata.js";
import { registerColorAdjustments } from "./color-adjustments.js";
/**
* Registry that imports and registers all tool routes.
* Each tool uses the createToolRoute factory from tool-factory.ts.
*
* Tools will be added here as they are implemented in Phase 2 Tasks 4-10.
*/
export async function registerToolRoutes(app: FastifyInstance): Promise<void> {
// Tool routes will be registered here as they are implemented.
// Example:
// const { registerResizeTool } = await import("./resize.js");
// registerResizeTool(app);
app.log.info("Tool routes registered");
registerResize(app);
registerCrop(app);
registerRotate(app);
registerConvert(app);
registerCompress(app);
registerStripMetadata(app);
registerColorAdjustments(app);
app.log.info("Tool routes registered (7 tools, 10 endpoints)");
}
+28
View File
@@ -0,0 +1,28 @@
import { z } from "zod";
import { createToolRoute } from "../tool-factory.js";
import { resize } from "@stirling-image/image-engine";
import sharp from "sharp";
import type { FastifyInstance } from "fastify";
const settingsSchema = z.object({
width: z.number().positive().optional(),
height: z.number().positive().optional(),
fit: z
.enum(["contain", "cover", "fill", "inside", "outside"])
.default("contain"),
withoutEnlargement: z.boolean().default(false),
percentage: z.number().positive().optional(),
});
export function registerResize(app: FastifyInstance) {
createToolRoute(app, {
toolId: "resize",
settingsSchema,
process: async (inputBuffer, settings, filename) => {
const image = sharp(inputBuffer);
const result = await resize(image, settings);
const buffer = await result.toBuffer();
return { buffer, filename, contentType: "image/png" };
},
});
}
+37
View File
@@ -0,0 +1,37 @@
import { z } from "zod";
import { createToolRoute } from "../tool-factory.js";
import { rotate, flip } from "@stirling-image/image-engine";
import sharp from "sharp";
import type { FastifyInstance } from "fastify";
const settingsSchema = z.object({
angle: z.number().default(0),
horizontal: z.boolean().default(false),
vertical: z.boolean().default(false),
});
export function registerRotate(app: FastifyInstance) {
createToolRoute(app, {
toolId: "rotate",
settingsSchema,
process: async (inputBuffer, settings, filename) => {
let image = sharp(inputBuffer);
// Apply rotation first
if (settings.angle !== 0) {
image = await rotate(image, { angle: settings.angle });
}
// Then apply flip/flop
if (settings.horizontal || settings.vertical) {
image = await flip(image, {
horizontal: settings.horizontal,
vertical: settings.vertical,
});
}
const buffer = await image.toBuffer();
return { buffer, filename, contentType: "image/png" };
},
});
}
@@ -0,0 +1,26 @@
import { z } from "zod";
import { createToolRoute } from "../tool-factory.js";
import { stripMetadata } from "@stirling-image/image-engine";
import sharp from "sharp";
import type { FastifyInstance } from "fastify";
const settingsSchema = z.object({
stripExif: z.boolean().default(false),
stripGps: z.boolean().default(false),
stripIcc: z.boolean().default(false),
stripXmp: z.boolean().default(false),
stripAll: z.boolean().default(true),
});
export function registerStripMetadata(app: FastifyInstance) {
createToolRoute(app, {
toolId: "strip-metadata",
settingsSchema,
process: async (inputBuffer, settings, filename) => {
const image = sharp(inputBuffer);
const result = await stripMetadata(image, settings);
const buffer = await result.toBuffer();
return { buffer, filename, contentType: "image/png" };
},
});
}