| 1 | // Búsqueda y lectura web para la elfa de Code (docs, errores, APIs). fetch |
| 2 | // directo si el sitio permite CORS; si no, cae al proxy del servidor |
| 3 | // (/proxy?url=… → mismo backend que Elffuss Claw). Sin gate de permisos: un |
| 4 | // agente de código necesita consultar internet de serie. |
| 5 | const MAX = 8000; |
| 6 | |
| 7 | function toText(html) { |
| 8 | const doc = new DOMParser().parseFromString(html, 'text/html'); |
| 9 | doc.querySelectorAll('script,style,noscript,svg,iframe').forEach(n => n.remove()); |
| 10 | return ((doc.body?.innerText || doc.body?.textContent || '').replace(/\n{3,}/g, '\n\n').trim()) || html.slice(0, MAX); |
| 11 | } |
| 12 | |
| 13 | async function proxyGet(url) { |
| 14 | let lastErr; |
| 15 | for (const target of [url, '/proxy?url=' + encodeURIComponent(url)]) { |
| 16 | try { const r = await fetch(target); if (!r.ok) throw new Error('HTTP ' + r.status); return await r.text(); } |
| 17 | catch (e) { lastErr = e; } |
| 18 | } |
| 19 | throw lastErr || new Error('sin respuesta'); |
| 20 | } |
| 21 | |
| 22 | export async function fetchUrl({ url } = {}) { |
| 23 | if (!/^https?:\/\//.test(url || '')) throw new Error('URL inválida (usa https://…)'); |
| 24 | const text = toText(await proxyGet(url)); |
| 25 | return `[${url}]\n` + (text.length > MAX ? text.slice(0, MAX) + '\n… (recortado)' : text); |
| 26 | } |
| 27 | |
| 28 | // Búsqueda REAL en DuckDuckGo. Parseo tolerante: cada resultado es un enlace |
| 29 | // con ?uddg=<url real>. Independiente de clases (robusto a cambios de HTML). |
| 30 | export async function search({ query } = {}) { |
| 31 | if (!query) throw new Error('Falta query'); |
| 32 | let html = ''; |
| 33 | for (const ep of ['https://html.duckduckgo.com/html/?q=', 'https://lite.duckduckgo.com/lite/?q=']) { |
| 34 | try { html = await proxyGet(ep + encodeURIComponent(query)); if (html.includes('uddg=') || html.includes('result')) break; } |
| 35 | catch { /* siguiente endpoint */ } |
| 36 | } |
| 37 | const doc = new DOMParser().parseFromString(html, 'text/html'); |
| 38 | const seen = new Set(), out = []; |
| 39 | for (const a of doc.querySelectorAll('a[href*="uddg="]')) { |
| 40 | const m = a.getAttribute('href').match(/uddg=([^&]+)/); |
| 41 | if (!m) continue; |
| 42 | const href = decodeURIComponent(m[1]); |
| 43 | const title = a.textContent.trim(); |
| 44 | if (!title || title.length < 3 || seen.has(href)) continue; |
| 45 | seen.add(href); |
| 46 | const block = a.closest('tr, div, article') || a.parentElement; |
| 47 | const snip = (block?.textContent || '').replace(title, '').replace(/\s+/g, ' ').trim().slice(0, 160); |
| 48 | out.push(`• ${title}\n ${href}${snip ? '\n ' + snip : ''}`); |
| 49 | if (out.length >= 8) break; |
| 50 | } |
| 51 | return out.length ? `Resultados para «${query}»:\n\n` + out.join('\n\n') : `Sin resultados para «${query}».`; |
| 52 | } |