Fix: Replace setTimeout with AbortSignal.timeout

This commit is contained in:
2026-02-13 18:28:52 -08:00
parent 86e55cc222
commit 62e683ad9f

View File

@@ -175,40 +175,26 @@ async function braveImageSearch(query, apiKey) {
async function fetchImage(imageUrl) { async function fetchImage(imageUrl) {
try { try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000);
const res = await fetch(imageUrl, { const res = await fetch(imageUrl, {
headers: { headers: {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
"Accept": "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8", "Accept": "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8",
}, },
redirect: "follow", redirect: "follow",
signal: controller.signal, signal: AbortSignal.timeout(5000),
cf: { cacheTtl: 0 }, cf: { cacheTtl: 0 },
}); });
if (!res.ok) { if (!res.ok) return null;
clearTimeout(timeoutId);
return null;
}
const ct = res.headers.get("content-type") || ""; const ct = res.headers.get("content-type") || "";
if (!ct.startsWith("image/")) { if (!ct.startsWith("image/")) return null;
clearTimeout(timeoutId);
return null;
}
// Check for massive files that might crash the worker (> 10MB) // Check for massive files that might crash the worker (> 10MB)
const size = res.headers.get("content-length"); const size = res.headers.get("content-length");
if (size && parseInt(size) > 10485760) { if (size && parseInt(size) > 10485760) return null;
clearTimeout(timeoutId);
return null;
}
// Consume body inside timeout scope so abort covers the full download
const buffer = await res.arrayBuffer(); const buffer = await res.arrayBuffer();
clearTimeout(timeoutId);
// Final size check for chunked responses without content-length // Final size check for chunked responses without content-length
if (buffer.byteLength > 10485760) return null; if (buffer.byteLength > 10485760) return null;