Restores and rewrites content on Home, Mobile SDK, DNS Protect, Halo CPE, For Operators, Financial Services, Why BlackDice, Investors and Contact to match the approved source copy, removing stray dashes site-wide in favour of plain punctuation. Removes an unreachable duplicate Contact page block that left a stray unclosed <div> in the markup. Shrinks and repads the Guardian Mobile SDK explorer widget so it fits without excess scrolling. Also includes in-progress nav, blog seed and demo scenario tweaks. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
171 lines
7.6 KiB
JavaScript
171 lines
7.6 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(/ /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 normaliseDashes(s)
|
||
}
|
||
|
||
// House style reads as British English — em dashes read as American, so every
|
||
// import normalises them to a spaced en dash rather than relying on the studio
|
||
// draft (or a future re-import) to get it right.
|
||
const normaliseDashes = (text) => String(text || '').replace(/\s*—\s*/g, ' – ')
|
||
|
||
const excerptOf = (post) =>
|
||
normaliseDashes((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: normaliseDashes(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 normalisedContent = Object.fromEntries(
|
||
Object.entries(draft.content || {}).map(([id, text]) => [id, normaliseDashes(text)]),
|
||
)
|
||
|
||
const seed = {
|
||
format: 'blackdice-react-content',
|
||
version: 1,
|
||
savedAt: draft.savedAt || new Date().toISOString(),
|
||
content: normalisedContent,
|
||
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}`)
|
||
}
|