Files
react-website/scripts/seed-content.mjs
T
MehboobKandClaude Sonnet 5 63a36e0dca Initial commit: BlackDice site rebuild with integrated CMS
Rebuilds content management around a single admin route (/admin —
"BlackDice Studio"), replacing blackdice-studio.html. Publishing writes
one JSON content document instead of regenerating HTML files, so it can
no longer overwrite hand-made site changes the way the old tool did.

- /admin: click-to-edit copy/images, article CRUD with a Word-safe rich
  text editor, demo clip management, per-page SEO, enquiry log, publish
  history with rollback
- Real per-page URLs for all pages and articles, each with its own
  meta/canonical/OG/JSON-LD
- Newsroom + article pages driven by the CMS post library, seeded from
  the old studio's export (17 articles) plus a drafted GSMA Open Gateway
  press release awaiting approval
- Demo sections on Mobile SDK and Halo CPE, interactive by default and
  upgradable to an uploaded clip per slot
- Dependency-free Node API server (auth, publish, uploads, snapshots,
  leads, live sitemap)
- Deployment configs for Node/nginx/IIS, Vercel and Netlify

See docs/ARCHITECTURE.md, docs/PROJECT-STRUCTURE.md, docs/CMS-GUIDE.md
and docs/DEPLOYMENT.md.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-12 23:52:44 +05:00

162 lines
7.1 KiB
JavaScript

/**
* Imports a blackdice-studio draft (blackdice-studio.json / any exported draft)
* into this project's content model.
*
* node scripts/seed-content.mjs <path-to-blackdice-studio.json> [--content-dir <dir>]
*
* · base64 hero images are written out as real files under public/content/posts/
* (the studio inlined them, which is what made its files 27MB)
* · Word-pasted article bodies are sanitised down to semantic HTML so they inherit
* the site's typography instead of carrying Aptos/black-on-dark inline styles
* · the result is written to src/cms/generated/seedContent.json — the factory
* content the site falls back to when nothing has been published yet
*/
import fs from 'node:fs'
import path from 'node:path'
import { resizeDirectory } from './resize-images.mjs'
const ROOT = path.resolve(import.meta.dirname, '..')
const OUT = path.join(ROOT, 'src/cms/generated/seedContent.json')
const HERO_DIR = path.join(ROOT, 'public/content/posts')
const args = process.argv.slice(2)
const src = args.find((a) => !a.startsWith('--'))
if (!src) {
console.error('usage: node scripts/seed-content.mjs <path-to-blackdice-studio.json>')
process.exit(1)
}
const contentDirIdx = args.indexOf('--content-dir')
const studioContentDir = contentDirIdx > -1 ? args[contentDirIdx + 1] : path.join(path.dirname(src), 'content')
// ── Body sanitiser ─────────────────────────────────────────────────────────────
// Word/Outlook paste carries inline styles that fight the site's design system.
// Keep the structure, drop the decoration.
const KEEP_TAGS = new Set([
'h2', 'h3', 'h4', 'p', 'ul', 'ol', 'li', 'strong', 'em', 'b', 'i', 'u', 'a', 'br',
'blockquote', 'img', 'figure', 'figcaption', 'table', 'thead', 'tbody', 'tr', 'td', 'th', 'hr',
])
const UNWRAP_TAGS = new Set(['span', 'div', 'font', 'section', 'article', 'o:p', 'st1:place', 'header', 'main'])
const KEEP_ATTRS = { a: ['href'], img: ['src', 'alt'] }
function sanitiseBody(html) {
let s = String(html || '')
s = s.replace(/<!--[\s\S]*?-->/g, '')
s = s.replace(/<\/?o:p[^>]*>/gi, '')
s = s.replace(/<\/?(?:xml|style|script)[^>]*>[\s\S]*?<\/(?:xml|style|script)>/gi, '')
// h1 in a body would compete with the page title
s = s.replace(/<(\/?)h1\b/gi, '<$1h2')
s = s.replace(/<(\/?)b\b/gi, '<$1strong').replace(/<(\/?)i\b/gi, '<$1em')
s = s.replace(/<(\/?)([a-zA-Z][\w:-]*)((?:"[^"]*"|'[^']*'|[^>"'])*?)(\/?)>/g, (_m, close, rawTag, attrs, selfClose) => {
const tag = rawTag.toLowerCase()
if (UNWRAP_TAGS.has(tag)) return ''
if (!KEEP_TAGS.has(tag)) return ''
if (close) return `</${tag}>`
const keep = KEEP_ATTRS[tag] || []
const kept = keep
.map((name) => {
const hit = new RegExp(`${name}\\s*=\\s*"([^"]*)"`, 'i').exec(attrs)
return hit ? ` ${name}="${hit[1].trim()}"` : ''
})
.join('')
const rel = tag === 'a' && /href\s*=\s*"https?:/i.test(attrs) ? ' target="_blank" rel="noopener"' : ''
return `<${tag}${kept}${rel}${selfClose ? ' /' : ''}>`
})
s = s.replace(/&nbsp;/g, ' ')
// Empty blocks left behind by unwrapping
for (let i = 0; i < 4; i++) {
s = s.replace(/<(p|h2|h3|h4|li|strong|em|u|blockquote)>\s*(?:<br\s*\/?>)*\s*<\/\1>/gi, '')
}
s = s.replace(/(<br\s*\/?>\s*){3,}/gi, '<br /><br />')
s = s.replace(/[ \t]+/g, ' ').replace(/\s*\n\s*/g, '\n').trim()
return s
}
const excerptOf = (post) =>
(post.excerpt || sanitiseBody(post.body).replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 260)).trim()
// ── Hero extraction ────────────────────────────────────────────────────────────
const EXT = { 'image/jpeg': 'jpg', 'image/png': 'png', 'image/webp': 'webp', 'image/gif': 'gif', 'image/svg+xml': 'svg' }
function extractHero(post) {
const hero = String(post.hero || '').trim()
if (!hero) return ''
if (/^https?:\/\//i.test(hero)) return hero
const dataUrl = /^data:([^;]+);base64,(.*)$/s.exec(hero)
if (dataUrl) {
const ext = EXT[dataUrl[1].toLowerCase()] || 'bin'
const file = `${post.slug}.${ext}`
fs.mkdirSync(HERO_DIR, { recursive: true })
fs.writeFileSync(path.join(HERO_DIR, file), Buffer.from(dataUrl[2], 'base64'))
return `/content/posts/${file}`
}
// A studio "content/<file>" reference — copy it across if we were given the folder.
const rel = hero.replace(/^\.?\/*/, '').replace(/^content\//, '')
const from = path.join(studioContentDir, rel)
if (fs.existsSync(from)) {
fs.mkdirSync(HERO_DIR, { recursive: true })
const file = `${post.slug}${path.extname(rel) || '.jpg'}`
fs.copyFileSync(from, path.join(HERO_DIR, file))
return `/content/posts/${file}`
}
console.warn(` ! hero not found for ${post.slug}: ${hero} — left empty`)
return ''
}
// ── Run ────────────────────────────────────────────────────────────────────────
const draft = JSON.parse(fs.readFileSync(src, 'utf8'))
if (!/^blackdice-(studio|cms)-draft$/.test(draft.format || '')) {
console.warn(`warning: unexpected format "${draft.format}" — importing anyway`)
}
// Posts authored in this repo rather than in the studio export (e.g. releases
// prepared ahead of approval). They survive a re-import, and any slug clash is
// resolved in their favour.
const EXTRA = path.join(ROOT, 'content-seed/additional-posts.json')
const extraPosts = fs.existsSync(EXTRA) ? JSON.parse(fs.readFileSync(EXTRA, 'utf8')) : []
const posts = (draft.posts || []).map((p) => ({
id: p.slug,
slug: p.slug,
title: p.title || 'Untitled',
category: ['insights', 'news', 'press', 'events'].includes(p.category) ? p.category : 'insights',
date: (p.date || '').slice(0, 10),
author: p.author || 'BlackDice Cyber',
excerpt: excerptOf(p),
hero: extractHero(p),
body: sanitiseBody(p.body),
status: 'published',
updatedAt: draft.savedAt || new Date().toISOString(),
}))
for (const extra of extraPosts) {
const at = posts.findIndex((p) => p.slug === extra.slug)
const normalised = { status: 'draft', author: 'BlackDice Cyber', hero: '', ...extra, id: extra.id || extra.slug }
if (at > -1) posts[at] = normalised
else posts.push(normalised)
}
posts.sort((a, b) => (a.date < b.date ? 1 : -1))
const seed = {
format: 'blackdice-react-content',
version: 1,
savedAt: draft.savedAt || new Date().toISOString(),
content: draft.content || {},
images: draft.images || {},
numbers: {},
posts,
}
fs.mkdirSync(path.dirname(OUT), { recursive: true })
fs.writeFileSync(OUT, JSON.stringify(seed, null, 2) + '\n')
// The studio inlined originals straight off a camera; serve something sensible.
resizeDirectory(HERO_DIR)
const kb = (n) => (n / 1024).toFixed(0) + 'KB'
console.log(`imported ${posts.length} posts → ${path.relative(ROOT, OUT)} (${kb(fs.statSync(OUT).size)})`)
for (const p of posts) {
console.log(` ${p.date} ${p.category.padEnd(8)} ${kb(p.body.length).padStart(6)} ${p.hero ? 'hero' : ' '} ${p.slug}`)
}