/** Fully decode all raster pixels with npm-lockfile-pinned sharp; no network. */ import sharp from 'sharp'; import { realpath } from 'node:fs/promises'; import { resolve, sep } from 'node:path'; import { fileURLToPath } from 'node:url'; sharp.cache(false); sharp.concurrency(1); export async function decodeBatch({ root, files }) { if (sharp.versions.sharp !== '0.34.5') { throw new Error(`Expected lockfile sharp0.34.5, found ${sharp.versions.sharp}`); } if (typeof root !== 'string' || !Array.isArray(files) || files.length > 10000) { throw new Error('Expected a public root and a bounded file array'); } const boundary = await realpath(root); const results = []; for (const file of files) { try { const candidate = await realpath(resolve(boundary, file)); if (!candidate.startsWith(boundary + sep)) throw new Error('Raster path outside public root'); const image = sharp(candidate, { failOn: 'error', animated: true, limitInputPixels: 64000000 }); const metadata = await image.metadata(); // metadata() alone is insufficient: force actual decode of every pixel. const { info } = await image.raw().toBuffer({ resolveWithObject: true }); results.push({ file, type: 'raster', valid: true, width: info.width, height: info.height, format: metadata.format, pages: metadata.pages ?? 1, decodedBytes: info.size, decoder: `sharp${sharp.versions.sharp}/libvips${sharp.versions.vips}` }); } catch (error) { results.push({ file, type: 'raster', valid: false, error: String(error.message), decoder: 'sharp0.34.5' }); } } return { decoder: 'sharp', version: sharp.versions.sharp, results }; } if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { try { const chunks = []; let size = 0; for await (const chunk of process.stdin) { size += chunk.length; if (size > 4000000) throw new Error('Raster manifest exceeds 4MB'); chunks.push(chunk); } const report = await decodeBatch(JSON.parse(Buffer.concat(chunks).toString('utf8'))); process.stdout.write(JSON.stringify(report) + '\n'); if (report.results.some(item => !item.valid)) process.exitCode = 1; } catch (error) { process.stderr.write(String(error.stack ?? error) + '\n'); process.exitCode = 2; } }