From 512ab3bca611ee822e98a6cdf99e318c438366cd Mon Sep 17 00:00:00 2001 From: Artur Moreira Date: Thu, 2 Apr 2026 09:09:07 +0000 Subject: [PATCH] feat(writer-pipeline): multi-source ingest (RSS, sitemap, HTML) for BIT-711 - Add ingest-sources with retries, sitemap index/urlset parsing, and HTML meta extraction - Preserve original article URLs in store; dedupe ids via canonical URL hash - Extend andebol.net.sources.json: FPA, IHF RSS, Handball Planet, Eurohandball sitemap (filtered) - Optional shortlist ?topic= query; strip common tracking query params in canonicalUrl - Add npm test (node:test) for sitemap and html-meta helpers Paperclip-Agent: Tiago Neves (urlKey tiago-neves; id 5d084b36-f38f-42a5-a92a-520005afda4f) Paperclip-Issue: BIT-711 Paperclip-Run: 83b79f64-d6b6-4efd-ab06-c5cc7d687169 Made-with: Cursor --- .../config/andebol.net.sources.json | 32 +- writer-pipeline/package.json | 1 + writer-pipeline/src/aggregator-server.ts | 7 +- writer-pipeline/src/config-load.ts | 7 +- writer-pipeline/src/html-meta.test.ts | 24 ++ writer-pipeline/src/html-meta.ts | 43 +++ writer-pipeline/src/http-retry.ts | 45 +++ writer-pipeline/src/ingest-sources.ts | 305 ++++++++++++++++++ writer-pipeline/src/rss-ingest.ts | 102 +----- writer-pipeline/src/sitemap-parse.test.ts | 38 +++ writer-pipeline/src/sitemap-parse.ts | 49 +++ writer-pipeline/src/store.ts | 23 +- writer-pipeline/src/types.ts | 26 +- 13 files changed, 598 insertions(+), 104 deletions(-) create mode 100644 writer-pipeline/src/html-meta.test.ts create mode 100644 writer-pipeline/src/html-meta.ts create mode 100644 writer-pipeline/src/http-retry.ts create mode 100644 writer-pipeline/src/ingest-sources.ts create mode 100644 writer-pipeline/src/sitemap-parse.test.ts create mode 100644 writer-pipeline/src/sitemap-parse.ts diff --git a/writer-pipeline/config/andebol.net.sources.json b/writer-pipeline/config/andebol.net.sources.json index f72f3a7..40e73c8 100644 --- a/writer-pipeline/config/andebol.net.sources.json +++ b/writer-pipeline/config/andebol.net.sources.json @@ -1,11 +1,39 @@ { "site": "andebol.net", - "feeds": [ + "sources": [ { "id": "fpa_portal_main", + "kind": "rss", "url": "https://portal.fpa.pt/feed/", "enabled": true, - "note": "FPA portal WordPress main feed (category /noticias/feed is empty). Add more feeds as needed; failures are skipped per source." + "topics": ["handball", "pt", "fpa"], + "note": "FPA portal WordPress main feed." + }, + { + "id": "ihf_rss", + "kind": "rss", + "url": "https://www.ihf.info/rss.xml", + "enabled": true, + "topics": ["handball", "ihf", "international"], + "note": "IHF official RSS (verified 200)." + }, + { + "id": "handball_planet", + "kind": "rss", + "url": "https://www.handball-planet.com/feed/", + "enabled": true, + "topics": ["handball", "media"], + "note": "Handball Planet WordPress feed (use www host — redirect stable)." + }, + { + "id": "eurohandball_sitemap", + "kind": "sitemap", + "url": "https://www.eurohandball.com/sitemap.xml", + "enabled": true, + "topics": ["handball", "ehf"], + "maxItems": 25, + "pathIncludes": ["/competitions/", "/news/", "/calendar/", "/match-center/"], + "note": "EHF/Eurohandball: main sitemap is huge; path filter skips /club/ noise; pages fetched for title/summary (no LLM)." } ] } diff --git a/writer-pipeline/package.json b/writer-pipeline/package.json index a3195e4..b46aa42 100644 --- a/writer-pipeline/package.json +++ b/writer-pipeline/package.json @@ -7,6 +7,7 @@ "scripts": { "build": "tsc", "typecheck": "tsc --noEmit", + "test": "npm run build && node --test dist/*.test.js", "aggregator": "node dist/aggregator-server.js", "aggregator:dev": "tsx src/aggregator-server.ts", "cycle": "node dist/run-cycle.js", diff --git a/writer-pipeline/src/aggregator-server.ts b/writer-pipeline/src/aggregator-server.ts index 73d1627..b5405bc 100644 --- a/writer-pipeline/src/aggregator-server.ts +++ b/writer-pipeline/src/aggregator-server.ts @@ -20,13 +20,14 @@ async function buildServer() { app.get('/health', async () => ({ ok: true, storePath })); app.get<{ - Querystring: { site?: string; limit?: string }; + Querystring: { site?: string; limit?: string; topic?: string }; }>('/shortlist', async (req) => { const site = req.query.site ?? 'andebol.net'; const limit = Math.min(50, Math.max(1, parseInt(req.query.limit ?? '10', 10))); + const topic = req.query.topic?.trim() || undefined; const store = await loadStore(storePath); - const items = shortlist(store, site, limit); - return { site, limit, count: items.length, items }; + const items = shortlist(store, site, limit, topic); + return { site, limit, topic: topic ?? null, count: items.length, items }; }); app.post<{ diff --git a/writer-pipeline/src/config-load.ts b/writer-pipeline/src/config-load.ts index b5b4469..80169ca 100644 --- a/writer-pipeline/src/config-load.ts +++ b/writer-pipeline/src/config-load.ts @@ -4,8 +4,11 @@ import type { SiteSourcesConfig } from './types.js'; export async function readSourcesConfig(filePath: string): Promise { const raw = await readFile(filePath, 'utf8'); const data = JSON.parse(raw) as SiteSourcesConfig; - if (!data?.site || !Array.isArray(data.feeds)) { - throw new Error(`Invalid sources config: ${filePath}`); + if (!data?.site) throw new Error(`Invalid sources config (missing site): ${filePath}`); + const hasSources = Array.isArray(data.sources) && data.sources.length > 0; + const hasFeeds = Array.isArray(data.feeds) && data.feeds.length > 0; + if (!hasSources && !hasFeeds) { + throw new Error(`Invalid sources config: need non-empty sources or feeds (${filePath})`); } return data; } diff --git a/writer-pipeline/src/html-meta.test.ts b/writer-pipeline/src/html-meta.test.ts new file mode 100644 index 0000000..e22e23f --- /dev/null +++ b/writer-pipeline/src/html-meta.test.ts @@ -0,0 +1,24 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { extractTitleAndSummary } from './html-meta.js'; + +test('extractTitleAndSummary prefers og tags', () => { + const html = ` + + + Ignore me + `; + const r = extractTitleAndSummary(html); + assert.equal(r.title, 'OG & Title'); + assert.ok(r.summary.includes('Hello world')); +}); + +test('extractTitleAndSummary falls back to title and meta description', () => { + const html = ` + Plain title + + `; + const r = extractTitleAndSummary(html); + assert.equal(r.title, 'Plain title'); + assert.ok(r.summary.includes('Desc here')); +}); diff --git a/writer-pipeline/src/html-meta.ts b/writer-pipeline/src/html-meta.ts new file mode 100644 index 0000000..8c45768 --- /dev/null +++ b/writer-pipeline/src/html-meta.ts @@ -0,0 +1,43 @@ +/** + * Lightweight title/description extraction (no DOM / cheerio). + */ +export function extractTitleAndSummary(html: string): { title: string; summary: string } { + const ogTitle = matchOne( + html, + /]*property=["']og:title["'][^>]*content=["']([^"']*)["']/i, + ); + const ogDesc = matchOne( + html, + /]*property=["']og:description["'][^>]*content=["']([^"']*)["']/i, + ); + const metaDesc = matchOne( + html, + /]*name=["']description["'][^>]*content=["']([^"']*)["']/i, + ); + const titleTag = matchOne(html, /]*>([\s\S]*?)<\/title>/i); + const title = decodeEntities(stripTags(ogTitle || titleTag || '')).trim() || 'Sem título'; + const summary = decodeEntities(stripTags(ogDesc || metaDesc || '')) + .replace(/\s+/g, ' ') + .trim() + .slice(0, 2000); + return { title, summary }; +} + +function matchOne(html: string, re: RegExp): string { + const m = re.exec(html); + return m?.[1] ? m[1] : ''; +} + +function stripTags(s: string): string { + return s.replace(/<[^>]+>/g, ' '); +} + +function decodeEntities(s: string): string { + return s + .replace(/ /gi, ' ') + .replace(/&/g, '&') + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/"/g, '"') + .replace(/'/g, "'"); +} diff --git a/writer-pipeline/src/http-retry.ts b/writer-pipeline/src/http-retry.ts new file mode 100644 index 0000000..ecc6da9 --- /dev/null +++ b/writer-pipeline/src/http-retry.ts @@ -0,0 +1,45 @@ +const DEFAULT_UA = 'BitReport-news-writer-pipeline/1.0'; + +export interface FetchTextOptions { + timeoutMs?: number; + retries?: number; + userAgent?: string; + accept?: string; +} + +function sleep(ms: number): Promise { + return new Promise((r) => setTimeout(r, ms)); +} + +/** + * GET url as text with bounded retries (transient network / 5xx). + */ +export async function fetchTextWithRetry( + url: string, + opts: FetchTextOptions = {}, +): Promise { + const timeoutMs = opts.timeoutMs ?? 15000; + const retries = Math.max(0, opts.retries ?? 2); + const ua = opts.userAgent ?? DEFAULT_UA; + const accept = opts.accept ?? '*/*'; + let lastErr: unknown; + for (let attempt = 0; attempt <= retries; attempt += 1) { + try { + const res = await fetch(url, { + redirect: 'follow', + headers: { 'User-Agent': ua, Accept: accept }, + signal: AbortSignal.timeout(timeoutMs), + }); + if (res.status >= 500 && attempt < retries) { + await sleep(400 * (attempt + 1)); + continue; + } + if (!res.ok) throw new Error(`HTTP ${res.status}`); + return await res.text(); + } catch (e) { + lastErr = e; + if (attempt < retries) await sleep(500 * (attempt + 1)); + } + } + throw lastErr instanceof Error ? lastErr : new Error(String(lastErr)); +} diff --git a/writer-pipeline/src/ingest-sources.ts b/writer-pipeline/src/ingest-sources.ts new file mode 100644 index 0000000..40e9e33 --- /dev/null +++ b/writer-pipeline/src/ingest-sources.ts @@ -0,0 +1,305 @@ +import Parser from 'rss-parser'; +import type { AggregatedItem, IngestSource, SiteSourcesConfig, SourceKind, StoreFile } from './types.js'; +import { canonicalUrl, itemId, upsertItem } from './store.js'; +import { fetchTextWithRetry } from './http-retry.js'; +import { extractTitleAndSummary } from './html-meta.js'; +import { + isSitemapIndexXml, + parseLooseLocs, + parseSitemapIndexLocs, + parseUrlsetEntries, + type SitemapUrlEntry, +} from './sitemap-parse.js'; + +const parser = new Parser(); + +const SITEMAP_MAX_CHILD_SITEMAPS = 10; +const SITEMAP_LOOSE_CAP = 250; + +export interface IngestResult { + store: StoreFile; + attempted: number; + succeeded: number; + failed: number; + newItems: number; + errors: string[]; +} + +/** Resolve config path for a site key (e.g. andebol.net). */ +export function sourcesConfigPath(site: string, configDir: string): string { + return `${configDir}/${site}.sources.json`; +} + +function normalizeSources(config: SiteSourcesConfig): IngestSource[] { + if (config.sources?.length) return config.sources; + const feeds = config.feeds ?? []; + return feeds.map((f) => ({ + id: f.id, + kind: 'rss' as const, + url: f.url, + enabled: f.enabled, + note: f.note, + })); +} + +function pickSummary(entry: { contentSnippet?: string; content?: string; summary?: string }): string { + const s = entry.contentSnippet || entry.summary || ''; + if (s) return s.replace(/\s+/g, ' ').trim().slice(0, 2000); + const c = entry.content || ''; + return c.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 2000); +} + +function publishedFromLastmod(lastmod: string | undefined, fallback: string): string { + if (!lastmod) return fallback; + const d = new Date(lastmod); + if (Number.isNaN(d.getTime())) return fallback; + return d.toISOString(); +} + +async function parseFeedUrl(url: string, timeoutMs: number, retries: number) { + const xml = await fetchTextWithRetry(url, { + timeoutMs, + retries, + accept: 'application/rss+xml, application/xml, text/xml, */*', + }); + return parser.parseString(xml); +} + +function filterByPath(entries: SitemapUrlEntry[], pathIncludes?: string[]): SitemapUrlEntry[] { + if (!pathIncludes?.length) return entries; + return entries.filter((e) => { + try { + const p = new URL(e.loc).pathname; + return pathIncludes.some((frag) => p.includes(frag)); + } catch { + return false; + } + }); +} + +function sortByLastmodDesc(entries: SitemapUrlEntry[]): SitemapUrlEntry[] { + return [...entries].sort((a, b) => { + const ta = a.lastmod ? Date.parse(a.lastmod) : 0; + const tb = b.lastmod ? Date.parse(b.lastmod) : 0; + return tb - ta; + }); +} + +async function collectSitemapEntries(rootUrl: string, source: IngestSource): Promise { + const timeoutMs = source.timeoutMs ?? 20000; + const retries = source.retries ?? 2; + const xml = await fetchTextWithRetry(rootUrl, { + timeoutMs, + retries, + accept: 'application/xml, text/xml, */*', + }); + + if (isSitemapIndexXml(xml)) { + const children = parseSitemapIndexLocs(xml).slice(0, SITEMAP_MAX_CHILD_SITEMAPS); + const merged: SitemapUrlEntry[] = []; + for (const childUrl of children) { + try { + const childXml = await fetchTextWithRetry(childUrl, { + timeoutMs, + retries, + accept: 'application/xml, text/xml, */*', + }); + let entries = parseUrlsetEntries(childXml); + if (!entries.length) { + const loose = parseLooseLocs(childXml); + entries = loose.map((loc) => ({ loc })); + } + merged.push(...entries); + } catch { + /* child failure: continue */ + } + } + return merged; + } + + let entries = parseUrlsetEntries(xml); + if (!entries.length) { + const loose = parseLooseLocs(xml); + entries = loose.slice(0, SITEMAP_LOOSE_CAP).map((loc) => ({ loc })); + } + return entries; +} + +function buildItem( + storeSite: string, + source: IngestSource, + originalUrl: string, + title: string, + summary: string, + publishedAt: string, + now: string, + kind: SourceKind, +): AggregatedItem { + const trimmed = originalUrl.trim(); + const id = itemId(canonicalUrl(trimmed)); + return { + id, + site: storeSite, + sourceFeedId: source.id, + url: trimmed, + sourceKind: kind, + topics: source.topics?.length ? [...source.topics] : undefined, + title, + summary, + publishedAt, + ingestedAt: now, + }; +} + +export async function ingestAllSources( + store: StoreFile, + config: SiteSourcesConfig, +): Promise { + const errors: string[] = []; + let current = store; + let attempted = 0; + let succeeded = 0; + let failed = 0; + let newItems = 0; + const now = new Date().toISOString(); + const sources = normalizeSources(config); + + for (const source of sources) { + if (!source.enabled) continue; + const kind = source.kind; + const timeoutMs = source.timeoutMs ?? (kind === 'sitemap' ? 20000 : 15000); + const retries = source.retries ?? 2; + + if (kind === 'rss') { + attempted += 1; + try { + const parsed = await parseFeedUrl(source.url, timeoutMs, retries); + succeeded += 1; + const items = parsed.items ?? []; + for (const entry of items) { + const link = entry.link?.trim(); + if (!link) continue; + const title = (entry.title || 'Sem título').replace(/\s+/g, ' ').trim(); + const summary = pickSummary(entry); + const publishedAt = entry.isoDate || entry.pubDate || entry.date || now; + const item = buildItem( + config.site, + source, + link, + title, + summary, + publishedAt, + now, + 'rss', + ); + const { store: next, isNew } = upsertItem(current, item); + current = next; + if (isNew) newItems += 1; + } + } catch (e) { + failed += 1; + const msg = e instanceof Error ? e.message : String(e); + errors.push(`rss ${source.id} (${source.url}): ${msg}`); + } + continue; + } + + if (kind === 'html_fetch') { + attempted += 1; + try { + const html = await fetchTextWithRetry(source.url, { + timeoutMs, + retries, + accept: 'text/html, application/xhtml+xml, */*', + }); + succeeded += 1; + const { title, summary } = extractTitleAndSummary(html); + const item = buildItem( + config.site, + source, + source.url, + title, + summary || '(sem resumo)', + now, + now, + 'html_fetch', + ); + const { store: next, isNew } = upsertItem(current, item); + current = next; + if (isNew) newItems += 1; + } catch (e) { + failed += 1; + const msg = e instanceof Error ? e.message : String(e); + errors.push(`html_fetch ${source.id} (${source.url}): ${msg}`); + } + continue; + } + + if (kind === 'sitemap') { + attempted += 1; + try { + let entries = await collectSitemapEntries(source.url, source); + entries = filterByPath(entries, source.pathIncludes); + entries = sortByLastmodDesc(entries); + const maxItems = source.maxItems ?? 30; + if (!source.pathIncludes?.length && entries.length > 200) { + errors.push( + `sitemap ${source.id}: no pathIncludes and ${entries.length} URLs — truncating to 200 before maxItems`, + ); + entries = entries.slice(0, 200); + } + const slice = entries.slice(0, maxItems); + if (!slice.length) { + succeeded += 1; + errors.push(`sitemap ${source.id}: no URLs after filters`); + continue; + } + let ok = 0; + for (const entry of slice) { + try { + const html = await fetchTextWithRetry(entry.loc, { + timeoutMs, + retries, + accept: 'text/html, application/xhtml+xml, */*', + }); + const { title, summary } = extractTitleAndSummary(html); + const publishedAt = publishedFromLastmod(entry.lastmod, now); + const item = buildItem( + config.site, + source, + entry.loc, + title, + summary || '(sem resumo)', + publishedAt, + now, + 'sitemap', + ); + const { store: next, isNew } = upsertItem(current, item); + current = next; + if (isNew) newItems += 1; + ok += 1; + } catch (e) { + const msg = e instanceof Error ? e.message : String(e); + errors.push(`sitemap ${source.id} page (${entry.loc}): ${msg}`); + } + } + if (ok > 0) succeeded += 1; + else failed += 1; + } catch (e) { + failed += 1; + const msg = e instanceof Error ? e.message : String(e); + errors.push(`sitemap ${source.id} (${source.url}): ${msg}`); + } + } + } + + return { store: current, attempted, succeeded, failed, newItems, errors }; +} + +/** @deprecated Use ingestAllSources */ +export async function ingestSiteFeeds( + store: StoreFile, + config: SiteSourcesConfig, +): Promise { + return ingestAllSources(store, config); +} diff --git a/writer-pipeline/src/rss-ingest.ts b/writer-pipeline/src/rss-ingest.ts index 0de7423..8824981 100644 --- a/writer-pipeline/src/rss-ingest.ts +++ b/writer-pipeline/src/rss-ingest.ts @@ -1,93 +1,9 @@ -import Parser from 'rss-parser'; -import type { AggregatedItem, SiteSourcesConfig, StoreFile } from './types.js'; -import { canonicalUrl, itemId, upsertItem } from './store.js'; - -const parser = new Parser(); - -async function parseFeedUrl(url: string) { - const res = await fetch(url, { - redirect: 'follow', - headers: { - 'User-Agent': 'BitReport-news-writer-pipeline/1.0', - Accept: 'application/rss+xml, application/xml, text/xml, */*', - }, - signal: AbortSignal.timeout(15000), - }); - if (!res.ok) throw new Error(`HTTP ${res.status}`); - const xml = await res.text(); - return parser.parseString(xml); -} - -function pickSummary(entry: { contentSnippet?: string; content?: string; summary?: string }): string { - const s = entry.contentSnippet || entry.summary || ''; - if (s) return s.replace(/\s+/g, ' ').trim().slice(0, 2000); - const c = entry.content || ''; - return c.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 2000); -} - -export interface IngestResult { - store: StoreFile; - attempted: number; - succeeded: number; - failed: number; - newItems: number; - errors: string[]; -} - -export async function ingestSiteFeeds( - store: StoreFile, - config: SiteSourcesConfig, -): Promise { - const errors: string[] = []; - let current = store; - let attempted = 0; - let succeeded = 0; - let failed = 0; - let newItems = 0; - const now = new Date().toISOString(); - - for (const feed of config.feeds) { - if (!feed.enabled) continue; - attempted += 1; - try { - const parsed = await parseFeedUrl(feed.url); - succeeded += 1; - const items = parsed.items ?? []; - for (const entry of items) { - const link = entry.link?.trim(); - if (!link) continue; - const url = canonicalUrl(link); - const id = itemId(url); - const title = (entry.title || 'Sem título').replace(/\s+/g, ' ').trim(); - const summary = pickSummary(entry); - const publishedAt = - entry.isoDate || entry.pubDate || entry.date || now; - - const agg: AggregatedItem = { - id, - site: config.site, - sourceFeedId: feed.id, - url, - title, - summary, - publishedAt, - ingestedAt: now, - }; - const { store: next, isNew } = upsertItem(current, agg); - current = next; - if (isNew) newItems += 1; - } - } catch (e) { - failed += 1; - const msg = e instanceof Error ? e.message : String(e); - errors.push(`feed ${feed.id} (${feed.url}): ${msg}`); - } - } - - return { store: current, attempted, succeeded, failed, newItems, errors }; -} - -/** Resolve config path for a site key (e.g. andebol.net). */ -export function sourcesConfigPath(site: string, configDir: string): string { - return `${configDir}/${site}.sources.json`; -} +/** + * Compatibility re-exports — implementation lives in ingest-sources.ts (BIT-711). + */ +export { + ingestAllSources, + ingestSiteFeeds, + sourcesConfigPath, +} from './ingest-sources.js'; +export type { IngestResult } from './ingest-sources.js'; diff --git a/writer-pipeline/src/sitemap-parse.test.ts b/writer-pipeline/src/sitemap-parse.test.ts new file mode 100644 index 0000000..b235ad6 --- /dev/null +++ b/writer-pipeline/src/sitemap-parse.test.ts @@ -0,0 +1,38 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { + isSitemapIndexXml, + parseSitemapIndexLocs, + parseUrlsetEntries, + parseLooseLocs, +} from './sitemap-parse.js'; + +test('parseUrlsetEntries pairs loc and lastmod', () => { + const xml = ` + https://ex.com/a2026-01-02 + https://ex.com/b + `; + const e = parseUrlsetEntries(xml); + assert.equal(e.length, 2); + assert.equal(e[0].loc, 'https://ex.com/a'); + assert.equal(e[0].lastmod, '2026-01-02'); + assert.equal(e[1].loc, 'https://ex.com/b'); + assert.equal(e[1].lastmod, undefined); +}); + +test('isSitemapIndexXml detects index', () => { + assert.equal(isSitemapIndexXml(''), true); + assert.equal(isSitemapIndexXml(''), false); +}); + +test('parseSitemapIndexLocs reads child sitemaps', () => { + const xml = ` + https://ex.com/news.xml + `; + assert.deepEqual(parseSitemapIndexLocs(xml), ['https://ex.com/news.xml']); +}); + +test('parseLooseLocs finds bare loc tags', () => { + const xml = `https://ex.com/x`; + assert.deepEqual(parseLooseLocs(xml), ['https://ex.com/x']); +}); diff --git a/writer-pipeline/src/sitemap-parse.ts b/writer-pipeline/src/sitemap-parse.ts new file mode 100644 index 0000000..4092465 --- /dev/null +++ b/writer-pipeline/src/sitemap-parse.ts @@ -0,0 +1,49 @@ +export interface SitemapUrlEntry { + loc: string; + lastmod?: string; +} + +export function isSitemapIndexXml(xml: string): boolean { + return /]*>([\s\S]*?)<\/sitemap>/gi; + let m: RegExpExecArray | null; + while ((m = blockRe.exec(xml)) !== null) { + const locM = /\s*([^<\s]+)\s*<\/loc>/i.exec(m[1]); + if (locM?.[1]) out.push(locM[1].trim()); + } + return out; +} + +/** blocks from a urlset sitemap. */ +export function parseUrlsetEntries(xml: string): SitemapUrlEntry[] { + const out: SitemapUrlEntry[] = []; + const blockRe = /]*>([\s\S]*?)<\/url>/gi; + let m: RegExpExecArray | null; + while ((m = blockRe.exec(xml)) !== null) { + const block = m[1]; + const locM = /\s*([^<\s]+)\s*<\/loc>/i.exec(block); + if (!locM?.[1]) continue; + const lastmodM = /\s*([^<]+?)\s*<\/lastmod>/i.exec(block); + out.push({ + loc: locM[1].trim(), + lastmod: lastmodM?.[1]?.trim(), + }); + } + return out; +} + +/** Fallback when there are tags but no wrappers. */ +export function parseLooseLocs(xml: string): string[] { + const out: string[] = []; + const re = /\s*([^<\s]+)\s*<\/loc>/gi; + let m: RegExpExecArray | null; + while ((m = re.exec(xml)) !== null) { + if (m[1]) out.push(m[1].trim()); + } + return out; +} diff --git a/writer-pipeline/src/store.ts b/writer-pipeline/src/store.ts index b79d04e..f205164 100644 --- a/writer-pipeline/src/store.ts +++ b/writer-pipeline/src/store.ts @@ -7,11 +7,23 @@ import type { AggregatedItem, StoreFile } from './types.js'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); export const DEFAULT_STORE_PATH = path.resolve(__dirname, '../var/aggregated-items.json'); +const TRACKING_QUERY_KEYS = new Set([ + 'fbclid', + 'gclid', + 'msclkid', + 'mc_cid', + 'mc_eid', + 'twclid', +]); + export function canonicalUrl(raw: string): string { try { const u = new URL(raw); - for (const key of [...u.searchParams.keys()]) { - if (key.toLowerCase().startsWith('utm_')) u.searchParams.delete(key); + u.hash = ''; + const keys = [...u.searchParams.keys()]; + for (const key of keys) { + const lower = key.toLowerCase(); + if (lower.startsWith('utm_') || TRACKING_QUERY_KEYS.has(lower)) u.searchParams.delete(key); } return u.toString(); } catch { @@ -65,9 +77,14 @@ export function shortlist( store: StoreFile, site: string, limit: number, + topic?: string, ): AggregatedItem[] { return store.items - .filter((i) => i.site === site && !i.wpDraftId && !i.skippedReason) + .filter((i) => { + if (i.site !== site || i.wpDraftId || i.skippedReason) return false; + if (!topic) return true; + return i.topics?.includes(topic) ?? false; + }) .sort((a, b) => (a.publishedAt < b.publishedAt ? 1 : a.publishedAt > b.publishedAt ? -1 : 0)) .slice(0, limit); } diff --git a/writer-pipeline/src/types.ts b/writer-pipeline/src/types.ts index 03f6c9a..af04879 100644 --- a/writer-pipeline/src/types.ts +++ b/writer-pipeline/src/types.ts @@ -1,3 +1,21 @@ +export type SourceKind = 'rss' | 'sitemap' | 'html_fetch'; + +export interface IngestSource { + id: string; + kind: SourceKind; + url: string; + enabled: boolean; + topics?: string[]; + note?: string; + /** Cap per-source items (sitemap URLs processed, or single html page). Default: 30 sitemap, 1 html_fetch */ + maxItems?: number; + /** For sitemap: keep URLs whose path includes any of these substrings */ + pathIncludes?: string[]; + retries?: number; + timeoutMs?: number; +} + +/** @deprecated Use IngestSource with kind rss — kept for legacy JSON configs */ export interface FeedSource { id: string; url: string; @@ -7,14 +25,20 @@ export interface FeedSource { export interface SiteSourcesConfig { site: string; - feeds: FeedSource[]; + /** Unified multi-source config (RSS, sitemap, HTML fetch) */ + sources?: IngestSource[]; + /** Legacy: treated as RSS sources when `sources` is absent */ + feeds?: FeedSource[]; } export interface AggregatedItem { id: string; site: string; sourceFeedId: string; + /** Original article URL from the source (preserved verbatim aside from trim) */ url: string; + sourceKind?: SourceKind; + topics?: string[]; title: string; summary: string; publishedAt: string;