Skip to content

Build your personal knowledge base with Trilium Notes

2.7 KB
Raw Blame
/**
 * Standalone image provider implementation.
 * Uses pure JavaScript for format detection without compression.
 * Images are saved as-is without resizing.
 */

import type { ImageCompressionOutcome, ImageCompressionPlan, ImageFormat, ImageProvider, ImageShrink, PreviewResizeOutcome, ProcessedImage } from "@triliumnext/core";
import { inspectImage, UNKNOWN_FORMAT } from "@triliumnext/core/src/services/image_inspect.js";

/**
 * Detect image type from buffer, delegating to the shared inspector so this runtime and the
 * inventory recognise exactly the same formats by exactly the same bytes.
 */
function getImageTypeFromBuffer(buffer: Uint8Array): ImageFormat | null {
    const { format, mime } = inspectImage(buffer);

    return format === UNKNOWN_FORMAT ? null : { ext: format, mime };
}

export const standaloneImageProvider: ImageProvider = {
    getImageType(buffer: Uint8Array): ImageFormat | null {
        return getImageTypeFromBuffer(buffer);
    },

    async processImage(buffer: Uint8Array, _originalName: string, _shrink: ImageShrink): Promise<ProcessedImage> {
        // Standalone doesn't do compression - just detect format and return original
        const format = getImageTypeFromBuffer(buffer) || { ext: "dat", mime: "application/octet-stream" };

        return {
            buffer,
            format
        };
    },

    async compressImage(): Promise<ImageCompressionOutcome> {
        // No decoder here, so there is nothing to recompress with — the request is answered rather
        // than refused, and the caller reports the images as untouched along with the reason.
        return { compressed: false, reason: "unsupported-platform" };
    },

    compressionConcurrency(): number {
        // Nothing to compress with, so nothing to spread over threads.
        return 1;
    },

    async planCompression(): Promise<ImageCompressionPlan> {
        // Settled before an image is so much as weighed: nothing here is going to compress it
        // whatever its header says, so a run over a tree reads none of them.
        return { skip: "unsupported-platform", decodeCost: null };
    },

    /**
     * Declined for the same reason as everything else on this runtime: there is no decoder to scale
     * a picture with.
     *
     * The preview is not lost to it. The caller keeps a cover image that is already small enough to
     * store as it came, and shows a preview without a picture where it is not — which is exactly
     * what the server does for a WebP its own decoder cannot read, so this is a path already
     * travelled rather than a new kind of degradation.
     */
    async resizeForPreview(): Promise<PreviewResizeOutcome> {
        return { resized: false, reason: "unsupported-platform" };
    }
};