Skip to content

Curated website design inspiration gallery, open zero-auth MCP server for AI agents, and shareable moodboard lists.

6.0 KB
Raw Blame
#!/usr/bin/env node
/**
 * Curator CLI for reviewing, approving, or dismissing website submissions
 * queued in Upstash Redis via https://designtaste.wtf/submit/ or MCP submit_site.
 *
 * Usage:
 *   npm run submissions                     List all pending submissions
 *   npm run submissions -- approve <id>     Capture screenshot, add to catalog, remove from queue
 *   npm run submissions -- dismiss <id>     Remove submission from pending queue
 */
import fs from "node:fs";
import path from "node:path";
import { execFileSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { CATEGORIES, safeWebsite } from "./gallery-catalog.mjs";
import { assertPublicTargetUrl } from "./capture-lib.mjs";
import { PENDING_SUBMISSIONS_HASH } from "../api/submit.js";

const ROOT = fileURLToPath(new URL("..", import.meta.url));

function loadLocalEnv() {
  for (const name of [".env.local", ".env"]) {
    const filePath = path.join(ROOT, name);
    if (!fs.existsSync(filePath)) continue;
    const text = fs.readFileSync(filePath, "utf8");
    for (const line of text.split(/\r?\n/)) {
      const trimmed = line.trim();
      if (!trimmed || trimmed.startsWith("#")) continue;
      const eq = trimmed.indexOf("=");
      if (eq === -1) continue;
      const key = trimmed.slice(0, eq).trim();
      let val = trimmed.slice(eq + 1).trim();
      if (
        (val.startsWith('"') && val.endsWith('"')) ||
        (val.startsWith("'") && val.endsWith("'"))
      ) {
        val = val.slice(1, -1);
      }
      if (!process.env[key]) process.env[key] = val;
    }
  }
}

function getRedis() {
  loadLocalEnv();
  const url = (
    process.env.KV_REST_API_URL ||
    process.env.UPSTASH_REDIS_REST_URL ||
    ""
  ).replace(/\/+$/, "");
  const token =
    process.env.KV_REST_API_TOKEN || process.env.UPSTASH_REDIS_REST_TOKEN || "";
  if (!url || !token) {
    console.error(
      "Missing KV_REST_API_URL / KV_REST_API_TOKEN.\nRun `vercel env pull .env.local` once to load your Upstash Redis credentials locally.",
    );
    process.exit(1);
  }
  return { url, token };
}

async function redisCommand(redis, command) {
  const res = await fetch(`${redis.url}/pipeline`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${redis.token}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify([command]),
  });
  if (!res.ok) {
    throw new Error(`Upstash Redis HTTP ${res.status}`);
  }
  const data = await res.json();
  if (data?.[0]?.error) throw new Error(data[0].error);
  return data?.[0]?.result;
}

async function fetchAllPending(redis) {
  const raw = await redisCommand(redis, ["HGETALL", PENDING_SUBMISSIONS_HASH]);
  const items = [];
  if (Array.isArray(raw)) {
    for (let i = 0; i < raw.length; i += 2) {
      const field = raw[i];
      const val = raw[i + 1];
      try {
        const parsed = JSON.parse(val);
        items.push({ ...parsed, normalizedUrl: parsed.normalizedUrl || field });
      } catch {
        // skip malformed
      }
    }
  } else if (raw && typeof raw === "object") {
    for (const [field, val] of Object.entries(raw)) {
      try {
        const parsed = JSON.parse(val);
        items.push({ ...parsed, normalizedUrl: parsed.normalizedUrl || field });
      } catch {
        // skip malformed
      }
    }
  }
  items.sort(
    (a, b) =>
      (b.votes || 1) - (a.votes || 1) ||
      String(b.submittedAt || "").localeCompare(String(a.submittedAt || "")),
  );
  return items;
}

async function main() {
  const [, , cmd = "list", arg] = process.argv;
  const redis = getRedis();
  const items = await fetchAllPending(redis);

  if (cmd === "list") {
    if (!items.length) {
      console.log("No pending submissions in the queue.");
      return;
    }
    console.log(`Pending submissions (${items.length}):\n`);
    for (const item of items) {
      const date = item.submittedAt ? item.submittedAt.slice(0, 10) : "—";
      const votes = item.votes > 1 ? ` [${item.votes} votes]` : "";
      console.log(`  ${item.id}${votes}  ${item.name} (${item.category || "Uncategorized"}) — ${date}`);
      console.log(`    URL:  ${item.url}`);
      if (item.note) console.log(`    Note: ${item.note}`);
      console.log("");
    }
    console.log("Approve: npm run submissions -- approve <id>");
    console.log("Dismiss: npm run submissions -- dismiss <id>");
    return;
  }

  if (cmd === "dismiss" || cmd === "approve") {
    if (!arg) {
      console.error(`Usage: npm run submissions -- ${cmd} <submission-id>`);
      process.exit(1);
    }
    const target = items.find((i) => i.id === arg || i.normalizedUrl === arg);
    if (!target) {
      console.error(`Submission not found: ${arg}`);
      process.exit(1);
    }

    if (cmd === "approve") {
      const parsedUrl = safeWebsite(target.url);
      await assertPublicTargetUrl(parsedUrl.toString());
      const category = CATEGORIES.includes(target.category)
        ? target.category
        : "Product";
      const cliArgs = [
        path.join(ROOT, "scripts/capture-site.mjs"),
        "--url",
        parsedUrl.toString(),
        "--name",
        target.name || parsedUrl.hostname.replace(/^www\./, ""),
        "--category",
        category,
        "--description",
        target.note
          ? target.note.slice(0, 220)
          : `Considered web design from ${target.name || parsedUrl.hostname}.`,
        "--observation",
        target.note || "Submitted via designtaste.wtf.",
      ];
      execFileSync(process.execPath, cliArgs, { stdio: "inherit" });
    }

    await redisCommand(redis, [
      "HDEL",
      PENDING_SUBMISSIONS_HASH,
      target.normalizedUrl,
    ]);
    console.log(
      cmd === "approve"
        ? `Approved ${target.name} (${target.url}) and removed ${target.id} from pending queue.`
        : `Dismissed ${target.id} (${target.url}) from pending queue.`,
    );
    return;
  }

  console.error(`Unknown command: ${cmd}\nExpected: list | approve <id> | dismiss <id>`);
  process.exit(1);
}

main().catch((err) => {
  console.error(err.message || err);
  process.exit(1);
});