import { $ } from "bun"; // --- PENGATURAN KURASI --- const menuAndalan = [ "dashboard.html", "dashboard-atur-json.ts", "github.css", "github-dark.css", "github-dark-dimmed.css", "halaman-pencarian.css", "halaman-pencarian.ts", "header.css", "header.ts", "header-logo-atas.html", "iposbrowser.ts", "json-xml.html", "lightbox.ts", "pemandu.css", "pemandu.ts", "response.ts", "sitemap.css", "ujihalaman.html", "homepage.ts", "homepage.css", "sitemap.ts", "data-provider.ts", "tema-newsprint.ts", "pariwara.ts", ]; const menuAsli = [ "icons", "fontawesome-webfonts", "fontawesome.css", "atom-one-dark.min.css", "atom-one-light.min.css", "default.min.css", "github-dark-dimmed.min.css", "github-dark.min.css", "github.min.css", "highlight.js", "marked.min.js", "monokai.min.css", "prism.min.css", "prism-okaidia.min.css", "prism-tomorrow.min.css", "prism-toolbar.min.css", "tokyo-night-dark.min.css", "vs-dark.min.css", "vs.min.css", "html2canvas.min.js", "html2pdf.bundle.min.js", "qrcode.min.js", ]; type FileSnapshot = Map; const sourceDir = import.meta.dir; const targetDir = `${sourceDir.replace(/\/dapur$/, "")}/ext`; const semuaMenu = [...menuAndalan, ...menuAsli]; const menuAndalanSet = new Set(menuAndalan); const menuAsliSet = new Set(menuAsli); // --- PENCATAT KEGAGALAN --- // Satu aset bermasalah tetap tidak menghentikan batch, tapi kegagalannya dicatat // dan di CI membuat skrip keluar dengan kode 1 (deploy tidak lanjut diam-diam). const gagal = new Map(); // nama aset -> alasan const tidakAda = new Set(); // entri menu tanpa berkas sumber const satuPesan = (x: unknown): string => { if (typeof x === "object" && x !== null) { const o = x as { message?: unknown; position?: { line?: number } | null }; const posisi = o.position?.line ? ` (baris ${o.position.line})` : ""; if (o.message !== undefined) return `${String(o.message)}${posisi}`; } return String(x); }; const pesanGalat = (e: unknown): string => e instanceof AggregateError ? e.errors.map(satuPesan).join(" | ") : satuPesan(e); const catatGagal = (name: string, alasan: string): void => { gagal.set(name, alasan); console.error(`❌ Gagal memasak ${name}: ${alasan}`); }; // fatal=true : kegagalan dicatat (CI keluar dengan kode 1). Dipakai untuk .ts, karena tidak ada cadangan yang valid. // fatal=false : cukup peringatan; pemanggil punya cadangan valid (salin apa adanya), mis. CSS/JS vendor. async function bangun(name: string, opsi: Parameters[0], fatal = true): Promise { let alasan: string; try { const built = await Bun.build(opsi); if (built.success && built.outputs[0]) return built.outputs[0]; alasan = built.logs.map(satuPesan).join(" | ") || "build tidak menghasilkan keluaran"; } catch (e) { alasan = pesanGalat(e); } if (fatal) catatGagal(name, alasan); else console.warn(`⚠️ ${name} tidak bisa di-bundle, disalin apa adanya: ${alasan}`); return null; } const isDirectory = (dirPath: string): boolean => { try { new Bun.Glob("*").scanSync({ cwd: dirPath }).next(); return true; } catch { return false; } }; async function copyDirNative(srcDir: string, destDir: string): Promise { await $`rm -rf ${destDir}`.quiet(); const glob = new Bun.Glob("**/*"); for await (const rel of glob.scan({ cwd: srcDir, onlyFiles: true })) { await Bun.write(`${destDir}/${rel}`, Bun.file(`${srcDir}/${rel}`)); } } async function masak(name: string): Promise { const sourcePath = `${sourceDir}/${name}`; const targetPath = `${targetDir}/${name}`; if (isDirectory(sourcePath)) { await copyDirNative(sourcePath, targetPath); return; } const srcFile = Bun.file(sourcePath); if (!(await srcFile.exists())) { tidakAda.add(name); return; } try { if (menuAsliSet.has(name)) { await Bun.write(targetPath, srcFile); return; } if (menuAndalanSet.has(name)) { const ext = name.split(".").pop(); if (ext === "ts" || ext === "js") { const outName = name.replace(/\.ts$/, ".js"); const finalOutPath = `${targetDir}/${outName}`; const hasil = await bangun( name, { entrypoints: [sourcePath], minify: true, format: "iife", target: "browser" }, ext === "ts", ); if (hasil) { await Bun.write(finalOutPath, hasil); gagal.delete(name); } else if (ext === "js") { // Sumber .js tetap valid kalau disalin apa adanya await Bun.write(finalOutPath, srcFile); } // Sumber .ts: JANGAN disalin mentah sebagai .js (itu kode TypeScript, bukan JavaScript). // Keluaran lama dibiarkan, kegagalan tetap tercatat. } else if (ext === "css") { const hasil = await bangun(name, { entrypoints: [sourcePath], minify: true }, false); if (hasil) { await Bun.write(targetPath, hasil); gagal.delete(name); } else { // CSS mentah tetap valid dipakai await Bun.write(targetPath, srcFile); } } else { await Bun.write(targetPath, srcFile); } } } catch (e) { // Satu aset bermasalah tidak menghentikan batch, tapi tidak lagi membisu catatGagal(name, pesanGalat(e)); } } async function sapuJagat(): Promise { if (!isDirectory(targetDir)) return; const allowedInEtalase = new Set(semuaMenu.map((name) => name.replace(/\.ts$/, ".js"))); const entries = [...new Bun.Glob("*").scanSync({ cwd: targetDir, onlyFiles: false })].sort(); for (const entry of entries) { if (entry.startsWith(".")) continue; if (!allowedInEtalase.has(entry)) { await $`rm -rf ${`${targetDir}/${entry}`}`.quiet(); } } } // --- EKSEKUSI UTAMA --- await sapuJagat(); await Promise.all(semuaMenu.map((name) => masak(name))); if (tidakAda.size > 0) { console.warn(`⚠️ ${tidakAda.size} entri menu tidak ada di dapur/ (dilewati): ${[...tidakAda].join(", ")}`); } const isCI = Bun.env.CI === "true" || Bun.env.FORGEJO_ACTIONS === "true" || Bun.env.GITHUB_ACTIONS === "true" || Bun.argv.includes("--once"); if (isCI) { if (gagal.size > 0) { console.error(`\n💥 ${gagal.size} aset gagal dimasak: ${[...gagal.keys()].join(", ")}`); process.exit(1); } process.exit(0); } else { // Watch mode lokal murni Bun tanpa node:fs const getSnapshot = async (): Promise => { const snap: FileSnapshot = new Map(); for (const item of semuaMenu) { const full = `${sourceDir}/${item}`; if (isDirectory(full)) { for await (const rel of new Bun.Glob("**/*").scan({ cwd: full, onlyFiles: true })) { snap.set(`${item}/${rel}`, Bun.file(`${full}/${rel}`).lastModified); } } else { const f = Bun.file(full); if (await f.exists()) snap.set(item, f.lastModified); } } return snap; }; let lastSnap = await getSnapshot(); console.log("👨‍🍳 Dapur Koki aktif memantau perubahan aset lokal..."); let sibuk = false; // putaran sebelumnya belum selesai -> lewati, jangan tumpang tindih setInterval(async () => { if (sibuk) return; sibuk = true; try { const currentSnap = await getSnapshot(); const changedRoots = new Set(); for (const [key, mtime] of currentSnap.entries()) { if (lastSnap.get(key) !== mtime) { const rootName = key.split("/")[0] ?? key; changedRoots.add(rootName); } } if (changedRoots.size > 0) { lastSnap = currentSnap; await Promise.all([...changedRoots].map((rootName) => masak(rootName))); } } finally { sibuk = false; } }, 500); }