Branchwell

PlainSearch / website / src / worker.js

1// PlainSearch: one search box, real websites ranked by fit and relevance.
2// Gemini with Google Search grounding finds and ranks pages; every result is
3// checked against the grounding sources or a live request before it is shown.
4
5const MODELS_DEFAULT = ["gemini-3.5-flash-lite", "gemini-flash-latest"];
6const MAX_RESULTS = 10;
7const CACHE_SECONDS = 6 * 60 * 60;
8
9export default {
10 async fetch(request, env, ctx) {
11 const url = new URL(request.url);
12 if (url.hostname === "www.plainsearch.ai") {
13 url.hostname = "plainsearch.ai";
14 return Response.redirect(url.toString(), 301);
15 }
16 switch (url.pathname) {
17 case "/":
18 return html(PAGE);
19 case "/api/search":
20 return search(request, env, ctx, url);
21 case "/favicon.svg":
22 return new Response(FAVICON, { headers: { "content-type": "image/svg+xml", "cache-control": "public, max-age=86400" } });
23 case "/favicon.ico":
24 return Response.redirect(url.origin + "/favicon.svg", 302);
25 case "/robots.txt":
26 return text("User-agent: *\nAllow: /\nDisallow: /api/\nSitemap: https://plainsearch.ai/sitemap.xml\n");
27 case "/sitemap.xml":
28 return new Response(`<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"><url><loc>https://plainsearch.ai/</loc></url></urlset>\n`, { headers: { "content-type": "application/xml" } });
29 case "/opensearch.xml":
30 return new Response(OPENSEARCH, { headers: { "content-type": "application/opensearchdescription+xml" } });
31 default:
32 return html(PAGE.replace("<!--status-->", "404"), 404);
33 }
34 },
35};
36
37function html(body, status = 200) {
38 return new Response(body, {
39 status,
40 headers: {
41 "content-type": "text/html; charset=utf-8",
42 "cache-control": "public, max-age=300",
43 "x-content-type-options": "nosniff",
44 "referrer-policy": "no-referrer",
45 "content-security-policy": "default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'",
46 },
47 });
48}
49function text(body) {
50 return new Response(body, { headers: { "content-type": "text/plain; charset=utf-8" } });
51}
52function json(obj, status = 200, extra = {}) {
53 return new Response(JSON.stringify(obj), {
54 status,
55 headers: { "content-type": "application/json; charset=utf-8", "referrer-policy": "no-referrer", ...extra },
56 });
57}
58
59async function search(request, env, ctx, url) {
60 const q = (url.searchParams.get("q") || "").replace(/\s+/g, " ").trim().slice(0, 300);
61 if (!q) return json({ error: "Type something to search for." }, 400);
62 if (!env.GEMINI_API_KEY) return json({ error: "Search is not set up yet." }, 503);
63
64 const cacheKey = new Request("https://plainsearch.ai/cache/v1?q=" + encodeURIComponent(q.toLowerCase()));
65 const cache = caches.default;
66 const hit = await cache.match(cacheKey);
67 if (hit) return hit;
68
69 let data;
70 try {
71 data = await runSearch(q, env);
72 } catch (err) {
73 console.log("search failed", String(err && err.stack || err));
74 return json({ error: "Search is busy right now. Try again in a moment." }, 502);
75 }
76 const res = json(data, 200, { "cache-control": `public, max-age=${CACHE_SECONDS}` });
77 if (data.results.length) ctx.waitUntil(cache.put(cacheKey, res.clone()));
78 return res;
79}
80
81async function runSearch(q, env) {
82 const started = Date.now();
83 const models = (env.GEMINI_MODEL ? [env.GEMINI_MODEL] : []).concat(MODELS_DEFAULT);
84 const prompt = `You are the ranking engine of a web search engine. Use Google Search to find the best real web pages for this query:
85
86"${q}"
87
88Return the ${MAX_RESULTS} most useful pages, best first. Rank by how well each page fits what the person is most likely looking for (intent), then by relevance, authority and freshness. Prefer the official site or the original source when one exists. Use exact, working URLs of specific pages that you found in the search results; never invent or guess a URL. No duplicates, at most two pages from the same site.
89
90Reply with only a JSON array, no prose and no code fences. Each item:
91{"title": "page title", "url": "https://...", "snippet": "one or two plain sentences on what the page offers for this query", "score": 0-100 fit}`;
92
93 // Two independent grounded passes run side by side and are merged. If a
94 // round still comes back empty, run another round (up to 3, within ~20s),
95 // pooling everything found so far, so people never see an empty page.
96 const poolText = [];
97 const poolChunks = [];
98 let results = [];
99 let lastErr;
100 for (let round = 0; round < 3 && !results.length; round++) {
101 if (round && Date.now() - started > 20000) break;
102 const runs = await Promise.allSettled([askModels(models, prompt, env), askModels(models, prompt + MORE, env)]);
103 const ok = runs.filter((r) => r.status === "fulfilled").map((r) => r.value);
104 if (!ok.length) { lastErr = runs[0].reason; continue; }
105 for (const o of ok) { poolText.push(...parseArray(o.text)); poolChunks.push(...o.chunks); }
106 results = await buildResults({ text: JSON.stringify(poolText), chunks: poolChunks });
107 }
108 if (!results.length) results = fallbackResults(poolText, poolChunks);
109 if (!results.length && lastErr) throw lastErr;
110 return { query: q, results, ms: Date.now() - started };
111}
112
113// Last resort when verification removed everything: show the model's own picks
114// and the raw Google source links (they redirect to the real pages).
115function fallbackResults(items, chunks) {
116 const out = [];
117 const seen = new Set();
118 const perHost = {};
119 const add = (title, url, snippet, site) => {
120 if (out.length >= MAX_RESULTS || !(isWebUrl(url) || (site && /^https:\/\/vertexaisearch\.cloud\.google\.com\//.test(url)))) return;
121 const n = normalize(url);
122 const h = site || host(url);
123 if (seen.has(n) || (perHost[h] || 0) >= 2) return;
124 seen.add(n);
125 perHost[h] = (perHost[h] || 0) + 1;
126 out.push({ title: title || h, url, snippet: snippet || "", score: 0, site: h });
127 };
128 for (const it of items) if (it && typeof it.url === "string") add(clean(it.title), it.url.trim(), clean(it.snippet));
129 // Google's source titles are usually the site's domain.
130 for (const c of chunks) add(c.title || "", c.uri, "", /^[a-z0-9.-]+\.[a-z]{2,}$/i.test(c.title || "") ? c.title.toLowerCase() : "");
131 return out;
132}
133
134const MORE = `
135
136Cast a wide net: run several different searches for this query (official sources, guides, references, reviews, news) so you can return a full list of 10 distinct pages.`;
137
138async function askModels(models, prompt, env) {
139 let lastErr;
140 for (const model of [...new Set(models)]) {
141 try {
142 return await callGemini(model, prompt, env.GEMINI_API_KEY);
143 } catch (err) {
144 lastErr = err;
145 if (!(err && err.retryable)) break;
146 }
147 }
148 throw lastErr;
149}
150
151async function callGemini(model, prompt, key) {
152 const res = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent`, {
153 method: "POST",
154 headers: { "content-type": "application/json", "x-goog-api-key": key },
155 body: JSON.stringify({
156 contents: [{ role: "user", parts: [{ text: prompt }] }],
157 tools: [{ google_search: {} }],
158 generationConfig: { temperature: 0.2 },
159 }),
160 });
161 if (!res.ok) {
162 const body = await res.text();
163 const err = new Error(`Gemini ${model} ${res.status}: ${body.slice(0, 300)}`);
164 err.retryable = res.status === 404 || res.status === 429 || res.status >= 500;
165 throw err;
166 }
167 const data = await res.json();
168 const cand = (data.candidates || [])[0] || {};
169 const textOut = ((cand.content || {}).parts || []).map((p) => p.text || "").join("");
170 const chunks = ((cand.groundingMetadata || {}).groundingChunks || [])
171 .map((c) => c.web)
172 .filter((w) => w && w.uri);
173 return { text: textOut, chunks };
174}
175
176async function buildResults({ text, chunks }) {
177 // Resolve grounding redirect links to the real pages they point at.
178 const grounded = (await Promise.all(chunks.map(async (c) => ({ title: c.title || "", url: await resolveRedirect(c.uri) }))))
179 .filter((g) => g.url && isWebUrl(g.url));
180 const groundedHosts = new Set(grounded.map((g) => host(g.url)));
181
182 let items = parseArray(text)
183 .filter((it) => it && typeof it.url === "string" && isWebUrl(it.url))
184 .map((it) => ({
185 title: clean(it.title) || host(it.url),
186 url: it.url.trim(),
187 snippet: clean(it.snippet),
188 score: Math.max(0, Math.min(100, Number(it.score) || 0)),
189 }));
190
191 // Keep a model result if its site was in the live search results, or if the page answers.
192 const checked = await Promise.all(
193 items.map(async (it) => (groundedHosts.has(host(it.url)) || (await pageExists(it.url)) ? it : null)),
194 );
195 items = checked.filter(Boolean);
196
197 // Add grounded pages the model did not list, after its ranked picks.
198 const have = new Set(items.map((it) => normalize(it.url)));
199 for (const g of grounded) {
200 if (items.length >= MAX_RESULTS) break;
201 if (have.has(normalize(g.url))) continue;
202 have.add(normalize(g.url));
203 items.push({ title: g.title || host(g.url), url: g.url, snippet: "", score: 0 });
204 }
205
206 const seen = new Set();
207 const perHost = {};
208 const out = [];
209 for (const it of items.sort((a, b) => b.score - a.score)) {
210 const n = normalize(it.url);
211 const h = host(it.url);
212 if (seen.has(n) || (perHost[h] || 0) >= 2) continue;
213 seen.add(n);
214 perHost[h] = (perHost[h] || 0) + 1;
215 out.push({ ...it, site: h });
216 if (out.length >= MAX_RESULTS) break;
217 }
218 return out;
219}
220
221async function resolveRedirect(uri) {
222 if (!/vertexaisearch\.cloud\.google\.com\/grounding-api-redirect/.test(uri)) return uri;
223 try {
224 const res = await fetch(uri, { method: "GET", redirect: "manual", signal: AbortSignal.timeout(4000) });
225 return res.headers.get("location") || "";
226 } catch {
227 return "";
228 }
229}
230
231async function pageExists(u) {
232 try {
233 const res = await fetch(u, {
234 method: "GET",
235 redirect: "follow",
236 headers: { "user-agent": "Mozilla/5.0 (compatible; PlainSearchBot/1.0; +https://plainsearch.ai)" },
237 signal: AbortSignal.timeout(3500),
238 });
239 try { res.body && res.body.cancel(); } catch {}
240 // Many sites refuse bots (401/403/429); the page still exists. Only treat missing pages as dead.
241 return res.status !== 404 && res.status !== 410 && res.status < 500;
242 } catch {
243 return false;
244 }
245}
246
247function parseArray(t) {
248 if (!t) return [];
249 const s = t.replace(/```(?:json)?/gi, "");
250 const a = s.indexOf("["), b = s.lastIndexOf("]");
251 if (a < 0 || b <= a) return [];
252 try {
253 const v = JSON.parse(s.slice(a, b + 1));
254 return Array.isArray(v) ? v : [];
255 } catch {
256 return [];
257 }
258}
259function isWebUrl(u) {
260 try {
261 const p = new URL(u);
262 return (p.protocol === "https:" || p.protocol === "http:") && !/vertexaisearch\.cloud\.google\.com/.test(p.hostname);
263 } catch {
264 return false;
265 }
266}
267function host(u) {
268 try { return new URL(u).hostname.replace(/^www\./, ""); } catch { return ""; }
269}
270function normalize(u) {
271 try {
272 const p = new URL(u);
273 return (p.hostname.replace(/^www\./, "") + p.pathname.replace(/\/+$/, "") + p.search).toLowerCase();
274 } catch { return u; }
275}
276function clean(s) {
277 return typeof s === "string" ? s.replace(/\s+/g, " ").trim().slice(0, 400) : "";
278}
279
280const FAVICON = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="14" fill="#1f5f4a"/><circle cx="28" cy="28" r="13" fill="none" stroke="#f6f4ee" stroke-width="6"/><path d="M38 38l12 12" stroke="#f6f4ee" stroke-width="6" stroke-linecap="round"/></svg>`;
281
282const OPENSEARCH = `<?xml version="1.0" encoding="UTF-8"?>
283<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
284<ShortName>PlainSearch</ShortName>
285<Description>Search the web with PlainSearch</Description>
286<InputEncoding>UTF-8</InputEncoding>
287<Image width="64" height="64" type="image/svg+xml">https://plainsearch.ai/favicon.svg</Image>
288<Url type="text/html" template="https://plainsearch.ai/?q={searchTerms}"/>
289</OpenSearchDescription>`;
290
291const PAGE = `<!doctype html>
292<html lang="en">
293<head>
294<meta charset="utf-8">
295<meta name="viewport" content="width=device-width, initial-scale=1">
296<title>PlainSearch</title>
297<meta name="description" content="PlainSearch is a simple web search engine. One box, real websites, ranked by how well they fit what you are looking for.">
298<link rel="canonical" href="https://plainsearch.ai/">
299<link rel="icon" href="/favicon.svg" type="image/svg+xml">
300<link rel="search" type="application/opensearchdescription+xml" title="PlainSearch" href="/opensearch.xml">
301<meta property="og:title" content="PlainSearch">
302<meta property="og:description" content="One box. Real websites, ranked by how well they fit.">
303<meta property="og:url" content="https://plainsearch.ai/">
304<meta property="og:type" content="website">
305<meta name="theme-color" content="#f6f4ee" media="(prefers-color-scheme: light)">
306<meta name="theme-color" content="#121512" media="(prefers-color-scheme: dark)">
307<script type="application/ld+json">{"@context":"https://schema.org","@type":"WebSite","name":"PlainSearch","url":"https://plainsearch.ai/","potentialAction":{"@type":"SearchAction","target":"https://plainsearch.ai/?q={search_term_string}","query-input":"required name=search_term_string"}}</script>
308<style>
309:root{--bg:#f6f4ee;--surface:#fffdf8;--ink:#1b1f1c;--muted:#5d655f;--line:#dcd8cc;--accent:#1f5f4a;--link:#1a4f8f;--visited:#5a3f8a;--focus:#1f5f4a33}
310@media (prefers-color-scheme:dark){:root{--bg:#121512;--surface:#1a1e1b;--ink:#ecebe4;--muted:#a3aaa3;--line:#2f3530;--accent:#7cc4a6;--link:#9cc3f5;--visited:#c7aef0;--focus:#7cc4a633}}
311*{box-sizing:border-box}
312html,body{margin:0}
313body{background:var(--bg);color:var(--ink);font:16px/1.5 ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;min-height:100vh;display:flex;flex-direction:column}
314a{color:var(--link)}
315main{flex:1;width:100%;max-width:760px;margin:0 auto;padding:0 16px}
316.home{display:flex;flex-direction:column;justify-content:center;min-height:62vh}
317.brand{display:flex;align-items:center;gap:10px;text-decoration:none;color:var(--ink)}
318.brand svg{width:34px;height:34px;flex:none}
319.brand span{font-size:30px;font-weight:650;letter-spacing:-.02em}
320.brand b{font-weight:650;color:var(--accent)}
321.home .brand{justify-content:center;margin-bottom:24px}
322.home .brand svg{width:46px;height:46px}
323.home .brand span{font-size:44px}
324.tag{text-align:center;color:var(--muted);margin:-12px 0 24px}
325form{display:flex;gap:8px;background:var(--surface);border:1px solid var(--line);border-radius:999px;padding:6px 6px 6px 20px;box-shadow:0 1px 2px #0000000d}
326form:focus-within{border-color:var(--accent);box-shadow:0 0 0 4px var(--focus)}
327input{flex:1;min-width:0;border:0;background:transparent;color:var(--ink);font:inherit;font-size:18px;outline:none;padding:8px 0}
328input::-webkit-search-cancel-button{display:none}
329button{border:0;border-radius:999px;background:var(--accent);color:var(--bg);font:inherit;font-weight:600;padding:10px 22px;cursor:pointer}
330button:hover{filter:brightness(1.08)}
331.top{display:none;align-items:center;gap:20px;padding:18px 0 14px;border-bottom:1px solid var(--line);margin-bottom:8px}
332.top form{flex:1}
333.searching .home{display:none}.searching .top{display:flex}
334.meta{color:var(--muted);font-size:14px;margin:12px 0 4px;min-height:21px}
335ol{list-style:none;margin:0;padding:0}
336li{padding:16px 0;border-bottom:1px solid var(--line)}
337li:last-child{border-bottom:0}
338.site{color:var(--muted);font-size:14px;overflow-wrap:anywhere}
339.site .rank{display:inline-block;min-width:22px;color:var(--accent);font-weight:600}
340li h2{margin:2px 0 4px;font-size:19px;font-weight:550;line-height:1.3}
341li h2 a{text-decoration:none}
342li h2 a:hover{text-decoration:underline}
343li h2 a:visited{color:var(--visited)}
344li p{margin:0;color:var(--ink);opacity:.86}
345.fit{display:inline-block;margin-left:8px;font-size:12px;color:var(--accent);border:1px solid var(--line);border-radius:999px;padding:0 8px;vertical-align:1px}
346.skeleton li div{height:12px;background:var(--line);border-radius:6px;margin:8px 0;animation:p 1.2s ease-in-out infinite}
347.skeleton li div:nth-child(1){width:30%}.skeleton li div:nth-child(2){width:70%;height:16px}.skeleton li div:nth-child(3){width:92%}
348@keyframes p{50%{opacity:.45}}
349.msg{padding:28px 0;color:var(--muted)}
350footer{text-align:center;color:var(--muted);font-size:13px;padding:28px 16px}
351@media (max-width:560px){.top{flex-direction:column;align-items:stretch;gap:12px}.top .brand span{font-size:24px}.home .brand span{font-size:36px}button{padding:10px 16px}input{font-size:17px}}
352@media (prefers-reduced-motion:reduce){.skeleton li div{animation:none}}
353</style>
354<!-- no-orphans --><style id="no-orphans">h1,h2,h3,h4,h5,h6,summary,legend,caption,blockquote{text-wrap:balance}p,li,dd,dt,figcaption,td,th,label,small{text-wrap:pretty}</style><script id="no-orphans-js">(function () {
355if (window.__noOrphans) return;
356window.__noOrphans = 1;
357var SKIP = /^(SCRIPT|STYLE|PRE|CODE|TEXTAREA|INPUT|SELECT|OPTION|SVG|MATH|KBD|SAMP|NOSCRIPT|TEMPLATE|IFRAME|CANVAS|TITLE)$/;
358var NB = ' ';
359var WS = /[ \\t\\n\\r]/;
360function skipped(el) {
361for (var n = el; n && n.nodeType === 1; n = n.parentNode) {
362if (SKIP.test(n.nodeName.toUpperCase()) || n.isContentEditable || n.hasAttribute('data-orphans-ok')) return true;
363}
364return false;
365}
366function blockOf(node, cache) {
367for (var el = node.parentNode; el && el.nodeType === 1; el = el.parentNode) {
368var d = cache.get(el);
369if (d === undefined) { d = getComputedStyle(el).display; cache.set(el, d); }
370if (d !== 'inline' && d !== 'contents') return el;
371}
372return null;
373}
374function fix(block, nodes) {
375var text = '';
376for (var i = 0; i < nodes.length; i++) text += nodes[i].nodeValue;
377var words = text.trim().split(/\\s+/);
378if (words.length < 3) return;
379var last = words[words.length - 1], prev = words[words.length - 2];
380if (last.indexOf(NB) >= 0 || last.length + prev.length > 30) return;
381var seenWord = false;
382for (i = nodes.length - 1; i >= 0; i--) {
383var s = nodes[i].nodeValue;
384for (var j = s.length - 1; j >= 0; j--) {
385var c = s.charAt(j);
386if (c === NB) { if (seenWord) return; continue; }
387if (WS.test(c)) {
388if (!seenWord) continue;
389var k = j;
390while (k > 0 && WS.test(s.charAt(k - 1))) k--;
391var node = nodes[i], before = s;
392node.nodeValue = s.slice(0, k) + NB + s.slice(j + 1);
393if (last.length + prev.length > 14) {
394var de = document.documentElement;
395if (block.scrollWidth > block.clientWidth + 1 || de.scrollWidth > de.clientWidth + 1) node.nodeValue = before;
396}
397return;
398}
399seenWord = true;
400}
401}
402}
403function run(root) {
404if (!root || root.nodeType !== 1 || skipped(root)) return;
405var cache = new Map(), blocks = [], groups = new Map();
406var w = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
407acceptNode: function (t) { return t.nodeValue.trim() && !skipped(t.parentNode) ? 1 : 3; }
408});
409for (var t = w.nextNode(); t; t = w.nextNode()) {
410var b = blockOf(t, cache);
411if (!b) continue;
412var g = groups.get(b);
413if (!g) { g = []; groups.set(b, g); blocks.push(b); }
414g.push(t);
415}
416for (var i = 0; i < blocks.length; i++) {
417var blk = blocks[i];
418if (!root.contains(blk) || blk === root.parentNode) continue;
419fix(blk, groups.get(blk));
420}
421}
422var queued = [], timer = 0;
423function flush() {
424timer = 0;
425var q = queued; queued = [];
426var cache = new Map(), seen = new Set();
427for (var i = 0; i < q.length; i++) {
428var n = q[i];
429if (!n || !n.isConnected) continue;
430var b = n.nodeType === 3 ? blockOf(n, cache) : (n.nodeType === 1 ? (getComputedStyle(n).display === 'inline' ? blockOf(n, cache) : n) : null);
431if (b && !seen.has(b)) { seen.add(b); run(b); }
432}
433}
434function start() {
435run(document.body);
436if (!window.MutationObserver) return;
437new MutationObserver(function (muts) {
438for (var i = 0; i < muts.length; i++) {
439var m = muts[i];
440if (m.type === 'characterData') queued.push(m.target);
441for (var j = 0; j < m.addedNodes.length; j++) queued.push(m.addedNodes[j]);
442}
443if (queued.length && !timer) timer = setTimeout(flush, 60);
444}).observe(document.body, { childList: true, subtree: true, characterData: true });
445}
446if (document.readyState === 'complete') setTimeout(start, 0);
447else window.addEventListener('load', function () { setTimeout(start, 0); });
448})();</script><!-- /no-orphans -->
449</head>
450<body>
451<main>
452 <section class="home">
453 <a class="brand" href="/" aria-label="PlainSearch home">${FAVICON}<span>Plain<b>Search</b></span></a>
454 <p class="tag">Real websites, ranked by how well they fit.</p>
455 <form role="search" action="/" method="get"><input type="search" name="q" placeholder="Search the web" aria-label="Search the web" autocomplete="off" autofocus><button type="submit">Search</button></form>
456 </section>
457 <header class="top">
458 <a class="brand" href="/" aria-label="PlainSearch home">${FAVICON}<span>Plain<b>Search</b></span></a>
459 <form role="search" action="/" method="get"><input type="search" name="q" aria-label="Search the web" autocomplete="off"><button type="submit">Search</button></form>
460 </header>
461 <div class="meta" id="meta" aria-live="polite"></div>
462 <ol id="results"></ol>
463</main>
464<footer>© PlainSearch</footer>
465<script>
466(function(){
467 var body=document.body, list=document.getElementById('results'), meta=document.getElementById('meta');
468 var inputs=document.querySelectorAll('input[name=q]'), seq=0;
469 function el(tag,cls,txt){var e=document.createElement(tag);if(cls)e.className=cls;if(txt!=null)e.textContent=txt;return e}
470 function safe(u){try{var p=new URL(u);return (p.protocol==='https:'||p.protocol==='http:')?p.href:'#'}catch(e){return '#'}}
471 function show(q,push){
472 q=(q||'').trim();
473 if(!q){body.classList.remove('searching');document.title='PlainSearch';list.innerHTML='';meta.textContent='';return}
474 body.classList.add('searching');
475 inputs.forEach(function(i){i.value=q});
476 document.title=q+' - PlainSearch';
477 if(push)history.pushState({q:q},'','/?q='+encodeURIComponent(q));
478 var me=++seq;
479 meta.textContent='Searching the web…';
480 list.className='skeleton';list.innerHTML='';
481 for(var k=0;k<5;k++){var li=el('li');li.appendChild(el('div'));li.appendChild(el('div'));li.appendChild(el('div'));list.appendChild(li)}
482 fetch('/api/search?q='+encodeURIComponent(q)).then(function(r){return r.json()}).then(function(d){
483 if(me!==seq)return;
484 list.className='';list.innerHTML='';
485 if(d.error){meta.textContent='';list.appendChild(el('li','msg',d.error));return}
486 var n=d.results.length;
487 meta.textContent=n?(n+' result'+(n===1?'':'s')+', best fit first'):'';
488 if(!n){list.appendChild(el('li','msg','No good matches found. Try different words.'));return}
489 d.results.forEach(function(r,i){
490 var li=el('li');
491 var s=el('div','site');s.appendChild(el('span','rank',(i+1)+'.'));s.appendChild(document.createTextNode(' '+r.site));
492 if(r.score>=85)s.appendChild(el('span','fit','Best fit'));
493 var h=el('h2'),a=el('a',null,r.title);a.href=safe(r.url);a.rel='noopener';h.appendChild(a);
494 li.appendChild(s);li.appendChild(h);
495 if(r.snippet)li.appendChild(el('p',null,r.snippet));
496 list.appendChild(li);
497 });
498 }).catch(function(){if(me!==seq)return;list.className='';list.innerHTML='';meta.textContent='';list.appendChild(el('li','msg','Could not reach PlainSearch. Check your connection and try again.'))});
499 }
500 document.querySelectorAll('form').forEach(function(f){f.addEventListener('submit',function(e){e.preventDefault();var q=f.querySelector('input').value;if(q.trim()){f.querySelector('input').blur();show(q,true)}})});
501 window.addEventListener('popstate',function(){show(new URLSearchParams(location.search).get('q'),false)});
502 show(new URLSearchParams(location.search).get('q'),false);
503})();
504</script>
505</body>
506</html>`;