// WEB SEARCH — DuckDuckGo's HTML endpoint, read once per query through the // pacer (release 27 D7: no service to run). Read only: titles, URLs and // snippets. The endpoint is injectable (`searchUrl`) for tests and for the // settings' web provider (S6). import { decodeEntities } from "../../social/htmlReader"; import { webPacer, WebRequestError, type WebPacer } from "./pacer"; export const DUCKDUCKGO_HTML_URL = "https://html.duckduckgo.com/html/"; export const WEB_SEARCH_DEFAULT_RESULTS = 6; export const WEB_SEARCH_MAX_RESULTS = 20; export type WebSearchResult = { title: string; url: string; snippet: string }; export type WebSearchOptions = { // How many results (default 6, at most 20). n?: number; searchUrl?: string; pacer?: WebPacer; signal?: AbortSignal; }; const strip = (html: string) => decodeEntities(html.replace(/<[^>]+>/g, "")).replace(/\s+/g, " ").trim(); // A result link: DuckDuckGo wraps it in a redirect (`/l/?uddg=`). function unwrap(href: string): string { const h = decodeEntities(href); const m = /[?&]uddg=([^&]+)/.exec(h); const url = m ? decodeURIComponent(m[1]!) : h.startsWith("//") ? `https:${h}` : h; return url; } // The results of one DuckDuckGo HTML page. export function parseDuckDuckGoHtml(html: string, n = WEB_SEARCH_DEFAULT_RESULTS): WebSearchResult[] { const out: WebSearchResult[] = []; const anchor = /]*class="[^"]*\bresult__a\b[^"]*"[^>]*>/g; const starts = [...html.matchAll(anchor)]; for (let i = 0; i < starts.length && out.length < n; i++) { const tag = starts[i]![0]; const from = starts[i]!.index! + tag.length; const to = i + 1 < starts.length ? starts[i + 1]!.index! : html.length; const chunk = html.slice(from, to); const href = /\bhref="([^"]*)"/.exec(tag)?.[1]; if (!href) continue; const url = unwrap(href); if (!/^https?:\/\//i.test(url)) continue; // Ads go through DuckDuckGo's own y.js; they are not results. if (/duckduckgo\.com\/y\.js/.test(url)) continue; const title = strip(chunk.slice(0, chunk.indexOf("") >= 0 ? chunk.indexOf("") : chunk.length)); const sn = /class="[^"]*\bresult__snippet\b[^"]*"[^>]*>([\s\S]*?)<\/(?:a|div|td)>/.exec(chunk); out.push({ title, url, snippet: sn ? strip(sn[1]!) : "" }); } return out; } export async function webSearch(query: string, opts: WebSearchOptions = {}): Promise { const q = query.trim(); if (!q) throw new WebRequestError("web search needs a query", null); const n = Math.min(WEB_SEARCH_MAX_RESULTS, Math.max(1, Math.floor(opts.n ?? WEB_SEARCH_DEFAULT_RESULTS))); const pacer = opts.pacer ?? webPacer; const url = opts.searchUrl ?? DUCKDUCKGO_HTML_URL; return pacer.request( url, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded", accept: "text/html" }, body: new URLSearchParams({ q }).toString(), ...(opts.signal ? { signal: opts.signal } : {}), }, async (res) => { if (!res.ok) throw new WebRequestError(`the search answered HTTP ${res.status}`, res.status); return parseDuckDuckGoHtml(await res.text(), n); }, ); } export function formatSearchResults(results: readonly WebSearchResult[]): string { if (results.length === 0) return "(no results)"; return results.map((r) => `- ${r.title}\n ${r.url}${r.snippet ? `\n ${r.snippet}` : ""}`).join("\n"); }