All files / scripts scb-fetch.ts

66.66% Statements 48/72
58.18% Branches 32/55
72.72% Functions 8/11
65.62% Lines 42/64

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                                                                                                      2x                                                                     2x                                 8x 8x 8x   6x 6x 6x 7x 7x 6x 6x 6x 4x 4x   2x     5x       5x 5x 3x       7x 3x 2x       3x 2x 2x 1x   1x 1x     1x 1x 1x 1x                   2x 2x 2x 2x 2x                                                                                                                               2x 2x 2x     2x              
#!/usr/bin/env tsx
/**
 * @module scripts/scb-fetch
 * @description CLI wrapper around the SCB MCP client for Swedish ground-truth
 * quantitative layers used alongside the IMF economic canon.
 */
 
import path from 'node:path';
import { pathToFileURL } from 'node:url';
 
import { SCBClient } from './scb-client.js';
import { persistSCBData } from './parliamentary-data/data-persistence.js';
 
export type SCBPresetKey = 'cpi' | 'aku' | 'household-economy' | 'fuel-prices';
 
export interface SCBPreset {
  readonly key: SCBPresetKey;
  readonly tableId: string;
  readonly label: string;
  readonly domain: string;
  readonly defaultValueCodes: Readonly<Record<string, string>>;
  readonly notes: string;
}
 
export interface SCBEconomicProvenance {
  readonly provider: 'scb';
  readonly dataflow: 'SCB PxWeb';
  readonly indicator: string;
  readonly tableId: string;
  readonly retrieved_at: string;
  readonly mcpTool: 'query_table';
}
 
export interface SCBFetchPayload {
  readonly provider: 'scb';
  readonly preset?: SCBPresetKey;
  readonly tableId: string;
  readonly label?: string;
  readonly valueCodes: Readonly<Record<string, string>>;
  readonly data: readonly unknown[];
  readonly status: 'ok' | 'no-data';
  readonly warning?: string;
  readonly economicProvenance: SCBEconomicProvenance;
}
 
interface ParsedArgs {
  readonly command: 'list-presets' | 'preset' | 'table' | 'help';
  readonly flags: ReadonlyMap<string, string>;
  readonly booleans: ReadonlySet<string>;
}
 
export const SCB_PRESETS: readonly SCBPreset[] = Object.freeze([
  {
    key: 'cpi',
    tableId: '0000003N',
    label: 'Consumer Price Index (KPI)',
    domain: 'inflation',
    defaultValueCodes: Object.freeze({ Tid: 'top(12)' }),
    notes: 'Monthly CPI / KPI layer for disposable-income and cost-of-living transmission analysis.',
  },
  {
    key: 'aku',
    tableId: '000003V8',
    label: 'Labour Force Survey (AKU)',
    domain: 'labour',
    defaultValueCodes: Object.freeze({ Tid: 'top(8)' }),
    notes: 'Quarterly labour-market layer for AKU unemployment and employment comparisons.',
  },
  {
    key: 'household-economy',
    tableId: 'HE0110A',
    label: 'Household economy (HEK / income distribution)',
    domain: 'household economy',
    defaultValueCodes: Object.freeze({ Tid: 'top(5)' }),
    notes: 'Household income and distribution layer for disposable-income impact estimates.',
  },
  {
    key: 'fuel-prices',
    tableId: 'PR0101A',
    label: 'Fuel and energy consumer-price components',
    domain: 'prices',
    defaultValueCodes: Object.freeze({ Tid: 'top(12)' }),
    notes: 'Fuel-price component layer for pump-price to CPI transmission analysis.',
  },
] as const);
 
const HELP = `tsx scripts/scb-fetch.ts <command> [flags]
 
Commands:
  list-presets  Print curated KPI / AKU / HEK / fuel-price presets
  preset        Fetch one curated preset by --preset
  table         Fetch one SCB table by --table-id
  help          Show this message
 
Flags:
  --preset <KEY>          cpi | aku | household-economy | fuel-prices
  --table-id <ID>         SCB table ID for table command
  --value-codes <JSON>    PxWeb value_codes JSON, e.g. '{"Tid":"top(10)"}'
  --periods <N>           Convenience fallback for Tid=top(N)
  --persist               Write output under analysis/data/scb/
`;
 
export function parseSCBArgs(argv: readonly string[]): ParsedArgs {
  const command = (argv[0] ?? 'help') as ParsedArgs['command'];
  const validCommands: readonly ParsedArgs['command'][] = ['list-presets', 'preset', 'table', 'help'];
  if (!validCommands.includes(command)) throw new Error(`unknown command ${command}`);
 
  const flags = new Map<string, string>();
  const booleans = new Set<string>();
  for (let i = 1; i < argv.length; i++) {
    const token = argv[i];
    if (!token.startsWith('--')) throw new Error(`unexpected positional argument ${token}`);
    const key = token.slice(2);
    const next = argv[i + 1];
    if (next !== undefined && !next.startsWith('--')) {
      flags.set(key, next);
      i++;
    } else {
      booleans.add(key);
    }
  }
  return { command, flags, booleans };
}
 
export function requireSCBFlag(flags: ReadonlyMap<string, string>, key: string): string {
  const value = flags.get(key);
  if (!value) throw new Error(`missing required flag --${key}`);
  return value;
}
 
export function parseSCBPreset(value: string): SCBPreset {
  const preset = SCB_PRESETS.find((item) => item.key === value);
  if (!preset) throw new Error(`unknown SCB preset ${value}`);
  return preset;
}
 
export function parseSCBValueCodes(raw: string | undefined, periods: string | undefined): Record<string, string> {
  if (raw) {
    const parsed = JSON.parse(raw) as unknown;
    if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
      throw new Error('--value-codes must be a JSON object');
    }
    return Object.fromEntries(
      Object.entries(parsed as Record<string, unknown>).map(([key, value]) => [key, String(value)]),
    );
  }
  Eif (periods) {
    const count = Number.parseInt(periods, 10);
    Iif (!Number.isInteger(count) || count < 1) throw new Error('--periods must be a positive integer');
    return { Tid: `top(${count})` };
  }
  return {};
}
 
export async function fetchSCBTablePayload(
  tableId: string,
  valueCodes: Readonly<Record<string, string>>,
  options: { preset?: SCBPreset; client?: SCBClient } = {},
): Promise<SCBFetchPayload> {
  const client = options.client ?? new SCBClient();
  const data = await client.getTableData(tableId, { ...valueCodes });
  const retrievedAt = new Date().toISOString();
  const status = data.length > 0 ? 'ok' : 'no-data';
  return {
    provider: 'scb',
    ...(options.preset ? { preset: options.preset.key, label: options.preset.label } : {}),
    tableId,
    valueCodes,
    data,
    status,
    ...(status === 'no-data' ? { warning: 'SCB returned no rows; callers should fall back to cached data if available.' } : {}),
    economicProvenance: {
      provider: 'scb',
      dataflow: 'SCB PxWeb',
      indicator: tableId,
      tableId,
      retrieved_at: retrievedAt,
      mcpTool: 'query_table',
    },
  };
}
 
async function runTable(
  tableId: string,
  valueCodes: Readonly<Record<string, string>>,
  booleans: ReadonlySet<string>,
  preset?: SCBPreset,
): Promise<void> {
  const payload = await fetchSCBTablePayload(tableId, valueCodes, { ...(preset ? { preset } : {}) });
  process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
  if (booleans.has('persist')) {
    persistSCBData(tableId, payload, {
      provider: 'scb',
      ...(preset ? { preset: preset.key } : {}),
      valueCodes,
    });
  }
}
 
async function main(): Promise<void> {
  const { command, flags, booleans } = parseSCBArgs(process.argv.slice(2));
  switch (command) {
    case 'list-presets':
      process.stdout.write(`${JSON.stringify({ presets: SCB_PRESETS }, null, 2)}\n`);
      return;
    case 'preset': {
      const preset = parseSCBPreset(requireSCBFlag(flags, 'preset'));
      const valueCodes = {
        ...preset.defaultValueCodes,
        ...parseSCBValueCodes(flags.get('value-codes'), flags.get('periods')),
      };
      await runTable(preset.tableId, valueCodes, booleans, preset);
      return;
    }
    case 'table': {
      const tableId = requireSCBFlag(flags, 'table-id');
      const valueCodes = parseSCBValueCodes(flags.get('value-codes'), flags.get('periods'));
      await runTable(tableId, valueCodes, booleans);
      return;
    }
    case 'help':
    default:
      process.stdout.write(HELP);
  }
}
 
function isDirectExecution(): boolean {
  const entry = process.argv[1];
  Iif (!entry) return false;
  return import.meta.url === pathToFileURL(path.resolve(entry)).href;
}
 
Iif (isDirectExecution()) {
  main().catch((error: unknown) => {
    const message = error instanceof Error ? error.message : String(error);
    process.stderr.write(`scb-fetch: ${message}\n`);
    process.exit(/^(missing|unknown|unexpected|--)/i.test(message) ? 2 : 1);
  });
}