#!/usr/bin/env node // One-shot migration: upload every file under public/portraits to // Cloudflare Images with a DETERMINISTIC custom id = its path relative to // public/ (e.g. "portraits/after-otis-cubist.png"). That makes the // delivery URL knowable without storing a manifest: // // https://imagedelivery.net//portraits/./ // // Idempotent: re-running treats "already exists" as success. Reads CF // creds from the environment or .env.local. // // node scripts/upload-portraits-to-cf.mjs # upload all // node scripts/upload-portraits-to-cf.mjs --dry # list only import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const ROOT = path.resolve(__dirname, '..'); const PUBLIC = path.join(ROOT, 'public'); const DIR = path.join(PUBLIC, 'portraits'); const CONCURRENCY = 10; const DRY = process.argv.includes('--dry'); function loadEnvLocal() { const p = path.join(ROOT, '.env.local'); if (!fs.existsSync(p)) return; for (const raw of fs.readFileSync(p, 'utf8').split('\n')) { const line = raw.trim(); if (!line || line.startsWith('#')) continue; const eq = line.indexOf('='); if (eq < 0) continue; const k = line.slice(0, eq).trim(); let v = line.slice(eq + 1).trim(); if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) v = v.slice(1, -1); if (!(k in process.env)) process.env[k] = v; } } loadEnvLocal(); const ACCOUNT = process.env.CF_ACCOUNT_ID; const TOKEN = process.env.CF_IMAGES_API_TOKEN; const HASH = process.env.CF_IMAGES_HASH; if (!ACCOUNT || !TOKEN || !HASH) { console.error('Missing CF_ACCOUNT_ID / CF_IMAGES_API_TOKEN / CF_IMAGES_HASH'); process.exit(1); } function walk(dir) { const out = []; for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { const abs = path.join(dir, entry.name); if (entry.isDirectory()) out.push(...walk(abs)); else if (/\.(png|jpe?g|webp)$/i.test(entry.name)) out.push(abs); } return out; } const files = walk(DIR).sort(); const idFor = (abs) => path.relative(PUBLIC, abs).split(path.sep).join('/'); // e.g. portraits/foo.png const UP = `https://api.cloudflare.com/client/v4/accounts/${ACCOUNT}/images/v1`; async function uploadOne(abs) { const id = idFor(abs); if (DRY) return { id, status: 'dry' }; const form = new FormData(); form.append('file', new Blob([fs.readFileSync(abs)]), path.basename(abs)); form.append('id', id); const res = await fetch(UP, { method: 'POST', headers: { Authorization: `Bearer ${TOKEN}` }, body: form }); const json = await res.json().catch(() => ({})); if (json.success) return { id, status: 'uploaded' }; const msg = (json.errors || []).map((e) => e.message).join('; '); // 5409 = "already exists" — fine, the bytes are present and the id is ours. if (/exist/i.test(msg) || (json.errors || []).some((e) => e.code === 5409)) return { id, status: 'exists' }; return { id, status: 'FAILED', msg: msg || `HTTP ${res.status}` }; } // Simple concurrency pool. let i = 0; const results = []; async function worker() { while (i < files.length) { const idx = i++; const r = await uploadOne(files[idx]); results.push(r); if (r.status === 'FAILED') console.error(` ✗ ${r.id}: ${r.msg}`); else if ((results.length % 25) === 0 || r.status === 'dry') console.log(` …${results.length}/${files.length} (${r.status})`); } } console.log(`${DRY ? '[DRY] ' : ''}${files.length} files under public/portraits → CF Images (id = relative path)`); await Promise.all(Array.from({ length: Math.min(CONCURRENCY, files.length) }, worker)); const by = (s) => results.filter((r) => r.status === s).length; console.log(`\nuploaded: ${by('uploaded')} already-existed: ${by('exists')} failed: ${by('FAILED')} (total ${results.length})`); // Manifest for reference (relPath -> public URL). Written outside the repo. const manifest = Object.fromEntries( results.filter((r) => r.status !== 'FAILED').map((r) => [r.id, `https://imagedelivery.net/${HASH}/${r.id}/public`]), ); fs.writeFileSync('/tmp/cf-portraits-manifest.json', JSON.stringify(manifest, null, 2)); console.log('manifest → /tmp/cf-portraits-manifest.json'); process.exit(by('FAILED') ? 1 : 0);