oculon 0.0.0-stage → 0.1.0
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 +342 -0
- package/dist/index.js +495 -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 +111 -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 +40 -0
- package/dist/modules/tortoise.js +104 -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 +44 -0
- package/dist/sources/opentimestamps.js +131 -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 +263 -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 +1143 -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 +135 -0
- package/dist/web/server.d.ts +69 -0
- package/dist/web/server.js +750 -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,63 @@
|
|
|
1
|
+
import { key, missingKey } from '../core/keys.js';
|
|
2
|
+
const TOKEN_URL = 'https://identity.dataspace.copernicus.eu/auth/realms/CDSE/protocol/openid-connect/token';
|
|
3
|
+
const PROCESS_URL = 'https://sh.dataspace.copernicus.eu/api/v1/process';
|
|
4
|
+
let token = null;
|
|
5
|
+
async function getToken(ctx) {
|
|
6
|
+
if (token && token.until > Date.now())
|
|
7
|
+
return { value: token.value };
|
|
8
|
+
const id = key('COPERNICUS_CLIENT_ID');
|
|
9
|
+
const secret = key('COPERNICUS_CLIENT_SECRET');
|
|
10
|
+
if (!id || !secret)
|
|
11
|
+
return { value: null, prov: missingKey('copernicus', 'COPERNICUS_CLIENT_ID and COPERNICUS_CLIENT_SECRET') };
|
|
12
|
+
const r = await ctx.http.postBytes(TOKEN_URL, new TextEncoder().encode(new URLSearchParams({ grant_type: 'client_credentials', client_id: id, client_secret: secret }).toString()), {
|
|
13
|
+
source: 'copernicus-auth',
|
|
14
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
|
15
|
+
timeoutMs: 30_000,
|
|
16
|
+
});
|
|
17
|
+
if (!r.data)
|
|
18
|
+
return { value: null, prov: r.prov };
|
|
19
|
+
try {
|
|
20
|
+
const j = JSON.parse(r.data.toString('utf8'));
|
|
21
|
+
if (!j.access_token)
|
|
22
|
+
return { value: null, prov: { ...r.prov, status: 'ERROR', note: 'no access token' } };
|
|
23
|
+
token = { value: j.access_token, until: Date.now() + Math.max(60, (j.expires_in ?? 600) - 60) * 1000 };
|
|
24
|
+
return { value: token.value };
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return { value: null, prov: { ...r.prov, status: 'ERROR', note: 'invalid token response' } };
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
const TRUE_COLOR = `//VERSION=3
|
|
31
|
+
function setup(){return{input:["B02","B03","B04","dataMask"],output:{bands:4}}}
|
|
32
|
+
function evaluatePixel(s){return[2.5*s.B04,2.5*s.B03,2.5*s.B02,s.dataMask]}`;
|
|
33
|
+
const RADAR = `//VERSION=3
|
|
34
|
+
function setup(){return{input:["VV","dataMask"],output:{bands:4}}}
|
|
35
|
+
function evaluatePixel(s){var v=Math.max(0,Math.log(0.05/0.02)*0.21+Math.log(Math.max(s.VV,0.0001))*0.21+0.6);return[v,v,v,s.dataMask]}`;
|
|
36
|
+
/** [south, north, west, east] box, time window, image width; returns a PNG. */
|
|
37
|
+
export async function sentinelImage(ctx, box, from, to, kind = 'optical', width = 1024) {
|
|
38
|
+
const t = await getToken(ctx);
|
|
39
|
+
if (!t.value)
|
|
40
|
+
return { png: null, prov: t.prov };
|
|
41
|
+
const [s, n, w, e] = box;
|
|
42
|
+
const latMid = ((s + n) / 2) * (Math.PI / 180);
|
|
43
|
+
const height = Math.max(64, Math.min(2048, Math.round((width * (n - s)) / ((e - w) * Math.cos(latMid)))));
|
|
44
|
+
const body = {
|
|
45
|
+
input: {
|
|
46
|
+
bounds: { bbox: [w, s, e, n], properties: { crs: 'http://www.opengis.net/def/crs/EPSG/0/4326' } },
|
|
47
|
+
data: [
|
|
48
|
+
kind === 'optical'
|
|
49
|
+
? { type: 'sentinel-2-l2a', dataFilter: { timeRange: { from: from.toISOString(), to: to.toISOString() }, mosaickingOrder: 'leastCC' } }
|
|
50
|
+
: { type: 'sentinel-1-grd', dataFilter: { timeRange: { from: from.toISOString(), to: to.toISOString() }, mosaickingOrder: 'mostRecent' }, processing: { orthorectify: true } },
|
|
51
|
+
],
|
|
52
|
+
},
|
|
53
|
+
output: { width, height, responses: [{ identifier: 'default', format: { type: 'image/png' } }] },
|
|
54
|
+
evalscript: kind === 'optical' ? TRUE_COLOR : RADAR,
|
|
55
|
+
};
|
|
56
|
+
const r = await ctx.http.postBytes(PROCESS_URL, new TextEncoder().encode(JSON.stringify(body)), {
|
|
57
|
+
source: 'copernicus',
|
|
58
|
+
headers: { authorization: `Bearer ${t.value}`, 'content-type': 'application/json', accept: 'image/png' },
|
|
59
|
+
timeoutMs: 120_000,
|
|
60
|
+
});
|
|
61
|
+
const ok = r.data && r.data.subarray(0, 4).toString('hex') === '89504e47';
|
|
62
|
+
return { png: ok ? r.data : null, prov: ok ? r.prov : { ...r.prov, status: r.prov.status === 'LIVE' ? 'ERROR' : r.prov.status, note: r.prov.note ?? r.data?.toString('utf8').slice(0, 160) } };
|
|
63
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* EVM signature decoding (no keys): 4-byte function selectors and 32-byte event topics to text signatures.
|
|
3
|
+
* Primary: openchain.xyz signature database (batch lookup, verified-contract hint, spam filter).
|
|
4
|
+
* Fallback: 4byte.directory (one request per hash; the oldest submission is taken as canonical).
|
|
5
|
+
* Signatures never change, so every answer is kept in the derived cache (not pruned); unknown hashes are
|
|
6
|
+
* re-asked after a week because new signatures get submitted all the time.
|
|
7
|
+
*/
|
|
8
|
+
import type { Ctx } from '../core/context.js';
|
|
9
|
+
/** Decode 4-byte function selectors (or full calldata) to text signatures such as `transfer(address,uint256)`. Keys are lowercase selectors; unknown or malformed input maps to null. */
|
|
10
|
+
export declare function decodeSelectors(ctx: Ctx, selectors: string[]): Promise<Record<string, string | null>>;
|
|
11
|
+
/** Decode 32-byte event topics (topic0) to text signatures such as `Transfer(address,address,uint256)`. */
|
|
12
|
+
export declare function decodeEvents(ctx: Ctx, topics: string[]): Promise<Record<string, string | null>>;
|
|
13
|
+
/** `transfer(address,uint256)` to `transfer`: a short method label for transaction lists. */
|
|
14
|
+
export declare const methodName: (sig: string | null | undefined) => string | null;
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
const OPENCHAIN = 'https://api.openchain.xyz/signature-database/v1/lookup';
|
|
2
|
+
const FOURBYTE = 'https://www.4byte.directory/api/v1';
|
|
3
|
+
const BATCH = 40;
|
|
4
|
+
/** 4byte answers one hash per request, so the fallback is capped per call. */
|
|
5
|
+
const FOURBYTE_MAX = 25;
|
|
6
|
+
const NULL_TTL_MS = 7 * 86_400_000;
|
|
7
|
+
const PATTERN = { function: /^0x[0-9a-f]{8}$/, event: /^0x[0-9a-f]{64}$/ };
|
|
8
|
+
const cacheKey = (kind, hash) => `derived:sig:${kind}:${hash}`;
|
|
9
|
+
function normalise(kind, raw) {
|
|
10
|
+
let h = raw.trim().toLowerCase();
|
|
11
|
+
if (!h.startsWith('0x'))
|
|
12
|
+
h = `0x${h}`;
|
|
13
|
+
// Accept full calldata for functions: the selector is its first four bytes.
|
|
14
|
+
if (kind === 'function' && /^0x[0-9a-f]{8,}$/.test(h))
|
|
15
|
+
h = h.slice(0, 10);
|
|
16
|
+
return PATTERN[kind].test(h) ? h : null;
|
|
17
|
+
}
|
|
18
|
+
/** Pick the best candidate: unfiltered first, then one seen in a verified contract. */
|
|
19
|
+
function pickOpenchain(list) {
|
|
20
|
+
if (!list?.length)
|
|
21
|
+
return null;
|
|
22
|
+
const ok = list.filter((x) => !x.filtered);
|
|
23
|
+
const pool = ok.length ? ok : list;
|
|
24
|
+
return (pool.find((x) => x.hasVerifiedContract) ?? pool[0]).name;
|
|
25
|
+
}
|
|
26
|
+
async function decode(ctx, kind, input) {
|
|
27
|
+
const out = {};
|
|
28
|
+
const nowMs = ctx.now().getTime();
|
|
29
|
+
const todo = [];
|
|
30
|
+
for (const raw of input) {
|
|
31
|
+
const h = normalise(kind, raw);
|
|
32
|
+
if (!h) {
|
|
33
|
+
out[raw] = null;
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
if (h in out)
|
|
37
|
+
continue;
|
|
38
|
+
const c = ctx.store.cacheGet(cacheKey(kind, h));
|
|
39
|
+
if (c) {
|
|
40
|
+
try {
|
|
41
|
+
const v = JSON.parse(c.body).name;
|
|
42
|
+
if (v !== null || nowMs - c.fetchedAt < NULL_TTL_MS) {
|
|
43
|
+
out[h] = v;
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
catch { }
|
|
48
|
+
}
|
|
49
|
+
out[h] = null;
|
|
50
|
+
todo.push(h);
|
|
51
|
+
}
|
|
52
|
+
if (!todo.length)
|
|
53
|
+
return out;
|
|
54
|
+
const save = (h, name) => {
|
|
55
|
+
out[h] = name;
|
|
56
|
+
ctx.store.cachePut(cacheKey(kind, h), JSON.stringify({ name }), nowMs);
|
|
57
|
+
};
|
|
58
|
+
// openchain: batch lookup.
|
|
59
|
+
const missing = [];
|
|
60
|
+
let openchainUp = true;
|
|
61
|
+
for (let i = 0; i < todo.length; i += BATCH) {
|
|
62
|
+
const chunk = todo.slice(i, i + BATCH);
|
|
63
|
+
const r = await ctx.http.get(`${OPENCHAIN}?${kind}=${chunk.join(',')}&filter=true`, { source: 'openchain', ttlSec: 86_400, timeoutMs: 20_000, retries: 1 });
|
|
64
|
+
const res = r.data?.ok !== false ? r.data?.result?.[kind] : undefined;
|
|
65
|
+
if (!res) {
|
|
66
|
+
openchainUp = false;
|
|
67
|
+
missing.push(...chunk);
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
for (const h of chunk) {
|
|
71
|
+
const name = pickOpenchain(res[h]);
|
|
72
|
+
if (name)
|
|
73
|
+
save(h, name);
|
|
74
|
+
else
|
|
75
|
+
missing.push(h);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
// 4byte.directory: fallback when openchain is down, and a second opinion for hashes openchain does not know.
|
|
79
|
+
const path = kind === 'function' ? 'signatures' : 'event-signatures';
|
|
80
|
+
for (const h of missing.slice(0, FOURBYTE_MAX)) {
|
|
81
|
+
const r = await ctx.http.get(`${FOURBYTE}/${path}/?hex_signature=${h}`, { source: '4byte', ttlSec: 86_400, timeoutMs: 20_000, retries: 1 });
|
|
82
|
+
// A failed request is not cached as "unknown", so the next call asks again.
|
|
83
|
+
if (!r.data)
|
|
84
|
+
continue;
|
|
85
|
+
const best = [...(r.data.results ?? [])].sort((a, b) => a.id - b.id)[0];
|
|
86
|
+
save(h, best?.text_signature ?? null);
|
|
87
|
+
}
|
|
88
|
+
// Past the 4byte cap: remember openchain's "unknown" answer for a week.
|
|
89
|
+
if (openchainUp)
|
|
90
|
+
for (const h of missing.slice(FOURBYTE_MAX))
|
|
91
|
+
save(h, null);
|
|
92
|
+
return out;
|
|
93
|
+
}
|
|
94
|
+
/** Decode 4-byte function selectors (or full calldata) to text signatures such as `transfer(address,uint256)`. Keys are lowercase selectors; unknown or malformed input maps to null. */
|
|
95
|
+
export function decodeSelectors(ctx, selectors) {
|
|
96
|
+
return decode(ctx, 'function', selectors);
|
|
97
|
+
}
|
|
98
|
+
/** Decode 32-byte event topics (topic0) to text signatures such as `Transfer(address,address,uint256)`. */
|
|
99
|
+
export function decodeEvents(ctx, topics) {
|
|
100
|
+
return decode(ctx, 'event', topics);
|
|
101
|
+
}
|
|
102
|
+
/** `transfer(address,uint256)` to `transfer`: a short method label for transaction lists. */
|
|
103
|
+
export const methodName = (sig) => (sig ? sig.split('(')[0] : null);
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** Social and research reach: YouTube, Bluesky, OpenAlex. */
|
|
2
|
+
import { type Ctx } from '../core/context.js';
|
|
3
|
+
import type { Sourced } from '../core/types.js';
|
|
4
|
+
export interface Video {
|
|
5
|
+
title: string;
|
|
6
|
+
channel: string;
|
|
7
|
+
date: string;
|
|
8
|
+
url: string;
|
|
9
|
+
}
|
|
10
|
+
export declare function youtube(ctx: Ctx, q: string, days?: number, max?: number): Promise<Sourced<Video[]>>;
|
|
11
|
+
export interface Post {
|
|
12
|
+
text: string;
|
|
13
|
+
author: string;
|
|
14
|
+
date: string;
|
|
15
|
+
likes: number;
|
|
16
|
+
reposts: number;
|
|
17
|
+
url: string;
|
|
18
|
+
}
|
|
19
|
+
/** Most-liked recent Bluesky posts matching the query. */
|
|
20
|
+
export declare function bluesky(ctx: Ctx, q: string, max?: number): Promise<Sourced<Post[]>>;
|
|
21
|
+
/** Number of scholarly works (OpenAlex) matching `q` published between two dates. */
|
|
22
|
+
export declare function openalexCount(ctx: Ctx, q: string, from: string, to: string): Promise<Sourced<number>>;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/** Social and research reach: YouTube, Bluesky, OpenAlex. */
|
|
2
|
+
import { DAY_MS, enc } from '../core/context.js';
|
|
3
|
+
import { key, noKey } from '../core/keys.js';
|
|
4
|
+
import { postJson } from './press.js';
|
|
5
|
+
export async function youtube(ctx, q, days = 7, max = 10) {
|
|
6
|
+
const k = key('YOUTUBE_API_KEY');
|
|
7
|
+
if (!k)
|
|
8
|
+
return noKey('youtube', 'YOUTUBE_API_KEY');
|
|
9
|
+
// Hour-aligned "after" keeps the cache key stable; search costs 100 quota units, so cache for 6 hours.
|
|
10
|
+
const after = new Date(Math.floor((ctx.now().getTime() - days * DAY_MS) / 3_600_000) * 3_600_000).toISOString();
|
|
11
|
+
const r = await ctx.http.get(`https://www.googleapis.com/youtube/v3/search?part=snippet&type=video&order=viewCount&maxResults=${max}&publishedAfter=${enc(after)}&q=${enc(q)}&key=${k}`, { source: 'youtube', ttlSec: 6 * 3600 });
|
|
12
|
+
return {
|
|
13
|
+
data: r.data?.items?.filter((i) => i.id.videoId).map((i) => ({ title: decodeEntities(i.snippet.title), channel: i.snippet.channelTitle, date: i.snippet.publishedAt, url: `https://www.youtube.com/watch?v=${i.id.videoId}` })) ?? null,
|
|
14
|
+
prov: r.prov,
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
const decodeEntities = (s) => s.replace(/'/g, "'").replace(/"/g, '"').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
18
|
+
let bskySession = null;
|
|
19
|
+
async function bskyToken(ctx) {
|
|
20
|
+
if (bskySession && bskySession.until > Date.now())
|
|
21
|
+
return { jwt: bskySession.jwt, prov: { source: 'bluesky', url: 'session', status: 'CACHED', fetchedAt: new Date().toISOString() } };
|
|
22
|
+
const id = key('BLUESKY_HANDLE');
|
|
23
|
+
const pw = key('BLUESKY_APP_PASSWORD');
|
|
24
|
+
if (!id || !pw)
|
|
25
|
+
return { jwt: null, prov: noKey('bluesky', 'BLUESKY_HANDLE and BLUESKY_APP_PASSWORD').prov };
|
|
26
|
+
// Session tokens are never cached on disk: ttl 0 and a unique cache key per minute.
|
|
27
|
+
const r = await postJson(ctx, 'https://bsky.social/xrpc/com.atproto.server.createSession', { identifier: id, password: pw, _t: Math.floor(Date.now() / 60_000) }, {}, 'bluesky', 0);
|
|
28
|
+
ctx.store.db.prepare("DELETE FROM cache WHERE key LIKE 'post:https://bsky.social/xrpc/com.atproto.server.createSession%'").run();
|
|
29
|
+
if (r.data?.accessJwt)
|
|
30
|
+
bskySession = { jwt: r.data.accessJwt, until: Date.now() + 60 * 60_000 };
|
|
31
|
+
return { jwt: r.data?.accessJwt ?? null, prov: r.prov };
|
|
32
|
+
}
|
|
33
|
+
/** Most-liked recent Bluesky posts matching the query. */
|
|
34
|
+
export async function bluesky(ctx, q, max = 25) {
|
|
35
|
+
const t = await bskyToken(ctx);
|
|
36
|
+
if (!t.jwt)
|
|
37
|
+
return { data: null, prov: t.prov };
|
|
38
|
+
const r = await ctx.http.get(`https://bsky.social/xrpc/app.bsky.feed.searchPosts?q=${enc(q)}&sort=top&limit=${max}`, { source: 'bluesky', ttlSec: 1800, headers: { authorization: `Bearer ${t.jwt}` } });
|
|
39
|
+
return {
|
|
40
|
+
data: r.data?.posts?.map((p) => ({
|
|
41
|
+
text: (p.record.text ?? '').slice(0, 280),
|
|
42
|
+
author: p.author.handle,
|
|
43
|
+
date: p.record.createdAt ?? '',
|
|
44
|
+
likes: p.likeCount ?? 0,
|
|
45
|
+
reposts: p.repostCount ?? 0,
|
|
46
|
+
url: `https://bsky.app/profile/${p.author.handle}/post/${p.uri.split('/').pop()}`,
|
|
47
|
+
})) ?? null,
|
|
48
|
+
prov: r.prov,
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/** Number of scholarly works (OpenAlex) matching `q` published between two dates. */
|
|
52
|
+
export async function openalexCount(ctx, q, from, to) {
|
|
53
|
+
const k = key('OPENALEX_API_KEY');
|
|
54
|
+
const r = await ctx.http.get(`https://api.openalex.org/works?search=${enc(q)}&filter=from_publication_date:${from},to_publication_date:${to}&per-page=1${k ? `&api_key=${k}` : ''}`, { source: 'openalex', ttlSec: 12 * 3600 });
|
|
55
|
+
return { data: r.data?.meta?.count ?? null, prov: r.prov };
|
|
56
|
+
}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
/** Space weather (NOAA SWPC, keyless; NASA DONKI and NeoWs, NASA_API_KEY or DEMO_KEY) and air quality (OpenAQ). */
|
|
2
|
+
import type { Ctx } from '../core/context.js';
|
|
3
|
+
import type { Provenance, Sourced } from '../core/types.js';
|
|
4
|
+
export interface KpReading {
|
|
5
|
+
time: string;
|
|
6
|
+
kp: number;
|
|
7
|
+
}
|
|
8
|
+
export declare function kpIndex(ctx: Ctx): Promise<Sourced<KpReading[]>>;
|
|
9
|
+
export interface Flare {
|
|
10
|
+
maxClass: string;
|
|
11
|
+
maxTime: string;
|
|
12
|
+
beginTime: string;
|
|
13
|
+
}
|
|
14
|
+
export declare function xrayFlares(ctx: Ctx): Promise<Sourced<Flare[]>>;
|
|
15
|
+
/** Flare class to a sortable magnitude: A1=1e-8 ... X1=1e-4 (W/m^2). */
|
|
16
|
+
export declare function flareFlux(cls: string): number;
|
|
17
|
+
export interface SwpcAlert {
|
|
18
|
+
productId: string;
|
|
19
|
+
/** SWPC message code, e.g. ALTK05 (alert, K-index 5), WARK04 (warning), WATA50 (watch), ALTXMF (X-ray M5). */
|
|
20
|
+
code: string;
|
|
21
|
+
kind: 'ALERT' | 'WARNING' | 'WATCH' | 'SUMMARY' | 'CANCEL' | 'OTHER';
|
|
22
|
+
issued: string;
|
|
23
|
+
title: string;
|
|
24
|
+
/** NOAA scale named in the message, e.g. G1, R2, S1. */
|
|
25
|
+
scale: string | null;
|
|
26
|
+
message: string;
|
|
27
|
+
}
|
|
28
|
+
/** Parse one SWPC alerts.json message body into a typed record. */
|
|
29
|
+
export declare function parseSwpcAlert(x: {
|
|
30
|
+
product_id?: string;
|
|
31
|
+
issue_datetime?: string;
|
|
32
|
+
message?: string;
|
|
33
|
+
}): SwpcAlert;
|
|
34
|
+
/** SWPC alerts, warnings, watches and summaries issued in the last ~30 days, newest first. */
|
|
35
|
+
export declare function swpcAlerts(ctx: Ctx): Promise<Sourced<SwpcAlert[]>>;
|
|
36
|
+
export interface SolarWind {
|
|
37
|
+
time: string | null;
|
|
38
|
+
speedKmS: number | null;
|
|
39
|
+
/** Total interplanetary magnetic field, nT. */
|
|
40
|
+
bt: number | null;
|
|
41
|
+
/** North-south component (GSM), nT. Strongly negative Bz drives geomagnetic storms. */
|
|
42
|
+
bz: number | null;
|
|
43
|
+
}
|
|
44
|
+
/** Latest solar wind speed and magnetic field at L1 (SWPC summary products). */
|
|
45
|
+
export declare function solarWind(ctx: Ctx): Promise<{
|
|
46
|
+
data: SolarWind | null;
|
|
47
|
+
prov: Provenance[];
|
|
48
|
+
}>;
|
|
49
|
+
export interface NoaaScales {
|
|
50
|
+
/** Current R (radio blackout), S (radiation storm), G (geomagnetic storm) levels, 0-5. */
|
|
51
|
+
now: {
|
|
52
|
+
r: number;
|
|
53
|
+
s: number;
|
|
54
|
+
g: number;
|
|
55
|
+
};
|
|
56
|
+
/** Next days: probability (%) of R1-R2 / R3+ blackouts and S1+ storms, plus the forecast G level. */
|
|
57
|
+
days: {
|
|
58
|
+
date: string;
|
|
59
|
+
rMinorProb: number | null;
|
|
60
|
+
rMajorProb: number | null;
|
|
61
|
+
sProb: number | null;
|
|
62
|
+
g: number;
|
|
63
|
+
}[];
|
|
64
|
+
}
|
|
65
|
+
export declare function noaaScales(ctx: Ctx): Promise<Sourced<NoaaScales>>;
|
|
66
|
+
export interface Forecast3Day {
|
|
67
|
+
issued: string | null;
|
|
68
|
+
observedKpMax24h: number | null;
|
|
69
|
+
expectedKpMax: number | null;
|
|
70
|
+
/** Highest forecast Kp per day, e.g. { 'Nov 19': 5 }. */
|
|
71
|
+
kpByDay: Record<string, number>;
|
|
72
|
+
rationale: string | null;
|
|
73
|
+
}
|
|
74
|
+
/** Parse SWPC's plain-text 3-day forecast. */
|
|
75
|
+
export declare function parseForecast3Day(txt: string): Forecast3Day;
|
|
76
|
+
export declare function forecast3Day(ctx: Ctx): Promise<Sourced<Forecast3Day>>;
|
|
77
|
+
export interface DonkiCme {
|
|
78
|
+
id: string;
|
|
79
|
+
start: string;
|
|
80
|
+
speedKmS: number | null;
|
|
81
|
+
halfAngle: number | null;
|
|
82
|
+
type: string | null;
|
|
83
|
+
/** WSA-ENLIL model predicts the shock reaching Earth (shock arrival time), or a glancing blow. */
|
|
84
|
+
earthArrival: string | null;
|
|
85
|
+
earthGlancing: boolean;
|
|
86
|
+
/** Model Kp range for the arrival (kp_90 .. kp_180), when the run gives one. */
|
|
87
|
+
kpPredicted: number | null;
|
|
88
|
+
note: string;
|
|
89
|
+
url: string;
|
|
90
|
+
}
|
|
91
|
+
interface DonkiCmeRaw {
|
|
92
|
+
activityID?: string;
|
|
93
|
+
startTime?: string;
|
|
94
|
+
note?: string;
|
|
95
|
+
link?: string;
|
|
96
|
+
cmeAnalyses?: {
|
|
97
|
+
isMostAccurate?: boolean;
|
|
98
|
+
speed?: number;
|
|
99
|
+
halfAngle?: number;
|
|
100
|
+
type?: string;
|
|
101
|
+
enlilList?: {
|
|
102
|
+
estimatedShockArrivalTime?: string | null;
|
|
103
|
+
isEarthGB?: boolean;
|
|
104
|
+
isEarthMinorImpact?: boolean;
|
|
105
|
+
kp_90?: number | null;
|
|
106
|
+
kp_135?: number | null;
|
|
107
|
+
kp_180?: number | null;
|
|
108
|
+
}[] | null;
|
|
109
|
+
}[] | null;
|
|
110
|
+
}
|
|
111
|
+
export declare function parseDonkiCme(c: DonkiCmeRaw): DonkiCme;
|
|
112
|
+
/** Coronal mass ejections in the last `days`, with WSA-ENLIL Earth-arrival predictions. */
|
|
113
|
+
export declare function donkiCmes(ctx: Ctx, days?: number): Promise<Sourced<DonkiCme[]>>;
|
|
114
|
+
export interface DonkiStorm {
|
|
115
|
+
id: string;
|
|
116
|
+
start: string;
|
|
117
|
+
kpMax: number;
|
|
118
|
+
url: string;
|
|
119
|
+
}
|
|
120
|
+
/** Geomagnetic storms (Kp >= 5) logged by DONKI in the last `days`. */
|
|
121
|
+
export declare function donkiStorms(ctx: Ctx, days?: number): Promise<Sourced<DonkiStorm[]>>;
|
|
122
|
+
export interface DonkiNotification {
|
|
123
|
+
type: string;
|
|
124
|
+
id: string;
|
|
125
|
+
issued: string;
|
|
126
|
+
title: string;
|
|
127
|
+
summary: string;
|
|
128
|
+
url: string;
|
|
129
|
+
}
|
|
130
|
+
/** NASA M2M space weather notifications (CME, flare, SEP, IPS, radiation belt...) in the last `days`. */
|
|
131
|
+
export declare function donkiNotifications(ctx: Ctx, days?: number): Promise<Sourced<DonkiNotification[]>>;
|
|
132
|
+
export interface CloseApproach {
|
|
133
|
+
id: string;
|
|
134
|
+
name: string;
|
|
135
|
+
time: string;
|
|
136
|
+
missLunar: number;
|
|
137
|
+
missKm: number;
|
|
138
|
+
velocityKmS: number;
|
|
139
|
+
diameterM: {
|
|
140
|
+
min: number;
|
|
141
|
+
max: number;
|
|
142
|
+
};
|
|
143
|
+
hazardous: boolean;
|
|
144
|
+
url: string;
|
|
145
|
+
}
|
|
146
|
+
/** Near-Earth object close approaches from today over the next `days` (max 7), closest first. */
|
|
147
|
+
export declare function closeApproaches(ctx: Ctx, days?: number): Promise<Sourced<CloseApproach[]>>;
|
|
148
|
+
export interface AirStation {
|
|
149
|
+
name: string;
|
|
150
|
+
distanceKm: number;
|
|
151
|
+
parameter: string;
|
|
152
|
+
value: number;
|
|
153
|
+
unit: string;
|
|
154
|
+
time: string;
|
|
155
|
+
}
|
|
156
|
+
/** Latest fine-particle (PM2.5) readings near a point, only stations that reported in the last 3 days. */
|
|
157
|
+
export declare function airQuality(ctx: Ctx, lat: number, lon: number): Promise<Sourced<AirStation[]>>;
|
|
158
|
+
/** US EPA PM2.5 category (2024 breakpoints). */
|
|
159
|
+
export declare function pm25Category(v: number): string;
|
|
160
|
+
export {};
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
import { key, noKey } from '../core/keys.js';
|
|
2
|
+
export async function kpIndex(ctx) {
|
|
3
|
+
const r = await ctx.http.get('https://services.swpc.noaa.gov/products/noaa-planetary-k-index.json', { source: 'noaa-swpc', ttlSec: 900 });
|
|
4
|
+
// The product has been published both as row arrays (header first) and as objects; accept either.
|
|
5
|
+
const rows = Array.isArray(r.data) ? r.data : [];
|
|
6
|
+
const data = rows
|
|
7
|
+
.map((x) => (Array.isArray(x) ? { time: String(x[0]), kp: Number(x[1]) } : { time: String(x.time_tag), kp: Number(x.Kp) }))
|
|
8
|
+
.filter((x) => Number.isFinite(x.kp));
|
|
9
|
+
return { data: r.data ? data : null, prov: r.prov };
|
|
10
|
+
}
|
|
11
|
+
export async function xrayFlares(ctx) {
|
|
12
|
+
const r = await ctx.http.get('https://services.swpc.noaa.gov/json/goes/primary/xray-flares-7-day.json', {
|
|
13
|
+
source: 'noaa-swpc',
|
|
14
|
+
ttlSec: 900,
|
|
15
|
+
});
|
|
16
|
+
return { data: r.data?.filter((f) => f.max_class).map((f) => ({ maxClass: f.max_class, maxTime: f.max_time ?? '', beginTime: f.begin_time ?? '' })) ?? null, prov: r.prov };
|
|
17
|
+
}
|
|
18
|
+
/** Flare class to a sortable magnitude: A1=1e-8 ... X1=1e-4 (W/m^2). */
|
|
19
|
+
export function flareFlux(cls) {
|
|
20
|
+
const m = /^([ABCMX])(\d+(?:\.\d+)?)/.exec(cls.trim().toUpperCase());
|
|
21
|
+
if (!m)
|
|
22
|
+
return 0;
|
|
23
|
+
const base = { A: 1e-8, B: 1e-7, C: 1e-6, M: 1e-5, X: 1e-4 }[m[1]];
|
|
24
|
+
return base * Number(m[2]);
|
|
25
|
+
}
|
|
26
|
+
/** Parse one SWPC alerts.json message body into a typed record. */
|
|
27
|
+
export function parseSwpcAlert(x) {
|
|
28
|
+
const msg = (x.message ?? '').replace(/\r/g, '');
|
|
29
|
+
const code = /Space Weather Message Code:\s*(\S+)/.exec(msg)?.[1] ?? x.product_id ?? '';
|
|
30
|
+
const head = /^(EXTENDED WARNING|WARNING|ALERT|CONTINUED ALERT|WATCH|SUMMARY|CANCEL[A-Z ]*?)\s*:\s*(.+)$/m.exec(msg);
|
|
31
|
+
const label = head?.[1] ?? '';
|
|
32
|
+
const kind = /WARNING/.test(label) ? 'WARNING' : /ALERT/.test(label) ? 'ALERT' : /WATCH/.test(label) ? 'WATCH' : /SUMMARY/.test(label) ? 'SUMMARY' : /CANCEL/.test(label) ? 'CANCEL' : 'OTHER';
|
|
33
|
+
const scale = /NOAA Scale:\s*([GRS][1-5])/i.exec(msg)?.[1]?.toUpperCase() ?? null;
|
|
34
|
+
const issuedRaw = (x.issue_datetime ?? '').trim();
|
|
35
|
+
const issued = issuedRaw ? `${issuedRaw.replace(' ', 'T').replace(/\.\d+$/, '')}Z` : '';
|
|
36
|
+
return { productId: x.product_id ?? '', code, kind, issued, title: head ? `${label}: ${head[2].trim()}` : msg.split('\n').find((l) => l.trim() && !/^(Space Weather Message Code|Serial Number|Issue Time)/.test(l))?.trim() ?? code, scale, message: msg.trim() };
|
|
37
|
+
}
|
|
38
|
+
/** SWPC alerts, warnings, watches and summaries issued in the last ~30 days, newest first. */
|
|
39
|
+
export async function swpcAlerts(ctx) {
|
|
40
|
+
const r = await ctx.http.get('https://services.swpc.noaa.gov/products/alerts.json', { source: 'noaa-swpc', ttlSec: 600 });
|
|
41
|
+
return { data: Array.isArray(r.data) ? r.data.map(parseSwpcAlert).sort((a, b) => b.issued.localeCompare(a.issued)) : null, prov: r.prov };
|
|
42
|
+
}
|
|
43
|
+
/** Latest solar wind speed and magnetic field at L1 (SWPC summary products). */
|
|
44
|
+
export async function solarWind(ctx) {
|
|
45
|
+
const [sp, mag] = await Promise.all([
|
|
46
|
+
ctx.http.get('https://services.swpc.noaa.gov/products/summary/solar-wind-speed.json', { source: 'noaa-swpc', ttlSec: 300 }),
|
|
47
|
+
ctx.http.get('https://services.swpc.noaa.gov/products/summary/solar-wind-mag-field.json', { source: 'noaa-swpc', ttlSec: 300 }),
|
|
48
|
+
]);
|
|
49
|
+
const s = Array.isArray(sp.data) ? sp.data[0] : undefined;
|
|
50
|
+
const m = Array.isArray(mag.data) ? mag.data[0] : undefined;
|
|
51
|
+
const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : typeof v === 'string' && v.trim() && Number.isFinite(Number(v)) ? Number(v) : null);
|
|
52
|
+
const data = s || m ? { time: s?.time_tag ?? m?.time_tag ?? null, speedKmS: num(s?.proton_speed), bt: num(m?.bt), bz: num(m?.bz_gsm) } : null;
|
|
53
|
+
return { data, prov: [sp.prov, mag.prov] };
|
|
54
|
+
}
|
|
55
|
+
export async function noaaScales(ctx) {
|
|
56
|
+
const r = await ctx.http.get('https://services.swpc.noaa.gov/products/noaa-scales.json', { source: 'noaa-swpc', ttlSec: 900 });
|
|
57
|
+
if (!r.data || typeof r.data !== 'object')
|
|
58
|
+
return { data: null, prov: r.prov };
|
|
59
|
+
const n = (v) => (v === null || v === undefined || v === '' ? null : Number(v));
|
|
60
|
+
const cur = r.data['0'];
|
|
61
|
+
const days = ['1', '2', '3'].map((k) => r.data[k]).filter((d) => Boolean(d));
|
|
62
|
+
return {
|
|
63
|
+
data: {
|
|
64
|
+
now: { r: n(cur?.R?.Scale) ?? 0, s: n(cur?.S?.Scale) ?? 0, g: n(cur?.G?.Scale) ?? 0 },
|
|
65
|
+
days: days.map((d) => ({ date: d.DateStamp ?? '', rMinorProb: n(d.R?.MinorProb), rMajorProb: n(d.R?.MajorProb), sProb: n(d.S?.Prob), g: n(d.G?.Scale) ?? 0 })),
|
|
66
|
+
},
|
|
67
|
+
prov: r.prov,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
/** Parse SWPC's plain-text 3-day forecast. */
|
|
71
|
+
export function parseForecast3Day(txt) {
|
|
72
|
+
const issued = /:Issued:\s*(.+)/.exec(txt)?.[1]?.trim() ?? null;
|
|
73
|
+
const observed = /greatest observed 3 hr Kp over the past 24 hours was\s+([\d.]+)/i.exec(txt.replace(/\s+/g, ' '));
|
|
74
|
+
const expected = /greatest expected 3 hr Kp for .+? is\s+([\d.]+)/i.exec(txt.replace(/\s+/g, ' '));
|
|
75
|
+
const kpByDay = {};
|
|
76
|
+
const block = /NOAA Kp index breakdown[^\n]*\n\s*\n?([^\n]+)\n((?:\s*\d\d-\d\dUT[^\n]*\n?)+)/.exec(txt);
|
|
77
|
+
if (block) {
|
|
78
|
+
const days = block[1].trim().split(/\s{2,}/);
|
|
79
|
+
for (const row of block[2].trim().split('\n')) {
|
|
80
|
+
const vals = row.replace(/\(G\d\)/g, '').trim().split(/\s+/).slice(1).map(Number);
|
|
81
|
+
vals.forEach((v, i) => {
|
|
82
|
+
const d = days[i];
|
|
83
|
+
if (d && Number.isFinite(v))
|
|
84
|
+
kpByDay[d] = Math.max(kpByDay[d] ?? 0, v);
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
const rationale = /A\. NOAA Geomagnetic[\s\S]*?Rationale:\s*([\s\S]+?)\n\s*\n/.exec(txt)?.[1]?.replace(/\s+/g, ' ').trim() ?? null;
|
|
89
|
+
return { issued, observedKpMax24h: observed ? Number(observed[1]) : null, expectedKpMax: expected ? Number(expected[1]) : null, kpByDay, rationale };
|
|
90
|
+
}
|
|
91
|
+
export async function forecast3Day(ctx) {
|
|
92
|
+
const r = await ctx.http.get('https://services.swpc.noaa.gov/text/3-day-forecast.txt', { source: 'noaa-swpc', as: 'text', ttlSec: 1800 });
|
|
93
|
+
return { data: r.data && r.data.includes('3-Day Forecast') ? parseForecast3Day(r.data) : null, prov: r.prov };
|
|
94
|
+
}
|
|
95
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
96
|
+
// NASA DONKI (space weather database) and NeoWs (near-Earth objects). NASA_API_KEY, falling back to DEMO_KEY
|
|
97
|
+
// (30 requests/hour, 50/day per IP).
|
|
98
|
+
const nasaKey = () => key('NASA_API_KEY') ?? 'DEMO_KEY';
|
|
99
|
+
const day = (d) => d.toISOString().slice(0, 10);
|
|
100
|
+
export function parseDonkiCme(c) {
|
|
101
|
+
const analyses = c.cmeAnalyses ?? [];
|
|
102
|
+
const best = analyses.find((a) => a.isMostAccurate) ?? analyses[0];
|
|
103
|
+
const runs = analyses.flatMap((a) => a.enlilList ?? []);
|
|
104
|
+
const hit = runs.filter((e) => e.estimatedShockArrivalTime).sort((a, b) => (a.estimatedShockArrivalTime ?? '').localeCompare(b.estimatedShockArrivalTime ?? ''));
|
|
105
|
+
const kps = runs.flatMap((e) => [e.kp_90, e.kp_135, e.kp_180]).filter((k) => typeof k === 'number');
|
|
106
|
+
return {
|
|
107
|
+
id: c.activityID ?? '',
|
|
108
|
+
start: c.startTime ?? '',
|
|
109
|
+
speedKmS: best?.speed ?? null,
|
|
110
|
+
halfAngle: best?.halfAngle ?? null,
|
|
111
|
+
type: best?.type ?? null,
|
|
112
|
+
earthArrival: hit[0]?.estimatedShockArrivalTime ?? null,
|
|
113
|
+
earthGlancing: runs.some((e) => e.isEarthGB || e.isEarthMinorImpact),
|
|
114
|
+
kpPredicted: kps.length ? Math.max(...kps) : null,
|
|
115
|
+
note: (c.note ?? '').slice(0, 300),
|
|
116
|
+
url: c.link ?? 'https://kauai.ccmc.gsfc.nasa.gov/DONKI/',
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
/** Coronal mass ejections in the last `days`, with WSA-ENLIL Earth-arrival predictions. */
|
|
120
|
+
export async function donkiCmes(ctx, days = 7) {
|
|
121
|
+
const end = ctx.now();
|
|
122
|
+
const start = new Date(end.getTime() - days * 86_400_000);
|
|
123
|
+
const r = await ctx.http.get(`https://api.nasa.gov/DONKI/CME?startDate=${day(start)}&endDate=${day(end)}&api_key=${nasaKey()}`, { source: 'nasa-donki', ttlSec: 3 * 3600, timeoutMs: 45_000 });
|
|
124
|
+
return { data: Array.isArray(r.data) ? r.data.map(parseDonkiCme) : null, prov: r.prov };
|
|
125
|
+
}
|
|
126
|
+
/** Geomagnetic storms (Kp >= 5) logged by DONKI in the last `days`. */
|
|
127
|
+
export async function donkiStorms(ctx, days = 30) {
|
|
128
|
+
const end = ctx.now();
|
|
129
|
+
const start = new Date(end.getTime() - days * 86_400_000);
|
|
130
|
+
const r = await ctx.http.get(`https://api.nasa.gov/DONKI/GST?startDate=${day(start)}&endDate=${day(end)}&api_key=${nasaKey()}`, {
|
|
131
|
+
source: 'nasa-donki',
|
|
132
|
+
ttlSec: 3 * 3600,
|
|
133
|
+
timeoutMs: 45_000,
|
|
134
|
+
});
|
|
135
|
+
return {
|
|
136
|
+
data: Array.isArray(r.data) ? r.data.map((g) => ({ id: g.gstID ?? '', start: g.startTime ?? '', kpMax: Math.max(0, ...(g.allKpIndex ?? []).map((k) => k.kpIndex ?? 0)), url: g.link ?? '' })) : null,
|
|
137
|
+
prov: r.prov,
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
/** NASA M2M space weather notifications (CME, flare, SEP, IPS, radiation belt...) in the last `days`. */
|
|
141
|
+
export async function donkiNotifications(ctx, days = 7) {
|
|
142
|
+
const end = ctx.now();
|
|
143
|
+
const start = new Date(end.getTime() - days * 86_400_000);
|
|
144
|
+
const r = await ctx.http.get(`https://api.nasa.gov/DONKI/notifications?startDate=${day(start)}&endDate=${day(end)}&type=all&api_key=${nasaKey()}`, { source: 'nasa-donki', ttlSec: 3 * 3600, timeoutMs: 45_000 });
|
|
145
|
+
return {
|
|
146
|
+
data: Array.isArray(r.data)
|
|
147
|
+
? r.data
|
|
148
|
+
.map((n) => {
|
|
149
|
+
const body = (n.messageBody ?? '').replace(/\r/g, '');
|
|
150
|
+
return {
|
|
151
|
+
type: n.messageType ?? '',
|
|
152
|
+
id: n.messageID ?? '',
|
|
153
|
+
issued: n.messageIssueTime ?? '',
|
|
154
|
+
title: /## Message Type:\s*(.+)/.exec(body)?.[1]?.trim() ?? n.messageType ?? '',
|
|
155
|
+
summary: (/## Summary:\s*([\s\S]+?)(?:\n## |$)/.exec(body)?.[1] ?? '').replace(/\s+/g, ' ').trim().slice(0, 400),
|
|
156
|
+
url: n.messageURL ?? '',
|
|
157
|
+
};
|
|
158
|
+
})
|
|
159
|
+
.sort((a, b) => b.issued.localeCompare(a.issued))
|
|
160
|
+
: null,
|
|
161
|
+
prov: r.prov,
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
/** Near-Earth object close approaches from today over the next `days` (max 7), closest first. */
|
|
165
|
+
export async function closeApproaches(ctx, days = 3) {
|
|
166
|
+
const start = ctx.now();
|
|
167
|
+
const end = new Date(start.getTime() + Math.max(0, Math.min(7, days) - 1) * 86_400_000);
|
|
168
|
+
const r = await ctx.http.get(`https://api.nasa.gov/neo/rest/v1/feed?start_date=${day(start)}&end_date=${day(end)}&api_key=${nasaKey()}`, { source: 'nasa-neows', ttlSec: 6 * 3600, timeoutMs: 45_000 });
|
|
169
|
+
if (!r.data?.near_earth_objects)
|
|
170
|
+
return { data: null, prov: r.prov };
|
|
171
|
+
const out = [];
|
|
172
|
+
for (const neo of Object.values(r.data.near_earth_objects).flat()) {
|
|
173
|
+
const ca = neo.close_approach_data?.find((c) => (c.orbiting_body ?? 'Earth') === 'Earth');
|
|
174
|
+
if (!ca)
|
|
175
|
+
continue;
|
|
176
|
+
out.push({
|
|
177
|
+
id: neo.id ?? '',
|
|
178
|
+
name: (neo.name ?? '').replace(/[()]/g, '').trim(),
|
|
179
|
+
time: ca.close_approach_date_full ?? ca.close_approach_date ?? '',
|
|
180
|
+
missLunar: Number(ca.miss_distance?.lunar ?? NaN),
|
|
181
|
+
missKm: Math.round(Number(ca.miss_distance?.kilometers ?? NaN)),
|
|
182
|
+
velocityKmS: Math.round(Number(ca.relative_velocity?.kilometers_per_second ?? NaN) * 10) / 10,
|
|
183
|
+
diameterM: { min: Math.round(neo.estimated_diameter?.meters?.estimated_diameter_min ?? 0), max: Math.round(neo.estimated_diameter?.meters?.estimated_diameter_max ?? 0) },
|
|
184
|
+
hazardous: neo.is_potentially_hazardous_asteroid === true,
|
|
185
|
+
url: neo.nasa_jpl_url ?? `https://ssd.jpl.nasa.gov/tools/sbdb_lookup.html#/?sstr=${neo.id ?? ''}`,
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
return { data: out.filter((x) => Number.isFinite(x.missLunar)).sort((a, b) => a.missLunar - b.missLunar), prov: r.prov };
|
|
189
|
+
}
|
|
190
|
+
/** Latest fine-particle (PM2.5) readings near a point, only stations that reported in the last 3 days. */
|
|
191
|
+
export async function airQuality(ctx, lat, lon) {
|
|
192
|
+
const k = key('OPENAQ_API_KEY');
|
|
193
|
+
if (!k)
|
|
194
|
+
return noKey('openaq', 'OPENAQ_API_KEY');
|
|
195
|
+
const headers = { 'x-api-key': k };
|
|
196
|
+
const locs = await ctx.http.get(`https://api.openaq.org/v3/locations?coordinates=${lat.toFixed(4)},${lon.toFixed(4)}&radius=25000&limit=50¶meters_id=2`, { source: 'openaq', ttlSec: 3600, headers });
|
|
197
|
+
if (!locs.data?.results)
|
|
198
|
+
return { data: null, prov: locs.prov };
|
|
199
|
+
const cutoff = ctx.now().getTime() - 3 * 86_400_000;
|
|
200
|
+
// A station can be "active" through other sensors while its PM2.5 sensor died years ago,
|
|
201
|
+
// so freshness is checked on each reading, not on the station.
|
|
202
|
+
const candidates = locs.data.results.filter((l) => l.datetimeLast?.utc && Date.parse(l.datetimeLast.utc) > cutoff).slice(0, 8);
|
|
203
|
+
const readings = await Promise.all(candidates.map(async (l) => {
|
|
204
|
+
const sensor = l.sensors?.find((s) => s.parameter?.name === 'pm25');
|
|
205
|
+
if (!sensor)
|
|
206
|
+
return null;
|
|
207
|
+
const latest = await ctx.http.get(`https://api.openaq.org/v3/locations/${l.id}/latest`, { source: 'openaq', ttlSec: 1800, headers });
|
|
208
|
+
// /latest returns every sensor at the station; take the PM2.5 one only. An exact 0 is a sensor fault.
|
|
209
|
+
const v = latest.data?.results?.find((x) => x.sensorsId === sensor.id && x.value !== undefined && x.value > 0);
|
|
210
|
+
const t = v?.datetime?.utc;
|
|
211
|
+
if (!v || !t || Date.parse(t) < cutoff)
|
|
212
|
+
return null;
|
|
213
|
+
return { name: l.name, distanceKm: Math.round((l.distance ?? 0) / 100) / 10, parameter: 'pm25', value: v.value, unit: sensor.parameter?.units ?? 'µg/m³', time: t };
|
|
214
|
+
}));
|
|
215
|
+
return { data: readings.filter((x) => x !== null), prov: locs.prov };
|
|
216
|
+
}
|
|
217
|
+
/** US EPA PM2.5 category (2024 breakpoints). */
|
|
218
|
+
export function pm25Category(v) {
|
|
219
|
+
if (v <= 9)
|
|
220
|
+
return 'good';
|
|
221
|
+
if (v <= 35.4)
|
|
222
|
+
return 'moderate';
|
|
223
|
+
if (v <= 55.4)
|
|
224
|
+
return 'unhealthy for sensitive groups';
|
|
225
|
+
if (v <= 125.4)
|
|
226
|
+
return 'unhealthy';
|
|
227
|
+
if (v <= 225.4)
|
|
228
|
+
return 'very unhealthy';
|
|
229
|
+
return 'hazardous';
|
|
230
|
+
}
|