Spaces:
Running
Running
File size: 9,963 Bytes
5f0ea8d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 | // Network layer for the page-reading and search tools. Order, cheapest and most private first:
// 1. direct fetch() the visitor's own (residential) IP; works only when the site sends CORS headers (APIs, Wikipedia, ...)
// 2. libcurl.js libcurl compiled to WebAssembly: it speaks TLS itself and tunnels TCP over a public WISP relay (a WebSocket
// proxy), so it needs no CORS permission, returns the raw HTML and may set any header, User-Agent included.
// Traffic then leaves from the relay's IP, which is why it only runs when step 1 failed. The TLS handshake
// is inside the WebAssembly, so a relay sees which host is contacted, not the content.
// (Jina Reader, defuddle.md and the Wayback Machine are tried by tools.js when both of these fail.)
// The retry policy follows sharp-search (github.com/Belluxx/sharp-search, MIT): Safari-like request first; on 202/401/403/405/429 or a
// bot-check page, retry as the link-preview crawlers many sites let through; keep whichever answer has the most text.
export const SAFARI_UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Safari/605.1.15';
export const BOT_UAS = ['facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)', 'Slackbot-LinkExpanding 1.0 (+https://api.slack.com/robots)', 'Twitterbot/1.0'];
const REFUSALS = new Set([202, 401, 403, 405, 429]);
export const CHALLENGE = /(id="anubis_version"|anubis_challenge|making sure you(?:'|')re not a bot|_incapsula_resource|ak_bmsc|attention required! \| cloudflare|cf-browser-verification|just a moment\.\.\.|challenge-platform|captcha-delivery\.com|px-captcha)/i;
// Public WISP relays (volunteer-run). Shuffled once per visit so no single relay takes everyone's traffic.
const RELAYS = ['wss://wisp.mercurywork.shop/', 'wss://anura.pro/', 'wss://fern.best/', 'wss://wisp.terbiumon.top/wisp/', 'wss://tomp.app/wisp',
'wss://nebulaservices.org/wisp/', 'wss://relay.widgetry.org/', 'wss://linuxontab-net.fly.dev/wisp'].sort(() => Math.random() - 0.5);
let relayAt = 0;
const relay = () => RELAYS[relayAt % RELAYS.length];
function hopRelay() { // a different relay is a different exit IP
relayAt++;
try { lc().set_websocket(relay()); return true; } catch { return false; }
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const aborted = (signal) => { if (signal?.aborted) throw new DOMException('Stopped', 'AbortError'); };
const withTimeout = (signal, ms) => { // AbortSignal.any is not in every browser yet
const c = new AbortController(), t = setTimeout(() => c.abort(), ms), on = () => c.abort();
signal?.addEventListener('abort', on, { once: true });
return { signal: c.signal, done: () => { clearTimeout(t); signal?.removeEventListener('abort', on); } };
};
// ------------------------------------------------------------------------------------------ libcurl.js loader
let curlReady = null, curlDead = false;
const lc = () => (typeof libcurl !== 'undefined' ? libcurl : null); // libcurl.js declares a top-level `const libcurl`: it is a global binding, not a window property
export function ensureLibcurl() { // the <script> tag in index.html may finish before or after we ask: handle both, with a timeout
if (curlDead) return Promise.reject(new Error('libcurl.js unavailable'));
return (curlReady ||= (async () => {
const limit = (p, ms, what) => Promise.race([p, new Promise((_, rej) => setTimeout(() => rej(new Error(what)), ms))]);
await limit(new Promise((res) => { if (lc()) return res(); const iv = setInterval(() => { if (lc()) { clearInterval(iv); res(); } }, 100); }), 12000, 'libcurl.js did not load (blocked CDN?)');
await limit(lc().load_wasm('libcurl.wasm'), 12000, 'libcurl.js wasm did not start');
lc().set_websocket(relay());
})().catch((e) => { curlDead = true; throw e; }));
}
// ------------------------------------------------------------------------------------------ fetching
const visibleLen = (t) => t.replace(/<(script|style)[\s\S]*?<\/\1>/gi, '').replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim().length;
const bad = (status, text) => REFUSALS.has(status) || status >= 500 || CHALLENGE.test(text.slice(0, 6000));
async function direct(url, signal, ms = 8000) {
const t = withTimeout(signal, ms);
try { const r = await fetch(url, { signal: t.signal, headers: { Accept: 'text/html,application/json,*/*;q=0.8' } }); return { status: r.status, text: await r.text(), how: 'direct' }; }
finally { t.done(); }
}
async function viaCurl(url, ua, signal, ms = 20000) {
const t = withTimeout(signal, ms);
try {
const r = await lc().fetch(url, { signal: t.signal, headers: { 'User-Agent': ua, Accept: 'text/html,application/xhtml+xml,application/json;q=0.9,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.9' } });
return { status: r.status, text: await r.text(), how: 'libcurl', ua: ua.split(/[\/ ]/)[0] };
} finally { t.done(); }
}
// Returns { status, text, how, tried } for the best answer found, or { status: 0, text: '', tried } when every route failed.
export async function rawFetch(url, { signal, direct: tryDirect = true, deadline = 75000 } = {}) {
const tried = [], t0 = Date.now(), over = () => Date.now() - t0 > deadline;
const stopped = (e) => { if (e?.name === 'AbortError' && signal?.aborted) throw e; };
if (tryDirect) {
try { const r = await direct(url, signal); tried.push(`direct HTTP ${r.status}`); if (r.status < 400 && r.text.trim() && !CHALLENGE.test(r.text.slice(0, 6000))) return { ...r, tried }; }
catch (e) { stopped(e); tried.push('direct blocked by CORS'); }
}
try { await ensureLibcurl(); } catch (e) { tried.push(String(e.message || e)); return { status: 0, text: '', tried }; }
let best = null, hops = 0, i = 0;
const ladder = [SAFARI_UA, ...BOT_UAS];
while (i < ladder.length && !over()) {
aborted(signal);
const ua = ladder[i];
let r;
try { r = await viaCurl(url, ua, signal); }
catch (e) { // relay down or TLS refused: another relay, same user agent
stopped(e); tried.push(`libcurl ${ua.split(/[\/ ]/)[0]}: ${String(e?.message || e).slice(0, 40)}`);
if (hops++ < 3 && hopRelay()) continue;
i++; continue;
}
tried.push(`libcurl ${r.ua} HTTP ${r.status}`);
if (r.status >= 500 && hops++ < 3 && hopRelay()) continue;
const ok = r.status < 400 && r.text.trim() && !CHALLENGE.test(r.text.slice(0, 6000));
if (ok && (!best || visibleLen(r.text) > visibleLen(best.text))) best = r;
if (ok && visibleLen(r.text) >= 500) break; // real content: done. Sparse page: a crawler user agent may be served the full text, keep trying
if (bad(r.status, r.text) && i === ladder.length - 1 && hops++ < 3 && hopRelay()) { i = 0; continue; } // all user agents refused: new exit IP, start over
i++;
}
return best ? { ...best, tried } : { status: 0, text: '', tried };
}
// ------------------------------------------------------------------------------------------ HTML -> markdown
const SKIP = new Set(['SCRIPT', 'STYLE', 'NOSCRIPT', 'SVG', 'IFRAME', 'TEMPLATE', 'NAV', 'FOOTER', 'ASIDE', 'FORM', 'BUTTON', 'SELECT', 'HEAD', 'DIALOG']);
const BLOCK = new Set(['P', 'DIV', 'SECTION', 'ARTICLE', 'MAIN', 'HEADER', 'UL', 'OL', 'LI', 'TABLE', 'TR', 'BLOCKQUOTE', 'PRE', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'FIGURE', 'DL', 'DT', 'DD', 'HR', 'BR']);
function abs(href, base) { try { const u = new URL(href, base); return /^https?:$/.test(u.protocol) ? u.href : ''; } catch { return ''; } }
export function htmlToMarkdown(html, base) {
const doc = new DOMParser().parseFromString(html, 'text/html');
const title = (doc.querySelector('title')?.textContent || '').replace(/\s+/g, ' ').trim();
const roots = [...doc.querySelectorAll('main, article, [role=main]')].sort((a, b) => b.textContent.length - a.textContent.length);
const root = roots[0] && roots[0].textContent.trim().length > 600 ? roots[0] : doc.body;
let out = '';
const walk = (n, ctx = {}) => {
if (n.nodeType === 3) { out += ctx.pre ? n.nodeValue : n.nodeValue.replace(/\s+/g, ' '); return; }
if (n.nodeType !== 1 || SKIP.has(n.tagName.toUpperCase()) || n.hasAttribute('hidden') || n.getAttribute('aria-hidden') === 'true') return;
const t = n.tagName.toUpperCase();
if (t === 'A') {
const href = abs(n.getAttribute('href') || '', base), label = n.textContent.replace(/\s+/g, ' ').trim();
if (!label) return;
if (href && !href.startsWith('javascript:') && !(n.getAttribute('href') || '').startsWith('#')) out += `[${label}](${href})`; else out += label;
return;
}
if (/^H[1-6]$/.test(t)) { out += `\n\n${'#'.repeat(+t[1])} `; n.childNodes.forEach((c) => walk(c, ctx)); out += '\n\n'; return; }
if (t === 'LI') { out += '\n- '; n.childNodes.forEach((c) => walk(c, ctx)); return; }
if (t === 'PRE') { out += '\n\n```\n'; n.childNodes.forEach((c) => walk(c, { ...ctx, pre: true })); out += '\n```\n\n'; return; }
if (t === 'TD' || t === 'TH') { n.childNodes.forEach((c) => walk(c, ctx)); out += ' | '; return; }
if (t === 'BLOCKQUOTE') { out += '\n\n> '; n.childNodes.forEach((c) => walk(c, ctx)); out += '\n\n'; return; }
if (t === 'IMG') { const alt = (n.getAttribute('alt') || '').trim(); if (alt.length > 3) out += `[image: ${alt}]`; return; }
const block = BLOCK.has(t);
if (block) out += t === 'BR' ? '\n' : '\n';
n.childNodes.forEach((c) => walk(c, ctx));
if (block && t !== 'BR') out += '\n';
};
walk(root);
const body = out.replace(/[ \t]+\n/g, '\n').replace(/\n[ \t]+/g, '\n').replace(/ {2,}/g, ' ').replace(/\n{3,}/g, '\n\n').trim();
return (title ? `Title: ${title}\n\nURL Source: ${base}\n\nMarkdown Content:\n` : `URL Source: ${base}\n\nMarkdown Content:\n`) + body;
}
|