|
| 1 | +import { Config } from "@/config/config" |
| 2 | +import type { MessageV2 } from "@/session/message-v2" |
| 3 | +import * as Log from "@opencode-ai/core/util/log" |
| 4 | +import { Context, Effect, Layer, Schema } from "effect" |
| 5 | +import fs from "fs" |
| 6 | + |
| 7 | +const MAX_BASE64_BYTES = 4.5 * 1024 * 1024 |
| 8 | +const MAX_WIDTH = 2000 |
| 9 | +const MAX_HEIGHT = 2000 |
| 10 | +const AUTO_RESIZE = true |
| 11 | +const JPEG_QUALITIES = [80, 85, 70, 55, 40] |
| 12 | +const log = Log.create({ service: "image" }) |
| 13 | + |
| 14 | +type Photon = typeof import("@silvia-odwyer/photon-node") |
| 15 | + |
| 16 | +let photonModule: Photon | null = null |
| 17 | +let photonPromise: Promise<Photon | null> | null = null |
| 18 | + |
| 19 | +function loadPhoton() { |
| 20 | + if (photonModule) return Promise.resolve(photonModule) |
| 21 | + if (photonPromise) return photonPromise |
| 22 | + |
| 23 | + photonPromise = (async () => { |
| 24 | + const photonWasm = (await import("@silvia-odwyer/photon-node/photon_rs_bg.wasm", { with: { type: "file" } })).default |
| 25 | + const original = fs.readFileSync |
| 26 | + fs.readFileSync = ((file: fs.PathOrFileDescriptor, options?: Parameters<typeof fs.readFileSync>[1]) => { |
| 27 | + if (typeof file === "string" && file.endsWith("photon_rs_bg.wasm")) return original(photonWasm, options) |
| 28 | + return original(file, options) |
| 29 | + }) as typeof fs.readFileSync |
| 30 | + try { |
| 31 | + photonModule = await import("@silvia-odwyer/photon-node") |
| 32 | + return photonModule |
| 33 | + } catch { |
| 34 | + photonModule = null |
| 35 | + return null |
| 36 | + } finally { |
| 37 | + fs.readFileSync = original |
| 38 | + } |
| 39 | + })() |
| 40 | + |
| 41 | + return photonPromise |
| 42 | +} |
| 43 | + |
| 44 | +export class PhotonUnavailableError extends Schema.TaggedErrorClass<PhotonUnavailableError>()( |
| 45 | + "ImagePhotonUnavailableError", |
| 46 | + {}, |
| 47 | +) { |
| 48 | + override get message() { |
| 49 | + return "Photon image processor is unavailable" |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +export class InvalidDataUrlError extends Schema.TaggedErrorClass<InvalidDataUrlError>()("ImageInvalidDataUrlError", { |
| 54 | + url: Schema.String, |
| 55 | +}) { |
| 56 | + override get message() { |
| 57 | + return "Image URL must be a base64 data URL" |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +export class DecodeError extends Schema.TaggedErrorClass<DecodeError>()("ImageDecodeError", {}) { |
| 62 | + override get message() { |
| 63 | + return "Image could not be decoded" |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +export class SizeError extends Schema.TaggedErrorClass<SizeError>()("ImageSizeError", { |
| 68 | + bytes: Schema.Number, |
| 69 | + max: Schema.Number, |
| 70 | + width: Schema.Number, |
| 71 | + height: Schema.Number, |
| 72 | + max_width: Schema.Number, |
| 73 | + max_height: Schema.Number, |
| 74 | +}) { |
| 75 | + override get message() { |
| 76 | + return `Image ${this.width}x${this.height} with base64 size ${this.bytes} exceeds configured limits and could not be resized below ${this.max_width}x${this.max_height}/${this.max} bytes` |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +export type Error = PhotonUnavailableError | InvalidDataUrlError | DecodeError | SizeError |
| 81 | + |
| 82 | +export interface Interface { |
| 83 | + readonly normalize: (input: MessageV2.FilePart) => Effect.Effect<MessageV2.FilePart, Error> |
| 84 | +} |
| 85 | + |
| 86 | +export class Service extends Context.Service<Service, Interface>()("@opencode/Image") {} |
| 87 | + |
| 88 | +export const layer = Layer.effect( |
| 89 | + Service, |
| 90 | + Effect.gen(function* () { |
| 91 | + const config = yield* Config.Service |
| 92 | + |
| 93 | + const normalize = Effect.fn("Image.normalize")(function* (input: MessageV2.FilePart) { |
| 94 | + const image = (yield* config.get()).attachment?.image |
| 95 | + const info = { |
| 96 | + autoResize: image?.auto_resize ?? AUTO_RESIZE, |
| 97 | + maxWidth: image?.max_width ?? MAX_WIDTH, |
| 98 | + maxHeight: image?.max_height ?? MAX_HEIGHT, |
| 99 | + maxBase64Bytes: image?.max_base64_bytes ?? MAX_BASE64_BYTES, |
| 100 | + } |
| 101 | + if (!info.autoResize) return input |
| 102 | + if (!input.url.startsWith("data:") || !input.url.includes(";base64,")) |
| 103 | + return yield* new InvalidDataUrlError({ url: input.url }) |
| 104 | + |
| 105 | + const base64 = input.url.slice(input.url.indexOf(";base64,") + ";base64,".length) |
| 106 | + const photon = yield* Effect.promise(loadPhoton) |
| 107 | + if (!photon) return yield* new PhotonUnavailableError() |
| 108 | + |
| 109 | + const decoded = yield* Effect.sync(() => { |
| 110 | + try { |
| 111 | + return photon.PhotonImage.new_from_byteslice(Buffer.from(base64, "base64")) |
| 112 | + } catch { |
| 113 | + return undefined |
| 114 | + } |
| 115 | + }) |
| 116 | + if (!decoded) return yield* new DecodeError() |
| 117 | + |
| 118 | + try { |
| 119 | + const originalWidth = decoded.get_width() |
| 120 | + const originalHeight = decoded.get_height() |
| 121 | + if ( |
| 122 | + originalWidth <= info.maxWidth && |
| 123 | + originalHeight <= info.maxHeight && |
| 124 | + Buffer.byteLength(base64, "utf8") <= info.maxBase64Bytes |
| 125 | + ) |
| 126 | + return input |
| 127 | + |
| 128 | + const scale = Math.min(1, info.maxWidth / originalWidth, info.maxHeight / originalHeight) |
| 129 | + for (const size of Array.from({ length: 32 }).reduce<Array<{ width: number; height: number }>>((acc) => { |
| 130 | + const previous = acc.at(-1) ?? { |
| 131 | + width: Math.max(1, Math.round(originalWidth * scale)), |
| 132 | + height: Math.max(1, Math.round(originalHeight * scale)), |
| 133 | + } |
| 134 | + const next = acc.length === 0 |
| 135 | + ? previous |
| 136 | + : { |
| 137 | + width: previous.width === 1 ? 1 : Math.max(1, Math.floor(previous.width * 0.75)), |
| 138 | + height: previous.height === 1 ? 1 : Math.max(1, Math.floor(previous.height * 0.75)), |
| 139 | + } |
| 140 | + return acc.some((item) => item.width === next.width && item.height === next.height) ? acc : [...acc, next] |
| 141 | + }, [])) { |
| 142 | + const resized = photon.resize(decoded, size.width, size.height, photon.SamplingFilter.Lanczos3) |
| 143 | + const candidate = [ |
| 144 | + { data: Buffer.from(resized.get_bytes()).toString("base64"), mime: "image/png" }, |
| 145 | + ...JPEG_QUALITIES.map((quality) => ({ |
| 146 | + data: Buffer.from(resized.get_bytes_jpeg(quality)).toString("base64"), |
| 147 | + mime: "image/jpeg", |
| 148 | + })), |
| 149 | + ] |
| 150 | + .map((item) => ({ ...item, bytes: Buffer.byteLength(item.data, "utf8") })) |
| 151 | + .filter((item) => item.bytes <= info.maxBase64Bytes) |
| 152 | + .sort((a, b) => a.bytes - b.bytes)[0] |
| 153 | + resized.free() |
| 154 | + |
| 155 | + if (candidate) { |
| 156 | + log.info("using resized image", { |
| 157 | + from_mime: input.mime, |
| 158 | + to_mime: candidate.mime, |
| 159 | + from: `${originalWidth}x${originalHeight}`, |
| 160 | + to: `${size.width}x${size.height}`, |
| 161 | + }) |
| 162 | + return { |
| 163 | + ...input, |
| 164 | + mime: candidate.mime, |
| 165 | + url: `data:${candidate.mime};base64,${candidate.data}`, |
| 166 | + } |
| 167 | + } |
| 168 | + } |
| 169 | + |
| 170 | + return yield* new SizeError({ |
| 171 | + bytes: Buffer.byteLength(base64, "utf8"), |
| 172 | + max: info.maxBase64Bytes, |
| 173 | + width: originalWidth, |
| 174 | + height: originalHeight, |
| 175 | + max_width: info.maxWidth, |
| 176 | + max_height: info.maxHeight, |
| 177 | + }) |
| 178 | + } finally { |
| 179 | + decoded.free() |
| 180 | + } |
| 181 | + }) |
| 182 | + |
| 183 | + return Service.of({ normalize }) |
| 184 | + }), |
| 185 | +) |
| 186 | + |
| 187 | +export const defaultLayer = layer.pipe(Layer.provide(Config.defaultLayer)) |
| 188 | + |
| 189 | +export * as Image from "./image" |
0 commit comments