import path, { join } from "node:path"; import { mkdir, rename, unlink } from "node:fs/promises"; // ========== CONFIG ========== const BASE_URL = "https://dalam.web.id"; const CACHE_FILE = "mini/srcset-gambar.txt"; const ARTIKEL_LITE = "artikel-lite.json"; const INLINE_IMG_DIR = path.join("img", "inline"); const FORBIDDEN_CHARS = /[*:"<>|?]/g; const PICTURE_SIGNATURE = "srcset_oleh_Fakhrul_Rijal"; const SKIP_EXTENSIONS = new Set([".svg", ".ico", ".gif"]); const ALLOWED_CATEGORIES = [ "gaya-hidup", "jejak-sejarah", "lainnya", "olah-media", "opini-sosial", "sistem-terbuka", "warta-tekno", ]; // ๐Ÿ”ฅ STANDAR CORE WEB VITALS (CWV) const TARGET_DESKTOP = 1208; const TARGET_MEDIUM = 960; const TARGET_MOBILE = 720; // ========== GLOBAL SETS & COUNTERS ========== const activeCache = new Set(); let totalAnimatedSkipped = 0; let totalInlineExtracted = 0; // Deteksi encoder WebP CLI sistem sekali di awal const CWEBP_BIN = Bun.which("cwebp"); const MAGICK_BIN = Bun.which("magick") || Bun.which("convert"); // ========== PATH & FS GUARDS (ANTI ENAMETOOLONG) ========== function isWithinLinuxPathLimits(targetPath: string, maxSegmentBytes = 250): boolean { if (!targetPath || Buffer.byteLength(targetPath, "utf8") > 3800) return false; const segments = targetPath.split(/[\\/]/); for (const seg of segments) { if (Buffer.byteLength(seg, "utf8") > maxSegmentBytes) return false; } return true; } function isValidLocalRepoPath(cleanPath: string): boolean { if (!cleanPath) return false; if (/^(?:data:|blob:|javascript:|mailto:|tel:|https?:|\/\/)/i.test(cleanPath)) { return false; } if (/[\0\r\n]/.test(cleanPath)) return false; return isWithinLinuxPathLimits(cleanPath, 245); } async function safeFileExists(absPath: string): Promise { if (!isWithinLinuxPathLimits(absPath, 255)) return false; try { return await Bun.file(absPath).exists(); } catch { return false; } } function makeSafeOutputBase(rawBase: string): string { const sanitized = rawBase.replace(FORBIDDEN_CHARS, "-"); if (Buffer.byteLength(sanitized, "utf8") <= 235) return sanitized; const hash = Bun.hash(sanitized).toString(16); return `${sanitized.slice(0, 210)}-${hash}`; } const isWebpBuffer = (buffer: Buffer): boolean => { return ( buffer.length > 12 && buffer.toString("ascii", 0, 4) === "RIFF" && buffer.toString("ascii", 8, 12) === "WEBP" ); }; // ========== NATIVE BINARY IMAGE METADATA PARSER ========== interface ImageMeta { width: number; height: number; pages: number; } function parseExifOrientation(view: DataView, tiffOffset: number): number { if (tiffOffset + 8 > view.byteLength) return 1; const endian = view.getUint16(tiffOffset, false); const little = endian === 0x4949; // "II" if (!little && endian !== 0x4d4d) return 1; // "MM" const firstIfdOffset = view.getUint32(tiffOffset + 4, little); const ifdStart = tiffOffset + firstIfdOffset; if (ifdStart + 2 > view.byteLength) return 1; const entries = view.getUint16(ifdStart, little); for (let i = 0; i < entries; i++) { const entryOffset = ifdStart + 2 + i * 12; if (entryOffset + 12 > view.byteLength) break; const tag = view.getUint16(entryOffset, little); if (tag === 0x0112) { return view.getUint16(entryOffset + 8, little); } } return 1; } async function getImageMetadataNative(filePath: string): Promise { if (!isWithinLinuxPathLimits(filePath, 255)) return null; try { const sliceBuf = await Bun.file(filePath).slice(0, 131072).arrayBuffer(); const bytes = new Uint8Array(sliceBuf); const view = new DataView(sliceBuf); const len = bytes.length; if (len < 12) return null; // 1. PNG (\x89PNG\r\n\x1a\n) if ( bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47 && len >= 24 ) { return { width: view.getUint32(16, false), height: view.getUint32(20, false), pages: 1, }; } // 2. WebP (RIFF....WEBP) if ( bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46 && bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50 && len >= 30 ) { const chunk = String.fromCharCode(bytes[12], bytes[13], bytes[14], bytes[15]); if (chunk === "VP8 " && len >= 30) { return { width: view.getUint16(26, true) & 0x3fff, height: view.getUint16(28, true) & 0x3fff, pages: 1, }; } if (chunk === "VP8L" && len >= 25) { const bits = view.getUint32(21, true); return { width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1, pages: 1, }; } if (chunk === "VP8X" && len >= 30) { const flags = bytes[20]; const isAnimated = (flags & 0x02) !== 0; const width = 1 + (bytes[24] | (bytes[25] << 8) | (bytes[26] << 16)); const height = 1 + (bytes[27] | (bytes[28] << 8) | (bytes[29] << 16)); let pages = 1; if (isAnimated) { let anmfCount = 0; let offset = 30; while (offset + 8 <= len) { const fourcc = String.fromCharCode( bytes[offset], bytes[offset + 1], bytes[offset + 2], bytes[offset + 3] ); const chunkSize = view.getUint32(offset + 4, true); if (fourcc === "ANMF") anmfCount++; offset += 8 + chunkSize + (chunkSize & 1); } pages = Math.max(anmfCount, 2); } return { width, height, pages }; } } // 3. JPEG (0xFF 0xD8) if (bytes[0] === 0xff && bytes[1] === 0xd8) { let pos = 2; let orientation = 1; while (pos + 4 < len) { if (bytes[pos] !== 0xff) { pos++; continue; } const marker = bytes[pos + 1]; if (marker === 0xff) { pos++; continue; } if (marker === 0xd9 || marker === 0xda) break; // EOI atau SOS if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) { pos += 2; continue; } const segLen = view.getUint16(pos + 2, false); if (segLen < 2) break; // APP1 EXIF Orientation if ( marker === 0xe1 && pos + 10 < len && bytes[pos + 4] === 0x45 && bytes[pos + 5] === 0x78 && bytes[pos + 6] === 0x69 && bytes[pos + 7] === 0x66 ) { orientation = parseExifOrientation(view, pos + 10); } // SOF0..SOF15 if ( marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc && pos + 9 < len ) { let height = view.getUint16(pos + 5, false); let width = view.getUint16(pos + 7, false); if (orientation >= 5) { [width, height] = [height, width]; } return { width, height, pages: 1 }; } pos += 2 + segLen; } } // 4. AVIF / HEIF (ISO BMFF ispe box) const strHead = new TextDecoder("latin1").decode(bytes); const ispeIdx = strHead.indexOf("ispe"); if (ispeIdx !== -1 && ispeIdx + 16 <= len) { return { width: view.getUint32(ispeIdx + 8, false), height: view.getUint32(ispeIdx + 12, false), pages: 1, }; } return null; } catch { return null; } } // ========== NATIVE WEBP ENCODERS ========== async function encodeWebpNative( srcPath: string, destPath: string, targetWidth: number, quality: number, sharpenSigma: number ): Promise { if (!isWithinLinuxPathLimits(srcPath, 255) || !isWithinLinuxPathLimits(destPath, 255)) { return false; } const ext = path.extname(srcPath).toLowerCase(); const tmpOut = `${destPath}.${Bun.randomUUIDv7()}.tmp.webp`; try { if (CWEBP_BIN && ext !== ".avif") { await Bun.$`${CWEBP_BIN} -quiet -q ${quality} -m 6 -preset text -resize ${targetWidth} 0 ${srcPath} -o ${tmpOut}`; await rename(tmpOut, destPath); return true; } if (MAGICK_BIN) { const resizeSpec = `${targetWidth}x>`; await Bun.$`${MAGICK_BIN} ${srcPath} -auto-orient -resize ${resizeSpec} -unsharp 0x${sharpenSigma} -quality ${quality} -define webp:method=6 -define webp:preprocessing=2 ${tmpOut}`; await rename(tmpOut, destPath); return true; } return false; } catch { return false; } finally { await unlink(tmpOut).catch(() => {}); } } async function writeBufferAsWebpOrFallback( buffer: Buffer, baseDir: string, fileHash: string, fallbackExt: string ): Promise { await mkdir(path.join(process.cwd(), baseDir), { recursive: true }); const isDirectAsset = fallbackExt === ".svg" || fallbackExt === ".gif" || isWebpBuffer(buffer); if (isDirectAsset) { const relPath = path.join(baseDir, `${fileHash}${fallbackExt}`); const absPath = path.join(process.cwd(), relPath); if (!(await safeFileExists(absPath))) { await Bun.write(absPath, buffer); } return relPath; } const webpRelPath = path.join(baseDir, `${fileHash}.webp`); const webpAbsPath = path.join(process.cwd(), webpRelPath); if (await safeFileExists(webpAbsPath)) { return webpRelPath; } const tmpIn = path.join(process.cwd(), baseDir, `${fileHash}.${Bun.randomUUIDv7()}${fallbackExt}`); const tmpOut = `${webpAbsPath}.${Bun.randomUUIDv7()}.tmp.webp`; try { await Bun.write(tmpIn, buffer); if (CWEBP_BIN && fallbackExt !== ".avif") { try { await Bun.$`${CWEBP_BIN} -quiet -q 95 -m 6 -preset text ${tmpIn} -o ${tmpOut}`; await rename(tmpOut, webpAbsPath); return webpRelPath; } catch { // Lanjut ke ImageMagick jika format input tidak didukung cwebp } } if (MAGICK_BIN) { await Bun.$`${MAGICK_BIN} ${tmpIn} -auto-orient -unsharp 0x0.3 -quality 95 -define webp:method=6 -define webp:preprocessing=2 ${tmpOut}`; await rename(tmpOut, webpAbsPath); return webpRelPath; } // Fallback tanpa encoder CLI: simpan dalam format biner aslinya const rawRelPath = path.join(baseDir, `${fileHash}${fallbackExt}`); const rawAbsPath = path.join(process.cwd(), rawRelPath); if (!(await safeFileExists(rawAbsPath))) { await Bun.write(rawAbsPath, buffer); } return rawRelPath; } finally { await unlink(tmpIn).catch(() => {}); await unlink(tmpOut).catch(() => {}); } } // ========== AUTO-EKSTRAK DATA:IMAGE BASE64 ========== const MIME_TO_EXT: Record = { "image/png": ".png", "image/jpeg": ".jpg", "image/jpg": ".jpg", "image/webp": ".webp", "image/gif": ".gif", "image/svg+xml": ".svg", "image/avif": ".avif", "image/bmp": ".bmp", }; function decodeDataImageUri(dataUri: string): { buffer: Buffer; ext: string } | null { const match = dataUri.match( /^data:(image\/[a-z0-9.+-]+)(?:;charset=[^;,]+)?(?:;(base64))?,(.*)$/is ); if (!match) return null; const mime = match[1].toLowerCase(); const isBase64 = Boolean(match[2]); const rawPayload = match[3] || ""; const ext = MIME_TO_EXT[mime]; if (!ext || !rawPayload) return null; try { const buffer = isBase64 ? Buffer.from(rawPayload.replace(/\s+/g, ""), "base64") : Buffer.from(decodeURIComponent(rawPayload), "utf8"); if (buffer.length < 16) return null; return { buffer, ext }; } catch { return null; } } async function extractInlineDataImages( htmlContent: string, htmlPath: string ): Promise<{ html: string; extractedCount: number }> { const foundDataUris = new Set(); const finder = new HTMLRewriter().on("body img", { element(el) { const src = el.getAttribute("src")?.trim(); if (src && /^data:image\//i.test(src)) { foundDataUris.add(src); } }, }); finder.transform(htmlContent); if (foundDataUris.size === 0) { return { html: htmlContent, extractedCount: 0 }; } const replacementMap = new Map(); for (const dataUri of foundDataUris) { const decoded = decodeDataImageUri(dataUri); if (!decoded) { console.warn(` โš ๏ธ Data URI korup/tidak didukung dilewati pada ${htmlPath}`); continue; } const fileHash = Bun.hash(decoded.buffer).toString(16); const savedRelPath = await writeBufferAsWebpOrFallback( decoded.buffer, INLINE_IMG_DIR, fileHash, decoded.ext ); const webUrl = `${BASE_URL}/${savedRelPath.replace(/\\/g, "/")}`; replacementMap.set(dataUri, webUrl); } if (replacementMap.size === 0) { return { html: htmlContent, extractedCount: 0 }; } let replacedInstances = 0; const replacer = new HTMLRewriter().on("body img", { element(el) { const src = el.getAttribute("src")?.trim(); if (!src) return; const newUrl = replacementMap.get(src); if (newUrl) { el.setAttribute("src", newUrl); replacedInstances++; } }, }); const updatedHtml = replacer.transform(htmlContent); if (replacedInstances > 0) { totalInlineExtracted += replacedInstances; console.log( ` โ†ณ ๐Ÿงฉ Ekstrak ${replacedInstances} gambar Base64 โ†’ ${INLINE_IMG_DIR}/ (${htmlPath})` ); } return { html: updatedHtml, extractedCount: replacedInstances }; } // ========== HELPERS ========== function isLocalSiteSrc(src: string): boolean { if (!src) return false; if (/^(?:data:|blob:|javascript:|mailto:|tel:|\/\/)/i.test(src)) return false; if (src.startsWith("/")) return true; if (src.startsWith(BASE_URL)) return true; return /^https?:\/\/(?:www\.)?dalam\.web\.id(?:\/|$)/i.test(src); } function normalizeToRepoPath(src: string): string { if (!isLocalSiteSrc(src)) return ""; const noQuery = src.split("?")[0].split("#")[0]; let rel = ""; if (noQuery.startsWith(BASE_URL)) { rel = noQuery.slice(BASE_URL.length).replace(/^\/+/, ""); } else { const hostPattern = /^https?:\/\/(?:www\.)?dalam\.web\.id(\/.*)?$/i; const m = noQuery.match(hostPattern); rel = m ? (m[1] || "").replace(/^\/+/, "") : noQuery.replace(/^\/+/, ""); } return isValidLocalRepoPath(rel) ? rel : ""; } async function loadRelatedImages(): Promise> { const imageSet = new Set(); const liteFile = Bun.file(ARTIKEL_LITE); if (!(await safeFileExists(ARTIKEL_LITE))) return imageSet; try { const data = await liteFile.json(); for (const cat of Object.values(data)) { if (Array.isArray(cat)) { for (const item of cat) { if (Array.isArray(item) && typeof item[2] === "string") { const cleanPath = normalizeToRepoPath(item[2]); if (cleanPath) { imageSet.add(cleanPath); activeCache.add(cleanPath); } } } } } } catch {} return imageSet; } async function generateRgImages(relatedImages: Set): Promise { let count = 0; const sortedRelatedImages = Array.from(relatedImages).sort(); for (const cleanPath of sortedRelatedImages) { if (!isValidLocalRepoPath(cleanPath)) continue; const fullPathSource = path.join(process.cwd(), cleanPath); if (!(await safeFileExists(fullPathSource))) continue; const dirName = path.dirname(cleanPath); const ext = path.extname(cleanPath); const baseNameSafe = makeSafeOutputBase(path.basename(cleanPath, ext)); const rgPath = path.join(dirName, `${baseNameSafe}-rg.webp`); const absRgPath = path.join(process.cwd(), rgPath); if (!(await safeFileExists(absRgPath))) { const meta = await getImageMetadataNative(fullPathSource); if (!meta?.width) continue; const targetW = Math.min(meta.width, 150); const ok = await encodeWebpNative(fullPathSource, absRgPath, targetW, 88, 0.4); if (ok) count++; } } return count; } // ========== HTML REWRITER TYPES ========== interface CandidateInfo { index: number; src: string; pictureIndex: number | null; } interface ImgAction { width: string; height: string; altIfMissing?: string; removeSrcset?: boolean; srcset?: string; sizes?: string; } // ========== CORE ========== async function processHtmlFile(htmlPath: string): Promise { const rawText = await Bun.file(htmlPath).text(); const normalizedRaw = rawText.replace(/\r\n/g, "\n"); // PASS 0: Ekstrak semua gambar data:image/... base64 ke img/inline/.webp const { html: htmlContent, extractedCount } = await extractInlineDataImages( normalizedRaw, htmlPath ); const candidates: CandidateInfo[] = []; let rawTitle = ""; let inTitle = false; let hasTitle = false; let activePictureIdx: number | null = null; let pictureCounter = 0; let imgCounter = 0; // PASS 1: Sensus gambar ke activeCache + kumpulkan kandidat & const censusRewriter = 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("picture", { element(el) { const currentPic = pictureCounter++; activePictureIdx = currentPic; el.onEndTag(() => { if (activePictureIdx === currentPic) activePictureIdx = null; }); }, }) .on("body img", { element(el) { const idx = imgCounter++; const src = el.getAttribute("src"); if (!src || !isLocalSiteSrc(src)) return; const cleanPath = normalizeToRepoPath(src); if (!cleanPath) return; const ext = path.extname(cleanPath).toLowerCase(); if (SKIP_EXTENSIONS.has(ext)) return; activeCache.add(cleanPath); candidates.push({ index: idx, src, pictureIndex: activePictureIdx, }); }, }); censusRewriter.transform(htmlContent); // Jika sudah ada signature DAN tidak ada gambar Base64 baru yang diekstrak, skip if (htmlContent.includes(PICTURE_SIGNATURE) && extractedCount === 0) { return "skipped"; } if (candidates.length === 0) { if (extractedCount > 0) { await Bun.write(htmlPath, htmlContent); return "processed"; } return "no-image"; } const pageTitle = rawTitle.split(" - ")[0].trim() || "Layar Kosong"; const imgActions = new Map<number, ImgAction>(); const pictureSourcesMap = new Map<number, string>(); let imageOrdinal = 0; for (const cand of candidates) { imageOrdinal++; const cleanPath = normalizeToRepoPath(cand.src); if (!cleanPath) continue; const fullPathSource = path.join(process.cwd(), cleanPath); if (!(await safeFileExists(fullPathSource))) continue; const meta = await getImageMetadataNative(fullPathSource); if (!meta?.width || !meta?.height) continue; const altFallback = ( imageOrdinal > 1 ? `${pageTitle} - ${imageOrdinal}` : pageTitle ).replace(/"/g, "\x26quot;"); // ๐Ÿ›ก๏ธ GUARD: WEBP ANIMASI if (meta.pages > 1) { imgActions.set(cand.index, { width: meta.width.toString(), height: meta.height.toString(), altIfMissing: altFallback, }); totalAnimatedSkipped++; console.log( ` โ†ณ ๐ŸŽž๏ธ WebP animasi terdeteksi (${meta.pages} frame) โ€” dibiarkan apa adanya: ${cleanPath}` ); continue; } const needsMobile = meta.width > TARGET_MOBILE; const needsMedium = meta.width > TARGET_MEDIUM; const finalDesktopWidth = meta.width > TARGET_DESKTOP ? TARGET_DESKTOP : meta.width; const finalMediumWidth = needsMedium ? TARGET_MEDIUM : meta.width; const finalMobileWidth = needsMobile ? TARGET_MOBILE : meta.width; const aspectRatio = meta.height / meta.width; const finalDesktopHeight = Math.round(finalDesktopWidth * aspectRatio); const dirName = path.dirname(cleanPath); const ext = path.extname(cleanPath); const baseNameSafe = makeSafeOutputBase(path.basename(cleanPath, ext)); const desktopPath = path.join(dirName, `${baseNameSafe}.webp`); const mediumPath = path.join(dirName, `${baseNameSafe}-md.webp`); const mobilePath = path.join(dirName, `${baseNameSafe}-sm.webp`); const absDesktopPath = path.join(process.cwd(), desktopPath); const absMediumPath = path.join(process.cwd(), mediumPath); const absMobilePath = path.join(process.cwd(), mobilePath); const needsDesktopResize = !(await safeFileExists(absDesktopPath)) || (absDesktopPath === fullPathSource && meta.width > TARGET_DESKTOP); const [hasMedFile, hasMobFile] = await Promise.all([ needsMedium ? safeFileExists(absMediumPath) : Promise.resolve(true), needsMobile ? safeFileExists(absMobilePath) : Promise.resolve(true), ]); if (needsDesktopResize) { await encodeWebpNative(fullPathSource, absDesktopPath, finalDesktopWidth, 92, 0.3); } if (needsMedium && !hasMedFile) { await encodeWebpNative(fullPathSource, absMediumPath, finalMediumWidth, 90, 0.4); } if (needsMobile && !hasMobFile) { await encodeWebpNative(fullPathSource, absMobilePath, finalMobileWidth, 88, 0.5); } const webDesktopUrl = `${BASE_URL}/${desktopPath.replace(/\\/g, "/")}`; const webMediumUrl = needsMedium ? `${BASE_URL}/${mediumPath.replace(/\\/g, "/")}` : null; const webMobileUrl = needsMobile ? `${BASE_URL}/${mobilePath.replace(/\\/g, "/")}` : null; if (cand.pictureIndex !== null) { if (needsMobile) { const mediumSource = needsMedium ? `\n <source type="image/webp" media="(min-width: ${finalMobileWidth + 1}px) and (max-width: ${finalMediumWidth}px)" srcset="${webMediumUrl}">` : ""; pictureSourcesMap.set( cand.pictureIndex, `<source type="image/webp" media="(max-width: ${finalMobileWidth}px)" srcset="${webMobileUrl}">${mediumSource}\n <source type="image/webp" srcset="${webDesktopUrl}">` ); } else { pictureSourcesMap.set( cand.pictureIndex, `<source type="image/webp" srcset="${webDesktopUrl}">` ); } } if (needsMobile) { const srcsetCandidates: string[] = []; srcsetCandidates.push(`${webMobileUrl} ${finalMobileWidth}w`); if (needsMedium) srcsetCandidates.push(`${webMediumUrl} ${finalMediumWidth}w`); srcsetCandidates.push(`${webDesktopUrl} ${finalDesktopWidth}w`); imgActions.set(cand.index, { width: finalDesktopWidth.toString(), height: finalDesktopHeight.toString(), altIfMissing: altFallback, srcset: srcsetCandidates.join(", "), sizes: `(max-width: ${finalDesktopWidth + 40}px) calc(100vw - 40px), ${finalDesktopWidth}px`, }); } else { imgActions.set(cand.index, { width: finalDesktopWidth.toString(), height: finalDesktopHeight.toString(), altIfMissing: altFallback, removeSrcset: true, }); } } if (imgActions.size === 0 && extractedCount === 0) return "no-change"; // PASS 2: Terapkan perubahan atribut, <source>, dan signature secara streaming let fileHasChanged = extractedCount > 0; let pass2PicCounter = 0; let pass2ActivePic: number | null = null; let pass2ImgCounter = 0; const transformRewriter = new HTMLRewriter() .on("picture", { element(el) { const pIdx = pass2PicCounter++; pass2ActivePic = pIdx; const newSources = pictureSourcesMap.get(pIdx); if (newSources) { el.prepend(newSources, { html: true }); fileHasChanged = true; } el.onEndTag(() => { if (pass2ActivePic === pIdx) pass2ActivePic = null; }); }, }) .on('picture > source[type="image/webp"]', { element(el) { if (pass2ActivePic !== null && pictureSourcesMap.has(pass2ActivePic)) { el.remove(); fileHasChanged = true; } }, }) .on("body img", { element(el) { const idx = pass2ImgCounter++; const action = imgActions.get(idx); if (!action) return; if ( el.getAttribute("width") !== action.width || el.getAttribute("height") !== action.height ) { el.setAttribute("width", action.width); el.setAttribute("height", action.height); fileHasChanged = true; } if (!el.getAttribute("alt")?.trim() && action.altIfMissing) { el.setAttribute("alt", action.altIfMissing); fileHasChanged = true; } if (action.removeSrcset) { if (el.hasAttribute("srcset") || el.hasAttribute("sizes")) { el.removeAttribute("srcset"); el.removeAttribute("sizes"); fileHasChanged = true; } } else if (action.srcset && action.sizes) { if ( el.getAttribute("srcset") !== action.srcset || el.getAttribute("sizes") !== action.sizes ) { el.setAttribute("srcset", action.srcset); el.setAttribute("sizes", action.sizes); fileHasChanged = true; } } }, }); let finalHtml = transformRewriter.transform(htmlContent); if (!fileHasChanged) return "no-change"; if (!finalHtml.includes(PICTURE_SIGNATURE)) { const signature = `<noscript>${PICTURE_SIGNATURE}</noscript>`; if (/<\/body>/i.test(finalHtml)) { finalHtml = finalHtml.replace(/<\/body>\s*$/i, "").trimEnd() + `${signature}</body>`; } else { finalHtml = finalHtml.trimEnd() + signature; } } await Bun.write(htmlPath, finalHtml); return "processed"; } // ========== MAIN ========== async function main(): Promise<void> { console.log("๐Ÿš€ Memulai Srcset & Thumbnail Generator (100% Native Bun)..."); if (!CWEBP_BIN && !MAGICK_BIN) { console.warn( "โš ๏ธ Peringatan: cwebp maupun magick tidak ditemukan di PATH. Konversi gambar baru dilewati." ); } console.log("๐Ÿงฉ Auto-Ekstrak Base64: AKTIF (data:image/* otomatis dipindah ke img/inline/)"); console.log("๐Ÿ›ก๏ธ Guard WebP Animasi: AKTIF (master tidak akan pernah ditimpa)"); console.log("๐Ÿ” Mengecek dan merekap seluruh data gambar aktif..."); const relatedImages = await loadRelatedImages(); const allFiles = ALLOWED_CATEGORIES.flatMap((cat) => { try { return [...new Bun.Glob("*.html").scanSync(cat)] .filter((f) => f !== "index.html") .map((f) => join(cat, f)) .sort(); } catch { return []; } }).sort(); const results = { processed: 0, skipped: 0, noImage: 0 }; for (const htmlPath of allFiles) { const result = await processHtmlFile(htmlPath); if (result === "processed") results.processed++; if (result === "skipped") results.skipped++; if (result === "no-image") results.noImage++; } const rgCreatedCount = await generateRgImages(relatedImages); // ๐Ÿ”ฅ UPDATE BUKU CATATAN (Sinkronisasi Penuh) ๐Ÿ”ฅ const sortedCache = Array.from(activeCache).sort(); await Bun.write(CACHE_FILE, sortedCache.join("\n") + "\n"); console.log(` โœ… SELESAI: Generator Selesai & Buku Catatan Diperbarui ------------------------------------- ๐Ÿ–ผ๏ธ File HTML Diproses : ${results.processed} (Baru diinjeksi srcset / ekstrak inline) ๐Ÿงฉ Gambar Base64 Ekstrak: ${totalInlineExtracted} gambar dipindah ke ${INLINE_IMG_DIR}/ โญ๏ธ File HTML Di-skip : ${results.skipped} (Aman) ๐Ÿ“„ HTML Tanpa Gambar : ${results.noImage} ๐ŸŽž๏ธ WebP Animasi Aman : ${totalAnimatedSkipped} gambar (dilewati, tidak diubah) ๐ŸŽฏ Target JSON Lite : ${relatedImages.size} file -rg โœจ Thumbnail -rg Baru : ${rgCreatedCount} file dibuat ๐Ÿ“ Catatan Srcset Baru : ${activeCache.size} gambar ditulis ulang ke srcset-gambar.txt ------------------------------------- Sekarang Tukang Sapu sudah bisa dipanggil untuk merazia zombie! ๐Ÿงน `); } await main();