Skip to content

CanvasAnvil is an open source AI diagram maker and flowchart generator - an infinite-canvas diagram editor and self-hosted drawio alternative that writes editable .drawio files. Text to diagram, then fix nodes, layout and labels in place. Also AI presentations, interior design CAD/BOM, posters and infographics.

3.4 KB
Raw Blame
#!/usr/bin/env node

import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { generateImageThroughGateway } from "./lib/gateway.mjs";
import { OPENAI_DEFAULT_BASE_URL } from "./lib/image-route.mjs";

function parseArgs(argv) {
  const args = {
    prompt: "",
    promptFile: "",
    output: "",
    configFile: "",
    referenceImageUrl: "",
    productImageUrl: "",
  };
  for (let i = 0; i < argv.length; i += 1) {
    const token = argv[i];
    if (token === "--prompt") {
      args.prompt = argv[i + 1] || "";
      i += 1;
    } else if (token === "--prompt-file") {
      args.promptFile = argv[i + 1] || "";
      i += 1;
    } else if (token === "--output" || token === "-o") {
      args.output = argv[i + 1] || "";
      i += 1;
    } else if (token === "--config-file") {
      args.configFile = argv[i + 1] || "";
      i += 1;
    } else if (token === "--reference-image-url") {
      args.referenceImageUrl = argv[i + 1] || "";
      i += 1;
    } else if (token === "--product-image-url") {
      args.productImageUrl = argv[i + 1] || "";
      i += 1;
    }
  }
  return args;
}

function fail(message) {
  console.error(message);
  process.exit(1);
}

// The skill's own config file, found from this script rather than from the
// caller's working directory, so the script can run from anywhere.
const DEFAULT_CONFIG_FILE = fileURLToPath(new URL("../config/image-provider.json", import.meta.url));

function loadConfig(configFile) {
  const target = configFile ? path.resolve(process.cwd(), configFile) : DEFAULT_CONFIG_FILE;
  if (!fs.existsSync(target)) {
    fail(`Missing provider config file: ${target}. Copy image-provider.example.json next to it and fill it in.`);
  }
  return JSON.parse(fs.readFileSync(target, "utf8"));
}

function decodeDataUrl(dataUrl) {
  const match = String(dataUrl || "").match(/^data:([^;]+);base64,(.*)$/);
  if (!match) fail("Image generation did not return a base64 data URL.");
  return {
    buffer: Buffer.from(match[2], "base64"),
  };
}

async function main() {
  const args = parseArgs(process.argv.slice(2));
  if (!args.output) fail("Missing --output <path-to-image>.");

  const prompt = args.promptFile
    ? fs.readFileSync(path.resolve(process.cwd(), args.promptFile), "utf8")
    : args.prompt;
  if (!String(prompt || "").trim()) fail("Missing prompt. Use --prompt or --prompt-file.");

  const rawConfig = loadConfig(args.configFile);
  const apiKey = String(rawConfig.apiKey || "").trim();
  const model = String(rawConfig.model || "").trim();
  const baseUrl = String(rawConfig.baseUrl || OPENAI_DEFAULT_BASE_URL).trim();

  if (!apiKey || !model) {
    fail(`Missing image configuration. Required: apiKey, model. Fill ${args.configFile || DEFAULT_CONFIG_FILE}.`);
  }

  const dataUrl = await generateImageThroughGateway({
    channel: {
      apiKey,
      baseUrl,
      model,
    },
    prompt,
    referenceImageUrl: args.referenceImageUrl || undefined,
    productImageUrl: args.productImageUrl || undefined,
  });

  const { buffer } = decodeDataUrl(dataUrl);
  const outputPath = path.resolve(process.cwd(), args.output);
  fs.mkdirSync(path.dirname(outputPath), { recursive: true });
  fs.writeFileSync(outputPath, buffer);
  console.log(`CAD image written to ${outputPath}`);
}

main().catch((error) => {
  console.error(error instanceof Error ? error.message : String(error));
  process.exit(1);
});