oculon 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +344 -2
- package/dist/agent.d.ts +47 -0
- package/dist/agent.js +104 -0
- package/dist/cases.d.ts +68 -0
- package/dist/cases.js +158 -0
- package/dist/cli/main.d.ts +12 -0
- package/dist/cli/main.js +1999 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +15 -0
- package/dist/core/context.d.ts +19 -0
- package/dist/core/context.js +19 -0
- package/dist/core/features.d.ts +22 -0
- package/dist/core/features.js +28 -0
- package/dist/core/graph.d.ts +38 -0
- package/dist/core/graph.js +81 -0
- package/dist/core/http.d.ts +42 -0
- package/dist/core/http.js +266 -0
- package/dist/core/keys.d.ts +8 -0
- package/dist/core/keys.js +22 -0
- package/dist/core/llm.d.ts +93 -0
- package/dist/core/llm.js +180 -0
- package/dist/core/merkle.d.ts +15 -0
- package/dist/core/merkle.js +46 -0
- package/dist/core/paths.d.ts +2 -0
- package/dist/core/paths.js +6 -0
- package/dist/core/png.d.ts +17 -0
- package/dist/core/png.js +101 -0
- package/dist/core/quota.d.ts +15 -0
- package/dist/core/quota.js +90 -0
- package/dist/core/stats.d.ts +24 -0
- package/dist/core/stats.js +67 -0
- package/dist/core/store.d.ts +20 -0
- package/dist/core/store.js +213 -0
- package/dist/core/text.d.ts +9 -0
- package/dist/core/text.js +30 -0
- package/dist/core/types.d.ts +38 -0
- package/dist/core/types.js +1 -0
- package/dist/index.d.ts +346 -0
- package/dist/index.js +503 -0
- package/dist/live.d.ts +53 -0
- package/dist/live.js +236 -0
- package/dist/mcp.d.ts +43 -0
- package/dist/mcp.js +651 -0
- package/dist/modules/airport.d.ts +60 -0
- package/dist/modules/airport.js +111 -0
- package/dist/modules/audit.d.ts +73 -0
- package/dist/modules/audit.js +211 -0
- package/dist/modules/bgp.d.ts +147 -0
- package/dist/modules/bgp.js +206 -0
- package/dist/modules/blackout.d.ts +41 -0
- package/dist/modules/blackout.js +98 -0
- package/dist/modules/brief.d.ts +26 -0
- package/dist/modules/brief.js +99 -0
- package/dist/modules/calendar.d.ts +27 -0
- package/dist/modules/calendar.js +145 -0
- package/dist/modules/calibrate.d.ts +46 -0
- package/dist/modules/calibrate.js +92 -0
- package/dist/modules/cloud.d.ts +32 -0
- package/dist/modules/cloud.js +94 -0
- package/dist/modules/condor.d.ts +66 -0
- package/dist/modules/condor.js +214 -0
- package/dist/modules/connect.d.ts +47 -0
- package/dist/modules/connect.js +114 -0
- package/dist/modules/contradictions.d.ts +27 -0
- package/dist/modules/contradictions.js +76 -0
- package/dist/modules/country.d.ts +82 -0
- package/dist/modules/country.js +136 -0
- package/dist/modules/cricket.d.ts +34 -0
- package/dist/modules/cricket.js +166 -0
- package/dist/modules/darkships.d.ts +219 -0
- package/dist/modules/darkships.js +400 -0
- package/dist/modules/defi.d.ts +237 -0
- package/dist/modules/defi.js +512 -0
- package/dist/modules/emailsec.d.ts +47 -0
- package/dist/modules/emailsec.js +146 -0
- package/dist/modules/exposure.d.ts +43 -0
- package/dist/modules/exposure.js +89 -0
- package/dist/modules/factcheck.d.ts +39 -0
- package/dist/modules/factcheck.js +127 -0
- package/dist/modules/falcon.d.ts +58 -0
- package/dist/modules/falcon.js +219 -0
- package/dist/modules/feedback.d.ts +24 -0
- package/dist/modules/feedback.js +37 -0
- package/dist/modules/fence.d.ts +52 -0
- package/dist/modules/fence.js +128 -0
- package/dist/modules/ferret.d.ts +47 -0
- package/dist/modules/ferret.js +220 -0
- package/dist/modules/filings.d.ts +86 -0
- package/dist/modules/filings.js +166 -0
- package/dist/modules/fires.d.ts +56 -0
- package/dist/modules/fires.js +150 -0
- package/dist/modules/hazards.d.ts +37 -0
- package/dist/modules/hazards.js +83 -0
- package/dist/modules/health.d.ts +24 -0
- package/dist/modules/health.js +82 -0
- package/dist/modules/heron.d.ts +68 -0
- package/dist/modules/heron.js +184 -0
- package/dist/modules/hound.d.ts +100 -0
- package/dist/modules/hound.js +301 -0
- package/dist/modules/impact.d.ts +39 -0
- package/dist/modules/impact.js +63 -0
- package/dist/modules/launches.d.ts +24 -0
- package/dist/modules/launches.js +61 -0
- package/dist/modules/listen.d.ts +48 -0
- package/dist/modules/listen.js +125 -0
- package/dist/modules/lynx.d.ts +43 -0
- package/dist/modules/lynx.js +127 -0
- package/dist/modules/magpie.d.ts +70 -0
- package/dist/modules/magpie.js +174 -0
- package/dist/modules/meerkat.d.ts +42 -0
- package/dist/modules/meerkat.js +293 -0
- package/dist/modules/monitor.d.ts +27 -0
- package/dist/modules/monitor.js +105 -0
- package/dist/modules/narratives.d.ts +33 -0
- package/dist/modules/narratives.js +136 -0
- package/dist/modules/owl.d.ts +71 -0
- package/dist/modules/owl.js +290 -0
- package/dist/modules/papers.d.ts +46 -0
- package/dist/modules/papers.js +135 -0
- package/dist/modules/personal.d.ts +54 -0
- package/dist/modules/personal.js +153 -0
- package/dist/modules/pulse.d.ts +19 -0
- package/dist/modules/pulse.js +59 -0
- package/dist/modules/raven.d.ts +80 -0
- package/dist/modules/raven.js +147 -0
- package/dist/modules/recall.d.ts +44 -0
- package/dist/modules/recall.js +123 -0
- package/dist/modules/regs.d.ts +88 -0
- package/dist/modules/regs.js +142 -0
- package/dist/modules/rewind.d.ts +22 -0
- package/dist/modules/rewind.js +68 -0
- package/dist/modules/sanctions.d.ts +62 -0
- package/dist/modules/sanctions.js +173 -0
- package/dist/modules/scam.d.ts +43 -0
- package/dist/modules/scam.js +149 -0
- package/dist/modules/scoop.d.ts +31 -0
- package/dist/modules/scoop.js +74 -0
- package/dist/modules/ships.d.ts +33 -0
- package/dist/modules/ships.js +113 -0
- package/dist/modules/sky.d.ts +47 -0
- package/dist/modules/sky.js +183 -0
- package/dist/modules/squawk.d.ts +46 -0
- package/dist/modules/squawk.js +106 -0
- package/dist/modules/tortoise.d.ts +59 -0
- package/dist/modules/tortoise.js +133 -0
- package/dist/modules/travel.d.ts +94 -0
- package/dist/modules/travel.js +241 -0
- package/dist/modules/urlcheck.d.ts +63 -0
- package/dist/modules/urlcheck.js +223 -0
- package/dist/modules/vulns.d.ts +142 -0
- package/dist/modules/vulns.js +276 -0
- package/dist/plugins.d.ts +41 -0
- package/dist/plugins.js +70 -0
- package/dist/report.d.ts +12 -0
- package/dist/report.js +90 -0
- package/dist/scheduler.d.ts +22 -0
- package/dist/scheduler.js +139 -0
- package/dist/sources/aircraft.d.ts +76 -0
- package/dist/sources/aircraft.js +107 -0
- package/dist/sources/airports.d.ts +28 -0
- package/dist/sources/airports.js +100 -0
- package/dist/sources/ais.d.ts +32 -0
- package/dist/sources/ais.js +111 -0
- package/dist/sources/apify.d.ts +28 -0
- package/dist/sources/apify.js +80 -0
- package/dist/sources/arxiv.d.ts +13 -0
- package/dist/sources/arxiv.js +27 -0
- package/dist/sources/certs.d.ts +12 -0
- package/dist/sources/certs.js +23 -0
- package/dist/sources/corp.d.ts +46 -0
- package/dist/sources/corp.js +60 -0
- package/dist/sources/earth.d.ts +39 -0
- package/dist/sources/earth.js +76 -0
- package/dist/sources/fda.d.ts +77 -0
- package/dist/sources/fda.js +121 -0
- package/dist/sources/finance.d.ts +181 -0
- package/dist/sources/finance.js +270 -0
- package/dist/sources/gdelt.d.ts +19 -0
- package/dist/sources/gdelt.js +33 -0
- package/dist/sources/github.d.ts +17 -0
- package/dist/sources/github.js +33 -0
- package/dist/sources/hackernews.d.ts +20 -0
- package/dist/sources/hackernews.js +37 -0
- package/dist/sources/labels.d.ts +21 -0
- package/dist/sources/labels.js +87 -0
- package/dist/sources/launch.d.ts +16 -0
- package/dist/sources/launch.js +41 -0
- package/dist/sources/ofac.d.ts +29 -0
- package/dist/sources/ofac.js +86 -0
- package/dist/sources/onchain.d.ts +77 -0
- package/dist/sources/onchain.js +189 -0
- package/dist/sources/opentimestamps.d.ts +49 -0
- package/dist/sources/opentimestamps.js +145 -0
- package/dist/sources/polymarket.d.ts +36 -0
- package/dist/sources/polymarket.js +70 -0
- package/dist/sources/predict.d.ts +18 -0
- package/dist/sources/predict.js +59 -0
- package/dist/sources/press.d.ts +30 -0
- package/dist/sources/press.js +111 -0
- package/dist/sources/resend.d.ts +14 -0
- package/dist/sources/resend.js +29 -0
- package/dist/sources/robinhood.d.ts +109 -0
- package/dist/sources/robinhood.js +129 -0
- package/dist/sources/sec.d.ts +67 -0
- package/dist/sources/sec.js +129 -0
- package/dist/sources/sentinel.d.ts +13 -0
- package/dist/sources/sentinel.js +63 -0
- package/dist/sources/signatures.d.ts +14 -0
- package/dist/sources/signatures.js +103 -0
- package/dist/sources/social.d.ts +22 -0
- package/dist/sources/social.js +56 -0
- package/dist/sources/space.d.ts +160 -0
- package/dist/sources/space.js +230 -0
- package/dist/sources/usgs.d.ts +17 -0
- package/dist/sources/usgs.js +24 -0
- package/dist/sources/wayback.d.ts +10 -0
- package/dist/sources/wayback.js +28 -0
- package/dist/sources/websec.d.ts +19 -0
- package/dist/sources/websec.js +40 -0
- package/dist/sources/wikidata.d.ts +11 -0
- package/dist/sources/wikidata.js +30 -0
- package/dist/sources/wikimedia.d.ts +28 -0
- package/dist/sources/wikimedia.js +52 -0
- package/dist/telegram.d.ts +104 -0
- package/dist/telegram.js +927 -0
- package/dist/web/assets/favicon-32.png +0 -0
- package/dist/web/assets/fx.js +178 -0
- package/dist/web/assets/icon-192.png +0 -0
- package/dist/web/assets/icon-512.png +0 -0
- package/dist/web/assets/icon-maskable-512.png +0 -0
- package/dist/web/assets/night-americas.jpg +0 -0
- package/dist/web/assets/night-emea.jpg +0 -0
- package/dist/web/assets/og.png +0 -0
- package/dist/web/assets/redsea-bm.jpg +0 -0
- package/dist/web/docs.html +281 -0
- package/dist/web/index.html +1828 -0
- package/dist/web/insights.d.ts +100 -0
- package/dist/web/insights.js +134 -0
- package/dist/web/landing.html +1144 -0
- package/dist/web/legal.html +176 -0
- package/dist/web/manifest.webmanifest +20 -0
- package/dist/web/mcp.html +104 -0
- package/dist/web/mcphttp.d.ts +10 -0
- package/dist/web/mcphttp.js +67 -0
- package/dist/web/openapi.d.ts +1 -0
- package/dist/web/openapi.js +51 -0
- package/dist/web/public.d.ts +45 -0
- package/dist/web/public.js +136 -0
- package/dist/web/server.d.ts +69 -0
- package/dist/web/server.js +764 -0
- package/dist/web/share.d.ts +35 -0
- package/dist/web/share.js +132 -0
- package/dist/web/sw.js +28 -0
- package/package.json +60 -4
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { key, noKey } from '../core/keys.js';
|
|
2
|
+
import { postJson } from './press.js';
|
|
3
|
+
/** Actor ids; override if one disappears from the Store. */
|
|
4
|
+
export const ACTORS = {
|
|
5
|
+
x: process.env.OCULON_APIFY_X_ACTOR || 'apidojo~tweet-scraper',
|
|
6
|
+
reddit: process.env.OCULON_APIFY_REDDIT_ACTOR || 'fatihtahta~reddit-scraper-search-fast',
|
|
7
|
+
tiktok: process.env.OCULON_APIFY_TIKTOK_ACTOR || 'clockworks~free-tiktok-scraper',
|
|
8
|
+
};
|
|
9
|
+
async function runActor(ctx, actor, input) {
|
|
10
|
+
const k = key('APIFY_TOKEN');
|
|
11
|
+
if (!k)
|
|
12
|
+
return noKey('apify', 'APIFY_TOKEN');
|
|
13
|
+
const url = `https://api.apify.com/v2/acts/${actor}/run-sync-get-dataset-items?timeout=120&memory=1024`;
|
|
14
|
+
const r = await postJson(ctx, url, input, { authorization: `Bearer ${k}` }, 'apify', 3 * 3600);
|
|
15
|
+
if (r.data && !Array.isArray(r.data))
|
|
16
|
+
return { data: null, prov: { ...r.prov, status: 'ERROR', note: r.data.error?.message?.slice(0, 160) ?? 'actor failed' } };
|
|
17
|
+
// Some actors answer [{noResults:true}] on a transient miss; never cache that.
|
|
18
|
+
if (Array.isArray(r.data) && (!r.data.length || r.data[0].noResults)) {
|
|
19
|
+
ctx.store.db.prepare('DELETE FROM cache WHERE key = ?').run(`post:${url}:${JSON.stringify(input)}`);
|
|
20
|
+
return { data: [], prov: { ...r.prov, note: 'no results' } };
|
|
21
|
+
}
|
|
22
|
+
return { data: r.data ?? null, prov: r.prov };
|
|
23
|
+
}
|
|
24
|
+
/** Seconds, milliseconds or a date string to ISO; '' when unparseable. */
|
|
25
|
+
export function isoDate(v) {
|
|
26
|
+
const t = typeof v === 'number' ? (v < 1e11 ? v * 1000 : v) : typeof v === 'string' ? (/^\d+(\.\d+)?$/.test(v) ? Number(v) * (Number(v) < 1e11 ? 1000 : 1) : Date.parse(v)) : NaN;
|
|
27
|
+
return Number.isFinite(t) ? new Date(t).toISOString() : '';
|
|
28
|
+
}
|
|
29
|
+
const n = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : 0);
|
|
30
|
+
export async function xPosts(ctx, q, max = 40) {
|
|
31
|
+
const r = await runActor(ctx, ACTORS.x, { searchTerms: [q], maxItems: max, sort: 'Top' });
|
|
32
|
+
return {
|
|
33
|
+
data: r.data
|
|
34
|
+
?.filter((t) => t.type === 'tweet' && t.url)
|
|
35
|
+
.map((t) => ({
|
|
36
|
+
platform: 'x',
|
|
37
|
+
text: (t.fullText ?? t.text ?? '').slice(0, 280),
|
|
38
|
+
author: t.author?.userName ?? '?',
|
|
39
|
+
date: isoDate(t.createdAt),
|
|
40
|
+
engagement: n(t.likeCount) + n(t.retweetCount) + n(t.replyCount) + n(t.quoteCount),
|
|
41
|
+
views: t.viewCount ?? null,
|
|
42
|
+
url: t.url,
|
|
43
|
+
})) ?? null,
|
|
44
|
+
prov: r.prov,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
export async function redditPosts(ctx, q, max = 25) {
|
|
48
|
+
const r = await runActor(ctx, ACTORS.reddit, { queries: [q], sort: 'new', maxPosts: max, scrapeComments: false });
|
|
49
|
+
return {
|
|
50
|
+
data: r.data
|
|
51
|
+
?.filter((p) => p.kind !== 'comment' && (p.title || p.body))
|
|
52
|
+
.map((p) => ({
|
|
53
|
+
platform: 'reddit',
|
|
54
|
+
text: `${p.subreddit ? `r/${p.subreddit}: ` : ''}${p.title ?? ''}${p.body ? ` ${p.body}` : ''}`.slice(0, 280),
|
|
55
|
+
author: p.author ?? '?',
|
|
56
|
+
date: isoDate(p.created_utc),
|
|
57
|
+
engagement: n(p.score) + n(p.num_comments),
|
|
58
|
+
views: null,
|
|
59
|
+
url: p.permalink ? (p.permalink.startsWith('http') ? p.permalink : `https://www.reddit.com${p.permalink}`) : (p.url ?? ''),
|
|
60
|
+
})) ?? null,
|
|
61
|
+
prov: r.prov,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
export async function tiktokPosts(ctx, q, max = 20) {
|
|
65
|
+
const r = await runActor(ctx, ACTORS.tiktok, { searchQueries: [q], resultsPerPage: max });
|
|
66
|
+
return {
|
|
67
|
+
data: r.data
|
|
68
|
+
?.filter((v) => v.webVideoUrl)
|
|
69
|
+
.map((v) => ({
|
|
70
|
+
platform: 'tiktok',
|
|
71
|
+
text: (v.text ?? '').slice(0, 280),
|
|
72
|
+
author: v.authorMeta?.name ?? '?',
|
|
73
|
+
date: isoDate(v.createTimeISO),
|
|
74
|
+
engagement: n(v.diggCount) + n(v.shareCount) + n(v.commentCount),
|
|
75
|
+
views: v.playCount ?? null,
|
|
76
|
+
url: v.webVideoUrl,
|
|
77
|
+
})) ?? null,
|
|
78
|
+
prov: r.prov,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type Ctx } from '../core/context.js';
|
|
2
|
+
import type { Sourced } from '../core/types.js';
|
|
3
|
+
export interface Paper {
|
|
4
|
+
id: string;
|
|
5
|
+
title: string;
|
|
6
|
+
published: string;
|
|
7
|
+
}
|
|
8
|
+
export declare function arxivQuery(q: string): string;
|
|
9
|
+
export declare function parseAtom(xml: string): Paper[];
|
|
10
|
+
/** Number of papers submitted between two instants (uses opensearch:totalResults, no entries fetched). */
|
|
11
|
+
export declare function paperCount(ctx: Ctx, query: string, fromMs: number, toMs: number): Promise<Sourced<number>>;
|
|
12
|
+
/** Newest papers matching the query. */
|
|
13
|
+
export declare function recentPapers(ctx: Ctx, query: string, max?: number): Promise<Sourced<Paper[]>>;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { enc } from '../core/context.js';
|
|
2
|
+
export function arxivQuery(q) {
|
|
3
|
+
const t = q.trim().replace(/"/g, '');
|
|
4
|
+
return /\s/.test(t) ? `all:"${t}"` : `all:${t}`;
|
|
5
|
+
}
|
|
6
|
+
const tag = (xml, name) => new RegExp(`<${name}[^>]*>([\\s\\S]*?)</${name}>`).exec(xml)?.[1]?.trim() ?? '';
|
|
7
|
+
export function parseAtom(xml) {
|
|
8
|
+
return [...xml.matchAll(/<entry>([\s\S]*?)<\/entry>/g)].map((m) => {
|
|
9
|
+
const e = m[1] ?? '';
|
|
10
|
+
return { id: tag(e, 'id'), title: tag(e, 'title').replace(/\s+/g, ' '), published: tag(e, 'published') };
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
const arxivStamp = (ms) => new Date(ms).toISOString().slice(0, 16).replace(/[-T:]/g, '');
|
|
14
|
+
/** Number of papers submitted between two instants (uses opensearch:totalResults, no entries fetched). */
|
|
15
|
+
export async function paperCount(ctx, query, fromMs, toMs) {
|
|
16
|
+
const q = `${arxivQuery(query)} AND submittedDate:[${arxivStamp(fromMs)} TO ${arxivStamp(toMs)}]`;
|
|
17
|
+
const url = `https://export.arxiv.org/api/query?search_query=${enc(q)}&max_results=1`;
|
|
18
|
+
const r = await ctx.http.get(url, { source: 'arxiv', as: 'text', ttlSec: 12 * 3600, timeoutMs: 45_000 });
|
|
19
|
+
const total = r.data === null ? null : Number(tag(r.data, 'opensearch:totalResults'));
|
|
20
|
+
return { data: total !== null && Number.isFinite(total) ? total : null, prov: r.prov };
|
|
21
|
+
}
|
|
22
|
+
/** Newest papers matching the query. */
|
|
23
|
+
export async function recentPapers(ctx, query, max = 300) {
|
|
24
|
+
const url = `https://export.arxiv.org/api/query?search_query=${enc(arxivQuery(query))}&sortBy=submittedDate&sortOrder=descending&max_results=${max}`;
|
|
25
|
+
const r = await ctx.http.get(url, { source: 'arxiv', as: 'text', ttlSec: 6 * 3600, timeoutMs: 45_000 });
|
|
26
|
+
return { data: r.data === null ? null : parseAtom(r.data), prov: r.prov };
|
|
27
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type Ctx } from '../core/context.js';
|
|
2
|
+
import type { Sourced } from '../core/types.js';
|
|
3
|
+
/** One certificate, reduced to what we need: which hostnames it covers and when it became valid. */
|
|
4
|
+
export interface CertEntry {
|
|
5
|
+
names: string[];
|
|
6
|
+
notBefore: string;
|
|
7
|
+
issuer: string;
|
|
8
|
+
}
|
|
9
|
+
/** Certificate Transparency logs via crt.sh (unexpired certs only). */
|
|
10
|
+
export declare function crtsh(ctx: Ctx, domain: string): Promise<Sourced<CertEntry[]>>;
|
|
11
|
+
/** Fallback CT source. Unauthenticated access returns a limited, oldest-first page, so results are partial. */
|
|
12
|
+
export declare function certspotter(ctx: Ctx, domain: string): Promise<Sourced<CertEntry[]>>;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { enc } from '../core/context.js';
|
|
2
|
+
/** Certificate Transparency logs via crt.sh (unexpired certs only). */
|
|
3
|
+
export async function crtsh(ctx, domain) {
|
|
4
|
+
const url = `https://crt.sh/?q=${enc(`%.${domain}`)}&output=json&exclude=expired`;
|
|
5
|
+
const r = await ctx.http.get(url, { source: 'crt.sh', ttlSec: 6 * 3600, timeoutMs: 60_000, retries: 1 });
|
|
6
|
+
const data = r.data?.map((row) => ({
|
|
7
|
+
names: row.name_value.split(/\s+/).filter(Boolean),
|
|
8
|
+
notBefore: row.not_before.endsWith('Z') ? row.not_before : `${row.not_before}Z`,
|
|
9
|
+
issuer: /O=([^,]+)/.exec(row.issuer_name)?.[1]?.replace(/"/g, '') ?? row.issuer_name,
|
|
10
|
+
})) ?? null;
|
|
11
|
+
return { data, prov: r.prov };
|
|
12
|
+
}
|
|
13
|
+
/** Fallback CT source. Unauthenticated access returns a limited, oldest-first page, so results are partial. */
|
|
14
|
+
export async function certspotter(ctx, domain) {
|
|
15
|
+
const url = `https://api.certspotter.com/v1/issuances?domain=${enc(domain)}&include_subdomains=true&expand=dns_names&expand=issuer`;
|
|
16
|
+
const r = await ctx.http.get(url, { source: 'certspotter', ttlSec: 6 * 3600, timeoutMs: 30_000, retries: 1 });
|
|
17
|
+
const data = r.data?.map((row) => ({
|
|
18
|
+
names: row.dns_names ?? [],
|
|
19
|
+
notBefore: row.not_before ?? '',
|
|
20
|
+
issuer: row.issuer?.friendly_name ?? row.issuer?.name ?? 'unknown',
|
|
21
|
+
})) ?? null;
|
|
22
|
+
return { data, prov: data ? { ...r.prov, note: [r.prov.note, 'partial: unauthenticated first page only'].filter(Boolean).join('; ') } : r.prov };
|
|
23
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/** Company footprints: hiring (Adzuna), litigation (CourtListener), UK registry (Companies House), brand (Brandfetch). */
|
|
2
|
+
import { type Ctx } from '../core/context.js';
|
|
3
|
+
import type { Sourced } from '../core/types.js';
|
|
4
|
+
export interface Hiring {
|
|
5
|
+
country: string;
|
|
6
|
+
openings: number;
|
|
7
|
+
sample: {
|
|
8
|
+
title: string;
|
|
9
|
+
location: string;
|
|
10
|
+
created: string;
|
|
11
|
+
url: string;
|
|
12
|
+
}[];
|
|
13
|
+
}
|
|
14
|
+
/** Open job ads naming the company, in the US and UK. */
|
|
15
|
+
export declare function hiring(ctx: Ctx, company: string): Promise<Sourced<Hiring[]>>;
|
|
16
|
+
export interface CourtCase {
|
|
17
|
+
name: string;
|
|
18
|
+
filed: string;
|
|
19
|
+
court: string;
|
|
20
|
+
url: string;
|
|
21
|
+
}
|
|
22
|
+
/** Most recently filed federal dockets mentioning the name. */
|
|
23
|
+
export declare function courtCases(ctx: Ctx, name: string, max?: number): Promise<Sourced<{
|
|
24
|
+
total: number;
|
|
25
|
+
cases: CourtCase[];
|
|
26
|
+
}>>;
|
|
27
|
+
export interface UkCompany {
|
|
28
|
+
name: string;
|
|
29
|
+
number: string;
|
|
30
|
+
status: string;
|
|
31
|
+
created: string;
|
|
32
|
+
address: string;
|
|
33
|
+
url: string;
|
|
34
|
+
}
|
|
35
|
+
export declare function ukCompany(ctx: Ctx, name: string): Promise<Sourced<UkCompany>>;
|
|
36
|
+
export interface Brand {
|
|
37
|
+
name: string;
|
|
38
|
+
domain: string;
|
|
39
|
+
description: string;
|
|
40
|
+
logo: string | null;
|
|
41
|
+
links: {
|
|
42
|
+
name: string;
|
|
43
|
+
url: string;
|
|
44
|
+
}[];
|
|
45
|
+
}
|
|
46
|
+
export declare function brand(ctx: Ctx, domain: string): Promise<Sourced<Brand>>;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/** Company footprints: hiring (Adzuna), litigation (CourtListener), UK registry (Companies House), brand (Brandfetch). */
|
|
2
|
+
import { enc } from '../core/context.js';
|
|
3
|
+
import { key, noKey } from '../core/keys.js';
|
|
4
|
+
/** Open job ads naming the company, in the US and UK. */
|
|
5
|
+
export async function hiring(ctx, company) {
|
|
6
|
+
const id = key('ADZUNA_APP_ID');
|
|
7
|
+
const k = key('ADZUNA_APP_KEY');
|
|
8
|
+
if (!id || !k)
|
|
9
|
+
return noKey('adzuna', 'ADZUNA_APP_ID and ADZUNA_APP_KEY');
|
|
10
|
+
const results = await Promise.all(['us', 'gb'].map((cc) => ctx.http.get(`https://api.adzuna.com/v1/api/jobs/${cc}/search/1?app_id=${id}&app_key=${k}&results_per_page=5&sort_by=date&company=${enc(company)}`, { source: 'adzuna', ttlSec: 6 * 3600 })));
|
|
11
|
+
const first = results.find((r) => r.data) ?? results[0];
|
|
12
|
+
const data = results.every((r) => !r.data)
|
|
13
|
+
? null
|
|
14
|
+
: results.map((r, i) => ({
|
|
15
|
+
country: i === 0 ? 'US' : 'GB',
|
|
16
|
+
openings: r.data?.count ?? 0,
|
|
17
|
+
sample: (r.data?.results ?? []).map((j) => ({ title: j.title.replace(/<[^>]+>/g, ''), location: j.location?.display_name ?? '', created: j.created, url: j.redirect_url })),
|
|
18
|
+
}));
|
|
19
|
+
return { data, prov: first.prov };
|
|
20
|
+
}
|
|
21
|
+
/** Most recently filed federal dockets mentioning the name. */
|
|
22
|
+
export async function courtCases(ctx, name, max = 10) {
|
|
23
|
+
const k = key('COURTLISTENER_TOKEN');
|
|
24
|
+
if (!k)
|
|
25
|
+
return noKey('courtlistener', 'COURTLISTENER_TOKEN');
|
|
26
|
+
const r = await ctx.http.get(`https://www.courtlistener.com/api/rest/v4/search/?q=${enc(`"${name.replace(/"/g, '')}"`)}&type=r&order_by=${enc('dateFiled desc')}`, { source: 'courtlistener', ttlSec: 6 * 3600, headers: { authorization: `Token ${k}` } });
|
|
27
|
+
return {
|
|
28
|
+
data: r.data
|
|
29
|
+
? {
|
|
30
|
+
total: r.data.count ?? 0,
|
|
31
|
+
cases: (r.data.results ?? []).slice(0, max).map((c) => ({ name: c.caseName, filed: c.dateFiled, court: c.court, url: `https://www.courtlistener.com${c.docket_absolute_url ?? ''}` })),
|
|
32
|
+
}
|
|
33
|
+
: null,
|
|
34
|
+
prov: r.prov,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
export async function ukCompany(ctx, name) {
|
|
38
|
+
const k = key('COMPANIES_HOUSE_API_KEY');
|
|
39
|
+
if (!k)
|
|
40
|
+
return noKey('companies-house', 'COMPANIES_HOUSE_API_KEY');
|
|
41
|
+
const r = await ctx.http.get(`https://api.company-information.service.gov.uk/search/companies?q=${enc(name)}&items_per_page=5`, { source: 'companies-house', ttlSec: 7 * 86_400, headers: { authorization: `Basic ${Buffer.from(`${k}:`).toString('base64')}` } });
|
|
42
|
+
const q = name.toLowerCase();
|
|
43
|
+
const items = r.data?.items ?? [];
|
|
44
|
+
const best = items.find((i) => i.title.toLowerCase().startsWith(q) && i.company_status === 'active') ?? items.find((i) => i.title.toLowerCase().includes(q));
|
|
45
|
+
return {
|
|
46
|
+
data: best ? { name: best.title, number: best.company_number, status: best.company_status, created: best.date_of_creation, address: best.address_snippet, url: `https://find-and-update.company-information.service.gov.uk${best.links?.self ?? ''}` } : null,
|
|
47
|
+
prov: r.prov,
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
export async function brand(ctx, domain) {
|
|
51
|
+
const k = key('BRANDFETCH_API_KEY');
|
|
52
|
+
if (!k)
|
|
53
|
+
return noKey('brandfetch', 'BRANDFETCH_API_KEY');
|
|
54
|
+
const r = await ctx.http.get(`https://api.brandfetch.io/v2/brands/${enc(domain)}`, { source: 'brandfetch', ttlSec: 30 * 86_400, headers: { authorization: `Bearer ${k}` } });
|
|
55
|
+
const d = r.data;
|
|
56
|
+
return {
|
|
57
|
+
data: d?.name ? { name: d.name, domain: d.domain ?? domain, description: (d.description ?? '').slice(0, 300), logo: d.logos?.[0]?.formats?.find((f) => f.format === 'png' || f.format === 'svg')?.src ?? null, links: d.links ?? [] } : null,
|
|
58
|
+
prov: r.prov,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/** Earth observation sources: NASA EONET natural events, NASA GIBS imagery, OpenStreetMap Nominatim geocoding. */
|
|
2
|
+
import { type Ctx } from '../core/context.js';
|
|
3
|
+
import type { Provenance, Sourced } from '../core/types.js';
|
|
4
|
+
export interface EonetEvent {
|
|
5
|
+
id: string;
|
|
6
|
+
title: string;
|
|
7
|
+
category: string;
|
|
8
|
+
date: string;
|
|
9
|
+
lat: number | null;
|
|
10
|
+
lon: number | null;
|
|
11
|
+
magnitude: number | null;
|
|
12
|
+
unit: string | null;
|
|
13
|
+
url: string;
|
|
14
|
+
}
|
|
15
|
+
/** Open natural events (storms, wildfires, volcanoes, floods, ...) updated in the last `days` days. */
|
|
16
|
+
export declare function eonetEvents(ctx: Ctx, days?: number): Promise<Sourced<EonetEvent[]>>;
|
|
17
|
+
export interface Place {
|
|
18
|
+
name: string;
|
|
19
|
+
lat: number;
|
|
20
|
+
lon: number;
|
|
21
|
+
/** [south, north, west, east] */
|
|
22
|
+
bbox: [number, number, number, number];
|
|
23
|
+
type: string;
|
|
24
|
+
importance: number;
|
|
25
|
+
}
|
|
26
|
+
/** True when every word of the query appears in the first part of the display name (the place itself). */
|
|
27
|
+
export declare function nameMatches(displayName: string, q: string): boolean;
|
|
28
|
+
/** Geocode with Nominatim (usage policy: max 1 request/second, identifying User-Agent; cached 30 days). */
|
|
29
|
+
export declare function geocode(ctx: Ctx, q: string, limit?: number): Promise<Sourced<Place[]>>;
|
|
30
|
+
export declare const NIGHT_LIGHTS = "VIIRS_NOAA20_GapFilled_BRDF_Corrected_DayNightBand_Radiance";
|
|
31
|
+
export declare const TRUE_COLOR = "MODIS_Terra_CorrectedReflectance_TrueColor";
|
|
32
|
+
/**
|
|
33
|
+
* One GIBS WMS image for a date. Past-date imagery does not change, so PNGs are cached (base64) for 30 days.
|
|
34
|
+
* Night lights are only published in Web Mercator; true color is requested in EPSG:4326 (lat,lon axis order).
|
|
35
|
+
*/
|
|
36
|
+
export declare function gibsImage(ctx: Ctx, layer: string, bbox: Place['bbox'], date: string, size?: number): Promise<{
|
|
37
|
+
png: Buffer | null;
|
|
38
|
+
prov: Provenance;
|
|
39
|
+
}>;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/** Earth observation sources: NASA EONET natural events, NASA GIBS imagery, OpenStreetMap Nominatim geocoding. */
|
|
2
|
+
import { enc } from '../core/context.js';
|
|
3
|
+
/** Open natural events (storms, wildfires, volcanoes, floods, ...) updated in the last `days` days. */
|
|
4
|
+
export async function eonetEvents(ctx, days = 7) {
|
|
5
|
+
const r = await ctx.http.get(`https://eonet.gsfc.nasa.gov/api/v3/events?status=open&days=${days}`, { source: 'nasa-eonet', ttlSec: 1800, timeoutMs: 40_000 });
|
|
6
|
+
const data = r.data?.events?.map((e) => {
|
|
7
|
+
const g = e.geometry[e.geometry.length - 1];
|
|
8
|
+
const point = g?.type === 'Point' && Array.isArray(g.coordinates) ? g.coordinates : null;
|
|
9
|
+
return {
|
|
10
|
+
id: e.id,
|
|
11
|
+
title: e.title,
|
|
12
|
+
category: e.categories[0]?.id ?? 'unknown',
|
|
13
|
+
date: g?.date ?? '',
|
|
14
|
+
lat: point?.[1] ?? null,
|
|
15
|
+
lon: point?.[0] ?? null,
|
|
16
|
+
magnitude: g?.magnitudeValue ?? null,
|
|
17
|
+
unit: g?.magnitudeUnit ?? null,
|
|
18
|
+
url: e.sources?.[0]?.url ?? e.link ?? `https://eonet.gsfc.nasa.gov/api/v3/events/${e.id}`,
|
|
19
|
+
};
|
|
20
|
+
}) ?? null;
|
|
21
|
+
return { data, prov: r.prov };
|
|
22
|
+
}
|
|
23
|
+
const MINOR = new Set(['road', 'street', 'house', 'building', 'amenity', 'shop', 'highway', 'residential', 'neighbourhood', 'postcode']);
|
|
24
|
+
/** True when every word of the query appears in the first part of the display name (the place itself). */
|
|
25
|
+
export function nameMatches(displayName, q) {
|
|
26
|
+
const head = (displayName.split(',')[0] ?? '').toLowerCase();
|
|
27
|
+
return q
|
|
28
|
+
.toLowerCase()
|
|
29
|
+
.split(/[^\p{L}\p{N}]+/u)
|
|
30
|
+
.filter(Boolean)
|
|
31
|
+
.every((w) => head.includes(w));
|
|
32
|
+
}
|
|
33
|
+
/** Geocode with Nominatim (usage policy: max 1 request/second, identifying User-Agent; cached 30 days). */
|
|
34
|
+
export async function geocode(ctx, q, limit = 5) {
|
|
35
|
+
const r = await ctx.http.get(`https://nominatim.openstreetmap.org/search?q=${enc(q)}&format=json&limit=${limit}&accept-language=en`, { source: 'nominatim', ttlSec: 30 * 86_400 });
|
|
36
|
+
const data = r.data?.map((p) => ({
|
|
37
|
+
name: p.display_name,
|
|
38
|
+
lat: Number(p.lat),
|
|
39
|
+
lon: Number(p.lon),
|
|
40
|
+
bbox: p.boundingbox.map(Number),
|
|
41
|
+
type: p.addresstype ?? p.type ?? 'place',
|
|
42
|
+
importance: p.importance ?? 0,
|
|
43
|
+
}))
|
|
44
|
+
// Keep Nominatim relevance order, but prefer results whose own name matches the query, and push
|
|
45
|
+
// streets/buildings last. (Sorting by importance alone let an unrelated, more famous city win.)
|
|
46
|
+
.map((p, i) => ({ p, i, match: nameMatches(p.name, q) }))
|
|
47
|
+
.sort((a, b) => Number(b.match) - Number(a.match) || Number(MINOR.has(a.p.type)) - Number(MINOR.has(b.p.type)) || a.i - b.i)
|
|
48
|
+
.map((x) => x.p) ?? null;
|
|
49
|
+
return { data, prov: r.prov };
|
|
50
|
+
}
|
|
51
|
+
export const NIGHT_LIGHTS = 'VIIRS_NOAA20_GapFilled_BRDF_Corrected_DayNightBand_Radiance';
|
|
52
|
+
export const TRUE_COLOR = 'MODIS_Terra_CorrectedReflectance_TrueColor';
|
|
53
|
+
const mercator = (lat, lon) => [(lon * 20037508.34) / 180, Math.log(Math.tan(((90 + lat) * Math.PI) / 360)) * 6378137];
|
|
54
|
+
/**
|
|
55
|
+
* One GIBS WMS image for a date. Past-date imagery does not change, so PNGs are cached (base64) for 30 days.
|
|
56
|
+
* Night lights are only published in Web Mercator; true color is requested in EPSG:4326 (lat,lon axis order).
|
|
57
|
+
*/
|
|
58
|
+
export async function gibsImage(ctx, layer, bbox, date, size = 256) {
|
|
59
|
+
const [s, n, w, e] = bbox;
|
|
60
|
+
const merc = layer === NIGHT_LIGHTS;
|
|
61
|
+
const box = merc ? [...mercator(s, w), ...mercator(n, e)].map((v) => Math.round(v)).join(',') : [s, w, n, e].join(',');
|
|
62
|
+
const crs = merc ? 'EPSG:3857' : 'EPSG:4326';
|
|
63
|
+
const url = `https://gibs.earthdata.nasa.gov/wms/${merc ? 'epsg3857' : 'epsg4326'}/best/wms.cgi?SERVICE=WMS&REQUEST=GetMap&VERSION=1.3.0&LAYERS=${layer}&CRS=${crs}&BBOX=${box}&WIDTH=${size}&HEIGHT=${size}&FORMAT=image/png&TIME=${date}`;
|
|
64
|
+
const key = `bytes:${url}`;
|
|
65
|
+
const cached = ctx.store.cacheGet(key);
|
|
66
|
+
if (cached && Date.now() - cached.fetchedAt < 30 * 86_400_000) {
|
|
67
|
+
return { png: Buffer.from(cached.body, 'base64'), prov: { source: 'nasa-gibs', url, status: 'CACHED', fetchedAt: new Date(cached.fetchedAt).toISOString() } };
|
|
68
|
+
}
|
|
69
|
+
const r = await ctx.http.getBytes(url, { source: 'nasa-gibs', timeoutMs: 60_000 });
|
|
70
|
+
if (r.data && r.data.subarray(0, 4).toString('latin1') !== '\x89PNG') {
|
|
71
|
+
return { png: null, prov: { ...r.prov, status: 'ERROR', note: r.data.toString('utf8').slice(0, 160).replace(/\s+/g, ' ') } };
|
|
72
|
+
}
|
|
73
|
+
if (r.data)
|
|
74
|
+
ctx.store.cachePut(key, r.data.toString('base64'));
|
|
75
|
+
return { png: r.data, prov: r.prov };
|
|
76
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Regulated-product trails (no keys):
|
|
3
|
+
* openFDA enforcement reports: drug, device and food recalls by recalling firm (api.fda.gov; 1,000 requests/day
|
|
4
|
+
* per IP without a key, 240/minute).
|
|
5
|
+
* ClinicalTrials.gov v2: trials a company sponsors or collaborates on, counted by status, plus recent terminations.
|
|
6
|
+
*/
|
|
7
|
+
import { type Ctx } from '../core/context.js';
|
|
8
|
+
import type { Provenance, Sourced } from '../core/types.js';
|
|
9
|
+
export type RecallCategory = 'drug' | 'device' | 'food';
|
|
10
|
+
export interface Recall {
|
|
11
|
+
category: RecallCategory;
|
|
12
|
+
recallNumber: string;
|
|
13
|
+
firm: string;
|
|
14
|
+
/** Class I: reasonable probability of serious harm or death. Class II: temporary or reversible harm. Class III: unlikely to cause harm. */
|
|
15
|
+
classification: string;
|
|
16
|
+
status: string;
|
|
17
|
+
product: string;
|
|
18
|
+
reason: string;
|
|
19
|
+
quantity: string;
|
|
20
|
+
distribution: string;
|
|
21
|
+
/** Dates as YYYY-MM-DD. */
|
|
22
|
+
initiated: string;
|
|
23
|
+
reported: string;
|
|
24
|
+
voluntary: string;
|
|
25
|
+
url: string;
|
|
26
|
+
}
|
|
27
|
+
export interface FirmRecalls {
|
|
28
|
+
firm: string;
|
|
29
|
+
/** All enforcement reports matching the firm name, per category (openFDA total). */
|
|
30
|
+
totals: Record<RecallCategory, number>;
|
|
31
|
+
/** Newest first, up to 10 per category. */
|
|
32
|
+
recent: Recall[];
|
|
33
|
+
/** Class I recalls reported within the window. */
|
|
34
|
+
newClassI: Recall[];
|
|
35
|
+
}
|
|
36
|
+
export declare function enforcement(ctx: Ctx, category: RecallCategory, firm: string, limit?: number): Promise<Sourced<{
|
|
37
|
+
total: number;
|
|
38
|
+
recalls: Recall[];
|
|
39
|
+
}>>;
|
|
40
|
+
/** Drug, device and food recalls for a firm. Each recall must name the firm (all query words), to drop look-alike firms. */
|
|
41
|
+
export declare function recalls(ctx: Ctx, firm: string, opts?: {
|
|
42
|
+
days?: number;
|
|
43
|
+
match?: (recallingFirm: string) => boolean;
|
|
44
|
+
}): Promise<{
|
|
45
|
+
data: FirmRecalls | null;
|
|
46
|
+
provenance: Provenance[];
|
|
47
|
+
}>;
|
|
48
|
+
export interface Trial {
|
|
49
|
+
nctId: string;
|
|
50
|
+
title: string;
|
|
51
|
+
status: string;
|
|
52
|
+
phases: string[];
|
|
53
|
+
leadSponsor: string;
|
|
54
|
+
conditions: string[];
|
|
55
|
+
enrollment: number | null;
|
|
56
|
+
whyStopped: string | null;
|
|
57
|
+
completionDate: string | null;
|
|
58
|
+
lastUpdate: string | null;
|
|
59
|
+
url: string;
|
|
60
|
+
}
|
|
61
|
+
export interface SponsorTrials {
|
|
62
|
+
sponsor: string;
|
|
63
|
+
counts: {
|
|
64
|
+
recruiting: number;
|
|
65
|
+
active: number;
|
|
66
|
+
completed: number;
|
|
67
|
+
terminated: number;
|
|
68
|
+
};
|
|
69
|
+
/** Terminated trials with a completion (stop) date inside the window, newest first. */
|
|
70
|
+
recentlyTerminated: Trial[];
|
|
71
|
+
}
|
|
72
|
+
/** Trials where the company is lead sponsor or collaborator (ClinicalTrials.gov query.spons). */
|
|
73
|
+
export declare function sponsorTrials(ctx: Ctx, sponsor: string, days?: number): Promise<{
|
|
74
|
+
data: SponsorTrials | null;
|
|
75
|
+
provenance: Provenance[];
|
|
76
|
+
}>;
|
|
77
|
+
export declare const isPhase3: (t: Trial) => boolean;
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Regulated-product trails (no keys):
|
|
3
|
+
* openFDA enforcement reports: drug, device and food recalls by recalling firm (api.fda.gov; 1,000 requests/day
|
|
4
|
+
* per IP without a key, 240/minute).
|
|
5
|
+
* ClinicalTrials.gov v2: trials a company sponsors or collaborates on, counted by status, plus recent terminations.
|
|
6
|
+
*/
|
|
7
|
+
import { DAY_MS, enc } from '../core/context.js';
|
|
8
|
+
const isoDay = (s) => (s && /^\d{8}$/.test(s) ? `${s.slice(0, 4)}-${s.slice(4, 6)}-${s.slice(6, 8)}` : (s ?? ''));
|
|
9
|
+
const compact = (s, n) => (s ?? '').replace(/\s+/g, ' ').trim().slice(0, n);
|
|
10
|
+
/** openFDA phrase search; quotes and other syntax characters in the name are dropped. */
|
|
11
|
+
const firmTerm = (firm) => `"${firm.replace(/["\\:()[\]{}+]/g, ' ').replace(/\s+/g, ' ').trim()}"`;
|
|
12
|
+
export async function enforcement(ctx, category, firm, limit = 10) {
|
|
13
|
+
const url = `https://api.fda.gov/${category}/enforcement.json?search=recalling_firm:${enc(firmTerm(firm))}&sort=report_date:desc&limit=${limit}`;
|
|
14
|
+
const r = await ctx.http.get(url, {
|
|
15
|
+
source: 'openfda',
|
|
16
|
+
ttlSec: 12 * 3600,
|
|
17
|
+
keep: (d) => ({
|
|
18
|
+
total: d.meta?.results?.total ?? d.results?.length ?? 0,
|
|
19
|
+
recalls: (d.results ?? []).map((x) => ({
|
|
20
|
+
category,
|
|
21
|
+
recallNumber: x.recall_number ?? '',
|
|
22
|
+
firm: x.recalling_firm ?? '',
|
|
23
|
+
classification: x.classification ?? '',
|
|
24
|
+
status: x.status ?? '',
|
|
25
|
+
product: compact(x.product_description, 240),
|
|
26
|
+
reason: compact(x.reason_for_recall, 300),
|
|
27
|
+
quantity: compact(x.product_quantity, 80),
|
|
28
|
+
distribution: compact(x.distribution_pattern, 160),
|
|
29
|
+
initiated: isoDay(x.recall_initiation_date),
|
|
30
|
+
reported: isoDay(x.report_date),
|
|
31
|
+
voluntary: x.voluntary_mandated ?? '',
|
|
32
|
+
// The openFDA record itself; FDA's enforcement-report site has no stable per-recall link.
|
|
33
|
+
url: `https://api.fda.gov/${category}/enforcement.json?search=recall_number:${enc(`"${x.recall_number ?? ''}"`)}`,
|
|
34
|
+
})),
|
|
35
|
+
}),
|
|
36
|
+
});
|
|
37
|
+
// openFDA answers 404 "No matches found" when nothing matches; that is an empty result, not an outage.
|
|
38
|
+
if (!r.data && r.prov.note === 'HTTP 404')
|
|
39
|
+
return { data: { total: 0, recalls: [] }, prov: r.prov };
|
|
40
|
+
return r;
|
|
41
|
+
}
|
|
42
|
+
/** Drug, device and food recalls for a firm. Each recall must name the firm (all query words), to drop look-alike firms. */
|
|
43
|
+
export async function recalls(ctx, firm, opts = {}) {
|
|
44
|
+
const days = opts.days ?? 90;
|
|
45
|
+
const cats = ['drug', 'device', 'food'];
|
|
46
|
+
const rs = await Promise.all(cats.map((c) => enforcement(ctx, c, firm)));
|
|
47
|
+
const provenance = rs.map((r) => r.prov);
|
|
48
|
+
if (rs.every((r) => !r.data))
|
|
49
|
+
return { data: null, provenance };
|
|
50
|
+
const words = firm.toLowerCase().split(/[^a-z0-9]+/).filter((w) => w.length > 1);
|
|
51
|
+
const match = opts.match ?? ((f) => words.every((w) => new RegExp(`\\b${w}\\b`).test(f.toLowerCase())));
|
|
52
|
+
const totals = { drug: 0, device: 0, food: 0 };
|
|
53
|
+
const recent = [];
|
|
54
|
+
cats.forEach((c, i) => {
|
|
55
|
+
const d = rs[i].data;
|
|
56
|
+
if (!d)
|
|
57
|
+
return;
|
|
58
|
+
const mine = d.recalls.filter((x) => match(x.firm));
|
|
59
|
+
// The total counts every firm the phrase matched; only report it when the sample is all this firm.
|
|
60
|
+
totals[c] = mine.length === d.recalls.length ? d.total : mine.length;
|
|
61
|
+
recent.push(...mine);
|
|
62
|
+
});
|
|
63
|
+
recent.sort((a, b) => b.reported.localeCompare(a.reported));
|
|
64
|
+
const since = new Date(ctx.now().getTime() - days * DAY_MS).toISOString().slice(0, 10);
|
|
65
|
+
return { data: { firm, totals, recent, newClassI: recent.filter((x) => x.classification === 'Class I' && x.reported >= since) }, provenance };
|
|
66
|
+
}
|
|
67
|
+
const CT = 'https://clinicaltrials.gov/api/v2/studies';
|
|
68
|
+
const CT_FIELDS = 'NCTId,BriefTitle,OverallStatus,Phase,WhyStopped,CompletionDate,LastUpdatePostDate,LeadSponsorName,Condition,EnrollmentCount';
|
|
69
|
+
const toTrial = (s) => {
|
|
70
|
+
const p = s.protocolSection ?? {};
|
|
71
|
+
const id = p.identificationModule?.nctId ?? '';
|
|
72
|
+
return {
|
|
73
|
+
nctId: id,
|
|
74
|
+
title: p.identificationModule?.briefTitle ?? '',
|
|
75
|
+
status: p.statusModule?.overallStatus ?? '',
|
|
76
|
+
phases: p.designModule?.phases ?? [],
|
|
77
|
+
leadSponsor: p.sponsorCollaboratorsModule?.leadSponsor?.name ?? '',
|
|
78
|
+
conditions: (p.conditionsModule?.conditions ?? []).slice(0, 4),
|
|
79
|
+
enrollment: p.designModule?.enrollmentInfo?.count ?? null,
|
|
80
|
+
whyStopped: p.statusModule?.whyStopped ?? null,
|
|
81
|
+
completionDate: p.statusModule?.completionDateStruct?.date ?? null,
|
|
82
|
+
lastUpdate: p.statusModule?.lastUpdatePostDateStruct?.date ?? null,
|
|
83
|
+
url: `https://clinicaltrials.gov/study/${id}`,
|
|
84
|
+
};
|
|
85
|
+
};
|
|
86
|
+
async function ctCount(ctx, sponsor, status) {
|
|
87
|
+
const r = await ctx.http.get(`${CT}?query.spons=${enc(sponsor)}&filter.overallStatus=${status}&pageSize=1&countTotal=true&fields=NCTId`, {
|
|
88
|
+
source: 'clinicaltrials',
|
|
89
|
+
ttlSec: 24 * 3600,
|
|
90
|
+
keep: (d) => ({ totalCount: d.totalCount ?? 0 }),
|
|
91
|
+
});
|
|
92
|
+
return { data: r.data ? (r.data.totalCount ?? 0) : null, prov: r.prov };
|
|
93
|
+
}
|
|
94
|
+
/** Trials where the company is lead sponsor or collaborator (ClinicalTrials.gov query.spons). */
|
|
95
|
+
export async function sponsorTrials(ctx, sponsor, days = 180) {
|
|
96
|
+
const [rec, act, done, term] = await Promise.all([
|
|
97
|
+
ctCount(ctx, sponsor, 'RECRUITING'),
|
|
98
|
+
ctCount(ctx, sponsor, 'ACTIVE_NOT_RECRUITING'),
|
|
99
|
+
ctCount(ctx, sponsor, 'COMPLETED'),
|
|
100
|
+
ctx.http.get(`${CT}?query.spons=${enc(sponsor)}&filter.overallStatus=TERMINATED&pageSize=20&countTotal=true&sort=CompletionDate:desc&fields=${CT_FIELDS}`, {
|
|
101
|
+
source: 'clinicaltrials',
|
|
102
|
+
ttlSec: 12 * 3600,
|
|
103
|
+
}),
|
|
104
|
+
]);
|
|
105
|
+
const provenance = [rec.prov, act.prov, done.prov, term.prov];
|
|
106
|
+
if (rec.data === null && act.data === null && done.data === null && !term.data)
|
|
107
|
+
return { data: null, provenance };
|
|
108
|
+
const today = ctx.now().toISOString().slice(0, 10);
|
|
109
|
+
const since = new Date(ctx.now().getTime() - days * DAY_MS).toISOString().slice(0, 10);
|
|
110
|
+
// CompletionDate may be "2026-10" (month only); compare as strings, which still orders correctly.
|
|
111
|
+
const recentlyTerminated = (term.data?.studies ?? []).map(toTrial).filter((t) => t.completionDate && t.completionDate >= since.slice(0, t.completionDate.length) && t.completionDate <= today);
|
|
112
|
+
return {
|
|
113
|
+
data: {
|
|
114
|
+
sponsor,
|
|
115
|
+
counts: { recruiting: rec.data ?? 0, active: act.data ?? 0, completed: done.data ?? 0, terminated: term.data?.totalCount ?? 0 },
|
|
116
|
+
recentlyTerminated,
|
|
117
|
+
},
|
|
118
|
+
provenance,
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
export const isPhase3 = (t) => t.phases.includes('PHASE3');
|