import { existsSync } from "node:fs"; import { unlink } from "node:fs/promises"; import { join } from "node:path"; const ROOT_DIR = "./deploy_dir"; const SQL_FILE = "./temp_sync.sql"; const TEMP_CONFIG = "/tmp/wrangler.toml"; // šŸŽÆ FILTER: File yang Harus Di-Skip const SKIP_PATTERNS = [ /^index\.html$/i, // Landing page /^agregat.*\.html$/i, // Agregat pages (agregat.html, agregat-2024.html, dll) ]; const shouldSkipFile = (filename: string): boolean => { return SKIP_PATTERNS.some((pattern) => pattern.test(filename)); }; /** * šŸ”— STOP WORDS: Kata Penghubung (Konjungsi) */ const STOP_WORDS: string[] = [ "dan", "atau", "tetapi", "sedangkan", "melainkan", "lalu", "kemudian", "padahal", "sesudah", "setelah", "sebelum", "sejak", "ketika", "sementara", "sambil", "selama", "sampai", "jika", "kalau", "asalkan", "bila", "andaikan", "sekiranya", "agar", "supaya", "biarpun", "meskipun", "walaupun", "seakan-akan", "seolah-olah", "sebab", "karena", "sehingga", "bahwa", "dengan", "biarpun demikian", "sekalipun begitu", "walaupun demikian", "meskipun begitu", "sesudah itu", "selanjutnya", "tambahan pula", "lagi pula", "selain itu", "sebaliknya", "sesungguhnya", "bahwasanya", "malahan", "bahkan", "akan tetapi", "namun", "kecuali itu", "dengan demikian", "oleh karena itu", "oleh sebab itu", "sebelum itu", "begitu pula", "demikian juga", "tambahan lagi", "di samping itu", "kedua", "akhirnya", "bagaimanapun juga", "sebagaimana", "sama halnya", "jadi", "akibatnya", "untuk maksud itu", "untuk mencapai hal itu", "ringkasnya", "secara singkat", "pada intinya", "sementara itu", "serta", "apabila", "bilamana", "guna", "ataupun", "bagai", "ibarat", "serupa", "mula-mula", "biar", "yaitu", "yakni", "asal", "maka", "adapun", "kendati", "lantaran", "alhasil", "andaikata", "manakala", ]; const escapeRegExp = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); const STOP_WORDS_PATTERN = new RegExp( "\\b(" + [...STOP_WORDS].sort((a, b) => b.length - a.length).map(escapeRegExp).join("|") + ")\\b", "gi" ); const stripStopWords = (text: string): string => { return text.replace(STOP_WORDS_PATTERN, " ").replace(/\s+/g, " ").trim(); }; const superCleanText = (text: string): string => { return text // 1. HAPUS MARKDOWN SYMBOLS .replace(/(\*\*|__)(.*?)\1/g, "$2") .replace(/(\*|_)(.*?)\1/g, "$2") .replace(/#+\s+/g, "") .replace(/\[(.*?)\]\(.*?\)/g, "$1") .replace(/>\s+/g, "") .replace(/`{1,3}.*?`{1,3}/g, "") // 2. HAPUS EMOJI & UNICODE .replace(/[\u{1F300}-\u{1F9FF}\u{1F600}-\u{1F64F}\u{1F680}-\u{1F6FF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}\u{1F1E6}-\u{1F1FF}\u{1F191}-\u{1F251}\u{1F004}\u{1F0CF}\u{1F170}-\u{1F171}\u{1F17E}-\u{1F17F}\u{1F18E}\u{3030}\u{2B50}\u{2B55}\u{2934}-\u{2935}\u{2B05}-\u{2B07}\u{2B1B}-\u{2B1C}\u{3297}\u{3299}]/gu, "") .replace(/[\u{1F3FB}-\u{1F3FF}]/gu, "") .replace(/[\uFE00-\uFE0F]/g, "") .replace(/\u200D/g, "") // 3. NETRALISIR SQL KEYWORDS .replace(/BEGIN\s+TRANSACTION/gi, "BEGIN_TRANSACTION") .replace(/COMMIT/gi, "COMMIT_DONE") .replace(/ROLLBACK/gi, "ROLLBACK_DONE") .replace(/SAVEPOINT/gi, "SAVEPOINT_DONE") // 4. CLEANUP AKHIR .replace(/\s+/g, " ") .replace(/'/g, "''") .trim(); }; const BLOCK_TAGS = new Set([ "p", "div", "section", "article", "main", "header", "h2", "h3", "h4", "h5", "h6", "li", "ul", "ol", "dl", "dt", "dd", "blockquote", "pre", "table", "tr", "td", "th", "br", "hr", "figcaption", ]); interface ArticleRecord { title: string; image: string; dateISO: string; bodyContent: string; description: string; file: string; } /** * šŸ“„ Extract metadata & content dari HTML file via HTMLRewriter Native Bun */ const extractArticleData = async ( filePath: string, file: string ): Promise> => { const html = await Bun.file(filePath).text(); let rawTitle = ""; let inTitle = false; let hasTitle = false; let ogImage = ""; let publishedTime = ""; let metaDesc = ""; let articleDepth = 0; let mainDepth = 0; let bodyDepth = 0; let ignoredDepth = 0; let hasArticle = false; let hasMain = false; const articleChunks: string[] = []; const mainChunks: string[] = []; const bodyChunks: string[] = []; const pushChunk = (text: string) => { if (!text) return; if (articleDepth > 0) articleChunks.push(text); if (mainDepth > 0) mainChunks.push(text); if (bodyDepth > 0) bodyChunks.push(text); }; const rewriter = new HTMLRewriter() .on("title", { element(el) { if (!hasTitle) { inTitle = true; el.onEndTag(() => { inTitle = false; hasTitle = true; }); } }, text(chunk) { if (inTitle && !hasTitle) { rawTitle += chunk.text; } }, }) .on("meta", { element(el) { const prop = el.getAttribute("property")?.toLowerCase() || ""; const name = el.getAttribute("name")?.toLowerCase() || ""; const content = el.getAttribute("content") || ""; if (!ogImage && prop === "og:image" && content) { ogImage = content; } if (!publishedTime && prop === "article:published_time" && content) { publishedTime = content; } if (!metaDesc && name === "description" && content) { metaDesc = content; } }, }) .on("article", { element(el) { hasArticle = true; articleDepth++; el.onEndTag(() => { articleDepth--; }); }, }) .on("main", { element(el) { hasMain = true; mainDepth++; el.onEndTag(() => { mainDepth--; }); }, }) .on("body", { element(el) { bodyDepth++; el.onEndTag(() => { bodyDepth--; }); }, }) .on( "script, style, meta, link, noscript, footer, nav, aside, h1, #header-placeholder, #loading-indicator", { element(el) { ignoredDepth++; if (!el.selfClosing) { el.onEndTag(() => { ignoredDepth--; }); } else { ignoredDepth--; } }, } ) .on("*", { element(el) { if (ignoredDepth === 0 && BLOCK_TAGS.has(el.tagName)) { pushChunk(" "); if (!el.selfClosing) { el.onEndTag(() => { if (ignoredDepth === 0) pushChunk(" "); }); } } }, text(chunk) { if (ignoredDepth === 0) { pushChunk(chunk.text); } }, }); rewriter.transform(html); const title = superCleanText(rawTitle || file); const image = (ogImage || "/thumbnail.webp").replace(/'/g, "''"); const dateISO = publishedTime || new Date().toISOString(); const description = metaDesc.replace(/'/g, "''"); const selectedText = hasArticle ? articleChunks.join("") : hasMain ? mainChunks.join("") : bodyChunks.join(""); const bodyContent = stripStopWords(superCleanText(selectedText)); return { title, image, dateISO, bodyContent, description }; }; /** * šŸ—ļø Generate SQL INSERT statement (Sesuai dengan kolom D1 yang baru) */ const generateInsertSQL = (data: { title: string; bodyContent: string; file: string; category: string; image: string; dateISO: string; code: string; description: string; }) => { return ( `INSERT INTO articles_fts (title, content, id, category, image, date, code, description) ` + `VALUES ('${data.title}', '${data.bodyContent}', '${data.file}', '${data.category}', '${data.image}', '${data.dateISO}', '${data.code}', '${data.description}');` ); }; // ============================================ // šŸš€ MAIN EXECUTION // ============================================ async function main(): Promise { const sqlCommands: string[] = ["DELETE FROM articles_fts;"]; let totalProcessed = 0; let totalSkipped = 0; const CATEGORY_MAP: Record = { "gaya-hidup": 1, "jejak-sejarah": 2, "lainnya": 3, "olah-media": 4, "opini-sosial": 5, "sistem-terbuka": 6, "warta-tekno": 7, }; const htmlGlob = new Bun.Glob("*.html"); for (const cat of Object.keys(CATEGORY_MAP)) { const catNumber = CATEGORY_MAP[cat]; const fullCatPath = join(ROOT_DIR, cat); if (!existsSync(fullCatPath)) continue; const files = Array.from( htmlGlob.scanSync({ cwd: fullCatPath, onlyFiles: true }) ).sort(); const categoryArticles: ArticleRecord[] = []; for (const file of files) { if (shouldSkipFile(file)) { totalSkipped++; continue; } try { const data = await extractArticleData(join(fullCatPath, file), file); categoryArticles.push({ ...data, file }); } catch (e: any) { console.error(`āŒ Gagal olah file: ${file} (${e?.message || e})`); } } // Sort berdasarkan tanggal (Oldest to Newest) categoryArticles.sort( (a, b) => new Date(a.dateISO).getTime() - new Date(b.dateISO).getTime() ); // Assign nomor urut dan masukkan ke SQL commands categoryArticles.forEach((article, index) => { const seqNumber = index + 1; const code = `${catNumber}-${seqNumber}`; sqlCommands.push(generateInsertSQL({ ...article, category: cat, code })); totalProcessed++; }); } await Bun.write(SQL_FILE, sqlCommands.join("\n")); try { if (await Bun.file(TEMP_CONFIG).exists()) { const proc = Bun.spawnSync( [ "bunx", "wrangler", "d1", "execute", "layarkosong-db", "--remote", `--file=${SQL_FILE}`, "-c", TEMP_CONFIG, ], { stdio: ["inherit", "inherit", "inherit"] } ); if (proc.exitCode !== 0) { throw new Error(`wrangler keluar dengan kode ${proc.exitCode}`); } console.log(`\nāœ… Sync D1 Berhasil!`); console.log(` šŸ“Š ${totalProcessed} artikel diproses | ${totalSkipped} file di-skip`); } else { console.error("āŒ File konfigurasi wrangler.toml tidak ditemukan."); process.exit(1); } } catch (err: any) { console.error(`āŒ Terjadi kesalahan saat update D1: ${err?.message || err}`); process.exit(1); } finally { await unlink(SQL_FILE).catch(() => {}); } } await main();