Something went wrong. Try again.
doll.systems community website
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273import { readFile, stat } from 'node:fs/promises';import sharp from 'sharp';import { imageKey, imageProfile, mediaFile, sourceFile, stillPath, variantPath,} from './image-files.mjs';import type { Artwork } from './layouts';
export type ImageAsset = { src: string; width: number; height: number };export type FeatureImage = ImageAsset & { alt: string; preview: ImageAsset };export type BackgroundImage = { src: string; exposure?: number; focus?: [number, number]; moonSway?: boolean;};type Prepared = { key: string; width: number };
const cache = new Map<string, { mtimeMs: number; size: number; result: Promise<Prepared> }>();
async function prepared(src: string): Promise<Prepared> { const source = await sourceFile(src); const { mtimeMs, size } = await stat(source); const cached = cache.get(src); if (cached?.mtimeMs === mtimeMs && cached.size === size) return cached.result; const result = (async () => { const input = await readFile(source); const key = imageKey(input); const { width } = (await sharp(input).metadata()).autoOrient; return { key, width }; })(); cache.set(src, { mtimeMs, size, result }); return result;}
async function asset(path: string): Promise<ImageAsset> { const { width, height } = await sharp(mediaFile(path)).metadata(); if (!width || !height) throw new Error(`Cannot read prepared image: ${path}`); return { src: path, width, height };}
export async function backgroundImage(definition: string | BackgroundImage): Promise<Artwork> { const { src, exposure = -0.035, focus = [0.5, 0.5], moonSway, } = typeof definition === 'string' ? { src: definition } : definition; const { key, width } = await prepared(src); const [background, still] = await Promise.all([ asset(variantPath(key, width, imageProfile.backgroundWidth)), asset(stillPath(key)), ]); return { ...background, still, exposure, focus, moonSway };}
export async function featureImage(image?: { src: string; alt: string;}): Promise<FeatureImage | undefined> { if (!image) return; const { key, width } = await prepared(image.src); const [feature, preview] = await Promise.all([ asset(variantPath(key, width, imageProfile.featureWidth)), asset(variantPath(key, width, imageProfile.previewWidth)), ]); return { ...feature, preview, alt: image.alt };}