@athenox/talos
Version:
Talos: a backend you describe instead of write. Declare a schema, write the rules in plain language, map URLs to sentences; a small built-in model turns them into query plans.
47 lines (46 loc) • 1.8 kB
JavaScript
import { createRequire } from 'node:module';
import { join } from 'node:path';
let lib;
/**
* sharp, from the app's own dependencies — Talos does not ship an image
* library, the app that stores images does. `useImages(sharp)` sets it
* explicitly; otherwise it is imported by name (a literal import, so a
* bundler's file tracing copies it into a production build — `.output` run on
* its own had no sharp), then looked up from the working directory.
*/
export function useImages(sharp) { lib = sharp; }
async function sharp() {
if (lib)
return lib;
try {
// @ts-ignore — optional peer dependency, not installed with Talos itself
const m = await import('sharp');
lib = m.default ?? m;
}
catch {
try {
lib = createRequire(join(process.cwd(), 'package.json'))('sharp');
}
catch {
throw new Error('image processing needs sharp: npm install sharp (or call useImages(sharp))');
}
}
return lib;
}
export const extOf = (o) => o.format ? `.${o.format === 'jpeg' ? 'jpg' : o.format}` : undefined;
export async function imageSize(data) {
const m = await (await sharp())(data).metadata();
return { width: m.width, height: m.height };
}
export async function processImage(data, o) {
let img = (await sharp())(data, { failOn: 'error' }).rotate();
if (o.width || o.height)
img = img.resize({ width: o.width, height: o.height, fit: o.fit ?? 'inside', withoutEnlargement: !(o.enlarge ?? o.fit === 'cover') });
if (o.keepMetadata)
img = img.keepMetadata();
if (o.format)
img = img.toFormat(o.format, o.quality ? { quality: o.quality } : {});
else if (o.quality)
img = img.jpeg({ quality: o.quality });
return img.toBuffer();
}