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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 24x 24x 32x 32x 16x 16x 16x 8x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 24x 24x 16x 3x 3x 3x 3x 3x 3x 24x 24x 24x 24x 16x 16x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 1x 1x 1x 1x | #!/usr/bin/env tsx
/**
* @module scripts/polling-fetch
* @description Aggregates latest polling-wave context for Sifo, Novus, and Demoskop.
*
* The script fetches a single page per provider, extracts the latest visible
* party percentages when possible, computes a simple cross-provider mean, and
* persists a versioned cache (`data/polling-context.json` by default) so the
* news pre-warm step has a stable polling context artifact even when one or
* more upstream pages fail.
*/
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { decodeHtmlEntities } from './html-utils.js';
export const PARTY_CODES = ['S', 'M', 'SD', 'V', 'MP', 'C', 'L', 'KD'] as const;
export type PartyCode = typeof PARTY_CODES[number];
export type PollProviderKey = 'sifo' | 'novus' | 'demoskop';
export interface PollingWave {
readonly provider: PollProviderKey;
readonly sourceUrl: string;
readonly fetchedAt: string;
readonly status: 'ok' | 'unavailable';
readonly title?: string;
readonly publishedAt?: string;
readonly fieldworkMonth?: string;
readonly sampleSize?: number;
readonly parties: Partial<Record<PartyCode, number>>;
readonly notes?: string;
}
export interface PollingAggregatePoint {
readonly mean: number;
readonly samples: number;
}
export interface PollingContext {
readonly schemaVersion: '1.0';
readonly cacheVersion: 1;
readonly generatedAt: string;
readonly providers: readonly PollingWave[];
readonly aggregate: {
readonly availableProviders: number;
readonly parties: Partial<Record<PartyCode, PollingAggregatePoint>>;
};
}
export interface PollingProviderDefinition {
readonly provider: PollProviderKey;
readonly url: string;
}
export interface PollingFetchConfig {
readonly providers?: readonly PollingProviderDefinition[];
readonly fetchFn?: typeof fetch;
readonly now?: () => string;
}
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const REPO_ROOT = path.resolve(__dirname, '..');
export const DEFAULT_POLLING_OUTPUT = path.join(REPO_ROOT, 'data', 'polling-context.json');
// Per-provider request timeout (ms). Each provider fails independently so a
// single hung page cannot stall the whole script under the 60 s action-level
// `timeout` and prevent the degraded `data/polling-context.json` artifact from
// being written.
export const POLLING_REQUEST_TIMEOUT_MS = 15_000;
export const DEFAULT_POLLING_PROVIDERS: readonly PollingProviderDefinition[] = Object.freeze([
{ provider: 'sifo', url: 'https://www.veriangroup.com/sv/expertis/politik-och-opinion/valjarbarometer' },
{ provider: 'novus', url: 'https://novus.se/valjarbarometer-arkiv/kategori/valjarbarometern/' },
// NOTE: Demoskop's public landing URL changed; the bare path
// `/v%C3%A4ljarbarometern/` returns 404. We start from the Demoskop home
// page so the follow-up-link heuristic in `findFollowUpPollingUrl` can
// discover the latest wave article rather than 404-ing immediately. This is
// best-effort — when discovery fails the entry is marked
// `status: "unavailable"` with a clear note.
{ provider: 'demoskop', url: 'https://demoskop.se/' },
]);
const CANONICAL_RE = /<link\b[^>]*rel=["']canonical["'][^>]*href=["']([^"']+)["'][^>]*>/i;
const HREF_RE = /<a\b[^>]*href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi;
const TITLE_RE = /<title[^>]*>([\s\S]*?)<\/title>/i;
const TAG_RE = /<[^>]+>/g;
const WHITESPACE_RE = /\s+/g;
const DATE_RE = /(20\d{2}-\d{2}-\d{2})/;
const MONTH_RE = /(20\d{2})[-/](0[1-9]|1[0-2])/;
const SAMPLE_SIZE_RE = /(?:sample\s*size|urval|\bn\b)\s*[:=]?\s*(\d{3,5})/i;
function stripHtml(html: string): string {
return decodeHtmlEntities(html).replace(TAG_RE, ' ').replace(WHITESPACE_RE, ' ').trim();
}
function extractNumericPartyShare(text: string, partyCode: PartyCode): number | undefined {
const patterns = [
new RegExp(`\\b${partyCode}\\b\\s*[:\\-]?\\s*(\\d{1,2}(?:[\\.,]\\d)?)\\s*%`, 'i'),
new RegExp(`\\b${partyCode}\\b\\s*[:\\-]?\\s*(\\d{1,2}(?:[\\.,]\\d)?)\\s+procent\\b`, 'i'),
];
for (const pattern of patterns) {
const match = pattern.exec(text);
if (!match?.[1]) continue;
const value = Number.parseFloat(match[1].replace(',', '.'));
Eif (Number.isFinite(value)) {
return value;
}
}
return undefined;
}
function isArchiveRootUrl(url: string): boolean {
// Treat archive listing pages and category roots as "canonical archive
// roots" we should NOT prefer over a specific polling article. Examples:
// https://novus.se/valjarbarometer-arkiv/
// https://example.test/category/valjarbarometer/
// https://example.test/arkiv/polls/
return /[-/](arkiv|category|kategori|tag)(\/|$)/i.test(new URL(url).pathname);
}
function findFollowUpPollingUrl(sourceUrl: string, html: string): string | null {
// First, walk anchor tags and prefer concrete article links that match the
// polling-wave pattern. We only fall back to <link rel="canonical"> when no
// article link is found, because canonical often points at an archive root.
for (const match of html.matchAll(HREF_RE)) {
const href = match[1];
const label = stripHtml(match[2] ?? '');
Iif (!href) continue;
const haystack = `${href} ${label}`.toLowerCase();
Iif (!/valjarbarometer|väljarbarometer/.test(haystack)) continue;
const resolved = new URL(href, sourceUrl).toString();
Iif (resolved === sourceUrl) continue;
Iif (isArchiveRootUrl(resolved)) continue;
return resolved;
}
const canonical = CANONICAL_RE.exec(html)?.[1];
Iif (canonical && canonical !== sourceUrl) {
return canonical;
}
return null;
}
export function extractPollingWaveFromHtml(
provider: PollProviderKey,
sourceUrl: string,
html: string,
fetchedAt: string,
): PollingWave {
const titleMatch = TITLE_RE.exec(html);
const title = titleMatch?.[1] ? stripHtml(titleMatch[1]) : undefined;
const text = stripHtml(html);
const publishedAt = DATE_RE.exec(text)?.[1];
const monthMatch = MONTH_RE.exec(text);
const fieldworkMonth = monthMatch ? `${monthMatch[1]}-${monthMatch[2]}` : publishedAt?.slice(0, 7);
const sampleSizeMatch = SAMPLE_SIZE_RE.exec(text);
const sampleSize = sampleSizeMatch?.[1] ? Number.parseInt(sampleSizeMatch[1], 10) : undefined;
const parties: Partial<Record<PartyCode, number>> = {};
for (const partyCode of PARTY_CODES) {
const value = extractNumericPartyShare(text, partyCode);
if (value !== undefined) {
parties[partyCode] = value;
}
}
const populatedParties = Object.keys(parties).length;
Eif (populatedParties >= 3) {
return {
provider,
sourceUrl,
fetchedAt,
status: 'ok',
title,
publishedAt,
fieldworkMonth,
sampleSize,
parties,
};
}
return {
provider,
sourceUrl,
fetchedAt,
status: 'unavailable',
title,
publishedAt,
fieldworkMonth,
sampleSize,
parties: {},
notes: `Could not extract enough party shares from ${provider} source page`,
};
}
export function buildPollingAggregate(waves: readonly PollingWave[]): PollingContext['aggregate'] {
const available = waves.filter((wave) => wave.status === 'ok');
const aggregate: Partial<Record<PartyCode, PollingAggregatePoint>> = {};
for (const partyCode of PARTY_CODES) {
const values = available
.map((wave) => wave.parties[partyCode])
.filter((value): value is number => typeof value === 'number' && Number.isFinite(value));
if (values.length === 0) continue;
const sum = values.reduce((acc, value) => acc + value, 0);
aggregate[partyCode] = {
mean: Number.parseFloat((sum / values.length).toFixed(2)),
samples: values.length,
};
}
return {
availableProviders: available.length,
parties: aggregate,
};
}
async function fetchWithTimeout(
fetchFn: typeof fetch,
url: string,
timeoutMs: number,
): Promise<{ response: Response; text: string }> {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
try {
const response = await fetchFn(url, {
signal: controller.signal,
headers: {
Accept: 'text/html,application/xhtml+xml',
'User-Agent': 'Mozilla/5.0 (compatible; Riksdagsmonitor polling-fetch)',
},
});
// Keep the abort active through body consumption so a stalled body read
// also gets terminated within the timeout budget.
const text = await response.text();
return { response, text };
} finally {
clearTimeout(timer);
}
}
export async function fetchPollingContext(config: PollingFetchConfig = {}): Promise<PollingContext> {
const providers = config.providers ?? DEFAULT_POLLING_PROVIDERS;
const fetchFn = config.fetchFn ?? globalThis.fetch;
const fetchedAt = config.now?.() ?? new Date().toISOString();
const waves = await Promise.all(
providers.map(async (provider): Promise<PollingWave> => {
try {
const { response, text: html } = await fetchWithTimeout(fetchFn, provider.url, POLLING_REQUEST_TIMEOUT_MS);
Iif (!response.ok) {
return {
provider: provider.provider,
sourceUrl: provider.url,
fetchedAt,
status: 'unavailable',
parties: {},
notes: `HTTP ${response.status} ${response.statusText}`,
};
}
// For known archive/category roots, prefer discovering and fetching a
// concrete polling-wave article before attempting extraction from the
// archive listing itself (which may contain mixed/stale percentages).
let extractionUrl = provider.url;
let extractionHtml = html;
let attemptedFollowUp = false;
if (isArchiveRootUrl(provider.url)) {
const preferredFollowUpUrl = findFollowUpPollingUrl(provider.url, html);
Eif (preferredFollowUpUrl) {
attemptedFollowUp = true;
const { response: followUpResponse, text: followUpHtml } = await fetchWithTimeout(fetchFn, preferredFollowUpUrl, POLLING_REQUEST_TIMEOUT_MS);
Eif (followUpResponse.ok) {
extractionUrl = preferredFollowUpUrl;
extractionHtml = followUpHtml;
}
}
}
let wave = extractPollingWaveFromHtml(provider.provider, extractionUrl, extractionHtml, fetchedAt);
Iif (wave.status === 'unavailable' && !attemptedFollowUp) {
const followUpUrl = findFollowUpPollingUrl(provider.url, html);
if (followUpUrl) {
const { response: followUpResponse, text: followUpHtml } = await fetchWithTimeout(fetchFn, followUpUrl, POLLING_REQUEST_TIMEOUT_MS);
if (followUpResponse.ok) {
wave = extractPollingWaveFromHtml(provider.provider, followUpUrl, followUpHtml, fetchedAt);
}
}
}
return wave;
} catch (error) {
return {
provider: provider.provider,
sourceUrl: provider.url,
fetchedAt,
status: 'unavailable',
parties: {},
notes: error instanceof Error ? error.message : String(error),
};
}
}),
);
return {
schemaVersion: '1.0',
cacheVersion: 1,
generatedAt: fetchedAt,
providers: waves,
aggregate: buildPollingAggregate(waves),
};
}
export function persistPollingContext(context: PollingContext, outputPath = DEFAULT_POLLING_OUTPUT): string {
fs.mkdirSync(path.dirname(outputPath), { recursive: true });
fs.writeFileSync(outputPath, `${JSON.stringify(context, null, 2)}\n`, 'utf8');
return outputPath;
}
function parseArgs(argv: readonly string[]): { output: string; persist: boolean } {
let output = DEFAULT_POLLING_OUTPUT;
let persist = true;
for (let i = 2; i < argv.length; i++) {
const token = argv[i];
if (token === '--output') {
output = argv[i + 1] ?? output;
i++;
continue;
}
if (token === '--no-persist') {
persist = false;
}
}
return { output, persist };
}
async function main(): Promise<void> {
const args = parseArgs(process.argv);
const context = await fetchPollingContext();
if (args.persist) {
persistPollingContext(context, args.output);
}
process.stdout.write(`${JSON.stringify(context, null, 2)}\n`);
}
Iif (path.resolve(fileURLToPath(import.meta.url)) === path.resolve(process.argv[1] ?? '')) {
main().catch((error: unknown) => {
console.error(`polling-fetch: ${error instanceof Error ? error.message : String(error)}`);
process.exit(1);
});
}
|