import { titleToCategory } from "./titleToCategory.ts"; const ROOT_DIR = import.meta.dir.replace(/\/dapur$/, ""); const C = { root: ROOT_DIR, art: `${ROOT_DIR}/artikel`, base: "https://dalam.web.id", limit: 30, // Limit membatasi RSS & JSON Lite cats: [ "gaya-hidup", "jejak-sejarah", "lainnya", "olah-media", "opini-sosial", "sistem-terbuka", "warta-tekno", ], hub: "https://pubsubhubbub.appspot.com/", // Hub WebSub publik }; // --- NATIVE BUN FILE HELPERS --- const scanHtmlFiles = (dir: string): string[] => { try { return [...new Bun.Glob("*.html").scanSync({ cwd: dir, onlyFiles: true })].sort(); } catch { return []; } }; const removeFileIfExists = async (filePath: string): Promise => { const f = Bun.file(filePath); if (await f.exists()) { await f.delete(); return true; } return false; }; // --- FORMAT KATEGORI OTOMATIS --- const getCategoryLabel = (catSlug: string): string => catSlug.replace(/-/g, " ").replace(/\b\w/g, (l) => l.toUpperCase()); const BASE_RE = C.base.replace(/\./g, "\\."); const decodeHTML = (str: string): string => { const entities: Record = { "&": "&", "<": "<", ">": ">", """: '"', "'": "'", "'": "'", "•": "•", "–": "–", "—": "—", " ": " ", }; let t = str.replace( /&(?:amp|lt|gt|quot|apos|#39|bull|ndash|mdash|nbsp);/gi, (match) => entities[match.toLowerCase()] ?? match ); t = t.replace(/&#(\\d+);/g, (_, dec: string) => String.fromCharCode(Number.parseInt(dec, 10)) ); t = t.replace(/&#x([a-f0-9]+);/gi, (_, hex: string) => String.fromCharCode(Number.parseInt(hex, 16)) ); return t.trim(); }; const buildDate = new Date().toISOString().split("T")[0]; const slug = (t: unknown): string => String(t) .toLowerCase() .trim() .replace(/^[^\w\s]*/u, "") .replace(/ & /g, "-and-") .replace(/[^a-z0-9\s-]/g, "") .replace(/\s+/g, "-") .replace(/-+/g, "-"); const iso = (d: string | number | Date): string => { const parsed = new Date(d); const base = isNaN(parsed.getTime()) ? new Date() : parsed; return base.toISOString(); }; const sanitize = (r: string): string => r.replace(/^\p{Emoji_Presentation}\s*/u, "").trim(); const mime = (u: string): string => ({ png: "image/png", webp: "image/webp", svg: "image/svg+xml" }[u.split(".").pop() || ""] || "image/jpeg"); const escapeAttr = (s: string): string => s.replace(/&/g, "&").replace(/"/g, """); const escapeHtml = (s: string): string => s .replace(/&/g, "&") .replace(//g, ">") .replace(/"/g, """) .replace(/'/g, "'"); /** * Helper Deterministik: Menghasilkan nilai Integer konsisten berdasarkan Hash String * Mencegah git diff noise di CI/CD akibat Math.random() */ const getDeterministicInt = (seed: string, min: number, max: number): number => { const hash = Number(Bun.hash(seed)); const range = Math.max(1, max - min + 1); return min + Math.abs(hash % range); }; // 🖼 dengan fallback bertingkat const imgWithFallback = (src: string, alt: string, extraAttrs = ""): string => { const smSrc = src.replace(/(\.[a-zA-Z0-9]+)$/, "-sm$1"); const mdSrc = src.replace(/(\.[a-zA-Z0-9]+)$/, "-md$1"); const onerror = `this.onerror=function(){this.onerror=function(){this.onerror=null;this.src='/thumbnail-sm.webp'};this.src='${src}'};this.src='${mdSrc}'`; return `${escapeAttr(alt)}`; }; const escapeXML = (s: string): string => s .replace(/&/g, "&") .replace(//g, ">") .replace(/"/g, """) .replace(/'/g, "'"); const safeCDATA = (s: string): string => s.replace(/]]>/g, "]]]]>"); const imgSize = async (url: string): Promise => { if (!url.startsWith(C.base)) return 0; const localFile = Bun.file(url.replace(C.base, C.root)); return (await localFile.exists()) ? localFile.size : 0; }; interface FeedItem { title: string; file: string; img: string; lastmod: string; desc: string; category: string; loc: string; finalModTime?: string; } const calculateFeedRootDate = (items: FeedItem[]): Date => { const now = new Date(); if (!items || items.length === 0) return now; const newestItemDate = new Date(items[0].lastmod); if (now.getTime() <= newestItemDate.getTime()) { const seed = items[0].loc || "feedroot"; const deterministicOffset = getDeterministicInt(seed, 60000, 180000); return new Date(newestItemDate.getTime() + deterministicOffset); } return now; }; const buildRss = ( t: string, items: FeedItem[], link: string, desc: string, sizes: Map = new Map() ): string => { const rootDate = calculateFeedRootDate(items); return `<![CDATA[${safeCDATA( decodeHTML(t) )}]]>${escapeXML(C.base)}/id-ID${rootDate.toUTCString()}${items .map( (it) => `<![CDATA[${safeCDATA(decodeHTML(it.title))}]]>${escapeXML( it.loc )}${escapeXML(it.loc)}${new Date( it.lastmod ).toUTCString()}` ) .join("")}`; }; const buildAtom = ( t: string, items: FeedItem[], feedUrl: string, desc: string, sizes: Map = new Map() ): string => { const rootDate = calculateFeedRootDate(items); return `${escapeXML( decodeHTML(t) )}${escapeXML(desc)}${escapeXML( C.base )}/${rootDate.toISOString()}${items .map( (it) => `${escapeXML(decodeHTML(it.title))}${escapeXML(it.loc)}${ it.lastmod }${ it.lastmod }Fakhrul Rijal` ) .join("")}`; }; const buildSitemapUrlset = (entries: string): string => `\n${entries}\n`; const buildSitemapIndex = (items: { loc: string; lastmod: string }[]): string => `\n${items .map( (it) => ` \n ${escapeXML(it.loc)}\n ${it.lastmod}\n ` ) .join("")}\n`; const cleanupOldSitemaps = async (): Promise => { let removed = 0; try { for (const f of new Bun.Glob("*.xml").scanSync({ cwd: C.root, onlyFiles: true })) { if (/^sitemap-.+\.xml$/i.test(f)) { if (await removeFileIfExists(`${C.root}/${f}`)) removed++; } } } catch { // Abaikan jika root belum dapat dipindai } for (const s of C.cats) { if (await removeFileIfExists(`${C.root}/${s}.xml`)) removed++; } return removed; }; const pingWebSub = async (feedUrls: string[]): Promise => { if (feedUrls.length === 0) { console.log("🔕 WebSub: nggak ada feed yang berubah, skip ping ke hub."); return; } try { const body = new URLSearchParams(); body.append("hub.mode", "publish"); feedUrls.forEach((u) => body.append("hub.url", u)); const res = await fetch(C.hub, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: body.toString(), signal: AbortSignal.timeout(10_000), }); console.log(`📡 WebSub ping → ${C.hub} → HTTP ${res.status} (${feedUrls.length} feed berubah)`); feedUrls.forEach((u) => console.log(` 🔗 ${u}`)); } catch (err: unknown) { const msg = err instanceof Error ? err.message : String(err); console.log(`⚠️ WebSub ping gagal (dilewati, tidak fatal): ${msg}`); } }; const upsertManagedBlock = async (filePath: string, block: string): Promise => { const MARK_START = "# --- BEGIN LK-AUTOGEN (komposisi.ts — jangan edit manual) ---"; const MARK_END = "# --- END LK-AUTOGEN ---"; const existing = await Bun.file(filePath) .text() .catch(() => ""); const startIdx = existing.indexOf(MARK_START); const endIdx = existing.indexOf(MARK_END); let stripped = existing; if (startIdx !== -1 && endIdx !== -1 && endIdx > startIdx) { stripped = existing.slice(0, startIdx) + existing.slice(endIdx + MARK_END.length); } stripped = stripped.trim(); const out = `${stripped ? stripped + "\n\n" : ""}${MARK_START}\n${block}\n${MARK_END}\n`; await Bun.write(filePath, out); }; const distribute = async ( f: string, cat: string, url: string, pre?: string, modTime?: string, prevData?: { url: string; title: string }, nextData?: { url: string; title: string }, articleTitle?: string ): Promise => { const catSlug = slug(cat); const dir = `${C.root}/${catSlug}`; const rawHtml = pre ?? (await Bun.file(`${C.art}/${f}`).text()); let html = rawHtml.replace(/\r\n/g, "\n"); // Normalisasi LF const catLabel = getCategoryLabel(catSlug); const tags = catLabel .split(",") .map((t) => t.trim()) .filter(Boolean); const tagsHtml = tags.map((t) => ``).join("\n "); let prevNextTags = ""; if (prevData) { const safeTitle = escapeAttr(prevData.title); prevNextTags += `\n `; } if (nextData) { const safeTitle = escapeAttr(nextData.title); prevNextTags += `\n `; } const catRssUrl = `${C.base}/${catSlug}.rss`; const catAtomUrl = `${C.base}/${catSlug}.atom`; const feedLinkTags = `\n \n `; html = html .replace(/