-
Notifications
You must be signed in to change notification settings - Fork 7.4k
feat(regulatory): add regulatory RSS fetch seeder #2564
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
lspassos1
wants to merge
3
commits into
koala73:main
Choose a base branch
from
lspassos1:feat/regulatory-rss-fetch-parse
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+479
−0
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,270 @@ | ||
| #!/usr/bin/env node | ||
| // @ts-check | ||
|
|
||
| import { pathToFileURL } from 'node:url'; | ||
| import { CHROME_UA } from './_seed-utils.mjs'; | ||
|
|
||
| const FEED_TIMEOUT_MS = 15_000; | ||
| const XML_ACCEPT = 'application/atom+xml, application/rss+xml, application/xml, text/xml, */*'; | ||
| const SEC_USER_AGENT = 'WorldMonitor/2.0 (monitor@worldmonitor.app)'; | ||
| const DEFAULT_FETCH = (...args) => globalThis.fetch(...args); | ||
|
|
||
| const REGULATORY_FEEDS = [ | ||
| { agency: 'SEC', url: 'https://www.sec.gov/news/pressreleases.rss', userAgent: SEC_USER_AGENT }, | ||
| { agency: 'CFTC', url: 'https://www.cftc.gov/RSS/RSSENF/rssenf.xml' }, | ||
| { agency: 'Federal Reserve', url: 'https://www.federalreserve.gov/feeds/press_all.xml' }, | ||
| { agency: 'FDIC', url: 'https://public.govdelivery.com/topics/USFDIC_26/feed.rss' }, | ||
| // FINRA still publishes this RSS endpoint over plain HTTP; HTTPS requests fail | ||
| // from both Node fetch and curl in validation, so keep the official feed URL | ||
| // and periodically recheck whether HTTPS starts working. | ||
| { agency: 'FINRA', url: 'http://feeds.finra.org/FINRANotices' }, | ||
| ]; | ||
|
|
||
| function decodeEntities(input) { | ||
| if (!input) return ''; | ||
| const named = input | ||
| .replace(/&/gi, '&') | ||
| .replace(/</gi, '<') | ||
| .replace(/>/gi, '>') | ||
| .replace(/"/gi, '"') | ||
| .replace(/'/gi, "'") | ||
| .replace(/ /gi, ' '); | ||
|
|
||
| return named | ||
| .replace(/&#(\d+);/g, (_, code) => String.fromCodePoint(Number(code))) | ||
| .replace(/&#x([0-9a-f]+);/gi, (_, code) => String.fromCodePoint(parseInt(code, 16))); | ||
| } | ||
|
|
||
| function stripHtml(input) { | ||
| return decodeEntities( | ||
| String(input || '') | ||
| .replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, '$1') | ||
| .replace(/<[^>]+>/g, ' ') | ||
| ).replace(/\s+/g, ' ').trim(); | ||
| } | ||
|
|
||
| function getTagValue(block, tagName) { | ||
| const match = block.match(new RegExp(`<${tagName}[^>]*>([\\s\\S]*?)<\\/${tagName}>`, 'i')); | ||
| return stripHtml(match?.[1] || ''); | ||
| } | ||
|
|
||
| function extractAtomLink(block) { | ||
| const linkTags = [...block.matchAll(/<link\b([^>]*)\/?>/gi)]; | ||
| if (linkTags.length === 0) return ''; | ||
|
|
||
| for (const [, attrs] of linkTags) { | ||
| const href = attrs.match(/\bhref=["']([^"']+)["']/i)?.[1]; | ||
| const rel = attrs.match(/\brel=["']([^"']+)["']/i)?.[1]?.toLowerCase() || ''; | ||
| if (href && (!rel || rel === 'alternate')) return decodeEntities(href.trim()); | ||
| } | ||
|
|
||
| for (const [, attrs] of linkTags) { | ||
| const href = attrs.match(/\bhref=["']([^"']+)["']/i)?.[1]; | ||
| if (href) return decodeEntities(href.trim()); | ||
| } | ||
|
|
||
| return ''; | ||
| } | ||
|
|
||
| function resolveFeedLink(link, feedUrl) { | ||
| if (!link) return ''; | ||
| try { | ||
| return new URL(link).href; | ||
| } catch {} | ||
| try { | ||
| return new URL(link, feedUrl).href; | ||
| } catch { | ||
| return ''; | ||
| } | ||
| } | ||
|
|
||
| function canonicalizeLink(link, feedUrl = '') { | ||
| const resolved = resolveFeedLink(link, feedUrl); | ||
| if (!resolved) return ''; | ||
| try { | ||
| const url = new URL(resolved); | ||
| url.hash = ''; | ||
| return url.href; | ||
| } catch { | ||
| return ''; | ||
| } | ||
| } | ||
|
|
||
| function toIsoDate(rawDate) { | ||
| const value = stripHtml(rawDate); | ||
| if (!value) return ''; | ||
| const ts = Date.parse(value); | ||
| return Number.isFinite(ts) ? new Date(ts).toISOString() : ''; | ||
| } | ||
|
|
||
| function slugifyTitle(title) { | ||
| return stripHtml(title) | ||
| .normalize('NFKD') | ||
| .replace(/[\u0300-\u036f]/g, '') | ||
| .toLowerCase() | ||
| .replace(/[^a-z0-9]+/g, '-') | ||
| .replace(/^-+|-+$/g, '') | ||
| .slice(0, 80); | ||
| } | ||
|
|
||
| function yyyymmdd(isoDate) { | ||
| return String(isoDate || '').slice(0, 10).replace(/-/g, ''); | ||
| } | ||
|
|
||
| function hhmmss(isoDate) { | ||
| return String(isoDate || '').slice(11, 19).replace(/:/g, ''); | ||
| } | ||
|
|
||
| function buildActionId(agency, title, publishedAt) { | ||
| const agencySlug = slugifyTitle(agency) || 'agency'; | ||
| const titleSlug = slugifyTitle(title) || 'untitled'; | ||
| const datePart = yyyymmdd(publishedAt) || 'undated'; | ||
| const timePart = hhmmss(publishedAt) || '000000'; | ||
| return `${agencySlug}-${titleSlug}-${datePart}-${timePart}`; | ||
| } | ||
|
|
||
| function parseRssItems(xml, feedUrl) { | ||
| const items = []; | ||
| const itemRegex = /<item\b[^>]*>([\s\S]*?)<\/item>/gi; | ||
| let match; | ||
| while ((match = itemRegex.exec(xml)) !== null) { | ||
| const block = match[1]; | ||
| const title = getTagValue(block, 'title'); | ||
| const description = getTagValue(block, 'description'); | ||
| const link = canonicalizeLink(getTagValue(block, 'link'), feedUrl); | ||
| const publishedAt = toIsoDate(getTagValue(block, 'pubDate') || getTagValue(block, 'updated')); | ||
| items.push({ title, description, link, publishedAt }); | ||
| } | ||
| return items; | ||
| } | ||
|
|
||
| function parseAtomEntries(xml, feedUrl) { | ||
| const entries = []; | ||
| const entryRegex = /<entry\b[^>]*>([\s\S]*?)<\/entry>/gi; | ||
| let match; | ||
| while ((match = entryRegex.exec(xml)) !== null) { | ||
| const block = match[1]; | ||
| const title = getTagValue(block, 'title'); | ||
| const description = getTagValue(block, 'summary') || getTagValue(block, 'content'); | ||
| const link = canonicalizeLink(extractAtomLink(block), feedUrl); | ||
| const publishedAt = toIsoDate( | ||
| getTagValue(block, 'updated') || getTagValue(block, 'published') || getTagValue(block, 'pubDate') | ||
| ); | ||
| entries.push({ title, description, link, publishedAt }); | ||
| } | ||
| return entries; | ||
| } | ||
|
|
||
| function parseFeed(xml, feedUrl) { | ||
| if (/<entry\b/i.test(xml)) return parseAtomEntries(xml, feedUrl); | ||
| return parseRssItems(xml, feedUrl); | ||
| } | ||
|
|
||
| function normalizeFeedItems(items, agency) { | ||
| return items | ||
| .filter((item) => item.title && item.link && item.publishedAt) | ||
| .map((item) => ({ | ||
| id: buildActionId(agency, item.title, item.publishedAt), | ||
| agency, | ||
| title: item.title, | ||
| description: item.description || '', | ||
| link: item.link, | ||
| publishedAt: item.publishedAt, | ||
| })); | ||
| } | ||
|
|
||
| function dedupeAndSortActions(actions) { | ||
| const seen = new Set(); | ||
| const deduped = []; | ||
| for (const action of actions) { | ||
| const key = canonicalizeLink(action.link); | ||
| if (!key || seen.has(key)) continue; | ||
| seen.add(key); | ||
lspassos1 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| deduped.push({ ...action, link: key }); | ||
| } | ||
|
|
||
| deduped.sort((a, b) => Date.parse(b.publishedAt) - Date.parse(a.publishedAt)); | ||
| return deduped; | ||
| } | ||
|
|
||
| async function fetchFeed(feed, fetchImpl = DEFAULT_FETCH) { | ||
| const headers = { | ||
| Accept: XML_ACCEPT, | ||
| 'User-Agent': feed.userAgent || CHROME_UA, | ||
| }; | ||
|
|
||
| const response = await fetchImpl(feed.url, { | ||
| headers, | ||
| signal: AbortSignal.timeout(FEED_TIMEOUT_MS), | ||
| }); | ||
|
|
||
| if (!response.ok) { | ||
| throw new Error(`${feed.agency}: HTTP ${response.status}`); | ||
| } | ||
|
|
||
| const xml = await response.text(); | ||
| const parsed = parseFeed(xml, feed.url); | ||
| return normalizeFeedItems(parsed, feed.agency); | ||
| } | ||
|
|
||
| async function fetchAllFeeds(fetchImpl = DEFAULT_FETCH, feeds = REGULATORY_FEEDS) { | ||
| const results = await Promise.allSettled(feeds.map((feed) => fetchFeed(feed, fetchImpl))); | ||
| const actions = []; | ||
| let successCount = 0; | ||
|
|
||
| for (let index = 0; index < results.length; index += 1) { | ||
| const result = results[index]; | ||
| const feed = feeds[index]; | ||
| if (result.status === 'fulfilled') { | ||
| successCount += 1; | ||
| actions.push(...result.value); | ||
| continue; | ||
| } | ||
| console.error(`[regulatory] ${feed.agency}: ${result.reason?.message || result.reason}`); | ||
| } | ||
|
|
||
| if (successCount === 0) { | ||
| throw new Error('All regulatory feeds failed'); | ||
| } | ||
|
|
||
| return dedupeAndSortActions(actions); | ||
| } | ||
|
|
||
| async function main(fetchImpl = DEFAULT_FETCH) { | ||
| const actions = await fetchAllFeeds(fetchImpl); | ||
| process.stdout.write(`${JSON.stringify(actions, null, 2)}\n`); | ||
| return actions; | ||
| } | ||
|
|
||
| const isDirectRun = process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href; | ||
|
|
||
| if (isDirectRun) { | ||
| main().catch((err) => { | ||
| console.error(`FETCH FAILED: ${err.message || err}`); | ||
| process.exit(1); | ||
| }); | ||
| } | ||
|
|
||
| export { | ||
| CHROME_UA, | ||
| FEED_TIMEOUT_MS, | ||
| REGULATORY_FEEDS, | ||
| SEC_USER_AGENT, | ||
| buildActionId, | ||
| canonicalizeLink, | ||
| decodeEntities, | ||
| dedupeAndSortActions, | ||
| extractAtomLink, | ||
| fetchAllFeeds, | ||
| fetchFeed, | ||
| getTagValue, | ||
| main, | ||
| normalizeFeedItems, | ||
| parseAtomEntries, | ||
| parseFeed, | ||
| parseRssItems, | ||
| resolveFeedLink, | ||
| slugifyTitle, | ||
| stripHtml, | ||
| toIsoDate, | ||
| }; | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.