149 lines
7.4 KiB
JavaScript
149 lines
7.4 KiB
JavaScript
// Backt statische SEO-Tags (canonical, Open Graph, Twitter, JSON-LD) in den
|
||
// <head> jeder Seite unter public/. Werte aus public/custom/seo-config.js,
|
||
// Logik äquivalent zu public/custom/seo.js. Idempotent (Marker-geschützter Block).
|
||
//
|
||
// Aufruf: node scripts/bake-seo.mjs
|
||
// Werte-Quelle bleibt seo-config.js; bei Config-Änderung neu ausführen.
|
||
import { readFileSync, writeFileSync, readdirSync } from 'node:fs';
|
||
import vm from 'node:vm';
|
||
import path from 'node:path';
|
||
import { fileURLToPath } from 'node:url';
|
||
|
||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||
const PUB = path.join(ROOT, 'public');
|
||
|
||
// seo-config.js laden (IIFE weist window.SEO_CONFIG zu)
|
||
const ctx = { window: {} };
|
||
vm.createContext(ctx);
|
||
vm.runInContext(readFileSync(path.join(PUB, 'custom/seo-config.js'), 'utf8'), ctx);
|
||
const cfg = ctx.window.SEO_CONFIG;
|
||
|
||
const SITE_URL = String(cfg.SITE_URL).replace(/\/$/, '');
|
||
const SITE_NAME = cfg.SITE_NAME;
|
||
const OG_IMAGE = cfg.DEFAULT_OG_IMAGE ? SITE_URL + cfg.DEFAULT_OG_IMAGE : '';
|
||
const biz = cfg.BUSINESS;
|
||
|
||
const esc = (s) => String(s).replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>');
|
||
const jsonEsc = (s) => String(s).replace(/</g, '\\u003c');
|
||
const reEsc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||
|
||
function placeNode(place) {
|
||
if (typeof place === 'string') return { '@type': 'City', name: place };
|
||
return { '@type': place.type, name: place.name };
|
||
}
|
||
|
||
function personBusinessGraph() {
|
||
return { '@context': 'https://schema.org', '@graph': [
|
||
{ '@type': 'Person', name: biz.personName, jobTitle: biz.personJobTitle, url: SITE_URL, email: biz.email, telephone: biz.telephone },
|
||
{ '@type': 'ProfessionalService', name: biz.name, url: SITE_URL, telephone: biz.telephone, email: biz.email,
|
||
address: { '@type': 'PostalAddress', addressLocality: biz.addressLocality, addressRegion: biz.addressRegion, addressCountry: biz.addressCountry },
|
||
areaServed: biz.areaServed.map(placeNode), priceRange: biz.priceRange }
|
||
]};
|
||
}
|
||
|
||
function breadcrumbListGraph(p) {
|
||
const segs = p.split('/').filter(Boolean);
|
||
const labels = {
|
||
portfolio: 'Portfolio', leistungen: 'Leistungen', sportfotografie: 'Sportfotografie', eventfotografie: 'Eventfotografie', 'über-mich': 'Über mich', kontakt: 'Kontakt', blog: 'Blog', archiv: 'Archiv',
|
||
'portfolio-fc-st-pauli': 'FC St. Pauli', 'portfolio-hamburger-sv': 'Hamburger SV', 'portfolio-frauen-bundesliga': 'Frauen-Bundesliga',
|
||
'portfolio-hannover-96': 'Hannover 96', 'portfolio-sv-meppen': 'SV Meppen', 'portfolio-deutschland-u21': 'Deutschland U21',
|
||
'portfolio-nfv-pokalfinale-2026': 'NFV-Pokalfinale 2026', 'portfolio-yes-con-2026': 'YES!CON 2026',
|
||
'portfolio-omr-yes-wecancer': 'OMR x yes!wecancer', 'portfolio-beach-soccer-cup': 'Beach Soccer Cup',
|
||
'portfolio-aufstiegsfeier': 'Aufstiegsfeier', 'portfolio-abiball': 'Abiball', 'portfolio-svg-lueneburg': 'SVG Lüneburg',
|
||
'portfolio-rhine-ruhr-3x3': 'Rhine-Ruhr 2025 – 3×3 Basketball', 'portfolio-rhine-ruhr-basketball': 'Rhine-Ruhr 2025 – Basketball',
|
||
'portfolio-rhine-ruhr-beachvolleyball': 'Rhine-Ruhr 2025 – Beachvolleyball', 'portfolio-rhine-ruhr-sport': 'Rhine-Ruhr 2025 – Sportarten'
|
||
};
|
||
const items = [{ '@type': 'ListItem', position: 1, name: 'Startseite', item: SITE_URL + '/' }];
|
||
let acc = '';
|
||
for (let i = 0; i < segs.length; i++) {
|
||
acc += '/' + segs[i];
|
||
const label = labels[segs[i]] || segs[i].replace(/^portfolio-/, '').replace(/-/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
|
||
items.push({ '@type': 'ListItem', position: i + 2, name: label, item: SITE_URL + acc });
|
||
}
|
||
return { '@context': 'https://schema.org', '@type': 'BreadcrumbList', itemListElement: items };
|
||
}
|
||
|
||
function serviceGraph(page) {
|
||
const data = page.service || {};
|
||
const serviceType = data.serviceType || biz.serviceType;
|
||
const areas = data.areaServed || biz.areaServed;
|
||
const services = data.services || biz.services;
|
||
return { '@context': 'https://schema.org', '@type': 'Service', serviceType,
|
||
provider: { '@type': 'ProfessionalService', name: biz.name, url: SITE_URL },
|
||
areaServed: areas.map(placeNode),
|
||
hasOfferCatalog: { '@type': 'OfferCatalog', name: serviceType + '-Leistungen',
|
||
itemListElement: services.map((name) => ({ '@type': 'Offer', itemOffered: { '@type': 'Service', name } })) } };
|
||
}
|
||
|
||
const BEGIN = '<!-- STATIC-SEO: canonical, Open Graph, Twitter, JSON-LD (aus seo-config.js gebacken) -->';
|
||
const END = '<!-- /STATIC-SEO -->';
|
||
|
||
function buildBlock(p) {
|
||
// 404-Fehlerseite: nicht indexieren, kein canonical/OG (keine eigene URL wert).
|
||
if (p === '/404') {
|
||
return '\t' + [BEGIN, '<meta name="robots" content="noindex">', END].join('\n\t');
|
||
}
|
||
const page = cfg.PAGES[p] || {};
|
||
const title = page.title || cfg.SITE_NAME;
|
||
const desc = page.desc || cfg.DEFAULT_DESCRIPTION;
|
||
const canonical = SITE_URL + (p === '/' ? '/' : p);
|
||
const ogType = p === '/' ? 'website' : 'article';
|
||
const L = [BEGIN,
|
||
`<link rel="canonical" href="${esc(canonical)}">`,
|
||
`<meta property="og:title" content="${esc(title)}">`,
|
||
`<meta property="og:description" content="${esc(desc)}">`,
|
||
`<meta property="og:url" content="${esc(canonical)}">`,
|
||
`<meta property="og:type" content="${ogType}">`,
|
||
`<meta property="og:site_name" content="${esc(SITE_NAME)}">`];
|
||
if (OG_IMAGE) L.push(`<meta property="og:image" content="${esc(OG_IMAGE)}">`);
|
||
L.push(`<meta name="twitter:card" content="summary_large_image">`,
|
||
`<meta name="twitter:title" content="${esc(title)}">`,
|
||
`<meta name="twitter:description" content="${esc(desc)}">`);
|
||
if (OG_IMAGE) L.push(`<meta name="twitter:image" content="${esc(OG_IMAGE)}">`);
|
||
const s = page.jsonld || [];
|
||
if (s.includes('person-business')) L.push(`<script type="application/ld+json" id="seo-person-business">${jsonEsc(JSON.stringify(personBusinessGraph()))}</script>`);
|
||
if (s.includes('breadcrumb')) L.push(`<script type="application/ld+json" id="seo-breadcrumb">${jsonEsc(JSON.stringify(breadcrumbListGraph(p)))}</script>`);
|
||
if (s.includes('service')) L.push(`<script type="application/ld+json" id="seo-service">${jsonEsc(JSON.stringify(serviceGraph(page)))}</script>`);
|
||
L.push(END);
|
||
return '\t' + L.join('\n\t');
|
||
}
|
||
|
||
let n = 0;
|
||
let skipped = 0;
|
||
for (const f of readdirSync(PUB).filter((x) => x.endsWith('.html'))) {
|
||
const fp = path.join(PUB, f);
|
||
const p = f === 'index.html' ? '/' : '/' + f.replace(/\.html$/, '');
|
||
let html = readFileSync(fp, 'utf8');
|
||
const page = cfg.PAGES[p] || {};
|
||
if (page.title) {
|
||
if (!/<title>[\s\S]*?<\/title>/i.test(html)) {
|
||
console.warn('kein <title> in', f);
|
||
skipped++;
|
||
continue;
|
||
}
|
||
html = html.replace(
|
||
/<title>[\s\S]*?<\/title>/i,
|
||
`<title>${esc(page.title)}</title>`
|
||
);
|
||
}
|
||
if (page.desc) {
|
||
const descriptionTag = `<meta name="description" content="${esc(page.desc)}">`;
|
||
if (/<meta\s+name=["']description["'][^>]*>/i.test(html)) {
|
||
html = html.replace(/<meta\s+name=["']description["'][^>]*>/i, descriptionTag);
|
||
} else {
|
||
html = html.replace('</title>', `</title>\n\t${descriptionTag}`);
|
||
}
|
||
}
|
||
const re = new RegExp('[\\t ]*' + reEsc(BEGIN) + '[\\s\\S]*?' + reEsc(END) + '\\n?');
|
||
html = html.replace(re, '');
|
||
if (!html.includes('</head>')) { console.warn('kein </head> in', f); skipped++; continue; }
|
||
html = html.replace('</head>', buildBlock(p) + '\n</head>');
|
||
writeFileSync(fp, html);
|
||
n++;
|
||
}
|
||
console.log(`Gebacken: ${n} Seiten`);
|
||
if (skipped) {
|
||
console.error(`${skipped} Seite(n) übersprungen.`);
|
||
process.exitCode = 1;
|
||
}
|