Spaces:
Running

EdgeAI / browse.js
encryptidai's picture
Encryptid EdgeAI from ai.encryptid.systems page, Hodge-5 weights from model repo
1d919a0 verified
Raw History Blame Contribute Delete
16.8 kB
// The person's browser makes the lookup. The terms already allow that.
// Nothing here sets a User-Agent. The browser sends its own.
// Wikipedia's API answers a page when the query includes origin=*.
const CHROME_RE = /\b(?:outdated browser|upgrade your browser|upgrade your web browser|enable javascript|javascript is (?:required|disabled)|turn on javascript)\b/i;
function fromCode(c) {
if (!Number.isFinite(c) || c <= 0 || c > 0x10ffff) return "";
try { return String.fromCodePoint(c); } catch { return ""; }
}
// Recipe pages store apostrophes as &#8217; and &#x27;. The quote is the page's words.
function decodeEntities(s) {
return String(s || "")
.replace(/&amp;/gi, "&")
.replace(/&#x([0-9a-f]+);/gi, (_, h) => fromCode(parseInt(h, 16)))
.replace(/&#(\d+);/g, (_, d) => fromCode(Number(d)))
.replace(/&lt;/gi, "<")
.replace(/&gt;/gi, ">")
.replace(/&quot;/gi, '"')
.replace(/&apos;/gi, "'")
.replace(/&nbsp;/gi, " ")
.replace(/&rsquo;|&lsquo;/gi, "'")
.replace(/&rdquo;|&ldquo;/gi, '"')
.replace(/&ndash;|&mdash;/gi, "-");
}
function clean(s) {
return decodeEntities(String(s || "").replace(/<[^>]+>/g, " ")).replace(/\s+/g, " ").trim();
}
function allowedPage(raw) {
let u;
try { u = new URL(String(raw)); } catch { return false; }
if (u.username || u.password) return false;
if (u.protocol !== "http:" && u.protocol !== "https:") return false;
const host = u.hostname.toLowerCase().replace(/\.$/, "");
if (!host || host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal")) return false;
if (host === "metadata.google.internal") return false;
if (/^(?:\d{1,3}\.){3}\d{1,3}$/.test(host) || host.includes(":")) {
if (host === "0.0.0.0" || host.startsWith("10.") || host.startsWith("127.") || host.startsWith("192.168.")) return false;
if (/^172\.(1[6-9]|2\d|3[0-1])\./.test(host)) return false;
if (/^169\.254\./.test(host)) return false;
if (host === "::1" || host.startsWith("fe80:") || host.startsWith("fc") || host.startsWith("fd")) return false;
}
return true;
}
export function wikiTitle(raw) {
let u;
try { u = new URL(String(raw)); } catch { return ""; }
const host = u.hostname.toLowerCase().replace(/^www\./, "");
if (host !== "en.wikipedia.org" || !u.pathname.startsWith("/wiki/")) return "";
let title = "";
try { title = decodeURIComponent(u.pathname.slice("/wiki/".length)); } catch { return ""; }
title = title.replace(/_/g, " ").trim();
if (!title || title.includes(":")) return "";
return title;
}
export function formatHits(hits) {
const list = (hits || []).filter((h) => h && h.title && h.url).slice(0, 5);
if (!list.length) return "";
const text = list.map((h, i) => {
const bit = h.snippet ? "\n" + h.snippet : "";
return (i + 1) + ". " + h.title + "\n" + h.url + bit;
}).join("\n\n");
return text.length > 1800 ? text.slice(0, 1800) : text;
}
export function parseWikiSearch(data) {
const rows = data && data.query && data.query.search;
if (!Array.isArray(rows)) return [];
const hits = [];
for (const row of rows) {
const title = clean(row && row.title).slice(0, 160);
if (!title) continue;
hits.push({
title,
url: "https://en.wikipedia.org/wiki/" + encodeURIComponent(title.replace(/ /g, "_")),
snippet: clean(row.snippet).slice(0, 180),
});
if (hits.length >= 5) break;
}
return hits;
}
export function parseWikiExtract(data) {
const pages = data && data.query && data.query.pages;
if (!pages) return "";
const page = Object.values(pages)[0];
const extract = page && page.extract;
if (!extract || page.missing != null) return "";
const paras = [];
for (const para of String(extract).split(/\n+/)) {
const t = clean(para);
if (!t || CHROME_RE.test(t)) continue;
if (t.split(/\s+/).length < 6) continue;
paras.push(t);
}
const body = paras.join("\n\n");
return body.length > 6000 ? body.slice(0, 6000) : body;
}
const NOT_A_PAGE = /(?:wikipedia\.org|wikimedia\.org|wikidata\.org|duckduckgo\.com|web\.archive\.org|archive\.org|doi\.org|dx\.doi\.org|books\.google\.|google\.com\/books|d-nb\.info|id\.loc\.gov)/i;
export function parseWikiExtlinks(data) {
const pages = data && data.query && data.query.pages;
if (!pages) return [];
const page = Object.values(pages)[0];
const rows = (page && page.extlinks) || [];
const hits = [];
const hosts = new Set();
for (const row of rows) {
const url = String((row && (row["*"] || row.url)) || "");
if (!/^https:\/\//i.test(url) || NOT_A_PAGE.test(url)) continue;
let host = "";
try { host = new URL(url).hostname.replace(/^www\./, ""); } catch { continue; }
if (!host || hosts.has(host)) continue;
hosts.add(host);
hits.push({ title: host, url, snippet: "" });
if (hits.length >= 3) break;
}
return hits;
}
function ddgUrl(href) {
const raw = String(href || "").replace(/&amp;/g, "&");
const m = /[?&]uddg=([^&]+)/.exec(raw);
if (!m) return "";
try { return decodeURIComponent(m[1]); } catch { return ""; }
}
export function parseDdgHtml(html) {
const hits = [];
const seen = new Set();
const re = /<a\b([^>]*\bclass="result__a"[^>]*)>([\s\S]*?)<\/a>/gi;
let m;
while ((m = re.exec(String(html || "")))) {
const href = /href="([^"]+)"/i.exec(m[1]);
const url = ddgUrl(href && href[1]);
if (!/^https?:\/\//i.test(url) || seen.has(url) || NOT_A_PAGE.test(url)) continue;
const title = clean(m[2]).slice(0, 160);
if (!title) continue;
seen.add(url);
hits.push({ title, url, snippet: "" });
if (hits.length >= 5) break;
}
return hits;
}
export function parseDdgInstant(data) {
const hits = [];
const seen = new Set();
function add(title, url, snippet) {
const u = String(url || "");
const name = clean(title).slice(0, 160);
if (!name || !/^https?:\/\//i.test(u) || seen.has(u) || NOT_A_PAGE.test(u)) return;
seen.add(u);
hits.push({ title: name, url: u, snippet: clean(snippet).slice(0, 180) });
}
if (data && data.AbstractURL) add(data.Heading || data.AbstractURL, data.AbstractURL, data.AbstractText);
const walk = (list) => {
for (const item of list || []) {
if (item && Array.isArray(item.Topics)) walk(item.Topics);
else if (item) add(item.Text, item.FirstURL, "");
}
};
walk(data && data.RelatedTopics);
return hits.slice(0, 5);
}
export function articleFromHTML(html) {
const raw = String(html || "")
.replace(/<script[\s\S]*?<\/script>/gi, " ")
.replace(/<style[\s\S]*?<\/style>/gi, " ")
.replace(/<(?:nav|header|footer|aside|form)\b[\s\S]*?<\/(?:nav|header|footer|aside|form)>/gi, " ");
const blocks = [];
const re = /<(p|li)\b[^>]*>([\s\S]*?)<\/\1>/gi;
let m;
while ((m = re.exec(raw))) {
const t = clean(m[2]);
if (!t || CHROME_RE.test(t)) continue;
const words = t.split(/\s+/).length;
const li = m[1].toLowerCase() === "li";
if (li ? words < 6 : words < 12 || !/[.!?]/.test(t)) continue;
blocks.push(li ? "- " + t : t);
if (blocks.length >= 40) break;
}
const body = blocks.join("\n\n");
if (!body || body.split(/\s+/).length < 12) return "";
return body.length > 6000 ? body.slice(0, 6000) : body;
}
// The local frame (frame.html on this origin) runs offscreen_script.js.
// method "fetch" is called with args[0]: { url, headers, request }.
// The handler JSON.parses the body. The frame returns a page as {"text": page}.
const OFFSCREEN_MAGIC = 91556947316803;
let testFrame = null;
let frameWait = null;
export function setLocalFrame(win) {
testFrame = win || null;
frameWait = null;
}
function canFrame(fetchImpl) {
if (testFrame) return true;
return (!fetchImpl || fetchImpl === globalThis.fetch) && typeof document !== "undefined" && !!document.getElementById("local-frame");
}
export function localFrameWindow() {
if (testFrame) return Promise.resolve(testFrame);
if (typeof document === "undefined") return Promise.resolve(null);
const frame = document.getElementById("local-frame");
if (!frame) return Promise.resolve(null);
let win = null;
try { win = frame.contentWindow; } catch { win = null; }
if (win && typeof win.frameFetch === "function") return Promise.resolve(win);
if (frameWait) return frameWait;
frameWait = new Promise((resolve) => {
const timer = setTimeout(() => resolve(null), 4000);
const done = () => {
clearTimeout(timer);
let ready = null;
try { ready = frame.contentWindow; } catch { ready = null; }
resolve(ready && typeof ready.frameFetch === "function" ? ready : null);
};
frame.addEventListener("load", done, { once: true });
});
return frameWait;
}
export function offscreenBody(raw) {
const s = typeof raw === "string" ? raw : "";
if (!s) return "";
try {
const j = JSON.parse(s);
if (j && typeof j === "object" && !Array.isArray(j) && typeof j.text === "string" && Object.keys(j).length === 1) return j.text;
} catch { /* the handler already returned the body */ }
return s;
}
function headerObject(src) {
const headers = {};
if (!src) return headers;
if (typeof src.forEach === "function") {
src.forEach((v, k) => { headers[k] = String(v); });
} else {
for (const [k, v] of Object.entries(src)) headers[k] = String(v);
}
for (const key of Object.keys(headers)) {
const low = key.toLowerCase();
if (low === "user-agent" || low === "cookie" || low === "authorization") delete headers[key];
}
return headers;
}
export function offscreenMessage(url, init) {
const headers = headerObject(init && init.headers);
if (!headers.Accept && !headers.accept) headers.Accept = "text/html,application/json";
const request = {
method: (init && init.method) || "GET",
credentials: "omit",
cache: "no-store",
};
if (init && init.body != null) request.body = typeof init.body === "string" ? init.body : String(init.body);
return {
magic: OFFSCREEN_MAGIC,
host: "*",
method: "fetch",
args: [{ url, headers, request }],
};
}
export async function offscreenRead(url, init) {
const win = await localFrameWindow();
if (!win || typeof win.frameFetch !== "function") return null;
let href = "";
try {
const base = typeof location !== "undefined" && location.href ? location.href : "https://ai.encryptid.systems/";
href = new URL(String(url), base).href;
} catch { return null; }
if (!/^https:\/\//i.test(href)) return null;
const reply = await win.frameFetch(offscreenMessage(href, init));
const result = reply && reply.result;
if (!result || result.ok === false && !result.text) return null;
return {
ok: !!result.ok,
status: Number(result.status) || 0,
headers: result.headers && typeof result.headers === "object" ? result.headers : {},
text: offscreenBody(result.text),
};
}
function asResponse(got) {
if (!got) {
return { ok: false, status: 0, headers: { get() { return ""; } }, text: async () => "", json: async () => null };
}
const text = got.text || "";
const table = got.headers || {};
return {
ok: !!got.ok && got.status >= 200 && got.status < 300,
status: got.status,
headers: {
get(name) {
const want = String(name || "").toLowerCase();
for (const [k, v] of Object.entries(table)) {
if (String(k).toLowerCase() === want) return String(v);
}
return "";
},
},
text: async () => text,
json: async () => JSON.parse(text),
};
}
// duck.ai and Gemini run in the local frame. The frame's script does the fetch.
export function pageFetch(fetchImpl) {
const base = fetchImpl || globalThis.fetch;
if (base !== globalThis.fetch) return base;
return async (input, init) => {
const url = typeof input === "string" ? input : (input && input.url) || "";
const got = await offscreenRead(url, init);
if (got && (got.text || got.ok)) return asResponse(got);
try { return await base(input, init); } catch { return asResponse(null); }
};
}
// The site search is the same origin. It is used when the browser cannot read the page.
async function serverLookup(path, params, fetchImpl) {
const f = fetchImpl || fetch;
const u = new URL(path, "http://champ.local");
for (const [k, v] of Object.entries(params)) u.searchParams.set(k, v);
try {
const r = await f(u.pathname + u.search, { headers: { Accept: "application/json" }, cache: "no-store" });
if (!r || !r.ok || typeof r.json !== "function") return "";
const j = await r.json();
if (!j || j.ok === false || typeof j.output !== "string") return "";
return j.output;
} catch {
return "";
}
}
async function browserJSON(url, fetchImpl) {
const f = fetchImpl || fetch;
const r = await f(url, { headers: { Accept: "application/json" }, cache: "no-store" });
if (!r || !r.ok || typeof r.json !== "function") return null;
return r.json();
}
// The host did not send a CORS header, so this origin reads the page and hands the text back.
async function originRead(url, init) {
if (typeof location === "undefined" || !location.origin) return null;
let href = "";
try { href = new URL(String(url), location.href).href; } catch { return null; }
if (!/^https:\/\//i.test(href)) return null;
try {
const r = await fetch(location.origin + "/api/read", {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json" },
cache: "no-store",
body: JSON.stringify({
url: href,
method: (init && init.method) || "GET",
headers: headerObject(init && init.headers),
body: init && init.body != null ? String(init.body) : "",
}),
});
if (!r.ok || typeof r.json !== "function") return null;
const j = await r.json();
if (!j || typeof j.text !== "string") return null;
return j;
} catch {
return null;
}
}
async function browserText(url, fetchImpl) {
const f = fetchImpl || fetch;
try {
const r = await f(url, { headers: { Accept: "text/html,application/json" }, cache: "no-store" });
if (r && r.ok && typeof r.text === "function") return await r.text();
} catch { /* this page cannot read the host */ }
if (f === globalThis.fetch) {
const got = await originRead(url);
if (got && got.status >= 200 && got.status < 300 && got.text) return got.text;
}
return "";
}
export async function browserSearch(source, q, fetchImpl) {
const query = clean(q).slice(0, 200);
if (!query) return "";
const kind = String(source || "").trim().toLowerCase();
try {
if (kind === "wiki" || kind === "wikipedia") {
const url = "https://en.wikipedia.org/w/api.php?action=query&list=search&format=json&origin=*&srlimit=5&srnamespace=0&srprop=snippet&srsearch=" + encodeURIComponent(query);
const found = parseWikiSearch(await browserJSON(url, fetchImpl));
return formatHits(found.slice(0, 1));
}
if (kind === "duckduckgo" || kind === "ddg") {
const htmlURL = "https://html.duckduckgo.com/html/?q=" + encodeURIComponent(query);
let htmlHits = parseDdgHtml(await browserText(htmlURL, fetchImpl));
if (!htmlHits.length && canFrame(fetchImpl)) {
const got = await offscreenRead(htmlURL);
if (got && got.ok) htmlHits = parseDdgHtml(got.text);
}
if (htmlHits.length) return formatHits(htmlHits);
const url = "https://api.duckduckgo.com/?q=" + encodeURIComponent(query) + "&format=json&no_html=1&no_redirect=1&skip_disambig=1";
const instant = formatHits(parseDdgInstant(await browserJSON(url, fetchImpl)));
if (instant) return instant;
// This host already searches when the browser cannot read the results page.
return serverLookup("/api/ext/search", { q: query, source: "duckduckgo" }, fetchImpl);
}
} catch {
return "";
}
return "";
}
export async function browserGather(raw, fetchImpl) {
const title = wikiTitle(raw);
try {
if (title) {
const url = "https://en.wikipedia.org/w/api.php?action=query&prop=extracts&explaintext=1&exsectionformat=plain&redirects=1&format=json&origin=*&titles=" + encodeURIComponent(title);
const text = parseWikiExtract(await browserJSON(url, fetchImpl));
return { output: text, exit_code: text ? 0 : 1 };
}
if (!allowedPage(raw)) return { output: "That address is not available.", exit_code: 1 };
let text = articleFromHTML(await browserText(raw, fetchImpl));
if (!text && canFrame(fetchImpl)) {
const got = await offscreenRead(raw);
if (got && got.text) text = articleFromHTML(got.text);
}
if (!text) text = await serverLookup("/api/ext/gather", { url: raw }, fetchImpl);
return { output: text, exit_code: text ? 0 : 1 };
} catch {
return { output: "", exit_code: 1 };
}
}