Lumen & Gesso / website · lumengesso.com / scripts / upload-portraits-to-cf.mjs
| 1 | #!/usr/bin/env node |
| 2 | // One-shot migration: upload every file under public/portraits to |
| 3 | // Cloudflare Images with a DETERMINISTIC custom id = its path relative to |
| 4 | // public/ (e.g. "portraits/after-otis-cubist.png"). That makes the |
| 5 | // delivery URL knowable without storing a manifest: |
| 6 | // |
| 7 | // https://imagedelivery.net/<HASH>/portraits/<name>.<ext>/<variant> |
| 8 | // |
| 9 | // Idempotent: re-running treats "already exists" as success. Reads CF |
| 10 | // creds from the environment or .env.local. |
| 11 | // |
| 12 | // node scripts/upload-portraits-to-cf.mjs # upload all |
| 13 | // node scripts/upload-portraits-to-cf.mjs --dry # list only |
| 14 | |
| 15 | import fs from 'node:fs'; |
| 16 | import path from 'node:path'; |
| 17 | import { fileURLToPath } from 'node:url'; |
| 18 | |
| 19 | const __dirname = path.dirname(fileURLToPath(import.meta.url)); |
| 20 | const ROOT = path.resolve(__dirname, '..'); |
| 21 | const PUBLIC = path.join(ROOT, 'public'); |
| 22 | const DIR = path.join(PUBLIC, 'portraits'); |
| 23 | const CONCURRENCY = 10; |
| 24 | const DRY = process.argv.includes('--dry'); |
| 25 | |
| 26 | function loadEnvLocal() { |
| 27 | const p = path.join(ROOT, '.env.local'); |
| 28 | if (!fs.existsSync(p)) return; |
| 29 | for (const raw of fs.readFileSync(p, 'utf8').split('\n')) { |
| 30 | const line = raw.trim(); |
| 31 | if (!line || line.startsWith('#')) continue; |
| 32 | const eq = line.indexOf('='); |
| 33 | if (eq < 0) continue; |
| 34 | const k = line.slice(0, eq).trim(); |
| 35 | let v = line.slice(eq + 1).trim(); |
| 36 | if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) v = v.slice(1, -1); |
| 37 | if (!(k in process.env)) process.env[k] = v; |
| 38 | } |
| 39 | } |
| 40 | loadEnvLocal(); |
| 41 | |
| 42 | const ACCOUNT = process.env.CF_ACCOUNT_ID; |
| 43 | const TOKEN = process.env.CF_IMAGES_API_TOKEN; |
| 44 | const HASH = process.env.CF_IMAGES_HASH; |
| 45 | if (!ACCOUNT || !TOKEN || !HASH) { |
| 46 | console.error('Missing CF_ACCOUNT_ID / CF_IMAGES_API_TOKEN / CF_IMAGES_HASH'); |
| 47 | process.exit(1); |
| 48 | } |
| 49 | |
| 50 | function walk(dir) { |
| 51 | const out = []; |
| 52 | for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { |
| 53 | const abs = path.join(dir, entry.name); |
| 54 | if (entry.isDirectory()) out.push(...walk(abs)); |
| 55 | else if (/\.(png|jpe?g|webp)$/i.test(entry.name)) out.push(abs); |
| 56 | } |
| 57 | return out; |
| 58 | } |
| 59 | |
| 60 | const files = walk(DIR).sort(); |
| 61 | const idFor = (abs) => path.relative(PUBLIC, abs).split(path.sep).join('/'); // e.g. portraits/foo.png |
| 62 | const UP = `https://api.cloudflare.com/client/v4/accounts/${ACCOUNT}/images/v1`; |
| 63 | |
| 64 | async function uploadOne(abs) { |
| 65 | const id = idFor(abs); |
| 66 | if (DRY) return { id, status: 'dry' }; |
| 67 | const form = new FormData(); |
| 68 | form.append('file', new Blob([fs.readFileSync(abs)]), path.basename(abs)); |
| 69 | form.append('id', id); |
| 70 | const res = await fetch(UP, { method: 'POST', headers: { Authorization: `Bearer ${TOKEN}` }, body: form }); |
| 71 | const json = await res.json().catch(() => ({})); |
| 72 | if (json.success) return { id, status: 'uploaded' }; |
| 73 | const msg = (json.errors || []).map((e) => e.message).join('; '); |
| 74 | // 5409 = "already exists" — fine, the bytes are present and the id is ours. |
| 75 | if (/exist/i.test(msg) || (json.errors || []).some((e) => e.code === 5409)) return { id, status: 'exists' }; |
| 76 | return { id, status: 'FAILED', msg: msg || `HTTP ${res.status}` }; |
| 77 | } |
| 78 | |
| 79 | // Simple concurrency pool. |
| 80 | let i = 0; |
| 81 | const results = []; |
| 82 | async function worker() { |
| 83 | while (i < files.length) { |
| 84 | const idx = i++; |
| 85 | const r = await uploadOne(files[idx]); |
| 86 | results.push(r); |
| 87 | if (r.status === 'FAILED') console.error(` ✗ ${r.id}: ${r.msg}`); |
| 88 | else if ((results.length % 25) === 0 || r.status === 'dry') console.log(` …${results.length}/${files.length} (${r.status})`); |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | console.log(`${DRY ? '[DRY] ' : ''}${files.length} files under public/portraits → CF Images (id = relative path)`); |
| 93 | await Promise.all(Array.from({ length: Math.min(CONCURRENCY, files.length) }, worker)); |
| 94 | |
| 95 | const by = (s) => results.filter((r) => r.status === s).length; |
| 96 | console.log(`\nuploaded: ${by('uploaded')} already-existed: ${by('exists')} failed: ${by('FAILED')} (total ${results.length})`); |
| 97 | |
| 98 | // Manifest for reference (relPath -> public URL). Written outside the repo. |
| 99 | const manifest = Object.fromEntries( |
| 100 | results.filter((r) => r.status !== 'FAILED').map((r) => [r.id, `https://imagedelivery.net/${HASH}/${r.id}/public`]), |
| 101 | ); |
| 102 | fs.writeFileSync('/tmp/cf-portraits-manifest.json', JSON.stringify(manifest, null, 2)); |
| 103 | console.log('manifest → /tmp/cf-portraits-manifest.json'); |
| 104 | process.exit(by('FAILED') ? 1 : 0); |