Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(news): native crypto-news aggregation + historical archive API

nirholasabf891f44995
diff --git a/api/_lib/news-sources.js b/api/_lib/news-sources.js
new file mode 100644
index 000000000..18a728478
--- /dev/null
+++ b/api/_lib/news-sources.js
@@ -0,0 +1,93 @@
+// Crypto-news source registry — ported from the cryptocurrency.cv aggregator
+// (same team; its Vercel deployment is retired, so three.ws now runs the
+// aggregation natively). Every entry is a real public RSS/Atom feed. Keys and
+// category names match the cryptocurrency.cv registry so archive records
+// (source_key) and live records line up.
+//
+// Categories are the canonical filter set exposed by /api/news/feed and the
+// /markets/news tabs. Keep them lowercase; the UI owns display labels.
+
+export const NEWS_SOURCES = {
+ // ── Tier 1: major outlets ────────────────────────────────────────────────
+ coindesk: { name: 'CoinDesk', url: 'https://www.coindesk.com/arc/outboundfeeds/rss/', category: 'general' },
+ theblock: { name: 'The Block', url: 'https://www.theblock.co/rss.xml', category: 'general' },
+ decrypt: { name: 'Decrypt', url: 'https://decrypt.co/feed', category: 'general' },
+ cointelegraph: { name: 'CoinTelegraph', url: 'https://cointelegraph.com/rss', category: 'general' },
+ blockworks: { name: 'Blockworks', url: 'https://blockworks.co/feed', category: 'general' },
+ cryptoslate: { name: 'CryptoSlate', url: 'https://cryptoslate.com/feed/', category: 'general' },
+ newsbtc: { name: 'NewsBTC', url: 'https://www.newsbtc.com/feed/', category: 'general' },
+ dailyhodl: { name: 'The Daily Hodl', url: 'https://dailyhodl.com/feed/', category: 'general' },
+ coinjournal: { name: 'CoinJournal', url: 'https://coinjournal.net/feed/', category: 'general' },
+ cryptopotato: { name: 'CryptoPotato', url: 'https://cryptopotato.com/feed/', category: 'general' },
+
+ // ── Bitcoin ──────────────────────────────────────────────────────────────
+ bitcoinmagazine: { name: 'Bitcoin Magazine', url: 'https://bitcoinmagazine.com/.rss/full/', category: 'bitcoin' },
+ bitcoinist: { name: 'Bitcoinist', url: 'https://bitcoinist.com/feed/', category: 'bitcoin' },
+
+ // ── Ethereum + L2 ────────────────────────────────────────────────────────
+ daily_gwei: { name: 'The Daily Gwei', url: 'https://thedailygwei.substack.com/feed', category: 'ethereum' },
+ optimism_blog: { name: 'Optimism', url: 'https://optimism.mirror.xyz/feed/atom', category: 'layer2' },
+ arbitrum_blog: { name: 'Arbitrum', url: 'https://arbitrum.io/blog/rss.xml', category: 'layer2' },
+ base_blog: { name: 'Base', url: 'https://base.mirror.xyz/feed/atom', category: 'layer2' },
+
+ // ── Solana ───────────────────────────────────────────────────────────────
+ solana_news: { name: 'Solana News', url: 'https://solana.com/news/rss.xml', category: 'solana' },
+
+ // ── DeFi / NFT ───────────────────────────────────────────────────────────
+ defiant: { name: 'The Defiant', url: 'https://thedefiant.io/feed', category: 'defi' },
+ nftnow: { name: 'NFT Now', url: 'https://nftnow.com/feed/', category: 'nft' },
+
+ // ── Trading / research / on-chain ────────────────────────────────────────
+ beincrypto: { name: 'BeInCrypto', url: 'https://beincrypto.com/feed/', category: 'trading' },
+ u_today: { name: 'U.Today', url: 'https://u.today/rss', category: 'trading' },
+ messari: { name: 'Messari', url: 'https://messari.io/rss', category: 'research' },
+ glassnode: { name: 'Glassnode Insights', url: 'https://insights.glassnode.com/rss/', category: 'research' },
+ cryptobriefing: { name: 'Crypto Briefing', url: 'https://cryptobriefing.com/feed/', category: 'research' },
+ intotheblock: { name: 'IntoTheBlock', url: 'https://medium.com/feed/intotheblock', category: 'onchain' },
+ coin_metrics: { name: 'Coin Metrics', url: 'https://coinmetrics.substack.com/feed', category: 'onchain' },
+
+ // ── Institutional / mainstream ───────────────────────────────────────────
+ coinbase_blog: { name: 'Coinbase Blog', url: 'https://www.coinbase.com/blog/rss.xml', category: 'institutional' },
+ binance_blog: { name: 'Binance Blog', url: 'https://www.binance.com/en/blog/rss.xml', category: 'institutional' },
+ kraken_blog: { name: 'Kraken Blog', url: 'https://blog.kraken.com/feed/', category: 'institutional' },
+ cnbc_crypto: { name: 'CNBC Crypto', url: 'https://www.cnbc.com/id/100727362/device/rss/rss.html', category: 'mainstream' },
+ techcrunch_crypto: { name: 'TechCrunch Crypto', url: 'https://techcrunch.com/category/cryptocurrency/feed/', category: 'mainstream' },
+
+ // ── Asia ─────────────────────────────────────────────────────────────────
+ wu_blockchain: { name: 'Wu Blockchain', url: 'https://wublock.substack.com/feed', category: 'asia' },
+ forkast: { name: 'Forkast News', url: 'https://forkast.news/feed/', category: 'asia' },
+
+ // ── Regulation / policy ──────────────────────────────────────────────────
+ sec_press: { name: 'SEC Press Releases', url: 'https://www.sec.gov/news/pressreleases.rss', category: 'regulation' },
+ coincenter: { name: 'Coin Center', url: 'https://www.coincenter.org/feed/', category: 'regulation' },
+
+ // ── Independent journalism ───────────────────────────────────────────────
+ protos: { name: 'Protos', url: 'https://protos.com/feed/', category: 'journalism' },
+ milkroad: { name: 'Milk Road', url: 'https://www.milkroad.com/feed/', category: 'journalism' },
+ unchained_crypto: { name: 'Unchained', url: 'https://unchainedcrypto.com/feed/', category: 'journalism' },
+};
+
+// Canonical category order for filter UIs. 'all' is implicit.
+export const NEWS_CATEGORIES = [
+ 'general',
+ 'bitcoin',
+ 'ethereum',
+ 'layer2',
+ 'solana',
+ 'defi',
+ 'nft',
+ 'trading',
+ 'research',
+ 'onchain',
+ 'institutional',
+ 'mainstream',
+ 'asia',
+ 'regulation',
+ 'journalism',
+];
+
+export function sourcesForCategory(category) {
+ const keys = Object.keys(NEWS_SOURCES);
+ if (!category || category === 'all') return keys;
+ return keys.filter((k) => NEWS_SOURCES[k].category === category);
+}
diff --git a/api/_lib/news.js b/api/_lib/news.js
new file mode 100644
index 000000000..cecd1a910
--- /dev/null
+++ b/api/_lib/news.js
@@ -0,0 +1,278 @@
+// Native crypto-news aggregation — the engine behind /api/news/feed, the
+// related-news rail on /coin/:id, and the /markets surfaces. Ported from the
+// cryptocurrency.cv aggregator (same team) after its Vercel deployment was
+// retired; three.ws now fetches the source RSS/Atom feeds directly.
+//
+// Design: per-source in-memory cache (5 min TTL) with serve-stale-on-error —
+// one slow or dead feed never blanks the page, and repeat requests within the
+// TTL cost zero upstream calls. Every article is real, parsed from the
+// publisher's own feed; nothing is fabricated.
+
+import { createHash } from 'node:crypto';
+import { XMLParser } from 'fast-xml-parser';
+import { NEWS_SOURCES, sourcesForCategory } from './news-sources.js';
+
+const FEED_TIMEOUT_MS = 7000;
+const FRESH_MS = 300_000; // refetch a source after 5 min
+const STALE_OK_MS = 24 * 3600_000; // serve a failed source's last-good copy up to 24h
+
+// key → { articles, fetchedAt, ok }
+const sourceCache = new Map();
+// de-duplicated in-flight refreshes so concurrent requests share one fetch
+const inflight = new Map();
+
+const str = (v) => (typeof v === 'string' && v.trim() ? v.trim() : null);
+
+export function stripHtml(s) {
+ return String(s || '')
+ .replace(/<[^>]+>/g, ' ')
+ .replace(/&nbsp;/g, ' ')
+ .replace(/&amp;/g, '&')
+ .replace(/&lt;/g, '<')
+ .replace(/&gt;/g, '>')
+ .replace(/&quot;/g, '"')
+ .replace(/&#0?39;|&apos;/g, "'")
+ .replace(/&#8217;|&rsquo;/g, "'")
+ .replace(/&#8220;|&#8221;|&ldquo;|&rdquo;/g, '"')
+ .replace(/&#8211;|&ndash;|&#8212;|&mdash;/g, '—')
+ .replace(/\s+/g, ' ')
+ .trim();
+}
+
+// Same 16-hex content-addressed ID scheme as the historical archive, so live
+// and archived records share an identity space.
+export function articleId(link) {
+ return createHash('sha256').update(String(link)).digest('hex').slice(0, 16);
+}
+
+// ── Sentiment (lexicon) ──────────────────────────────────────────────────────
+// Fast keyword sentiment matching the archive's { score, label, confidence }
+// shape. Used for live articles, which arrive without the offline enrichment
+// the 662k archived records carry.
+
+const POSITIVE = [
+ 'surge', 'surges', 'soar', 'soars', 'rally', 'rallies', 'jump', 'jumps', 'gain', 'gains',
+ 'all-time high', 'ath', 'record high', 'breakout', 'bullish', 'adoption', 'approval',
+ 'approve', 'approved', 'partnership', 'integration', 'launch', 'launches', 'upgrade',
+ 'milestone', 'inflow', 'inflows', 'accumulate', 'accumulation', 'outperform', 'recovery',
+ 'rebound', 'green', 'wins', 'settle', 'settlement approved',
+];
+const NEGATIVE = [
+ 'crash', 'crashes', 'plunge', 'plunges', 'dump', 'dumps', 'selloff', 'sell-off', 'slump',
+ 'hack', 'hacked', 'exploit', 'exploited', 'breach', 'stolen', 'scam', 'fraud', 'lawsuit',
+ 'sues', 'sued', 'charges', 'ban', 'bans', 'banned', 'crackdown', 'bearish', 'liquidation',
+ 'liquidations', 'outflow', 'outflows', 'bankruptcy', 'insolvent', 'collapse', 'warning',
+ 'red', 'drop', 'drops', 'falls', 'tumble', 'tumbles', 'rug pull', 'delist', 'delisting',
+];
+
+export function lexiconSentiment(text) {
+ const t = ` ${String(text || '').toLowerCase()} `;
+ let pos = 0;
+ let neg = 0;
+ for (const w of POSITIVE) if (t.includes(w)) pos++;
+ for (const w of NEGATIVE) if (t.includes(w)) neg++;
+ const hits = pos + neg;
+ if (!hits) return { score: 0, label: 'neutral', confidence: 0.5 };
+ const score = Math.max(-1, Math.min(1, (pos - neg) / Math.max(2, hits)));
+ const label =
+ score > 0.5 ? 'very_positive' : score > 0.1 ? 'positive' : score < -0.5 ? 'very_negative' : score < -0.1 ? 'negative' : 'neutral';
+ return { score: Number(score.toFixed(2)), label, confidence: Math.min(0.9, 0.5 + hits * 0.1) };
+}
+
+// ── Ticker extraction ────────────────────────────────────────────────────────
+// $SYMBOL mentions plus a wordlist of majors whose bare names/symbols are
+// unambiguous in crypto headlines.
+
+const TICKER_WORDS = new Map([
+ ['bitcoin', 'BTC'], ['btc', 'BTC'], ['ethereum', 'ETH'], ['eth', 'ETH'], ['ether', 'ETH'],
+ ['solana', 'SOL'], ['sol', 'SOL'], ['xrp', 'XRP'], ['ripple', 'XRP'], ['bnb', 'BNB'],
+ ['dogecoin', 'DOGE'], ['doge', 'DOGE'], ['cardano', 'ADA'], ['ada', 'ADA'],
+ ['tether', 'USDT'], ['usdt', 'USDT'], ['usdc', 'USDC'], ['avalanche', 'AVAX'],
+ ['avax', 'AVAX'], ['polkadot', 'DOT'], ['chainlink', 'LINK'], ['litecoin', 'LTC'],
+ ['polygon', 'MATIC'], ['tron', 'TRX'], ['shiba inu', 'SHIB'], ['shib', 'SHIB'],
+ ['sui', 'SUI'], ['aptos', 'APT'], ['near', 'NEAR'], ['arbitrum', 'ARB'], ['optimism', 'OP'],
+ ['pepe', 'PEPE'], ['bonk', 'BONK'], ['aave', 'AAVE'], ['uniswap', 'UNI'], ['maker', 'MKR'],
+ ['stellar', 'XLM'], ['monero', 'XMR'], ['cosmos', 'ATOM'], ['filecoin', 'FIL'],
+ ['hedera', 'HBAR'], ['injective', 'INJ'], ['celestia', 'TIA'], ['jito', 'JTO'],
+ ['jupiter', 'JUP'], ['worldcoin', 'WLD'], ['toncoin', 'TON'], ['hyperliquid', 'HYPE'],
+]);
+
+export function extractTickers(text) {
+ const found = new Set();
+ const t = String(text || '');
+ for (const m of t.matchAll(/\$([A-Z][A-Z0-9]{1,9})\b/g)) found.add(m[1]);
+ const lower = ` ${t.toLowerCase().replace(/[^a-z0-9$ ]/g, ' ')} `;
+ for (const [word, sym] of TICKER_WORDS) {
+ if (lower.includes(` ${word} `)) found.add(sym);
+ }
+ return [...found].slice(0, 8);
+}
+
+// ── Feed parsing ─────────────────────────────────────────────────────────────
+
+function firstImage(html) {
+ const m = String(html || '').match(/<img[^>]+src=["']([^"']+)["']/i);
+ return m ? m[1] : null;
+}
+
+function normalizeLink(it) {
+ // RSS: <link>url</link>. Atom: <link href="..."/> possibly an array with
+ // rel variants — prefer rel="alternate", else the first href.
+ if (typeof it?.link === 'string') return str(it.link);
+ if (it?.link?.['@href']) return str(it.link['@href']);
+ if (Array.isArray(it?.link)) {
+ const alt = it.link.find((l) => l?.['@rel'] === 'alternate' && l?.['@href']);
+ const any = it.link.find((l) => l?.['@href']);
+ return str(alt?.['@href']) || str(any?.['@href']);
+ }
+ return null;
+}
+
+export function parseFeed(xml, sourceKey) {
+ const src = NEWS_SOURCES[sourceKey];
+ const parser = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: '@' });
+ const doc = parser.parse(xml);
+ const items = doc?.rss?.channel?.item || doc?.feed?.entry || doc?.['rdf:RDF']?.item || [];
+ return (Array.isArray(items) ? items : [items])
+ .map((it) => {
+ const link = normalizeLink(it);
+ const title = stripHtml(str(it?.title?.['#text']) || str(it?.title) || '');
+ if (!link || !title) return null;
+ const rawDesc =
+ str(it?.description) ||
+ str(it?.summary?.['#text']) ||
+ str(it?.summary) ||
+ str(it?.['content:encoded']) ||
+ str(it?.content?.['#text']) ||
+ '';
+ const image =
+ str(it?.['media:content']?.['@url']) ||
+ (Array.isArray(it?.['media:content']) ? str(it['media:content'][0]?.['@url']) : null) ||
+ str(it?.['media:thumbnail']?.['@url']) ||
+ str(it?.enclosure?.['@url']) ||
+ firstImage(it?.['content:encoded'] || rawDesc);
+ const pubDate = str(it?.pubDate) || str(it?.published) || str(it?.updated) || str(it?.['dc:date']);
+ const iso = pubDate && !Number.isNaN(Date.parse(pubDate)) ? new Date(pubDate).toISOString() : null;
+ const author =
+ stripHtml(str(it?.['dc:creator']) || str(it?.author?.name) || str(it?.author) || '') || null;
+ const description = stripHtml(rawDesc).slice(0, 320) || null;
+ return {
+ id: articleId(link),
+ title,
+ link,
+ description,
+ image,
+ author,
+ source: src?.name || sourceKey,
+ source_key: sourceKey,
+ category: src?.category || 'general',
+ pub_date: iso,
+ tickers: extractTickers(`${title} ${description || ''}`),
+ sentiment: lexiconSentiment(`${title} ${description || ''}`),
+ };
+ })
+ .filter(Boolean);
+}
+
+async function fetchSource(key) {
+ const src = NEWS_SOURCES[key];
+ const resp = await fetch(src.url, {
+ headers: {
+ accept: 'application/rss+xml, application/atom+xml, application/xml, text/xml;q=0.9, */*;q=0.8',
+ 'user-agent': 'Mozilla/5.0 (compatible; three.ws-news/1.0; +https://three.ws)',
+ },
+ signal: AbortSignal.timeout(FEED_TIMEOUT_MS),
+ redirect: 'follow',
+ });
+ if (!resp.ok) throw new Error(`${key} ${resp.status}`);
+ return parseFeed(await resp.text(), key);
+}
+
+async function refreshSource(key) {
+ if (inflight.has(key)) return inflight.get(key);
+ const p = fetchSource(key)
+ .then((articles) => {
+ sourceCache.set(key, { articles, fetchedAt: Date.now(), ok: true });
+ return articles;
+ })
+ .catch(() => {
+ const prev = sourceCache.get(key);
+ if (prev) {
+ // keep last-good copy but mark the failure time so we retry next call
+ sourceCache.set(key, { ...prev, fetchedAt: Date.now(), ok: false });
+ return prev.articles;
+ }
+ sourceCache.set(key, { articles: [], fetchedAt: Date.now(), ok: false });
+ return [];
+ })
+ .finally(() => inflight.delete(key));
+ inflight.set(key, p);
+ return p;
+}
+
+async function ensureSources(keys) {
+ const now = Date.now();
+ await Promise.all(
+ keys.map((key) => {
+ const hit = sourceCache.get(key);
+ if (hit && now - hit.fetchedAt < FRESH_MS) return null;
+ return refreshSource(key);
+ }),
+ );
+ return keys.flatMap((key) => {
+ const hit = sourceCache.get(key);
+ if (!hit) return [];
+ // drop sources whose last-good copy is ancient — stale beyond 24h reads as fake-live
+ if (!hit.ok && now - hit.fetchedAt > STALE_OK_MS) return [];
+ return hit.articles;
+ });
+}
+
+function dedupe(articles) {
+ const seen = new Set();
+ const out = [];
+ for (const a of articles) {
+ const titleKey = a.title.toLowerCase().replace(/[^a-z0-9]/g, '').slice(0, 80);
+ if (seen.has(a.id) || (titleKey && seen.has(titleKey))) continue;
+ seen.add(a.id);
+ if (titleKey) seen.add(titleKey);
+ out.push(a);
+ }
+ return out;
+}
+
+/**
+ * Aggregate live news across the registry.
+ * @param {object} opts { category, source, q, limit, offset }
+ * @returns {{ articles: Array, total: number, sources_ok: number, sources_total: number }}
+ */
+export async function getNews({ category, source, q, limit = 30, offset = 0 } = {}) {
+ let keys;
+ if (source && NEWS_SOURCES[source]) keys = [source];
+ else if (source) return { articles: [], total: 0, sources_ok: 0, sources_total: 0 };
+ else keys = sourcesForCategory(category);
+
+ const all = await ensureSources(keys);
+ let articles = dedupe(all).sort(
+ (a, b) => new Date(b.pub_date || 0) - new Date(a.pub_date || 0),
+ );
+ if (q) {
+ const needle = q.toLowerCase();
+ articles = articles.filter((a) =>
+ `${a.title} ${a.description || ''} ${a.tickers.join(' ')}`.toLowerCase().includes(needle),
+ );
+ }
+ const total = articles.length;
+ const sources_ok = keys.filter((k) => sourceCache.get(k)?.ok).length;
+ return {
+ articles: articles.slice(offset, offset + limit),
+ total,
+ sources_ok,
+ sources_total: keys.length,
+ };
+}
+
+/** Search all sources — used by the /coin/:id related-news rail. */
+export async function searchNews(q, limit = 8) {
+ return getNews({ q, limit });
+}
diff --git a/api/news/archive.js b/api/news/archive.js
new file mode 100644
index 000000000..3b9b1b291
--- /dev/null
+++ b/api/news/archive.js
@@ -0,0 +1,306 @@
+// GET /api/news/archive
+// ---------------------------------------------------------------------------
+// The three.ws historical crypto-news archive: 662,047 enriched articles
+// spanning September 2017 → February 2026 (CryptoPanic english corpus +
+// Odaily chinese corpus + the cryptocurrency.cv live archiver), recovered
+// from the cryptocurrency.cv archive and hosted on the platform's own GCS
+// bucket (gs://three-ws-news-archive). Largest free crypto-news dataset
+// anywhere; every record carries tickers, tags, sentiment, language, and
+// (where captured) market context at publication time.
+//
+// Data layout (public bucket, gzip at rest, transparently decoded):
+// articles/YYYY-MM.jsonl one enriched article per line
+// meta/stats.json corpus-wide statistics
+// indexes/by-{date,source,ticker}.json
+//
+// Modes:
+// ?stats=true corpus statistics + available month range
+// ?months=true list of queryable months
+// ?trending=true top tickers over the newest archived weeks
+// default query mode — filters below
+//
+// Query params (query mode):
+// q full-text (title + description)
+// ticker e.g. BTC — matches the enriched tickers field
+// source source_key or source name substring
+// category enriched category
+// sentiment positive | negative | neutral
+// lang en | zh
+// start_date / end_date YYYY-MM-DD, bounds the month window
+// limit 1–100 (default 50), offset for pagination
+//
+// Serving model: newest-first month scan with early stop once the requested
+// page is filled, capped at MAX_MONTHS_PER_SCAN months per request. Parsed
+// months are LRU-cached in compact form so repeat queries are warm. The
+// response always reports exactly which months were scanned so the UI can be
+// honest about coverage ("narrow the date range to search older years").
+
+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+
+const GCS_BASE = 'https://storage.googleapis.com/three-ws-news-archive';
+const GCS_LIST =
+ 'https://storage.googleapis.com/storage/v1/b/three-ws-news-archive/o?prefix=articles/&fields=items(name)&maxResults=500';
+
+const MAX_MONTHS_PER_SCAN = 12;
+const MONTH_FETCH_CONCURRENCY = 3;
+const MONTH_CACHE_MAX = 5;
+
+// month "YYYY-MM" → compact article records (newest month files are ~2–11 MB
+// raw; compact form keeps only serving fields). LRU by Map insertion order.
+const monthCache = new Map();
+// small metadata caches: { value, expiresAt }
+let statsCache = null;
+let monthsCache = null;
+const META_TTL_MS = 3600_000;
+
+const str = (v) => (typeof v === 'string' && v.trim() ? v.trim() : null);
+
+function compact(a) {
+ return {
+ id: a.id,
+ title: a.title,
+ link: str(a.link) || str(a.canonical_link),
+ description: str(a.description) ? a.description.slice(0, 240) : null,
+ source: a.source || a.source_key || 'unknown',
+ source_key: a.source_key || 'unknown',
+ category: a.category || 'general',
+ pub_date: a.pub_date || a.first_seen || null,
+ tickers: Array.isArray(a.tickers) ? a.tickers.slice(0, 8) : [],
+ tags: Array.isArray(a.tags) ? a.tags.slice(0, 6) : [],
+ sentiment: a.sentiment ? { label: a.sentiment.label, score: a.sentiment.score } : null,
+ lang: a.meta?.language || 'en',
+ is_breaking: !!a.meta?.is_breaking,
+ market_context: a.market_context
+ ? {
+ btc_price: a.market_context.btc_price ?? null,
+ eth_price: a.market_context.eth_price ?? null,
+ fear_greed_index: a.market_context.fear_greed_index ?? null,
+ }
+ : null,
+ };
+}
+
+async function fetchJson(url, timeoutMs = 15_000) {
+ const resp = await fetch(url, {
+ headers: { accept: 'application/json' },
+ signal: AbortSignal.timeout(timeoutMs),
+ });
+ if (!resp.ok) throw new Error(`archive upstream ${resp.status}`);
+ return resp.json();
+}
+
+async function getStats() {
+ if (statsCache && statsCache.expiresAt > Date.now()) return statsCache.value;
+ const value = await fetchJson(`${GCS_BASE}/meta/stats.json`);
+ statsCache = { value, expiresAt: Date.now() + META_TTL_MS };
+ return value;
+}
+
+async function getMonths() {
+ if (monthsCache && monthsCache.expiresAt > Date.now()) return monthsCache.value;
+ const listing = await fetchJson(GCS_LIST);
+ const value = (listing.items || [])
+ .map((o) => {
+ const m = /^articles\/(\d{4}-\d{2})\.jsonl$/.exec(o.name);
+ return m ? m[1] : null;
+ })
+ .filter(Boolean)
+ .sort(); // ascending YYYY-MM
+ if (!value.length) throw new Error('archive month listing is empty');
+ monthsCache = { value, expiresAt: Date.now() + META_TTL_MS };
+ return value;
+}
+
+async function loadMonth(month) {
+ if (monthCache.has(month)) {
+ const records = monthCache.get(month);
+ monthCache.delete(month);
+ monthCache.set(month, records); // refresh LRU recency
+ return records;
+ }
+ const resp = await fetch(`${GCS_BASE}/articles/${month}.jsonl`, {
+ signal: AbortSignal.timeout(30_000),
+ });
+ if (!resp.ok) throw new Error(`month ${month} → ${resp.status}`);
+ const text = await resp.text();
+ const records = [];
+ for (const line of text.split('\n')) {
+ if (!line.trim()) continue;
+ try {
+ records.push(compact(JSON.parse(line)));
+ } catch {
+ // skip the malformed line, keep the month
+ }
+ }
+ // newest-first inside the month so early-stop pagination is stable
+ records.sort((a, b) => new Date(b.pub_date || 0) - new Date(a.pub_date || 0));
+ monthCache.set(month, records);
+ while (monthCache.size > MONTH_CACHE_MAX) {
+ monthCache.delete(monthCache.keys().next().value);
+ }
+ return records;
+}
+
+function buildPredicate({ q, ticker, source, category, sentiment, lang, startDate, endDate }) {
+ const needle = q ? q.toLowerCase() : null;
+ const tickerUpper = ticker ? ticker.toUpperCase() : null;
+ const sourceLower = source ? source.toLowerCase() : null;
+ const startIso = startDate ? `${startDate}T00:00:00.000Z` : null;
+ const endIso = endDate ? `${endDate}T23:59:59.999Z` : null;
+ return (a) => {
+ if (tickerUpper && !a.tickers.includes(tickerUpper)) return false;
+ if (sourceLower && !a.source_key.toLowerCase().includes(sourceLower) && !a.source.toLowerCase().includes(sourceLower))
+ return false;
+ if (category && a.category !== category) return false;
+ if (lang && a.lang !== lang) return false;
+ if (sentiment) {
+ const label = a.sentiment?.label || 'neutral';
+ if (sentiment === 'positive' && !label.includes('positive')) return false;
+ if (sentiment === 'negative' && !label.includes('negative')) return false;
+ if (sentiment === 'neutral' && label !== 'neutral') return false;
+ }
+ if ((startIso || endIso) && !a.pub_date) return false;
+ if (startIso && a.pub_date < startIso) return false;
+ if (endIso && a.pub_date > endIso) return false;
+ if (needle && !`${a.title} ${a.description || ''}`.toLowerCase().includes(needle)) return false;
+ return true;
+ };
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.marketFeedIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const params = new URL(req.url, 'http://x').searchParams;
+
+ try {
+ if (params.get('stats') === 'true') {
+ const [stats, months] = await Promise.all([getStats(), getMonths()]);
+ return json(
+ res, 200,
+ {
+ stats: {
+ total_articles: stats.total_articles,
+ total_with_date: stats.total_with_date,
+ total_with_url: stats.total_with_url,
+ undated_articles: stats.total_articles - stats.total_with_date,
+ first_article_date: stats.first_article_date,
+ last_article_date: stats.last_article_date,
+ languages: ['en', 'zh'],
+ top_sources: Object.entries(stats.sources || {})
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, 30)
+ .map(([key, count]) => ({ key, count })),
+ },
+ months: { first: months[0], last: months[months.length - 1], count: months.length },
+ },
+ { 'cache-control': 'public, max-age=600, s-maxage=3600, stale-while-revalidate=86400' },
+ );
+ }
+
+ if (params.get('months') === 'true') {
+ const months = await getMonths();
+ return json(res, 200, { months }, {
+ 'cache-control': 'public, max-age=600, s-maxage=3600, stale-while-revalidate=86400',
+ });
+ }
+
+ if (params.get('trending') === 'true') {
+ const months = await getMonths();
+ const recent = months.slice(-2);
+ const counts = new Map();
+ for (const month of recent) {
+ for (const a of await loadMonth(month)) {
+ for (const t of a.tickers) counts.set(t, (counts.get(t) || 0) + 1);
+ }
+ }
+ const trending = [...counts.entries()]
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, 20)
+ .map(([ticker, count]) => ({ ticker, count }));
+ return json(res, 200, { trending, window: recent }, {
+ 'cache-control': 'public, max-age=600, s-maxage=3600, stale-while-revalidate=86400',
+ });
+ }
+
+ // ── query mode ─────────────────────────────────────────────────────────
+ const q = (params.get('q') || '').trim().slice(0, 120) || null;
+ const ticker = (params.get('ticker') || '').trim().slice(0, 12) || null;
+ const source = (params.get('source') || '').trim().slice(0, 40) || null;
+ const category = (params.get('category') || '').trim().toLowerCase() || null;
+ const sentiment = (params.get('sentiment') || '').trim().toLowerCase() || null;
+ const lang = (params.get('lang') || '').trim().toLowerCase() || null;
+ const startDate = (params.get('start_date') || '').trim() || null;
+ const endDate = (params.get('end_date') || '').trim() || null;
+ const limit = Math.min(Math.max(1, parseInt(params.get('limit') || '50', 10) || 50), 100);
+ const offset = Math.max(0, parseInt(params.get('offset') || '0', 10) || 0);
+
+ const dateRe = /^\d{4}-\d{2}-\d{2}$/;
+ if (startDate && !dateRe.test(startDate)) return error(res, 400, 'bad_date', 'start_date must be YYYY-MM-DD');
+ if (endDate && !dateRe.test(endDate)) return error(res, 400, 'bad_date', 'end_date must be YYYY-MM-DD');
+ if (startDate && endDate && startDate > endDate)
+ return error(res, 400, 'bad_range', 'start_date is after end_date');
+ if (sentiment && !['positive', 'negative', 'neutral'].includes(sentiment))
+ return error(res, 400, 'bad_sentiment', 'sentiment must be positive, negative, or neutral');
+ if (lang && !['en', 'zh'].includes(lang)) return error(res, 400, 'bad_lang', 'lang must be en or zh');
+
+ const allMonths = await getMonths();
+ let window = allMonths;
+ if (startDate) window = window.filter((m) => m >= startDate.slice(0, 7));
+ if (endDate) window = window.filter((m) => m <= endDate.slice(0, 7));
+ if (!window.length) {
+ return json(res, 200, {
+ articles: [], total_scanned_matches: 0, limit, offset,
+ scanned: { months: [], complete: true },
+ hint: 'no archive months inside that date range',
+ });
+ }
+ // newest → oldest
+ window = [...window].reverse();
+
+ const matches = buildPredicate({ q, ticker, source, category, sentiment, lang, startDate, endDate });
+ const need = offset + limit + 1; // +1 lets hasMore be exact within the scan
+ const scannedMonths = [];
+ let found = [];
+ for (let i = 0; i < window.length && scannedMonths.length < MAX_MONTHS_PER_SCAN; i += MONTH_FETCH_CONCURRENCY) {
+ const batch = window.slice(i, Math.min(i + MONTH_FETCH_CONCURRENCY, window.length))
+ .slice(0, MAX_MONTHS_PER_SCAN - scannedMonths.length);
+ const loaded = await Promise.all(batch.map((m) => loadMonth(m).catch(() => null)));
+ for (let b = 0; b < batch.length; b++) {
+ if (!loaded[b]) continue; // month failed to load; reported via scanned list
+ scannedMonths.push(batch[b]);
+ found = found.concat(loaded[b].filter(matches));
+ }
+ if (found.length >= need) break;
+ }
+
+ found.sort((a, b) => new Date(b.pub_date || 0) - new Date(a.pub_date || 0));
+ const monthsRemaining = window.length - scannedMonths.length;
+ const body = {
+ articles: found.slice(offset, offset + limit),
+ total_scanned_matches: found.length,
+ limit,
+ offset,
+ has_more: offset + limit < found.length || monthsRemaining > 0,
+ scanned: {
+ months: scannedMonths,
+ from: scannedMonths[scannedMonths.length - 1] || null,
+ to: scannedMonths[0] || null,
+ complete: monthsRemaining === 0,
+ months_remaining: monthsRemaining,
+ },
+ };
+ if (monthsRemaining > 0) {
+ body.hint = `scanned the newest ${scannedMonths.length} months of this range — add start_date/end_date to reach older articles`;
+ }
+ return json(res, 200, body, {
+ 'cache-control': 'public, max-age=120, s-maxage=300, stale-while-revalidate=3600',
+ });
+ } catch (err) {
+ return error(res, 502, 'archive_unavailable', `news archive is unreachable right now: ${err.message}`);
+ }
+});
diff --git a/api/news/feed.js b/api/news/feed.js
new file mode 100644
index 000000000..7e74a10b2
--- /dev/null
+++ b/api/news/feed.js
@@ -0,0 +1,72 @@
+// GET /api/news/feed
+// ---------------------------------------------------------------------------
+// Live aggregated crypto news across the native source registry
+// (api/_lib/news-sources.js — 37 first-party publisher feeds). Powers
+// /markets/news, the /markets hub strip, and anything else that wants a real
+// cross-source headline feed.
+//
+// Query params:
+// category one of NEWS_CATEGORIES (default: all)
+// source a single source_key (overrides category)
+// q case-insensitive full-text filter (title/description/tickers)
+// limit 1–50 (default 30)
+// offset pagination offset
+// meta=1 include the source registry + category list in the response
+//
+// Aggregation results are cached per source for 5 minutes inside
+// api/_lib/news.js, so this endpoint is cheap under load; CDN caches 120s.
+
+import { cors, json, method, wrap } from '../_lib/http.js';
+import { rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { getNews } from '../_lib/news.js';
+import { NEWS_SOURCES, NEWS_CATEGORIES } from '../_lib/news-sources.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.marketFeedIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const params = new URL(req.url, 'http://x').searchParams;
+ const category = (params.get('category') || '').trim().toLowerCase() || undefined;
+ const source = (params.get('source') || '').trim().toLowerCase() || undefined;
+ const q = (params.get('q') || '').trim().slice(0, 80) || undefined;
+ const limit = Math.min(Math.max(1, parseInt(params.get('limit') || '30', 10) || 30), 50);
+ const offset = Math.max(0, parseInt(params.get('offset') || '0', 10) || 0);
+
+ if (category && category !== 'all' && !NEWS_CATEGORIES.includes(category)) {
+ return json(res, 400, {
+ error: 'bad_category',
+ message: `unknown category "${category}"`,
+ categories: NEWS_CATEGORIES,
+ });
+ }
+ if (source && !NEWS_SOURCES[source]) {
+ return json(res, 400, { error: 'bad_source', message: `unknown source "${source}"` });
+ }
+
+ const result = await getNews({ category, source, q, limit, offset });
+
+ const body = {
+ articles: result.articles,
+ total: result.total,
+ limit,
+ offset,
+ sources_ok: result.sources_ok,
+ sources_total: result.sources_total,
+ fetched_at: new Date().toISOString(),
+ };
+ if (params.get('meta') === '1') {
+ body.categories = NEWS_CATEGORIES;
+ body.sources = Object.entries(NEWS_SOURCES).map(([key, s]) => ({
+ key,
+ name: s.name,
+ category: s.category,
+ }));
+ }
+ return json(res, 200, body, {
+ 'cache-control': 'public, max-age=60, s-maxage=120, stale-while-revalidate=600',
+ });
+});