Branchwell

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
15import fs from 'node:fs';
16import path from 'node:path';
17import { fileURLToPath } from 'node:url';
18
19const __dirname = path.dirname(fileURLToPath(import.meta.url));
20const ROOT = path.resolve(__dirname, '..');
21const PUBLIC = path.join(ROOT, 'public');
22const DIR = path.join(PUBLIC, 'portraits');
23const CONCURRENCY = 10;
24const DRY = process.argv.includes('--dry');
25
26function 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}
40loadEnvLocal();
41
42const ACCOUNT = process.env.CF_ACCOUNT_ID;
43const TOKEN = process.env.CF_IMAGES_API_TOKEN;
44const HASH = process.env.CF_IMAGES_HASH;
45if (!ACCOUNT || !TOKEN || !HASH) {
46 console.error('Missing CF_ACCOUNT_ID / CF_IMAGES_API_TOKEN / CF_IMAGES_HASH');
47 process.exit(1);
48}
49
50function 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
60const files = walk(DIR).sort();
61const idFor = (abs) => path.relative(PUBLIC, abs).split(path.sep).join('/'); // e.g. portraits/foo.png
62const UP = `https://api.cloudflare.com/client/v4/accounts/${ACCOUNT}/images/v1`;
63
64async 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.
80let i = 0;
81const results = [];
82async 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
92console.log(`${DRY ? '[DRY] ' : ''}${files.length} files under public/portraits → CF Images (id = relative path)`);
93await Promise.all(Array.from({ length: Math.min(CONCURRENCY, files.length) }, worker));
94
95const by = (s) => results.filter((r) => r.status === s).length;
96console.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.
99const manifest = Object.fromEntries(
100 results.filter((r) => r.status !== 'FAILED').map((r) => [r.id, `https://imagedelivery.net/${HASH}/${r.id}/public`]),
101);
102fs.writeFileSync('/tmp/cf-portraits-manifest.json', JSON.stringify(manifest, null, 2));
103console.log('manifest → /tmp/cf-portraits-manifest.json');
104process.exit(by('FAILED') ? 1 : 0);