Files
stackpol/blog.js
T

107 lines
11 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Stack POL blog (2026-11-09, Marty: "use the same engine for the blog"): InstantAdPay/LinkSpin's blog.js, ported. Same
// sanitizer, paging, tags, related posts, RSS, BlogPosting + Breadcrumb JSON-LD. Storage is the repo itself: one JSON file per
// post in content/blog/<slug>.json ({ title, slug, excerpt, body (HTML), cover, tags[], publishedAt ISO, updated ISO }), loaded at
// boot, so posts ship with a deploy and are versioned in git. A post with publishedAt in the future stays hidden until then.
'use strict';
const fs = require('fs');
const path = require('path');
const { SITE, esc, head, tail, ZONES, spot } = require('./layout');
const AUTHOR = 'Marty Bostick';
const PER_PAGE = 9;
const DIR = path.join(__dirname, 'content', 'blog');
const slugify = s => String(s || '').toLowerCase().replace(/['’]/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 80);
const words = html => String(html || '').replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim();
const readMinutes = html => Math.max(1, Math.round(words(html).split(' ').length / 220));
const fmtDate = ts => new Date(ts).toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric', timeZone: 'America/Chicago' });
function sanitize(html) {
const src = String(html || '').replace(/ /g, ' ').replace(/<(script|style|iframe|object|embed|form)\b[\s\S]*?<\/\1\s*>/gi, '').replace(/<(script|style|iframe|object|embed|form|input)\b[^>]*>/gi, '').replace(/<!--[\s\S]*?-->/g, '').replace(/\son[a-z]+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, '');
const ALLOW = new Set(['p', 'br', 'hr', 'h2', 'h3', 'h4', 'ul', 'ol', 'li', 'b', 'strong', 'i', 'em', 'u', 'a', 'img', 'blockquote', 'pre', 'code', 'figure', 'figcaption', 'table', 'thead', 'tbody', 'tr', 'th', 'td']);
const safeSrc = s => /^(\/img\/[a-z0-9._-]+\.(png|jpg|webp|gif)|https:\/\/[^\s"'<>]+)$/i.test(s);
return src.replace(/<\s*(\/?)\s*([a-zA-Z0-9]+)((?:[^>"']|"[^"]*"|'[^']*')*)>/g, (m, close, tag, attrs) => {
tag = tag.toLowerCase();
if (!ALLOW.has(tag)) return '';
if (close) return '</' + tag + '>';
if (tag === 'a') {
const hm = /href\s*=\s*(?:"([^"]*)"|'([^']*)')/i.exec(attrs || ''); const href = (hm && (hm[1] || hm[2])) || '';
if (!/^(https?:\/\/|\/)[^\s"'<>]*$/i.test(href)) return '';
const internal = href.startsWith('/') || href.startsWith(SITE);
return '<a href="' + href.replace(/"/g, '%22') + '"' + (internal ? '' : ' target="_blank" rel="noopener"') + '>';
}
if (tag === 'img') {
const sm = /src\s*=\s*(?:"([^"]*)"|'([^']*)')/i.exec(attrs || ''); const s = (sm && (sm[1] || sm[2])) || '';
const am = /alt\s*=\s*(?:"([^"]*)"|'([^']*)')/i.exec(attrs || ''); const alt = (am && (am[1] || am[2])) || '';
return safeSrc(s) ? '<img src="' + s.replace(/"/g, '%22') + '" alt="' + esc(alt) + '" loading="lazy">' : '';
}
return '<' + tag + '>';
});
}
let POSTS = [];
function load() {
const out = [];
let files = []; try { files = fs.readdirSync(DIR).filter(f => f.endsWith('.json')); } catch (e) {}
for (const f of files) {
try {
const r = JSON.parse(fs.readFileSync(path.join(DIR, f), 'utf8'));
const slug = slugify(r.slug || r.title); if (!slug || !r.title) continue;
const body = sanitize(r.body);
const pub = Date.parse(r.publishedAt) || 0;
out.push({ slug, title: String(r.title).slice(0, 140), seoTitle: r.seoTitle || '', excerpt: String(r.excerpt || words(body).slice(0, 200)).slice(0, 300), body, cover: r.cover || '', coverAlt: r.coverAlt || r.title,
tags: (r.tags || []).map(t => String(t).toLowerCase()).slice(0, 8), publishedAt: pub, created: pub, updated: Date.parse(r.updated) || pub, faq: Array.isArray(r.faq) ? r.faq : [] });
} catch (e) { console.error('[blog] bad post file', f, e.message); }
}
POSTS = out.sort((a, b) => b.publishedAt - a.publishedAt);
return POSTS.length;
}
const listPublished = () => POSTS.filter(p => p.publishedAt && p.publishedAt <= Date.now());
const get = slug => listPublished().find(p => p.slug === slugify(slug)) || null;
const cardHtml = p => '<a class="post-card" href="/blog/' + esc(p.slug) + '">' + (p.cover ? '<img src="' + esc(p.cover) + '" alt="' + esc(p.coverAlt) + '" loading="lazy" width="1200" height="630">' : '')
+ '<div class="pc"><h3>' + esc(p.title) + '</h3><p>' + esc(p.excerpt) + '</p><p class="meta">' + fmtDate(p.publishedAt) + ' · ' + readMinutes(p.body) + ' min read</p></div></a>';
function renderIndex(page, tag) {
const all = tag ? listPublished().filter(p => p.tags.includes(tag)) : listPublished();
const pages = Math.max(1, Math.ceil(all.length / PER_PAGE)); page = Math.min(Math.max(1, page || 1), pages);
const slice = all.slice((page - 1) * PER_PAGE, page * PER_PAGE);
const title = (tag ? tag + ' · ' : '') + 'Stack POL Blog: Earning POL Across the Network' + (page > 1 ? ' (page ' + page + ')' : '');
const desc = 'Guides to every program that pays POL in the network, weekly payout recaps from the public ledger, and Polygon basics for earners.';
const p = tag ? '/blog/tag/' + encodeURIComponent(tag) : '/blog' + (page > 1 ? '/page/' + page : '');
let h = head({ title, desc, path: p, nav: '/blog', noindex: !!tag, jsonld: [{ '@context': 'https://schema.org', '@type': 'Blog', name: 'Stack POL Blog', url: SITE + '/blog', description: desc, publisher: { '@type': 'Organization', name: 'Stack POL', url: SITE } }] });
h += '<section style="padding:40px 0 10px"><p class="kick">' + (tag ? 'Tag: ' + esc(tag) : 'The Stack POL blog') + '</p><h1>Earning POL across the network, <span style="color:var(--gold)">one stack at a time</span></h1><p class="lead">' + esc(desc) + '</p></section>';
h += slice.length ? '<div class="posts">' + slice.map(cardHtml).join('') + '</div>' : '<p class="lead">Nothing published yet. Check back soon.</p>';
h += spot(ZONES.banner, ZONES.strip);
if (pages > 1) h += '<div class="pager">' + (page > 1 ? '<a href="/blog' + (page - 1 > 1 ? '/page/' + (page - 1) : '') + '">&larr; Newer</a>' : '<span></span>') + (page < pages ? '<a href="/blog/page/' + (page + 1) + '">Older &rarr;</a>' : '<span></span>') + '</div>';
return h + tail();
}
function related(p) {
return listPublished().filter(x => x.slug !== p.slug).map(x => ({ x, s: x.tags.filter(t => p.tags.includes(t)).length })).sort((a, b) => b.s - a.s || b.x.publishedAt - a.x.publishedAt).slice(0, 3).map(r => r.x);
}
function renderPost(p) {
const url = SITE + '/blog/' + p.slug;
const ld = [{ '@context': 'https://schema.org', '@type': 'BlogPosting', headline: p.title, description: p.excerpt, image: p.cover ? (p.cover.startsWith('http') ? p.cover : SITE + p.cover) : SITE + '/og-stackpol-1200x630.jpg',
datePublished: new Date(p.publishedAt).toISOString(), dateModified: new Date(p.updated).toISOString(), wordCount: words(p.body).split(' ').length, keywords: p.tags.join(', '),
author: { '@type': 'Person', name: AUTHOR, url: SITE + '/blog' }, publisher: { '@type': 'Organization', name: 'Stack POL', url: SITE, logo: { '@type': 'ImageObject', url: SITE + '/apple-touch-icon.png' } }, mainEntityOfPage: { '@type': 'WebPage', '@id': url } },
{ '@context': 'https://schema.org', '@type': 'BreadcrumbList', itemListElement: [{ '@type': 'ListItem', position: 1, name: 'Stack POL', item: SITE + '/' }, { '@type': 'ListItem', position: 2, name: 'Blog', item: SITE + '/blog' }, { '@type': 'ListItem', position: 3, name: p.title, item: url }] }];
if (p.faq.length) ld.push({ '@context': 'https://schema.org', '@type': 'FAQPage', mainEntity: p.faq.map(q => ({ '@type': 'Question', name: q.q, acceptedAnswer: { '@type': 'Answer', text: q.a } })) });
let h = head({ title: (p.seoTitle || p.title) + ' | Stack POL', ogTitle: p.title, desc: p.excerpt, path: '/blog/' + p.slug, image: p.cover, imageAlt: p.coverAlt, type: 'article', article: p, nav: '/blog', jsonld: ld });
h += '<div class="bl"><p class="crumb"><a href="/">Stack POL</a> / <a href="/blog">Blog</a>' + (p.tags[0] ? ' / <a href="/blog/tag/' + encodeURIComponent(p.tags[0]) + '">' + esc(p.tags[0]) + '</a>' : '') + '</p>';
h += '<h1>' + esc(p.title) + '</h1><p class="meta">By ' + AUTHOR + ' · ' + fmtDate(p.publishedAt) + (p.updated > p.publishedAt + 864e5 ? ' · updated ' + fmtDate(p.updated) : '') + ' · ' + readMinutes(p.body) + ' min read</p>';
if (p.cover) h += '<img class="cover" src="' + esc(p.cover) + '" alt="' + esc(p.coverAlt) + '" width="1200" height="630">';
h += '<article>' + p.body;
if (p.faq.length) h += '<h2>Questions people ask</h2>' + p.faq.map(q => '<h3>' + esc(q.q) + '</h3><p>' + esc(q.a) + '</p>').join('');
h += '</article>' + spot(ZONES.blogBox, ZONES.blogBox);
if (p.tags.length) h += '<p class="tags" style="margin-top:22px">' + p.tags.map(t => '<a href="/blog/tag/' + encodeURIComponent(t) + '">' + esc(t) + '</a>').join('') + '</p>';
h += '<p class="share" style="margin-top:18px"><a href="https://x.com/intent/tweet?url=' + encodeURIComponent(url) + '&text=' + encodeURIComponent(p.title) + '" target="_blank" rel="noopener">Share on X</a><a href="https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(url) + '" target="_blank" rel="noopener">Share on Facebook</a><a href="https://t.me/share/url?url=' + encodeURIComponent(url) + '&text=' + encodeURIComponent(p.title) + '" target="_blank" rel="noopener">Telegram</a></p>';
h += '<div class="author"><span class="av">M</span><div><b>' + AUTHOR + '</b><span>Founder of InstantAdPay, LinkSpin and the Crypto Team Build Network. Twenty-plus years of internet marketing, and a habit of writing down what actually worked.</span></div></div>';
const rel = related(p); if (rel.length) h += '<div style="margin-top:40px"><h2 style="margin-bottom:14px">Keep reading</h2><div class="posts">' + rel.map(cardHtml).join('') + '</div></div>';
h += '<p class="disc">Stack POL shows payouts from programs in the network. Nothing here is investment advice, no income is guaranteed, and cryptocurrency involves risk of loss.</p></div>';
return h + tail();
}
function rss() {
const items = listPublished().slice(0, 30).map(p => '<item><title>' + esc(p.title) + '</title><link>' + SITE + '/blog/' + p.slug + '</link><guid isPermaLink="true">' + SITE + '/blog/' + p.slug + '</guid><pubDate>' + new Date(p.publishedAt).toUTCString() + '</pubDate><description>' + esc(p.excerpt) + '</description></item>').join('');
return '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"><channel><title>Stack POL Blog</title><link>' + SITE + '/blog</link><description>Guides to every program that pays POL in the network, payout recaps and Polygon basics.</description><language>en-us</language>' + items + '</channel></rss>';
}
module.exports = { load, listPublished, get, renderIndex, renderPost, rss, cardHtml, fmtDate, readMinutes };