Skip to content

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

4.4 KB
Raw Blame
import { readFile, writeFile, mkdir } from "node:fs/promises";
import { existsSync } from "node:fs";
import { createHash } from "node:crypto";
import { fileURLToPath } from "node:url";
import { join } from "node:path";
import sharp from "sharp";
import { CATEGORIES, safeWebsite, validateSites } from "./gallery-catalog.mjs";
import {
  launchCaptureBrowser,
  captureStitchedWebsite,
} from "./capture-lib.mjs";

const inputPath = process.argv[2];
if (!inputPath) {
  console.error("Usage: node scripts/batch-add.mjs <candidates.json> [--concurrency 6]");
  process.exit(1);
}
const concIdx = process.argv.indexOf("--concurrency");
const concurrency = concIdx > -1 ? Number(process.argv[concIdx + 1]) : 6;

const candidates = JSON.parse(await readFile(inputPath, "utf8"));
const root = fileURLToPath(new URL("../apps/gallery/", import.meta.url));
const catalogPath = join(root, "sites.json");
const sites = JSON.parse(await readFile(catalogPath, "utf8"));

const existingIds = new Set(sites.map((s) => s.id));
const existingUrls = new Set(
  sites.map((s) => {
    const u = new URL(s.url);
    return (
      u.hostname.replace(/^www\./, "") + u.pathname.replace(/\/$/, "") + u.search
    );
  }),
);

const todo = candidates.filter((c) => {
  const u = safeWebsite(c.url);
  const norm =
    u.hostname.replace(/^www\./, "") + u.pathname.replace(/\/$/, "") + u.search;
  if (existingIds.has(c.id) || existingUrls.has(norm)) {
    console.log(`  [exists] ${c.id}`);
    return false;
  }
  if (!CATEGORIES.includes(c.category)) {
    throw new Error(`Invalid category "${c.category}" for ${c.id}`);
  }
  return true;
});

console.log(`Capturing ${todo.length} new curated sites (concurrency=${concurrency})...`);
const today = new Date().toISOString().slice(0, 10);
await mkdir(join(root, "assets"), { recursive: true });

const browser = await launchCaptureBrowser();
const added = [];
const failed = [];
let cursor = 0;

async function worker() {
  while (cursor < todo.length) {
    const c = todo[cursor++];
    try {
      const parsed = safeWebsite(c.url);
      const imageRel = `assets/${c.id}.jpg`;
      const absImage = join(root, imageRel);
      let result;
      if (existsSync(absImage)) {
        const buf = await readFile(absImage);
        const meta = await sharp(buf).metadata();
        if (meta.width >= 600 && meta.height >= 400) {
          result = {
            width: meta.width,
            height: meta.height,
            slices: meta.height > 1000 ? 5 : 1,
            sha256: createHash("sha256").update(buf).digest("hex"),
            captureMethod:
              meta.height > 1000
                ? "Stitched full-page capture at 1440px viewport with repeated sticky chrome hidden."
                : "Single-viewport capture at 1440×900.",
            reused: true,
          };
        }
      }
      if (!result) {
        result = await captureStitchedWebsite(browser, parsed.toString(), {
          maxHeight: 4200,
          timeoutMs: 22000,
        });
        await writeFile(absImage, result.buffer);
      }
      added.push({
        id: c.id,
        name: c.name,
        url: parsed.toString(),
        category: c.category,
        tags: c.tags,
        description: c.description,
        observation: c.observation,
        image: imageRel,
        capturedAt: today,
        viewport: { width: 1440, height: 900 },
        credit: c.credit || c.name,
        imageDimensions: { width: result.width, height: result.height },
        captureSha256: result.sha256,
        captureMethod: result.captureMethod,
      });
      console.log(
        `  [${result.reused ? "reused" : "added"}] ${c.id}: ${result.width}×${result.height} (${result.slices} slices)`,
      );
    } catch (err) {
      failed.push({ id: c.id, url: c.url, error: err.message });
      console.log(`  [skip] ${c.id}: ${err.message}`);
    }
  }
}

try {
  await Promise.all(
    Array.from({ length: Math.min(concurrency, todo.length || 1) }, worker),
  );
} finally {
  await browser.close();
}

// Preserve curated order from candidate list and assign ranks cleanly.
const byId = new Map(added.map((e) => [e.id, e]));
for (const c of todo) {
  const entry = byId.get(c.id);
  if (entry) {
    entry.rank = sites.length;
    sites.push(entry);
  }
}

await validateSites(sites, root);
await writeFile(catalogPath, JSON.stringify(sites, null, 2) + "\n");
console.log(`\nAdded ${added.length} new sites (total: ${sites.length}). Skipped: ${failed.length}.`);
if (failed.length) console.log(JSON.stringify(failed, null, 2));