@cliwant/mcp-sam-gov 1.2.0 → 1.3.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/README.ja.md +12 -7
- package/README.ko.md +12 -7
- package/README.md +28 -10
- package/dist/bea.d.ts +105 -0
- package/dist/bea.d.ts.map +1 -0
- package/dist/bea.js +303 -0
- package/dist/bea.js.map +1 -0
- package/dist/dol.d.ts +118 -0
- package/dist/dol.d.ts.map +1 -0
- package/dist/dol.js +421 -0
- package/dist/dol.js.map +1 -0
- package/dist/keys.d.ts +10 -8
- package/dist/keys.d.ts.map +1 -1
- package/dist/keys.js +36 -8
- package/dist/keys.js.map +1 -1
- package/dist/lda.d.ts +105 -0
- package/dist/lda.d.ts.map +1 -0
- package/dist/lda.js +317 -0
- package/dist/lda.js.map +1 -0
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +210 -3
- package/dist/server.js.map +1 -1
- package/package.json +1 -1
- package/src/bea.ts +372 -0
- package/src/dol.ts +515 -0
- package/src/keys.ts +39 -8
- package/src/lda.ts +385 -0
- package/src/server.ts +234 -3
package/src/bea.ts
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* bea.ts — BEA (Bureau of Economic Analysis) Regional Economic Accounts — the
|
|
3
|
+
* REGIONAL / SUB-NATIONAL economic lane (ADR-0051). County / state / MSA GDP by
|
|
4
|
+
* industry (CAGDP2 / SAGDP2N) and personal income (CAINC1 / SAINC1) — the
|
|
5
|
+
* place-of-performance market context that neither the national FRED macro series
|
|
6
|
+
* nor the Census establishment counts carry.
|
|
7
|
+
*
|
|
8
|
+
* ★ THIS IS THE SERVER'S THIRD KEY-REQUIRED SOURCE (Census CBP #1, FRED #2). The
|
|
9
|
+
* BEA Data API has NO keyless tier: every request needs `UserID=`. So, honestly:
|
|
10
|
+
* with NO `BEA_API_KEY` this tool THROWS an `invalid_input` config error BEFORE
|
|
11
|
+
* any fetch (never a fake-empty, never a keyless-pretend). The other 116 tools
|
|
12
|
+
* stay keyless — this key is scoped to this one source. (Contrast the OPTIONAL
|
|
13
|
+
* keys of datagov/bls/nvd, which lift a tier but are not required.)
|
|
14
|
+
*
|
|
15
|
+
* This module MIRRORS the census-economic.ts / fred.ts key-required precedent: a
|
|
16
|
+
* `beaApiKey()` env seam, a pre-fetch `invalid_input` THROW when unset, the
|
|
17
|
+
* fixed-host SSRF assert + `redirect:"error"`, and a data-absence-sentinel→null
|
|
18
|
+
* idiom (Census's negative floor / FRED's `"."` — here BEA's string suppression
|
|
19
|
+
* codes `(NA) (D) (NM) (L) *`). It REUSES `getJson` (the shared fetch envelope) /
|
|
20
|
+
* `driftError` / `num`·`str` (coerce.ts, null-never-0/empty) / `withMeta`·`buildMeta`.
|
|
21
|
+
* The key rides ONLY in the `UserID=` query param, NOWHERE else (never the label,
|
|
22
|
+
* `_meta.source`, notes, or a log — the K-test).
|
|
23
|
+
*
|
|
24
|
+
* GET https://apps.bea.gov/api/data
|
|
25
|
+
* ?UserID=<BEA_API_KEY> (REQUIRED)
|
|
26
|
+
* &method=GetData&datasetname=Regional&ResultFormat=json (fixed)
|
|
27
|
+
* &TableName=<tableName> (e.g. CAGDP2, SAGDP2N, CAINC1)
|
|
28
|
+
* &GeoFips=<geoFips> (STATE | county FIPS | MSA)
|
|
29
|
+
* &LineCode=<lineCode> (industry line, or ALL)
|
|
30
|
+
* &Year=<year> (YYYY | LAST5 | ALL)
|
|
31
|
+
* &Frequency=<frequency> (A | Q)
|
|
32
|
+
* → { BEAAPI:{ Results:{ Statistic, UnitOfMeasure, Dimensions:[…],
|
|
33
|
+
* Data:[{ Code, GeoFips, GeoName, TimePeriod, CL_UNIT, UNIT_MULT,
|
|
34
|
+
* DataValue, NoteRef }], Notes:[{ NoteRef, NoteText }] } } }
|
|
35
|
+
*
|
|
36
|
+
* ★ HONESTY (ADR-0051 P1–P5):
|
|
37
|
+
* [KEY] no key ⇒ invalid_input THROW pre-fetch (0 fetch); the message names
|
|
38
|
+
* BEA_API_KEY + the free-signup URL.
|
|
39
|
+
* [P1] BEA GetData returns the COMPLETE set for the filter (no server
|
|
40
|
+
* pagination) ⇒ totalAvailable = the row count, complete:true. NEVER
|
|
41
|
+
* fabricated.
|
|
42
|
+
* [★P2] ★the crux: a missing/invalid key (and any bad-parameter request) returns
|
|
43
|
+
* HTTP **200** carrying `BEAAPI.Results.Error` — NOT an HTTP error status.
|
|
44
|
+
* The catch-ladder checks `Results.Error` FIRST (BEFORE the Data-array
|
|
45
|
+
* drift check) and throws invalid_input SURFACING `APIErrorDescription`
|
|
46
|
+
* (+ code) — NEVER read as an empty result. `Data:[]` (a genuine empty
|
|
47
|
+
* array) ⇒ honest empty (returned:0, complete:true). A 5xx/timeout ⇒
|
|
48
|
+
* upstream_unavailable THROW. A 200 non-JSON ⇒ schema_drift.
|
|
49
|
+
* [★P3] `DataValue` is a STRING WITH COMMAS ("1,234,567") — strip commas then
|
|
50
|
+
* `num()`. The suppression/not-available sentinels `(NA) (D) (NM) (L) *`
|
|
51
|
+
* (and any non-numeric after the comma-strip) map to **null** (withheld),
|
|
52
|
+
* NEVER 0 — a real "0" stays 0. `UNIT_MULT` (power-of-10 multiplier) is
|
|
53
|
+
* reported as `unitMult` and `CL_UNIT` as `unitOfMeasure`; the raw value is
|
|
54
|
+
* surfaced WITH the multiplier — it is NEVER multiplied in (that would lose
|
|
55
|
+
* precision and double-count against the disclosed multiplier).
|
|
56
|
+
* [P4] `BEAAPI` / `Results` / `Data` absent or non-array ⇒ driftError — BUT
|
|
57
|
+
* ONLY after the Results.Error check (an Error response is P2, not drift).
|
|
58
|
+
* [SSRF] fixed host `apps.bea.gov`; `tableName` ^[A-Za-z0-9]{2,20}$; `geoFips`
|
|
59
|
+
* ^[A-Za-z0-9]{2,10}$; `lineCode` ^([0-9]{1,4}|ALL)$; `year`
|
|
60
|
+
* ^\d{4}$|LAST5|ALL; `frequency` {A,Q}. All VALUES ride URLSearchParams;
|
|
61
|
+
* the key rides `UserID=` ONLY.
|
|
62
|
+
*/
|
|
63
|
+
|
|
64
|
+
import { ToolErrorCarrier } from "./errors.js";
|
|
65
|
+
import { getJson, driftError } from "./datasource.js";
|
|
66
|
+
import { num, str } from "./coerce.js";
|
|
67
|
+
import { withMeta, type MetaBundle, type ResponseMeta } from "./meta.js";
|
|
68
|
+
|
|
69
|
+
// Re-export the shared honesty coercion (single audited copy in ./coerce.js —
|
|
70
|
+
// ADR-0005 v2 FIX-C) so a `num` regression fails together across sources. NO local
|
|
71
|
+
// num/str; the sentinel/comma-strip map is a WRAPPER around num, not a fork.
|
|
72
|
+
export { num };
|
|
73
|
+
|
|
74
|
+
// ─── SSRF core: the single fixed host + base path ─────────────────
|
|
75
|
+
export const BEA_HOST = "apps.bea.gov";
|
|
76
|
+
const BEA_PATH = "/api/data";
|
|
77
|
+
// HOST+path label — surfaces in ToolError.upstreamEndpoint; the key rides ONLY in
|
|
78
|
+
// the UserID= query param, so no token can ever appear here.
|
|
79
|
+
const BEA_LABEL = "bea:/api/data";
|
|
80
|
+
|
|
81
|
+
// ─── Validation charclasses (SSRF + "verify the input" honesty) ───
|
|
82
|
+
const TABLE_RE = /^[A-Za-z0-9]{2,20}$/; // e.g. CAGDP2, SAGDP2N, CAINC1
|
|
83
|
+
const GEOFIPS_RE = /^[A-Za-z0-9]{2,10}$/; // STATE | county FIPS | MSA code
|
|
84
|
+
const LINECODE_RE = /^([0-9]{1,4}|ALL)$/; // industry line, or ALL
|
|
85
|
+
const YEAR_RE = /^\d{4}$/; // a single 4-digit year
|
|
86
|
+
const YEAR_KEYWORDS = new Set(["LAST5", "ALL"]);
|
|
87
|
+
const FREQUENCIES = new Set(["A", "Q"]);
|
|
88
|
+
|
|
89
|
+
const DEFAULT_YEAR = "LAST5";
|
|
90
|
+
const DEFAULT_FREQUENCY = "A";
|
|
91
|
+
|
|
92
|
+
// BEA encodes a suppressed / not-available cell as one of these string codes in
|
|
93
|
+
// DataValue: (NA)=not available, (D)=disclosure-suppressed, (NM)=not meaningful,
|
|
94
|
+
// (L)=less than half the unit, *=statistically insignificant. Any of these — and
|
|
95
|
+
// any non-numeric value after the comma-strip — is a data-absence marker, NEVER a
|
|
96
|
+
// number and NEVER 0.
|
|
97
|
+
const BEA_SUPPRESSION = new Set(["(NA)", "(D)", "(NM)", "(L)", "*"]);
|
|
98
|
+
|
|
99
|
+
// ─── Honesty notes (ADR-0051 required set) ────────────────────────
|
|
100
|
+
const KEY_REQUIRED_NOTE =
|
|
101
|
+
"This source REQUIRES a free BEA_API_KEY (the BEA Data API has no keyless tier). The key is sent ONLY as the UserID= query parameter to apps.bea.gov and is NEVER logged, echoed, or placed in this response.";
|
|
102
|
+
const DATAVALUE_NOTE =
|
|
103
|
+
"dataValue is parsed from BEA's comma-formatted DataValue string ('1,234,567' → 1234567). BEA suppression/not-available codes ((NA)/(D)/(NM)/(L)/*) map to null (withheld) — NEVER 0 (a genuine 0 is preserved as 0).";
|
|
104
|
+
const UNIT_MULT_NOTE =
|
|
105
|
+
"unitMult is BEA's UNIT_MULT (a power-of-10 multiplier) and unitOfMeasure is CL_UNIT (the unit label). The raw dataValue is surfaced ALONGSIDE unitMult and is NOT multiplied by it — apply unitMult yourself if a scaled figure is needed (multiplying here would lose precision and double-count).";
|
|
106
|
+
const NO_PAGINATION_NOTE =
|
|
107
|
+
"BEA GetData returns the COMPLETE set of rows matching the filter (no server-side pagination); totalAvailable equals the number of rows returned. Narrow with geoFips / lineCode / year to reduce the row count.";
|
|
108
|
+
|
|
109
|
+
// ─── The key seam (REQUIRED; value NEVER leaked past the UserID= param) ──
|
|
110
|
+
/** Read BEA_API_KEY from env; trim; return the value or undefined (unset/blank). */
|
|
111
|
+
export function beaApiKey(): string | undefined {
|
|
112
|
+
const raw = process.env.BEA_API_KEY;
|
|
113
|
+
const trimmed = typeof raw === "string" ? raw.trim() : "";
|
|
114
|
+
return trimmed ? trimmed : undefined;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// ─── Curated row / note shapes ────────────────────────────────────
|
|
118
|
+
export type BeaRegionalRow = {
|
|
119
|
+
geoFips: string | null; // GeoFips (a STRING — leading zeros survive)
|
|
120
|
+
geoName: string | null; // GeoName (e.g. "California")
|
|
121
|
+
timePeriod: string | null; // TimePeriod (e.g. "2022")
|
|
122
|
+
lineCode: string | null; // Code (the industry line — a STRING, structure-bearing)
|
|
123
|
+
dataValue: number | null; // DataValue — comma-stripped num; suppressed ⇒ null
|
|
124
|
+
unitOfMeasure: string | null; // CL_UNIT — the unit label
|
|
125
|
+
unitMult: number | null; // UNIT_MULT — power-of-10 multiplier (reported, NOT applied)
|
|
126
|
+
noteRef: string | null; // NoteRef — the footnote key(s) for this row
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
export type BeaNote = {
|
|
130
|
+
noteRef: string | null; // NoteRef
|
|
131
|
+
noteText: string | null; // NoteText
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* num(), but for BEA's comma-formatted DataValue string. Strips a suppression code
|
|
136
|
+
* ((NA)/(D)/(NM)/(L)/*) → null, otherwise removes thousands commas and defers to
|
|
137
|
+
* num (so "1,234,567" ⇒ 1234567, a genuine "0" ⇒ 0, and any residual non-numeric
|
|
138
|
+
* ⇒ null — NEVER a fabricated 0).
|
|
139
|
+
*/
|
|
140
|
+
export function beaDataValue(v: unknown): number | null {
|
|
141
|
+
if (typeof v === "string") {
|
|
142
|
+
const s = v.trim();
|
|
143
|
+
if (s === "" || BEA_SUPPRESSION.has(s)) return null;
|
|
144
|
+
return num(s.replace(/,/g, ""));
|
|
145
|
+
}
|
|
146
|
+
return num(v);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export type BeaRegionalDataArgs = {
|
|
150
|
+
tableName?: string;
|
|
151
|
+
geoFips?: string;
|
|
152
|
+
lineCode?: string;
|
|
153
|
+
year?: string; // ^\d{4}$ | LAST5 | ALL (default LAST5)
|
|
154
|
+
frequency?: string; // A | Q (default A)
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Fetch BEA Regional Economic Accounts rows for a table × geography × line filter
|
|
159
|
+
* → normalized rows + summarized BEA Notes + honest `_meta`. REQUIRES BEA_API_KEY
|
|
160
|
+
* (throws invalid_input pre-fetch when unset). ★A missing/invalid key (and any bad
|
|
161
|
+
* parameter) surfaces as an HTTP-200 `BEAAPI.Results.Error` carrier which is
|
|
162
|
+
* detected and thrown as invalid_input BEFORE the Data-array shape check.
|
|
163
|
+
*/
|
|
164
|
+
export async function regionalData(
|
|
165
|
+
args: BeaRegionalDataArgs,
|
|
166
|
+
): Promise<MetaBundle> {
|
|
167
|
+
// ── [KEY] REQUIRED key — throw an honest config error BEFORE any fetch. ──
|
|
168
|
+
const key = beaApiKey();
|
|
169
|
+
if (key === undefined) {
|
|
170
|
+
throw new ToolErrorCarrier({
|
|
171
|
+
kind: "invalid_input",
|
|
172
|
+
retryable: false,
|
|
173
|
+
message:
|
|
174
|
+
"BEA Regional Economic Accounts requires a free API key. Get one at https://apps.bea.gov/API/signup/ and set BEA_API_KEY.",
|
|
175
|
+
upstreamEndpoint: BEA_LABEL,
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// ── Validate + default the inputs (belt-and-suspenders behind the server Zod;
|
|
180
|
+
// a DIRECT handler call bypasses Zod). All ride in the query string. ──
|
|
181
|
+
const tableName = args.tableName ?? "";
|
|
182
|
+
if (!TABLE_RE.test(tableName)) {
|
|
183
|
+
throw new ToolErrorCarrier({
|
|
184
|
+
kind: "invalid_input",
|
|
185
|
+
retryable: false,
|
|
186
|
+
message: `Invalid tableName ${JSON.stringify(tableName)} — expected a BEA Regional table code (^[A-Za-z0-9]{2,20}$), e.g. "CAGDP2" (county GDP by industry), "SAGDP2N" (state GDP), "CAINC1" (personal income).`,
|
|
187
|
+
upstreamEndpoint: BEA_LABEL,
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const geoFips = args.geoFips ?? "";
|
|
192
|
+
if (!GEOFIPS_RE.test(geoFips)) {
|
|
193
|
+
throw new ToolErrorCarrier({
|
|
194
|
+
kind: "invalid_input",
|
|
195
|
+
retryable: false,
|
|
196
|
+
message: `Invalid geoFips ${JSON.stringify(geoFips)} — expected a BEA GeoFips selector (^[A-Za-z0-9]{2,10}$), e.g. "STATE" (all states), a county FIPS like "06075", or an MSA code.`,
|
|
197
|
+
upstreamEndpoint: BEA_LABEL,
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const lineCode = args.lineCode ?? "";
|
|
202
|
+
if (!LINECODE_RE.test(lineCode)) {
|
|
203
|
+
throw new ToolErrorCarrier({
|
|
204
|
+
kind: "invalid_input",
|
|
205
|
+
retryable: false,
|
|
206
|
+
message: `Invalid lineCode ${JSON.stringify(lineCode)} — expected an integer industry line (^[0-9]{1,4}$), e.g. "1", or "ALL" for every line.`,
|
|
207
|
+
upstreamEndpoint: BEA_LABEL,
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const year = args.year ?? DEFAULT_YEAR;
|
|
212
|
+
if (!YEAR_KEYWORDS.has(year) && !YEAR_RE.test(year)) {
|
|
213
|
+
throw new ToolErrorCarrier({
|
|
214
|
+
kind: "invalid_input",
|
|
215
|
+
retryable: false,
|
|
216
|
+
message: `Invalid year ${JSON.stringify(year)} — expected a 4-digit year (^\\d{4}$), "LAST5", or "ALL".`,
|
|
217
|
+
upstreamEndpoint: BEA_LABEL,
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
const frequency = args.frequency ?? DEFAULT_FREQUENCY;
|
|
222
|
+
if (!FREQUENCIES.has(frequency)) {
|
|
223
|
+
throw new ToolErrorCarrier({
|
|
224
|
+
kind: "invalid_input",
|
|
225
|
+
retryable: false,
|
|
226
|
+
message: `Invalid frequency ${JSON.stringify(frequency)} — expected one of A (annual), Q (quarterly).`,
|
|
227
|
+
upstreamEndpoint: BEA_LABEL,
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// ── Build the query (all VALUES via URLSearchParams — no host/path steer; the
|
|
232
|
+
// REQUIRED key rides ONLY here in UserID=). ──
|
|
233
|
+
const params = new URLSearchParams();
|
|
234
|
+
params.set("UserID", key);
|
|
235
|
+
params.set("method", "GetData");
|
|
236
|
+
params.set("datasetname", "Regional");
|
|
237
|
+
params.set("ResultFormat", "json");
|
|
238
|
+
params.set("TableName", tableName);
|
|
239
|
+
params.set("GeoFips", geoFips);
|
|
240
|
+
params.set("LineCode", lineCode);
|
|
241
|
+
params.set("Year", year);
|
|
242
|
+
params.set("Frequency", frequency);
|
|
243
|
+
|
|
244
|
+
const url = `https://${BEA_HOST}${BEA_PATH}?${params.toString()}`;
|
|
245
|
+
// Belt-and-suspenders: the fixed host + strictly-validated query leave nothing to
|
|
246
|
+
// steer the authority; assert the built URL cannot have been moved off-host.
|
|
247
|
+
const built = new URL(url);
|
|
248
|
+
if (built.hostname !== BEA_HOST || built.protocol !== "https:") {
|
|
249
|
+
throw new ToolErrorCarrier({
|
|
250
|
+
kind: "invalid_input",
|
|
251
|
+
retryable: false,
|
|
252
|
+
message: `Constructed BEA URL host ${JSON.stringify(built.hostname)} (${built.protocol}) is not ${BEA_HOST} over https — refusing to fetch (SSRF safety).`,
|
|
253
|
+
upstreamEndpoint: BEA_LABEL,
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// ── Fetch through the shared envelope. The key rides UserID= ONLY (never the
|
|
258
|
+
// label/_meta); redirect:"error" fails closed on any off-host 3xx (it could
|
|
259
|
+
// carry the key away). A 5xx/timeout ⇒ upstream_unavailable THROW; a 200
|
|
260
|
+
// non-JSON body ⇒ getJson's r.json() throws a SyntaxError ⇒ we reclassify to
|
|
261
|
+
// schema_drift. ★A missing/invalid key returns HTTP 200 with an Error carrier,
|
|
262
|
+
// so it does NOT surface here — it is detected in the parse ladder below. ──
|
|
263
|
+
let body: unknown;
|
|
264
|
+
try {
|
|
265
|
+
body = await getJson<unknown>(url, { label: BEA_LABEL, redirect: "error" });
|
|
266
|
+
} catch (e) {
|
|
267
|
+
if (e instanceof SyntaxError) {
|
|
268
|
+
throw driftError(
|
|
269
|
+
BEA_LABEL,
|
|
270
|
+
"BEA /api/data returned a non-JSON body at HTTP 200 — treating as schema drift (never read as an empty result).",
|
|
271
|
+
);
|
|
272
|
+
}
|
|
273
|
+
throw e; // 5xx → upstream_unavailable, 404 → not_found, 429 → rate_limited …
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// ── [P4] Navigate BEAAPI.Results. An absent BEAAPI/Results is drift — BUT the
|
|
277
|
+
// Results.Error check (P2) comes FIRST below, since an error RESPONSE also
|
|
278
|
+
// carries BEAAPI.Results (with an Error member, not a Data array). ──
|
|
279
|
+
const beaapi = (body as { BEAAPI?: unknown } | null)?.BEAAPI;
|
|
280
|
+
if (beaapi === null || typeof beaapi !== "object") {
|
|
281
|
+
throw driftError(
|
|
282
|
+
BEA_LABEL,
|
|
283
|
+
"BEA response is missing the `BEAAPI` envelope — treating as schema drift (never a fabricated empty).",
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
const results = (beaapi as { Results?: unknown }).Results;
|
|
287
|
+
if (results === null || typeof results !== "object") {
|
|
288
|
+
throw driftError(
|
|
289
|
+
BEA_LABEL,
|
|
290
|
+
"BEA response is missing `BEAAPI.Results` — treating as schema drift (never a fabricated empty).",
|
|
291
|
+
);
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// ── [★P2] The CRUX: a missing/invalid key (or any bad parameter) returns HTTP
|
|
295
|
+
// 200 carrying `BEAAPI.Results.Error` — checked HERE, BEFORE the Data-array
|
|
296
|
+
// drift check, so an error response is surfaced as invalid_input CARRYING the
|
|
297
|
+
// APIErrorDescription (+ code), NEVER read as an empty result. ──
|
|
298
|
+
const errNode = (results as { Error?: unknown }).Error;
|
|
299
|
+
if (errNode !== undefined && errNode !== null) {
|
|
300
|
+
const errObj = (Array.isArray(errNode) ? errNode[0] : errNode) as
|
|
301
|
+
| Record<string, unknown>
|
|
302
|
+
| undefined;
|
|
303
|
+
const code = str(errObj?.APIErrorCode);
|
|
304
|
+
const desc = str(errObj?.APIErrorDescription);
|
|
305
|
+
throw new ToolErrorCarrier({
|
|
306
|
+
kind: "invalid_input",
|
|
307
|
+
retryable: false,
|
|
308
|
+
message: desc
|
|
309
|
+
? `BEA rejected the request${code ? ` (APIErrorCode ${code})` : ""}: ${desc}. Check BEA_API_KEY and the tableName / geoFips / lineCode / year parameters.`
|
|
310
|
+
: `BEA rejected the request${code ? ` (APIErrorCode ${code})` : ""} — check BEA_API_KEY and the tableName / geoFips / lineCode / year parameters.`,
|
|
311
|
+
upstreamEndpoint: BEA_LABEL,
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
// ── [P4] `Data` MUST be an array (a missing/non-array is drift, never a
|
|
316
|
+
// fabricated empty). An EMPTY array is a genuine honest-empty (below). ──
|
|
317
|
+
const data = (results as { Data?: unknown }).Data;
|
|
318
|
+
if (!Array.isArray(data)) {
|
|
319
|
+
throw driftError(
|
|
320
|
+
BEA_LABEL,
|
|
321
|
+
"BEA `BEAAPI.Results.Data` is missing or not an array — treating as schema drift (never a fabricated empty).",
|
|
322
|
+
);
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
// ── [P3] Map each Data row (comma-stripped/sentinel→null DataValue; UNIT_MULT /
|
|
326
|
+
// CL_UNIT reported, NOT applied). ──
|
|
327
|
+
const rows: BeaRegionalRow[] = (data as unknown[]).map((raw) => {
|
|
328
|
+
const row = (raw ?? {}) as Record<string, unknown>;
|
|
329
|
+
return {
|
|
330
|
+
geoFips: str(row.GeoFips),
|
|
331
|
+
geoName: str(row.GeoName),
|
|
332
|
+
timePeriod: str(row.TimePeriod),
|
|
333
|
+
lineCode: str(row.Code),
|
|
334
|
+
dataValue: beaDataValue(row.DataValue),
|
|
335
|
+
unitOfMeasure: str(row.CL_UNIT),
|
|
336
|
+
unitMult: num(row.UNIT_MULT),
|
|
337
|
+
noteRef: str(row.NoteRef),
|
|
338
|
+
};
|
|
339
|
+
});
|
|
340
|
+
|
|
341
|
+
// ── Summarize the BEA Notes (footnotes). A missing/non-array Notes ⇒ []. ──
|
|
342
|
+
const notesNode = (results as { Notes?: unknown }).Notes;
|
|
343
|
+
const notes: BeaNote[] = Array.isArray(notesNode)
|
|
344
|
+
? (notesNode as unknown[]).map((raw) => {
|
|
345
|
+
const n = (raw ?? {}) as Record<string, unknown>;
|
|
346
|
+
return { noteRef: str(n.NoteRef), noteText: str(n.NoteText) };
|
|
347
|
+
})
|
|
348
|
+
: [];
|
|
349
|
+
|
|
350
|
+
// ── [P1] The COMPLETE set for the filter (no server pagination). ──
|
|
351
|
+
const totalAvailable = rows.length;
|
|
352
|
+
|
|
353
|
+
const meta: Partial<ResponseMeta> = {
|
|
354
|
+
// MODE only — never the key value (K-test).
|
|
355
|
+
source: "apps.bea.gov /api/data (BEA Regional Economic Accounts; BEA_API_KEY)",
|
|
356
|
+
keylessMode: false, // ★KEYED — the third key-required source
|
|
357
|
+
returned: rows.length,
|
|
358
|
+
totalAvailable,
|
|
359
|
+
filtersApplied: [
|
|
360
|
+
`tableName:${tableName}`,
|
|
361
|
+
`geoFips:${geoFips}`,
|
|
362
|
+
`lineCode:${lineCode}`,
|
|
363
|
+
`year:${year}`,
|
|
364
|
+
`frequency:${frequency}`,
|
|
365
|
+
],
|
|
366
|
+
filtersDropped: [],
|
|
367
|
+
fieldsUnavailable: [],
|
|
368
|
+
notes: [KEY_REQUIRED_NOTE, DATAVALUE_NOTE, UNIT_MULT_NOTE, NO_PAGINATION_NOTE],
|
|
369
|
+
};
|
|
370
|
+
|
|
371
|
+
return withMeta({ rows, notes }, meta);
|
|
372
|
+
}
|