Impresiones Online

Licencias y código fuente

Información del conversor PDF a PCL de los trabajos y pruebas de la ESP32.

Ghostscript

La ruta de la ESP32 usa el paquete Ghostscript de Debian para generar PCL3 o PCLm. Ghostscript está licenciado bajo GNU AGPL versión 3. El Worker no incluye el binario ni un módulo WebAssembly: envía la conversión a un servicio separado del VPS. Los archivos descargados por la ruta CUPS siguen siendo los PDF originales.

Código fuente del conversor PDF→PCL

El conversor recibe peticiones HMAC firmadas, valida papel y límites, y borra sus temporales al terminar. El almacenamiento del trabajo en la aplicación sigue su ciclo normal:

Ver converter/server.mjs
import { createHash, createHmac, timingSafeEqual } from "node:crypto";
import { createReadStream, createWriteStream } from "node:fs";
import { mkdtemp, open, readFile, rm, stat } from "node:fs/promises";
import { spawn } from "node:child_process";
import { createServer } from "node:http";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { Transform } from "node:stream";
import { pipeline } from "node:stream/promises";
import {
  buildConverterSignaturePayload,
  buildGhostscriptArgs,
  PCL_OUTPUT_FORMATS,
} from "../worker/src/pdf-to-pcl-options.js";

export const PCL_DOCUMENT_FORMAT = PCL_OUTPUT_FORMATS.pcl.documentFormat;
export const PCLM_DOCUMENT_FORMAT = PCL_OUTPUT_FORMATS.pclm.documentFormat;
export const MAX_PDF_BYTES = 10 * 1024 * 1024;
export const MAX_PCL_BYTES = 64 * 1024 * 1024;
export const MAX_PDF_PAGES = 500;

const MAX_CLOCK_SKEW_SECONDS = 120;
const MAX_IN_FLIGHT_REQUESTS = 4;
const AUTH_FAILURE_WINDOW_SECONDS = 15 * 60;
const MAX_AUTH_FAILURES = 10;
const MAX_AUTH_FAILURE_ENTRIES = 8192;
const GHOSTSCRIPT_TIMEOUT_MS = 120_000;
const MAX_PAGE_COUNT_OUTPUT_BYTES = 128;
const SECURITY_HEADERS = {
  "Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'",
  "Cross-Origin-Resource-Policy": "same-origin",
  "Referrer-Policy": "no-referrer",
  "X-Content-Type-Options": "nosniff",
  "X-Frame-Options": "DENY",
};

class ConverterError extends Error {
  constructor(status, code) {
    super(code);
    this.status = status;
    this.code = code;
  }
}

export function signConverterRequest(secret, fields) {
  const payload = buildConverterSignaturePayload(fields);
  return createHmac("sha256", secret).update(payload).digest("hex");
}

function sendJson(response, status, body, extraHeaders = {}) {
  if (response.destroyed || response.headersSent) return;
  const bytes = Buffer.from(JSON.stringify(body));
  response.writeHead(status, {
    "Cache-Control": "no-store",
    Connection: "close",
    "Content-Length": String(bytes.byteLength),
    "Content-Type": "application/json; charset=utf-8",
    ...SECURITY_HEADERS,
    ...extraHeaders,
  });
  response.end(bytes);
}

function header(request, name) {
  const value = request.headers[name];
  return typeof value === "string" ? value : "";
}

function clientIdentity(request) {
  const cloudflareIp = header(request, "cf-connecting-ip");
  if (/^[0-9a-f:.]{3,45}$/i.test(cloudflareIp)) return `cf:${cloudflareIp}`;
  return `socket:${request.socket.remoteAddress ?? "unknown"}`;
}

function isAuthRateLimited(failures, identity, nowSeconds) {
  const entry = failures.get(identity);
  if (!entry) return false;
  if (entry.expiresAt <= nowSeconds) {
    failures.delete(identity);
    return false;
  }
  return entry.attempts >= MAX_AUTH_FAILURES;
}

function recordAuthFailure(failures, identity, nowSeconds) {
  const previous = failures.get(identity);
  const entry = previous && previous.expiresAt > nowSeconds
    ? { attempts: previous.attempts + 1, expiresAt: previous.expiresAt }
    : { attempts: 1, expiresAt: nowSeconds + AUTH_FAILURE_WINDOW_SECONDS };
  failures.set(identity, entry);
  if (entry.attempts === MAX_AUTH_FAILURES) {
    console.warn("pcl_converter_auth_throttled", { code: "too_many_invalid_signatures" });
  }
  if (failures.size > MAX_AUTH_FAILURE_ENTRIES) {
    const oldest = failures.keys().next().value;
    if (oldest) failures.delete(oldest);
  }
}

function validSignature(secret, fields, provided) {
  if (!/^[0-9a-f]{64}$/i.test(provided)) return false;
  const expected = Buffer.from(signConverterRequest(secret, fields), "hex");
  const actual = Buffer.from(provided, "hex");
  return actual.length === expected.length && timingSafeEqual(actual, expected);
}

async function hasPdfHeader(path) {
  const file = await open(path, "r");
  try {
    const prefix = Buffer.alloc(1024);
    const { bytesRead } = await file.read(prefix, 0, prefix.length, 0);
    return prefix.subarray(0, bytesRead).includes(Buffer.from("%PDF-"));
  } finally {
    await file.close();
  }
}

function runGhostscript(binary, args, { captureStdout = false } = {}) {
  return new Promise((resolve, reject) => {
    const child = spawn(binary, args, {
      stdio: ["ignore", captureStdout ? "pipe" : "ignore", "ignore"],
    });
    let output = "";
    let timedOut = false;
    let outputTooLarge = false;
    const timer = setTimeout(() => {
      timedOut = true;
      child.kill("SIGKILL");
    }, GHOSTSCRIPT_TIMEOUT_MS);

    if (captureStdout) {
      child.stdout.on("data", (chunk) => {
        if (output.length + chunk.length > MAX_PAGE_COUNT_OUTPUT_BYTES) {
          outputTooLarge = true;
          child.kill("SIGKILL");
          return;
        }
        output += chunk.toString("utf8");
      });
    }

    child.once("error", (error) => {
      clearTimeout(timer);
      reject(new ConverterError(error.code === "ENOENT" ? 503 : 502,
        error.code === "ENOENT" ? "converter_unavailable" : "conversion_failed"));
    });
    child.once("close", (code) => {
      clearTimeout(timer);
      if (timedOut) return reject(new ConverterError(504, "conversion_timeout"));
      if (outputTooLarge) return reject(new ConverterError(422, "invalid_pdf"));
      if (code !== 0) return reject(new ConverterError(422, "conversion_failed"));
      resolve(output);
    });
  });
}

async function countPdfPages(binary, inputPath) {
  const output = await runGhostscript(binary, [
    "-q",
    "-dSAFER",
    `--permit-file-read=${inputPath}`,
    "-dNODISPLAY",
    "-c",
    `(${inputPath}) (r) file runpdfbegin pdfpagecount = quit`,
  ], { captureStdout: true });
  const countText = output.trim();
  if (!/^\d+$/.test(countText)) throw new ConverterError(422, "invalid_pdf");
  const count = Number(countText);
  if (!Number.isSafeInteger(count) || count < 1 || count > MAX_PDF_PAGES) {
    throw new ConverterError(422, "invalid_pdf");
  }
  return count;
}

async function renderPdfToPcl({ binary, inputPath, directory, paperSize, firstPageOnly, outputFormat = "pcl" }) {
  const format = PCL_OUTPUT_FORMATS[outputFormat];
  if (!format) throw new ConverterError(422, "unsupported_output_format");
  const probeOutput = join(directory, `probe.${format.extension}`);
  try {
    buildGhostscriptArgs({ inputPath, outputPath: probeOutput, paperSize, pageNumber: 1, outputFormat });
  } catch (error) {
    if (error instanceof RangeError) throw new ConverterError(422, "unsupported_paper_size");
    throw error;
  }

  const pageCount = firstPageOnly ? 1 : await countPdfPages(binary, inputPath);
  const combinedPath = join(directory, `combined.${format.extension}`);
  if (outputFormat === "pclm") {
    const args = buildGhostscriptArgs({
      inputPath,
      outputPath: combinedPath,
      paperSize,
      pageNumber: firstPageOnly ? 1 : undefined,
      outputFormat,
    });
    await runGhostscript(binary, args);

    const output = await stat(combinedPath).catch(() => null);
    if (!output || output.size < 16) throw new ConverterError(422, "conversion_failed");
    if (output.size > MAX_PCL_BYTES) throw new ConverterError(413, "output_too_large");
    const handle = await open(combinedPath, "r");
    try {
      const prefix = Buffer.alloc(64);
      const { bytesRead } = await handle.read(prefix, 0, prefix.length, 0);
      // A PCLm file is a constrained PDF and must identify itself as PCLm.
      // A generic PDF with the right Content-Type is not a valid substitute.
      if (!/^%PDF-\d\.\d\r?\n%PCLm\s/.test(prefix.subarray(0, bytesRead).toString("ascii"))) {
        throw new ConverterError(422, "conversion_failed");
      }
    } finally {
      await handle.close();
    }
    return { path: combinedPath, size: output.size, pageCount };
  }

  let totalBytes = 0;

  for (let pageNumber = 1; pageNumber <= pageCount; pageNumber += 1) {
    const pagePath = join(directory, `page-${pageNumber}.${format.extension}`);
    const args = buildGhostscriptArgs({ inputPath, outputPath: pagePath, paperSize, pageNumber, outputFormat });
    await runGhostscript(binary, args);

    const page = await stat(pagePath).catch(() => null);
    if (!page || page.size < 2) throw new ConverterError(422, "conversion_failed");
    if (totalBytes + page.size > MAX_PCL_BYTES) throw new ConverterError(413, "output_too_large");

    const handle = await open(pagePath, "r");
    try {
      const prefix = Buffer.alloc(2);
      const { bytesRead } = await handle.read(prefix, 0, prefix.length, 0);
      if (bytesRead < 2 || prefix[0] !== 0x1b) throw new ConverterError(422, "conversion_failed");
    } finally {
      await handle.close();
    }

    await pipeline(
      createReadStream(pagePath),
      createWriteStream(combinedPath, { flags: pageNumber === 1 ? "w" : "a", mode: 0o600 }),
    );
    totalBytes += page.size;
    await rm(pagePath, { force: true });
  }

  return { path: combinedPath, size: totalBytes, pageCount };
}

export function createConverterServer({ secret, ghostscriptBinary = "gs", maxConcurrency = 1 } = {}) {
  if (typeof secret !== "string" || secret.trim().length < 32) {
    throw new TypeError("A converter HMAC secret of at least 32 characters is required");
  }

  let inFlightRequests = 0;
  let activeConversions = 0;
  const usedNonces = new Map();
  const authFailures = new Map();

  const server = createServer((request, response) => {
    void handleRequest(request, response).catch((error) => {
      if (response.destroyed || response.headersSent) {
        response.destroy();
        return;
      }
      if (error instanceof ConverterError) {
        sendJson(response, error.status, { error: error.code });
        return;
      }
      console.error("pcl_converter_request_failed", { code: "internal_error" });
      sendJson(response, 500, { error: "conversion_failed" });
    });
  });

  server.headersTimeout = 10_000;
  server.requestTimeout = 60_000;
  server.keepAliveTimeout = 5_000;

  async function handleRequest(request, response) {
    const pathname = new URL(request.url ?? "/", "http://converter.local").pathname;
    if (request.method === "GET" && pathname === "/healthz") {
      sendJson(response, 200, { ok: true });
      return;
    }
    if (request.method !== "POST" || pathname !== "/v1/convert") {
      sendJson(response, 404, { error: "not_found" });
      return;
    }
    if (inFlightRequests >= MAX_IN_FLIGHT_REQUESTS) {
      sendJson(response, 429, { error: "converter_busy" });
      return;
    }
    const identity = clientIdentity(request);
    const requestNowSeconds = Math.floor(Date.now() / 1000);
    if (isAuthRateLimited(authFailures, identity, requestNowSeconds)) {
      sendJson(response, 429, { error: "converter_busy" }, { "Retry-After": String(AUTH_FAILURE_WINDOW_SECONDS) });
      return;
    }
    inFlightRequests += 1;

    let directory;
    try {
      if (header(request, "content-type").split(";")[0].trim().toLowerCase() !== "application/pdf") {
        throw new ConverterError(415, "unsupported_media_type");
      }

      const lengthText = header(request, "content-length");
      if (!/^\d+$/.test(lengthText)) throw new ConverterError(411, "content_length_required");
      const contentLength = Number(lengthText);
      if (!Number.isSafeInteger(contentLength) || contentLength < 1) {
        throw new ConverterError(400, "invalid_request");
      }
      if (contentLength > MAX_PDF_BYTES) throw new ConverterError(413, "input_too_large");

      const timestamp = header(request, "x-pcl-timestamp");
      const nonce = header(request, "x-pcl-nonce");
      const paperSize = header(request, "x-pcl-paper-size");
      const firstPageValue = header(request, "x-pcl-first-page-only");
      const outputFormat = (header(request, "x-pcl-output-format") || "pcl").toLowerCase();
      const providedSignature = header(request, "x-pcl-signature");
      if (!/^\d{10}$/.test(timestamp) || !/^[a-zA-Z0-9-]{16,80}$/.test(nonce)
        || paperSize.length > 40 || !["true", "false"].includes(firstPageValue)
        || !/^[0-9a-f]{64}$/i.test(providedSignature)) {
        recordAuthFailure(authFailures, identity, Math.floor(Date.now() / 1000));
        throw new ConverterError(401, "unauthorized");
      }
      if (!PCL_OUTPUT_FORMATS[outputFormat]) throw new ConverterError(400, "invalid_request");
      const nowSeconds = Math.floor(Date.now() / 1000);
      if (Math.abs(nowSeconds - Number(timestamp)) > MAX_CLOCK_SKEW_SECONDS) {
        recordAuthFailure(authFailures, identity, nowSeconds);
        throw new ConverterError(401, "unauthorized");
      }

      directory = await mkdtemp(join(tmpdir(), "impresiones-pcl-"));
      const inputPath = join(directory, "input.pdf");
      const digest = createHash("sha256");
      let receivedBytes = 0;
      const hashStream = new Transform({
        transform(chunk, _encoding, callback) {
          receivedBytes += chunk.length;
          if (receivedBytes > MAX_PDF_BYTES) {
            callback(new ConverterError(413, "input_too_large"));
            return;
          }
          digest.update(chunk);
          callback(null, chunk);
        },
      });
      await pipeline(request, hashStream, createWriteStream(inputPath, { flags: "wx", mode: 0o600 }))
        .catch((error) => {
          if (error instanceof ConverterError) throw error;
          throw new ConverterError(400, "invalid_request");
        });
      if (receivedBytes !== contentLength) throw new ConverterError(400, "invalid_request");

      const fields = {
        timestamp,
        nonce,
        paperSize,
        firstPageOnly: firstPageValue === "true",
        sha256: digest.digest("hex"),
        outputFormat,
      };
      if (!validSignature(secret, fields, providedSignature)) {
        recordAuthFailure(authFailures, identity, Math.floor(Date.now() / 1000));
        throw new ConverterError(401, "unauthorized");
      }
      authFailures.delete(identity);

      for (const [seenNonce, expiresAt] of usedNonces) {
        if (expiresAt < nowSeconds) usedNonces.delete(seenNonce);
      }
      if (usedNonces.has(nonce)) throw new ConverterError(409, "replayed_request");
      if (usedNonces.size >= 4096) throw new ConverterError(429, "converter_busy");
      usedNonces.set(nonce, nowSeconds + MAX_CLOCK_SKEW_SECONDS * 2);

      if (!await hasPdfHeader(inputPath)) throw new ConverterError(422, "invalid_pdf");
      if (activeConversions >= maxConcurrency) throw new ConverterError(429, "converter_busy");

      activeConversions += 1;
      const startedAt = Date.now();
      try {
        const converted = await renderPdfToPcl({
          binary: ghostscriptBinary,
          inputPath,
          directory,
          paperSize,
          firstPageOnly: fields.firstPageOnly,
          outputFormat: fields.outputFormat,
        });
        response.writeHead(200, {
          "Cache-Control": "no-store",
          "Content-Length": String(converted.size),
          "Content-Type": PCL_OUTPUT_FORMATS[fields.outputFormat].documentFormat,
          ...SECURITY_HEADERS,
          "X-PCL-Converter-Version": PCL_OUTPUT_FORMATS[fields.outputFormat].converterVersion,
          "X-PCL-Page-Count": String(converted.pageCount),
        });
        await pipeline(createReadStream(converted.path), response);
        console.info("pcl_conversion_complete", {
          inputBytes: receivedBytes,
          outputBytes: converted.size,
          pageCount: converted.pageCount,
          outputFormat: fields.outputFormat,
          mime: PCL_OUTPUT_FORMATS[fields.outputFormat].documentFormat,
          durationMs: Date.now() - startedAt,
          firstPageOnly: fields.firstPageOnly,
        });
      } finally {
        activeConversions -= 1;
      }
    } finally {
      inFlightRequests -= 1;
      if (directory) await rm(directory, { recursive: true, force: true });
    }
  }

  return server;
}

async function start() {
  const secretPath = process.env.PCL_CONVERTER_SECRET_FILE ?? "/run/secrets/pcl-hmac";
  const secret = (await readFile(secretPath, "utf8")).trim();
  const port = Number(process.env.PORT ?? "8787");
  if (!Number.isInteger(port) || port < 1 || port > 65_535) throw new Error("Invalid PORT");
  const server = createConverterServer({ secret });
  server.listen(port, "0.0.0.0", () => {
    console.info("pcl_converter_ready", { port, devices: ["pcl3", "pclm"] });
  });
  process.once("SIGTERM", () => server.close());
  process.once("SIGINT", () => server.close());
}

if (import.meta.url === `file://${process.argv[1]}`) {
  start().catch((error) => {
    console.error("pcl_converter_start_failed", { code: error?.code ?? "startup_error" });
    process.exitCode = 1;
  });
}
Ver worker/src/pdf-to-pcl-client.ts
import { buildConverterSignaturePayload, PCL_OUTPUT_FORMATS } from "./pdf-to-pcl-options.js";
import type { PclOutputFormat } from "./pdf-to-pcl-options.js";

export type { PclOutputFormat } from "./pdf-to-pcl-options.js";

export const PCL_DOCUMENT_FORMAT = PCL_OUTPUT_FORMATS.pcl.documentFormat;
export const PCLM_DOCUMENT_FORMAT = PCL_OUTPUT_FORMATS.pclm.documentFormat;
export const MAX_PDF_INPUT_BYTES = 10 * 1024 * 1024;
export const MAX_PCL_OUTPUT_BYTES = 64 * 1024 * 1024;
const MAX_PDF_PAGES = 500;
const CONVERTER_TIMEOUT_MS = 180_000;

export type PclConversionErrorCode =
  | "invalid_pdf"
  | "unsupported_paper_size"
  | "unsupported_output_format"
  | "conversion_failed"
  | "output_too_large"
  | "converter_busy"
  | "converter_unavailable";

export class PclConversionError extends Error {
  readonly code: PclConversionErrorCode;

  constructor(code: PclConversionErrorCode) {
    super(code);
    this.name = "PclConversionError";
    this.code = code;
  }
}

export type PclConversionResult = {
  body: ReadableStream<Uint8Array>;
  size: number;
  pageCount: number;
  documentFormat: string;
};

type ConverterConfig = {
  url?: string;
  secret?: string;
};

function looksLikePdf(bytes: Uint8Array): boolean {
  const header = new TextDecoder().decode(bytes.subarray(0, Math.min(bytes.length, 1024)));
  return header.includes("%PDF-");
}

function bytesToHex(bytes: Uint8Array): string {
  return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
}

export function pclOutputFormatForDocumentFormat(documentFormat: string): PclOutputFormat | null {
  const normalized = documentFormat.trim().toLowerCase();
  if (normalized === PCL_DOCUMENT_FORMAT.toLowerCase()) return "pcl";
  if (normalized === PCLM_DOCUMENT_FORMAT.toLowerCase()) return "pclm";
  return null;
}

function remoteErrorCode(value: unknown): PclConversionErrorCode {
  if (!value || typeof value !== "object" || !("error" in value)) return "conversion_failed";
  const error = (value as { error?: unknown }).error;
  if (error === "unsupported_paper_size") return "unsupported_paper_size";
  if (error === "output_too_large") return "output_too_large";
  if (error === "converter_busy") return "converter_busy";
  if (error === "converter_unavailable") return "converter_unavailable";
  if (error === "invalid_pdf" || error === "input_too_large") return "invalid_pdf";
  return "conversion_failed";
}

async function hmacHex(secret: string, payload: string): Promise<string> {
  const key = await crypto.subtle.importKey(
    "raw",
    new TextEncoder().encode(secret),
    { name: "HMAC", hash: "SHA-256" },
    false,
    ["sign"],
  );
  const signature = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(payload));
  return bytesToHex(new Uint8Array(signature));
}

/** Ask the private VPS service to render a PDF and return its bounded PCL stream. */
export async function convertPdfToPcl(
  pdf: Uint8Array,
  paperSize = "",
  options: { firstPageOnly?: boolean; outputFormat?: PclOutputFormat } = {},
  config: ConverterConfig = {},
): Promise<PclConversionResult> {
  if (!pdf.byteLength || pdf.byteLength > MAX_PDF_INPUT_BYTES || !looksLikePdf(pdf)) {
    throw new PclConversionError("invalid_pdf");
  }
  if (!config.url || !config.secret || config.secret.length < 32) {
    throw new PclConversionError("converter_unavailable");
  }
  const outputFormat = options.outputFormat ?? "pcl";
  const format = PCL_OUTPUT_FORMATS[outputFormat];
  if (!format) throw new PclConversionError("unsupported_output_format");

  let endpoint: URL;
  try {
    endpoint = new URL("/v1/convert", config.url);
  } catch {
    throw new PclConversionError("converter_unavailable");
  }
  if (endpoint.protocol !== "https:") throw new PclConversionError("converter_unavailable");

  const timestamp = String(Math.floor(Date.now() / 1000));
  const nonce = crypto.randomUUID();
  const firstPageOnly = options.firstPageOnly === true;
  const sha256 = bytesToHex(new Uint8Array(await crypto.subtle.digest("SHA-256", pdf)));
  const fields = { timestamp, nonce, paperSize, firstPageOnly, sha256, outputFormat };
  const signature = await hmacHex(config.secret, buildConverterSignaturePayload(fields));

  let response: Response;
  try {
    response = await fetch(endpoint, {
      method: "POST",
      redirect: "manual",
      signal: AbortSignal.timeout(CONVERTER_TIMEOUT_MS),
      headers: {
        "Content-Type": "application/pdf",
        "X-PCL-Timestamp": timestamp,
        "X-PCL-Nonce": nonce,
        "X-PCL-Paper-Size": paperSize,
        "X-PCL-First-Page-Only": String(firstPageOnly),
        "X-PCL-Signature": signature,
        ...(outputFormat === "pclm" ? { "X-PCL-Output-Format": outputFormat } : {}),
      },
      body: pdf,
    });
  } catch {
    throw new PclConversionError("converter_unavailable");
  }

  if (!response.ok) {
    const body: unknown = await response.json().catch(() => null);
    const code = remoteErrorCode(body);
    if (response.status === 429) throw new PclConversionError("converter_busy");
    if (response.status === 413 && code !== "output_too_large") {
      throw new PclConversionError("invalid_pdf");
    }
    if (response.status >= 500 && code !== "converter_busy") {
      throw new PclConversionError("converter_unavailable");
    }
    throw new PclConversionError(code);
  }

  const contentType = (response.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase();
  if (contentType !== format.documentFormat.toLowerCase()) {
    throw new PclConversionError("conversion_failed");
  }
  const size = Number(response.headers.get("content-length"));
  const pageCount = Number(response.headers.get("x-pcl-page-count"));
  if (!Number.isSafeInteger(size) || size < 2) throw new PclConversionError("conversion_failed");
  if (size > MAX_PCL_OUTPUT_BYTES) throw new PclConversionError("output_too_large");
  if (!Number.isSafeInteger(pageCount) || pageCount < 1 || pageCount > MAX_PDF_PAGES) {
    throw new PclConversionError("conversion_failed");
  }
  if (!response.body) throw new PclConversionError("conversion_failed");

  return { body: response.body, size, pageCount, documentFormat: format.documentFormat };
}
Ver worker/src/pdf-to-pcl-options.js
export const PCL_OUTPUT_FORMATS = Object.freeze({
  pcl: Object.freeze({
    device: "pcl3",
    subdevice: "unspec",
    colorModel: "CMYK",
    documentFormat: "application/vnd.hp-PCL",
    extension: "pcl",
    converterVersion: "ghostscript-10-pcl3-v1",
  }),
  pclm: Object.freeze({
    device: "pclm",
    colorModel: "RGB",
    documentFormat: "application/PCLm",
    extension: "pclm",
    converterVersion: "ghostscript-10-pclm-v1",
  }),
});

const paperSizes = {
  a0: { width: 2384, height: 3370, gsName: "a0" },
  a1: { width: 1684, height: 2384, gsName: "a1" },
  a2: { width: 1191, height: 1684, gsName: "a2" },
  a3: { width: 841.89, height: 1190.55, gsName: "a3" },
  a4: { width: 595.28, height: 841.89, gsName: "a4" },
  a5: { width: 420, height: 595, gsName: "a5" },
  carta: { width: 612, height: 792, gsName: "letter" },
  letter: { width: 612, height: 792, gsName: "letter" },
  usletter: { width: 612, height: 792, gsName: "letter" },
  "85x11": { width: 612, height: 792, gsName: "letter" },
  legal: { width: 612, height: 1008, gsName: "legal" },
  oficio: { width: 612, height: 1008, gsName: "legal" },
  uslegal: { width: 612, height: 1008, gsName: "legal" },
  "85x14": { width: 612, height: 1008, gsName: "legal" },
  "11x17": { width: 792, height: 1224, gsName: "tabloid" },
  tabloid: { width: 792, height: 1224, gsName: "tabloid" },
  executive: { width: 522, height: 756, gsName: "executive" },
  "3x5": { width: 216, height: 360 },
  "4x6": { width: 288, height: 432 },
  "5x7": { width: 360, height: 504 },
  "5x8": { width: 360, height: 576 },
  "8x10": { width: 576, height: 720 },
  "24x36": { width: 1728, height: 2592 },
  "30x42": { width: 2160, height: 3024 },
  "36x48": { width: 2592, height: 3456 },
};

function normalizedPaperSize(value) {
  return value.toLowerCase().replace(/[^a-z0-9]/g, "");
}

function paperSizeArguments(paperSize) {
  if (!paperSize.trim()) return [];

  const size = paperSizes[normalizedPaperSize(paperSize)];
  if (!size) throw new RangeError("unsupported_paper_size");

  const media = size.gsName
    ? [`-sPAPERSIZE=${size.gsName}`]
    : [
      `-dDEVICEWIDTHPOINTS=${size.width}`,
      `-dDEVICEHEIGHTPOINTS=${size.height}`,
    ];
  return [...media, "-dFIXEDMEDIA", "-dPDFFitPage"];
}

export function buildConverterSignaturePayload({
  timestamp,
  nonce,
  paperSize,
  firstPageOnly,
  sha256,
  outputFormat = "pcl",
}) {
  if (!PCL_OUTPUT_FORMATS[outputFormat]) throw new RangeError("unsupported_output_format");
  if (outputFormat === "pclm") {
    return [
      "v2",
      timestamp,
      nonce,
      paperSize,
      firstPageOnly ? "1" : "0",
      outputFormat,
      sha256,
    ].join("\n");
  }
  return [
    "v1",
    timestamp,
    nonce,
    paperSize,
    firstPageOnly ? "1" : "0",
    sha256,
  ].join("\n");
}

export function buildGhostscriptArgs({
  inputPath,
  outputPath,
  paperSize = "",
  pageNumber,
  outputFormat = "pcl",
}) {
  if (pageNumber !== undefined && (!Number.isSafeInteger(pageNumber) || pageNumber < 1)) {
    throw new RangeError("invalid_page_number");
  }
  const format = PCL_OUTPUT_FORMATS[outputFormat];
  if (!format) throw new RangeError("unsupported_output_format");
  return [
    "-q",
    "-dSAFER",
    "-dNOPAUSE",
    "-dBATCH",
    `-sDEVICE=${format.device}`,
    ...(format.subdevice ? [`-sSubdevice=${format.subdevice}`] : []),
    `-sColorModel=${format.colorModel}`,
    "-r300",
    ...paperSizeArguments(paperSize),
    ...(pageNumber === undefined ? [] : [`-dFirstPage=${pageNumber}`, `-dLastPage=${pageNumber}`]),
    `-sOutputFile=${outputPath}`,
    inputPath,
  ];
}
¿Necesitas ayuda?
Escríbeme por WhatsApp