Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 | 143x 9x 9x 9x 9x 123x 46x 46x 46x 82x 46x 9x 99x 99x 99x 297x 3x 3x 99x 99x 99x 99x 99x 99x 17x 17x 17x 17x 17x 17x 17x 119x 119x 92x 27x 27x 27x 27x 30x 30x 1x 1x 29x 29x 2x 2x 2x 29x 29x 29x 4x 4x 4x 4x 29x 29x 17x 9x 9x 9x 9x 10x 10x 9x 9x 10x 10x 10x 10x 10x 9x 8x 8x 8x 8x 58x 58x 57x 57x 58x 58x 58x 8x 20x 20x 20x 20x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 6x 6x 6x 6x 6x 6x 6x 2x 2x 2x 2x 2x 2x 2x 2x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x | /**
* @module parliamentary-data/data-persistence
* @description Persists raw MCP data to a structured, version-controlled
* directory tree under `analysis/data/`. Every document, vote, event, or
* MP record fetched from MCP tools is written here with a consistent
* filename derived from its official Riksdag identifier (e.g. `dok_id`,
* `intressent_id`, `bet`).
*
* **Collision-free design** (v2):
* - **Data files** (`{id}.json`) contain ONLY the raw source data — no
* injected metadata. Two parallel workflows writing the same document
* produce byte-identical output, eliminating git merge conflicts.
* - **Sidecar metadata** (`{id}.meta.json`) tracks provenance (at minimum
* fetch timestamp and MCP tool name) in a separate file that is safely
* overwritten on each run. Riksdag/Riksdag-regeringen documents also
* include `riksmöte` and `documentType`, while external MCP tools
* (World Bank, SCB, etc.) use tool-specific fields (e.g. indicator /
* country, tableId / query) instead.
* - **All MCP tools**: riksdag-regering, World Bank, SCB, and any other
* MCP tool responses are stored under `analysis/data/`.
*
* Design principles:
* - **Upsert**: writes overwrite existing files (mutable data like MP
* profiles) or create new ones (immutable data like dated votes).
* - **Provenance**: sidecar `.meta.json` files track fetch origin.
* - **Date-stamped**: time-bound data (votes, events) is stored under
* `analysis/data/{type}/YYYY-MM-DD/` subdirectories.
* - **Side-effect-aware**: this module intentionally writes to disk;
* callers control when persistence is triggered.
*
* @author Hack23 AB
* @license Apache-2.0
*/
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import type { RawDocument } from '../data-transformers/types.js';
import type { DownloadedData, DocumentTypeKey } from './data-downloader.js';
// ---------------------------------------------------------------------------
// Utility — sanitize dok_id for use as filename
// ---------------------------------------------------------------------------
/**
* Sanitize a Riksdag document identifier for safe use as a filename.
* Lowercases, replaces non-alphanumeric characters (preserving Swedish chars
* and hyphens), collapses runs of hyphens, trims leading/trailing hyphens,
* and caps at 100 characters.
*/
export function sanitizeDokId(dokId: string): string {
return dokId
.toLowerCase()
.replace(/[^a-z0-9åäö-]/g, '-')
.replace(/-+/g, '-')
.replace(/^-|-$/g, '')
.slice(0, 100);
}
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const REPO_ROOT = path.resolve(__dirname, '../..');
const DATA_ROOT = path.join(REPO_ROOT, 'analysis', 'data');
/** ISO 8601 date format pattern (YYYY-MM-DD). Checks format only, not date validity. */
const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
/** All known document/data types that appear in sidecar metadata. */
export type PersistenceDocumentType =
| DocumentTypeKey
| 'events'
| 'mps'
| 'government'
| 'worldbank'
| 'imf'
| 'statskontoret'
| 'scb'
| 'riksbank'
| string; // extensible for generic MCP servers
/** Sidecar metadata written alongside data files. */
export interface PersistenceMetadata {
fetchedAt: string;
mcpTool: string;
riksmote: string;
documentType: PersistenceDocumentType;
}
/** Summary returned after a persistence run. */
export interface PersistenceResult {
/**
* Total logical records persisted.
*
* Note: a single logical record may produce multiple physical files or
* data/sidecar pairs (for example, votes written under both
* `documents/votes/` and `votes/{date}/`), but it is counted once here.
*/
written: number;
/** Total null/empty entries skipped. */
skipped: number;
/** Root directory the data was written to. */
dataRoot: string;
}
/** Description of an MCP tool call for generic response storage. */
export interface MCPToolCall {
/** MCP tool name (e.g. 'get_propositioner', 'search_tables', 'get-country-info') */
tool: string;
/** Parameters passed to the tool */
params: Record<string, unknown>;
/** MCP server identifier (e.g. 'riksdag-regering', 'scb', 'world-bank') */
server: string;
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function ensureDir(dir: string): void {
fs.mkdirSync(dir, { recursive: true });
}
/**
* Resolve the best identifier for a document.
* Falls back through the standard candidate chain.
*/
export function resolveDocId(doc: RawDocument, index: number): string {
const record = doc as Record<string, unknown>;
const candidates = [
record['dok_id'],
record['dokument_id'],
record['id'],
record['rel_dok_id'],
record['titel'],
record['title'],
];
const id = candidates.find(
(c): c is string => typeof c === 'string' && c.trim().length > 0,
)?.trim() ?? `unknown-${index + 1}`;
return sanitizeDokId(id) || `unknown-${index + 1}`;
}
/**
* Fields that the in-memory pipeline annotates onto documents for the
* manifest/coverage layer but that must NOT be written into raw
* `analysis/data/` files. Persisting these breaks byte-identical output
* across parallel workflows (every run has a fresh `retrievedAt`).
*/
const STRIPPED_METADATA_FIELDS = new Set<string>([
'mcpCoverageState',
'mcpProvenance',
'mcpSignals',
]);
/**
* Return a shallow clone of `doc` with in-memory MCP coverage metadata removed.
*
* Coverage state and provenance live in the manifest and sidecar `.meta.json`,
* not in the raw persisted document, so this guarantees the data files remain
* byte-identical regardless of how the in-memory record was decorated upstream.
*/
function stripInMemoryCoverageMetadata(doc: RawDocument): RawDocument {
const record = doc as Record<string, unknown>;
let cloned: Record<string, unknown> | null = null;
for (const field of STRIPPED_METADATA_FIELDS) {
if (field in record) {
if (!cloned) cloned = { ...record };
delete cloned[field];
}
}
return (cloned ?? record) as RawDocument;
}
/**
* Write raw data to disk as pretty-printed JSON (NO metadata injection).
* Metadata is written to a separate sidecar file to prevent merge conflicts
* when parallel workflows persist the same document.
*
* In-memory MCP coverage annotations (`mcpCoverageState`, `mcpProvenance`,
* `mcpSignals`) are stripped from the persisted JSON so byte-identical output
* is preserved across parallel workflows; provenance is carried in the
* sidecar `.meta.json` and the downstream manifest instead.
*/
function writeDocumentAndMeta(
dir: string,
baseFilename: string,
doc: RawDocument,
metadata: PersistenceMetadata,
): void {
ensureDir(dir);
const persistable = stripInMemoryCoverageMetadata(doc);
fs.writeFileSync(
path.join(dir, baseFilename),
JSON.stringify(persistable, null, 2),
'utf8',
);
const metaFilename = baseFilename.replace(/\.json$/, '.meta.json');
fs.writeFileSync(
path.join(dir, metaFilename),
JSON.stringify(metadata, null, 2),
'utf8',
);
}
// ---------------------------------------------------------------------------
// Public API — Riksdag documents
// ---------------------------------------------------------------------------
/**
* Persist all downloaded MCP data to the structured `analysis/data/` tree.
*
* Documents are organised by type under `analysis/data/documents/{type}/`.
* Date-stamped data (votes, events) is further partitioned by date.
*
* Data files contain only raw source data (no metadata injection) to ensure
* parallel workflows writing the same document produce identical output,
* preventing git merge conflicts.
*
* @param data - Downloaded data collections from `downloadAllDocuments()`
* @param riksmote - Current riksmöte identifier (e.g. "2025/26")
* @param mcpToolMap - Map of document type → MCP tool name for provenance
* @param dataRoot - Override for the data root directory (for testing)
* @returns Summary of files written and skipped.
*/
export function persistDownloadedData(
data: DownloadedData,
riksmote: string,
mcpToolMap?: Partial<Record<DocumentTypeKey, string>>,
dataRoot: string = DATA_ROOT,
): PersistenceResult {
const defaultToolMap: Record<DocumentTypeKey, string> = {
propositions: 'get_propositioner',
motions: 'get_motioner',
committeeReports: 'get_betankanden',
votes: 'search_voteringar',
speeches: 'search_anforanden',
questions: 'get_fragor',
interpellations: 'get_interpellationer',
};
const toolMap = { ...defaultToolMap, ...mcpToolMap };
const fetchedAt = new Date().toISOString();
let written = 0;
let skipped = 0;
const docTypes: DocumentTypeKey[] = [
'propositions',
'motions',
'committeeReports',
'votes',
'speeches',
'questions',
'interpellations',
];
for (const docType of docTypes) {
const docs = data[docType];
if (!docs || docs.length === 0) {
continue;
}
const typeDir = path.join(dataRoot, 'documents', docType);
const metadata: PersistenceMetadata = {
fetchedAt,
mcpTool: toolMap[docType],
riksmote,
documentType: docType,
};
const seenIds = new Set<string>();
for (let i = 0; i < docs.length; i++) {
const doc = docs[i];
if (!doc) {
skipped++;
continue;
}
let docId = resolveDocId(doc, i);
if (seenIds.has(docId)) {
let suffix = 1;
while (seenIds.has(`${docId}-${suffix}`)) suffix++;
docId = `${docId}-${suffix}`;
}
seenIds.add(docId);
const filename = `${docId}.json`;
if (docType === 'votes' && doc.datum) {
const voteDate = typeof doc.datum === 'string'
? doc.datum.slice(0, 10)
: '';
Eif (ISO_DATE_RE.test(voteDate)) {
const voteDateDir = path.join(dataRoot, 'votes', voteDate);
writeDocumentAndMeta(voteDateDir, filename, doc, {
...metadata,
documentType: 'votes',
});
}
}
writeDocumentAndMeta(typeDir, filename, doc, metadata);
written++;
}
}
return { written, skipped, dataRoot: dataRoot };
}
/**
* Persist a set of calendar events to `analysis/data/events/{date}/`.
* @param dataRoot - Override for the data root directory (for testing)
*/
export function persistEvents(
events: RawDocument[],
riksmote: string,
dataRoot: string = DATA_ROOT,
): PersistenceResult {
const fetchedAt = new Date().toISOString();
let written = 0;
let skipped = 0;
for (let i = 0; i < events.length; i++) {
const event = events[i];
if (!event) { skipped++; continue; }
const record = event as Record<string, unknown>;
const dateStr = typeof record['datum'] === 'string'
? (record['datum'] as string).slice(0, 10)
: typeof record['from'] === 'string'
? (record['from'] as string).slice(0, 10)
: '';
const eventDate = ISO_DATE_RE.test(dateStr) ? dateStr : 'undated';
const eventDir = path.join(dataRoot, 'events', eventDate);
const eventId = resolveDocId(event, i);
writeDocumentAndMeta(eventDir, `${eventId}.json`, event, {
fetchedAt,
mcpTool: 'get_calendar_events',
riksmote,
documentType: 'events',
});
written++;
}
return { written, skipped, dataRoot: dataRoot };
}
/**
* Persist MP profiles to `analysis/data/mps/`.
* @param dataRoot - Override for the data root directory (for testing)
*/
export function persistMPs(
mps: RawDocument[],
riksmote: string,
dataRoot: string = DATA_ROOT,
): PersistenceResult {
const fetchedAt = new Date().toISOString();
let written = 0;
let skipped = 0;
for (let i = 0; i < mps.length; i++) {
const mp = mps[i];
if (!mp) { skipped++; continue; }
const record = mp as Record<string, unknown>;
const id = (typeof record['intressent_id'] === 'string' && record['intressent_id'])
|| resolveDocId(mp, i);
const sanitized = sanitizeDokId(id) || `mp-${i + 1}`;
writeDocumentAndMeta(path.join(dataRoot, 'mps'), `${sanitized}.json`, mp, {
fetchedAt,
mcpTool: 'search_ledamoter',
riksmote,
documentType: 'mps',
});
written++;
}
return { written, skipped, dataRoot: dataRoot };
}
// ---------------------------------------------------------------------------
// Public API — Generic MCP response storage
// ---------------------------------------------------------------------------
/**
* Sanitize a path segment to prevent path traversal.
* Preserves underscores (common in MCP tool names like get_voting_group)
* but removes slashes, null bytes, and dots-only sequences.
*/
function sanitizePathSegment(segment: string): string {
let safe = segment.replace(/[/\\:\0]/g, '_');
if (/^\.+$/.test(safe)) safe = '_dots_';
safe = safe.replace(/[^a-zA-Z0-9_\-åäöÅÄÖ]/g, '_')
.replace(/_+/g, '_')
.replace(/^_|_$/g, '')
.slice(0, 100);
return safe || 'unknown';
}
/**
* Persist a generic MCP tool response. Supports any MCP server (riksdag,
* SCB, World Bank, etc.). Responses are stored under:
* `analysis/data/mcp-responses/{server}/{tool}/{id}.json`
*
* The response data is stored as-is (no metadata injection). A sidecar
* `.meta.json` tracks provenance.
*
* @param call - Description of the MCP tool call
* @param response - Raw response data from the MCP tool
* @param id - Unique identifier for this response (e.g. dok_id, table_id, country code)
* @param dataRoot - Override for the data root directory (for testing)
* @returns The absolute path where the response was written.
*/
export function persistMCPResponse(
call: MCPToolCall,
response: unknown,
id: string,
dataRoot: string = DATA_ROOT,
riksmote?: string,
): string {
const sanitized = sanitizeDokId(id) || `response-${crypto.randomUUID()}`;
const safeServer = sanitizePathSegment(call.server);
const safeTool = sanitizePathSegment(call.tool);
const dir = path.join(dataRoot, 'mcp-responses', safeServer, safeTool);
ensureDir(dir);
const filename = `${sanitized}.json`;
fs.writeFileSync(
path.join(dir, filename),
JSON.stringify(response, null, 2),
'utf8',
);
const resolvedRiksmote = riksmote
?? (typeof call.params.rm === 'string' ? call.params.rm : '');
const metaFilename = `${sanitized}.meta.json`;
const metadata: PersistenceMetadata & { params: Record<string, unknown> } = {
fetchedAt: new Date().toISOString(),
mcpTool: call.tool,
riksmote: resolvedRiksmote,
documentType: call.server,
params: call.params,
};
fs.writeFileSync(
path.join(dir, metaFilename),
JSON.stringify(metadata, null, 2),
'utf8',
);
return path.join(dir, filename);
}
/**
* Persist World Bank API response data.
* Stored under `analysis/data/worldbank/{indicator}/{country}.json`
*
* @param indicator - World Bank indicator ID (e.g. 'NY.GDP.MKTP.CD')
* @param country - Country code (e.g. 'SWE')
* @param response - Raw API response data
* @param dataRoot - Override for the data root directory (for testing)
*/
export function persistWorldBankData(
indicator: string,
country: string,
response: unknown,
dataRoot: string = DATA_ROOT,
): string {
const dir = path.join(dataRoot, 'worldbank', sanitizeDokId(indicator));
ensureDir(dir);
const filename = `${sanitizeDokId(country)}.json`;
fs.writeFileSync(
path.join(dir, filename),
JSON.stringify(response, null, 2),
'utf8',
);
const metaFilename = `${sanitizeDokId(country)}.meta.json`;
fs.writeFileSync(
path.join(dir, metaFilename),
JSON.stringify({
fetchedAt: new Date().toISOString(),
mcpTool: 'world-bank-api',
indicator,
country,
}, null, 2),
'utf8',
);
return path.join(dir, filename);
}
/**
* Persist IMF API response data (Datamapper JSON or SDMX 3.0).
*
* Stored under `analysis/data/imf/{indicator}/{country}.json`, mirroring the
* World Bank persistence layout. Introduced by the hybrid IMF integration
* (Economic Data Contract v2.0, 2026-04). Supports all IMF providers:
* Datamapper (WEO) and SDMX 3.0 (IFS/BOP/FM/GFS/DOTS/MFS), all accessed
* through the pure-TypeScript client `scripts/imf-client.ts` (there is no
* Python MCP / `uvx` runtime; agentic workflows invoke the `tsx
* scripts/imf-fetch.ts` CLI via the `bash` tool).
*
* @param indicator - IMF indicator code (e.g. 'NGDP_RPCH', 'GGXWDG_NGDP',
* 'PCPIPCH', 'LUR', 'FM_EXP_G01_GDP_PT').
* @param country - IMF AREA code (ISO3 for Datamapper; varies by dataset
* per `scripts/imf-codes.ts`).
* @param response - Raw IMF response payload.
* @param options - Optional provenance (`database`, `projectionVintage`,
* `dataRoot` override for testing).
* @returns Absolute path to the persisted data file.
*/
export function persistIMFData(
indicator: string,
country: string,
response: unknown,
options: {
database?: string;
projectionVintage?: string;
dataRoot?: string;
} = {},
): string {
const dataRoot = options.dataRoot ?? DATA_ROOT;
const dir = path.join(dataRoot, 'imf', sanitizeDokId(indicator));
ensureDir(dir);
const filename = `${sanitizeDokId(country)}.json`;
fs.writeFileSync(
path.join(dir, filename),
JSON.stringify(response, null, 2),
'utf8',
);
const metaFilename = `${sanitizeDokId(country)}.meta.json`;
fs.writeFileSync(
path.join(dir, metaFilename),
JSON.stringify({
fetchedAt: new Date().toISOString(),
mcpTool: 'imf-ts-client',
indicator,
country,
...(options.database ? { database: options.database } : {}),
...(options.projectionVintage ? { projectionVintage: options.projectionVintage } : {}),
}, null, 2),
'utf8',
);
return path.join(dir, filename);
}
/**
* Persist Statskontoret open-data responses and derived datasets.
*
* Stored under `analysis/data/statskontoret/{dataset}/{artifact}.json`.
* Statskontoret data is public and unauthenticated; provenance sidecars record
* the source dataset and the TypeScript client/CLI used to retrieve or derive
* the artifact.
*
* @param dataset - Statskontoret source key (e.g. 'myndighetsforteckning').
* @param artifact - Logical artifact name (e.g. 'downloads',
* 'headcount-by-department').
* @param response - Raw or derived Statskontoret payload.
* @param dataRoot - Override for the data root directory (for testing).
* @returns Absolute path to the persisted data file.
*/
export function persistStatskontoretData(
dataset: string,
artifact: string,
response: unknown,
dataRoot: string = DATA_ROOT,
): string {
const dir = path.join(dataRoot, 'statskontoret', sanitizeDokId(dataset));
ensureDir(dir);
const sanitizedArtifact = sanitizeDokId(artifact);
const filename = `${sanitizedArtifact}.json`;
fs.writeFileSync(
path.join(dir, filename),
JSON.stringify(response, null, 2),
'utf8',
);
const metaFilename = `${sanitizedArtifact}.meta.json`;
fs.writeFileSync(
path.join(dir, metaFilename),
JSON.stringify({
fetchedAt: new Date().toISOString(),
mcpTool: 'statskontoret-ts-client',
dataset,
artifact,
}, null, 2),
'utf8',
);
return path.join(dir, filename);
}
/**
* Persist SCB (Statistics Sweden) table data.
* Stored under `analysis/data/scb/{tableId}.json`
*
* @param tableId - SCB table identifier (e.g. 'BE0101A')
* @param response - Raw SCB API response data
* @param query - Optional query parameters used for provenance
* @param dataRoot - Override for the data root directory (for testing)
*/
export function persistSCBData(
tableId: string,
response: unknown,
query?: Record<string, unknown>,
dataRoot: string = DATA_ROOT,
): string {
const dir = path.join(dataRoot, 'scb');
ensureDir(dir);
const sanitized = sanitizeDokId(tableId);
const filename = `${sanitized}.json`;
fs.writeFileSync(
path.join(dir, filename),
JSON.stringify(response, null, 2),
'utf8',
);
const metaFilename = `${sanitized}.meta.json`;
fs.writeFileSync(
path.join(dir, metaFilename),
JSON.stringify({
fetchedAt: new Date().toISOString(),
mcpTool: 'scb-pxweb',
tableId,
...(query ? { query } : {}),
}, null, 2),
'utf8',
);
return path.join(dir, filename);
}
/**
* Persist Riksbank public web/JSON artifacts.
*
* Stored under `analysis/data/riksbank/{kind}.json`. Riksbank data is public
* and unauthenticated; provenance sidecars record the source URL/kind and the
* TypeScript CLI used to retrieve it.
*
* @param kind - Logical artifact kind (e.g. 'repo-rate-path', 'minutes').
* @param response - Raw or normalized Riksbank payload.
* @param dataRoot - Override for the data root directory (for testing).
* @returns Absolute path to the persisted data file.
*/
export function persistRiksbankData(
kind: string,
response: unknown,
dataRoot: string = DATA_ROOT,
): string {
const dir = path.join(dataRoot, 'riksbank');
ensureDir(dir);
const sanitized = sanitizeDokId(kind);
const filename = `${sanitized}.json`;
fs.writeFileSync(
path.join(dir, filename),
JSON.stringify(response, null, 2),
'utf8',
);
const candidateUrl = typeof response === 'object' && response !== null && 'url' in response
? (response as { url?: unknown }).url
: undefined;
const sourceUrl = typeof candidateUrl === 'string' && candidateUrl.length > 0
? candidateUrl
: undefined;
const metaFilename = `${sanitized}.meta.json`;
fs.writeFileSync(
path.join(dir, metaFilename),
JSON.stringify({
fetchedAt: new Date().toISOString(),
mcpTool: 'riksbank-ts-client',
kind,
...(sourceUrl ? { url: sourceUrl } : {}),
}, null, 2),
'utf8',
);
return path.join(dir, filename);
}
/**
* Return the absolute path to the data repository root.
* Useful for callers that need to reference persisted files.
*/
export function getDataRoot(): string {
return DATA_ROOT;
}
|