Lumen & Gesso / website · lumengesso.com / scripts / rewrite-portraits-to-cdn.mjs
| 1 | #!/usr/bin/env node |
| 2 | // One-shot codemod: rewrite every "/portraits/<name>.<ext>" reference in |
| 3 | // the app source to its Cloudflare Images delivery URL. hero-* images use |
| 4 | // the high-res `print` variant; everything else uses `public`. Only edits |
| 5 | // the three app files that reference portraits — NOT scripts/ (those read |
| 6 | // the local source files). Idempotent: skips a file already migrated. |
| 7 | |
| 8 | import fs from 'node:fs'; |
| 9 | import path from 'node:path'; |
| 10 | import { fileURLToPath } from 'node:url'; |
| 11 | |
| 12 | const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); |
| 13 | function loadEnvLocal() { |
| 14 | const p = path.join(ROOT, '.env.local'); |
| 15 | for (const raw of fs.readFileSync(p, 'utf8').split('\n')) { |
| 16 | const line = raw.trim(); |
| 17 | if (!line || line.startsWith('#')) continue; |
| 18 | const eq = line.indexOf('='); if (eq < 0) continue; |
| 19 | const k = line.slice(0, eq).trim(); |
| 20 | let v = line.slice(eq + 1).trim(); |
| 21 | if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) v = v.slice(1, -1); |
| 22 | if (!(k in process.env)) process.env[k] = v; |
| 23 | } |
| 24 | } |
| 25 | loadEnvLocal(); |
| 26 | const HASH = process.env.CF_IMAGES_HASH; |
| 27 | if (!HASH) { console.error('CF_IMAGES_HASH missing'); process.exit(1); } |
| 28 | const CDN = `https://imagedelivery.net/${HASH}`; |
| 29 | |
| 30 | const TARGETS = ['app/page.tsx', 'app/data/styleCatalog.ts', 'app/data/transformPairs.ts']; |
| 31 | const RE = /\/portraits\/([A-Za-z0-9._\-/]+?\.(?:png|jpe?g|webp))/g; |
| 32 | |
| 33 | let total = 0; |
| 34 | for (const rel of TARGETS) { |
| 35 | const file = path.join(ROOT, rel); |
| 36 | let s = fs.readFileSync(file, 'utf8'); |
| 37 | if (s.includes('imagedelivery.net')) { console.log(` skip (already migrated): ${rel}`); continue; } |
| 38 | let n = 0; |
| 39 | s = s.replace(RE, (_m, p1) => { |
| 40 | n++; |
| 41 | const variant = p1.split('/').pop().startsWith('hero-') ? 'print' : 'public'; |
| 42 | return `${CDN}/portraits/${p1}/${variant}`; |
| 43 | }); |
| 44 | fs.writeFileSync(file, s); |
| 45 | total += n; |
| 46 | console.log(` ${rel}: ${n} refs rewritten`); |
| 47 | } |
| 48 | console.log(`Total: ${total} references → ${CDN}/portraits/<name>/<variant>`); |