← Files Flows by plugin.spaceARCHIVED FILE

lib/screenshots.mjs

3.61 KB · Nov 30, 2026 · 00:17 UTC

↓ Download file

import { mkdir, realpath, writeFile, rm } from 'node:fs/promises';
import { dirname, isAbsolute, relative, resolve } from 'node:path';
import { randomUUID } from 'node:crypto';
import { updateDocument } from './write-document.mjs';

export function pngDimensions(buffer) {
  if (buffer.length > 8 * 1024 * 1024) throw new Error('Screenshot exceeds 8 MB. Use a viewport capture.');
  if (buffer.length < 24 || !buffer.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) || buffer.toString('ascii', 12, 16) !== 'IHDR') throw new Error('Use a PNG screenshot.');
  const width = buffer.readUInt32BE(16), height = buffer.readUInt32BE(20);
  if (!width || !height || width > 30000 || height > 30000) throw new Error('Unsupported screenshot dimensions.');
  return { width, height };
}

export function imageDimensions(buffer) {
  if (buffer.length > 8 * 1024 * 1024) throw new Error('Screenshot exceeds 8 MB. Use a viewport capture.');
  if (buffer[0] === 137) return { ...pngDimensions(buffer), format: 'png' };
  if (buffer[0] !== 0xff || buffer[1] !== 0xd8) throw new Error('Use a PNG or JPEG screenshot.');
  // JPEG dimensions live in a start-of-frame segment, before compressed pixels.
  let offset = 2;
  while (offset + 4 <= buffer.length) {
    if (buffer[offset++] !== 0xff) break;
    while (buffer[offset] === 0xff) offset++;
    const marker = buffer[offset++];
    if (marker === 0xda || marker === 0xd9 || offset + 2 > buffer.length) break;
    const length = buffer.readUInt16BE(offset);
    if (length < 2 || offset + length > buffer.length) break;
    if ([0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf].includes(marker)) {
      if (length < 8) break;
      const height = buffer.readUInt16BE(offset + 3), width = buffer.readUInt16BE(offset + 5);
      if (!width || !height || width > 30000 || height > 30000) break;
      return { width, height, format: 'jpeg' };
    }
    offset += length;
  }
  throw new Error('Invalid JPEG screenshot dimensions.');
}

export async function saveScreenshot(file, { nodeId, profile, buffer, method, url }) {
  const { format, ...dimensions } = imageDimensions(buffer);
  const root = await realpath(dirname(file));
  const folder = resolve(root, 'screens');
  await mkdir(folder, { recursive: true });
  const realFolder = await realpath(folder);
  const part = relative(root, realFolder);
  if (!part || part.startsWith('..') || isAbsolute(part)) throw new Error('Screenshot directory must stay inside the flow directory.');
  const name = `${randomUUID()}.${format === 'jpeg' ? 'jpg' : 'png'}`;
  const absolutePath = resolve(realFolder, name);
  await writeFile(absolutePath, buffer, { flag: 'wx', mode: 0o600 });
  const capture = { path: `screens/${name}`, ...dimensions, viewport: { width: profile.width, height: profile.height }, capturedAt: new Date().toISOString(), method };
  if (url) { const source = new URL(url); capture.url = `${source.origin}${source.pathname}`; }
  return { nodeId, profileId: profile.id, capture, absolutePath };
}

export async function attachScreenshots(file, revision, shots, settings) {
  return updateDocument(file, revision, document => {
    if (settings) document.captureSettings = settings;
    for (const shot of shots) {
      const node = document.nodes.find(node => node.id === shot.nodeId && node.type === 'screen');
      if (!node) throw new Error(`Screen node ${shot.nodeId} does not exist.`);
      node.screenshots = { ...node.screenshots, [shot.profileId]: shot.capture };
    }
    return document;
  });
}

export async function discardScreenshots(shots) {
  await Promise.all(shots.map(shot => rm(shot.absolutePath, { force: true })));
}

SHA-256: 1ee18af5beb25be53209f3f3ffb6194af47ca095e33aab6afb5e0630352ca25e