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 | 344x 74x 11x 4x 14x 14x 14x 14x 13x 72x 14x 14x 4x 2x 2x 2x 2x 2x 5x 2x 3x 5x 5x 3x 5x 5x 5x 5x 5x 5x 5x 5x 4x 6x 5x 5x 7x 5x 5x 5x 5x 5x 2x 2x 3x 17x | /**
* @fileoverview Legislative sub-client for European Parliament API
*
* Handles legislative procedures, procedure events, and adopted texts.
*
* @module clients/ep/legislativeClient
*/
import type {
Procedure,
AdoptedText,
EPEvent,
PaginatedResponse,
} from '../../types/europeanParliament.js';
import {
transformProcedure as _transformProcedure,
transformAdoptedText as _transformAdoptedText,
transformEvent as _transformEvent,
} from './transformers.js';
import {
BaseEPClient,
APIError,
type EPClientConfig,
type EPSharedResources,
type JSONLDResponse,
} from './baseClient.js';
import { DEFAULT_TIMEOUTS } from '../../utils/timeout.js';
// ─── Legislative Client ───────────────────────────────────────────────────────
/**
* Sub-client for legislative procedures and adopted-texts EP API endpoints.
*
* @extends BaseEPClient
* @public
*/
export class LegislativeClient extends BaseEPClient {
constructor(config: EPClientConfig = {}, shared?: EPSharedResources) {
super(config, shared);
}
// ─── Transform helpers ────────────────────────────────────────────────────
private transformProcedure(apiData: Record<string, unknown>): Procedure {
return _transformProcedure(apiData);
}
private transformAdoptedText(apiData: Record<string, unknown>): AdoptedText {
return _transformAdoptedText(apiData);
}
private transformEvent(apiData: Record<string, unknown>): EPEvent {
return _transformEvent(apiData);
}
// ─── Public methods ───────────────────────────────────────────────────────
/**
* Returns legislative procedures.
* **EP API Endpoint:** `GET /procedures`
*
* **Note:** The EP API `/procedures` endpoint does **not** support a
* `year` query parameter per the OpenAPI spec — it only has
* `process-type`. Callers needing year-specific counts must filter
* client-side.
*
* @param params - limit, offset
* @returns Paginated list of procedures
*/
async getProcedures(params: {
limit?: number;
offset?: number;
} = {}): Promise<PaginatedResponse<Procedure>> {
const limit = params.limit ?? 50;
const offset = params.offset ?? 0;
const apiParams: Record<string, unknown> = {
format: 'application/ld+json',
offset,
limit,
};
// Note: `year` is NOT a valid param for /procedures per EP API spec.
// Not forwarded to avoid misleading callers or future API validation failures.
const response = await this.get<JSONLDResponse>('procedures', apiParams);
const items = Array.isArray(response.data) ? response.data : [];
const procedures = items.map((item) => this.transformProcedure(item));
const hasMore = procedures.length === limit;
return { data: procedures, total: procedures.length + offset + (hasMore ? 1 : 0), limit, offset, hasMore };
}
/**
* Returns a single procedure by ID.
*
* The EP API wraps single-item responses in a JSON-LD `data` array,
* so this method extracts `data[0]` before transforming.
*
* **EP API Endpoint:** `GET /procedures/{process-id}`
*
* @param processId - Procedure **process-id** in `"YYYY-NNNN"` format (e.g. `"2024-0006"`).
* This is different from the human-readable `Procedure.id` (`"COD/YYYY/NNNN"`) or
* `Procedure.reference` (`"YYYY/NNNN(COD)"`) fields.
* @throws {APIError} When the procedure is not found (404)
*/
async getProcedureById(processId: string): Promise<Procedure> {
if (processId.trim() === '') {
throw new APIError('Procedure process-id is required', 400);
}
const response = await this.get<Record<string, unknown>>(
`procedures/${processId}`,
{ format: 'application/ld+json' }
);
const dataArray = response['data'];
Iif (Array.isArray(dataArray) && dataArray.length > 0) {
return this.transformProcedure(dataArray[0] as Record<string, unknown>);
}
return this.transformProcedure(response);
}
/**
* Returns events linked to a procedure.
* **EP API Endpoint:** `GET /procedures/{process-id}/events`
*
* @param processId - Procedure process ID
* @param params - limit, offset
*/
async getProcedureEvents(
processId: string,
params: { limit?: number; offset?: number } = {}
): Promise<PaginatedResponse<EPEvent>> {
if (processId.trim() === '') {
throw new APIError('Procedure process-id is required', 400);
}
const limit = params.limit ?? 50;
const offset = params.offset ?? 0;
const response = await this.get<JSONLDResponse>(
`procedures/${processId}/events`,
{ format: 'application/ld+json', offset, limit }
);
const items = Array.isArray(response.data) ? response.data : [];
const events = items.map((item) => this.transformEvent(item));
const hasMore = events.length === limit;
return { data: events, total: events.length + offset + (hasMore ? 1 : 0), limit, offset, hasMore };
}
/**
* Returns adopted texts.
* **EP API Endpoint:** `GET /adopted-texts`
*
* @param params - year, limit, offset
*/
async getAdoptedTexts(params: {
year?: number;
limit?: number;
offset?: number;
} = {}): Promise<PaginatedResponse<AdoptedText>> {
const limit = params.limit ?? 50;
const offset = params.offset ?? 0;
const apiParams: Record<string, unknown> = {
format: 'application/ld+json',
offset,
limit,
};
if (params.year !== undefined) apiParams['year'] = params.year;
const response = await this.get<JSONLDResponse>('adopted-texts', apiParams);
const items = Array.isArray(response.data) ? response.data : [];
const texts = items.map((item) => this.transformAdoptedText(item));
const hasMore = texts.length === limit;
return { data: texts, total: texts.length + offset + (hasMore ? 1 : 0), limit, offset, hasMore };
}
/**
* Retrieves recently updated procedures via the feed endpoint.
* **EP API Endpoint:** `GET /procedures/feed`
*
* **Note:** The EP API `procedures/feed` endpoint is significantly slower
* than other feed endpoints — it typically takes 25–40 s even for `one-week`
* and 120+ seconds for `one-month`. An extended minimum timeout of 120 s
* is always applied.
*/
async getProceduresFeed(params: {
timeframe?: string;
startDate?: string;
processType?: string;
} = {}): Promise<JSONLDResponse> {
return this.get<JSONLDResponse>('procedures/feed', {
format: 'application/ld+json',
...(params.timeframe !== undefined ? { timeframe: params.timeframe } : {}),
...(params.startDate !== undefined ? { 'start-date': params.startDate } : {}),
...(params.processType !== undefined ? { 'process-type': params.processType } : {}),
}, DEFAULT_TIMEOUTS.EP_FEED_SLOW_REQUEST_MS);
}
/**
* Retrieves recently updated adopted texts via the feed endpoint.
* **EP API Endpoint:** `GET /adopted-texts/feed`
*
* Configurable-window feed. Extended timeout applied for `one-month`.
*/
async getAdoptedTextsFeed(params: {
timeframe?: string;
startDate?: string;
workType?: string;
} = {}): Promise<JSONLDResponse> {
const minimumTimeout = params.timeframe === 'one-month'
? DEFAULT_TIMEOUTS.EP_FEED_SLOW_REQUEST_MS
: undefined;
return this.get<JSONLDResponse>('adopted-texts/feed', {
format: 'application/ld+json',
...(params.timeframe !== undefined ? { timeframe: params.timeframe } : {}),
...(params.startDate !== undefined ? { 'start-date': params.startDate } : {}),
...(params.workType !== undefined ? { 'work-type': params.workType } : {}),
}, minimumTimeout);
}
/**
* Returns a single event within a procedure by event ID.
* **EP API Endpoint:** `GET /procedures/{process-id}/events/{event-id}`
*
* @param processId - Procedure process ID
* @param eventId - Event identifier within the procedure
*/
async getProcedureEventById(processId: string, eventId: string): Promise<EPEvent> {
if (processId.trim() === '') {
throw new APIError('Procedure process-id is required', 400);
}
if (eventId.trim() === '') {
throw new APIError('Event ID is required', 400);
}
const response = await this.get<JSONLDResponse>(
`procedures/${processId}/events/${eventId}`,
{ format: 'application/ld+json' }
);
// EP API wraps single-item responses in a `data` array
if (Array.isArray(response.data)) {
if (response.data.length === 0) {
throw new APIError(
`Procedure event not found for process-id "${processId}" and event ID "${eventId}"`,
404
);
}
return this.transformEvent(response.data[0] ?? {});
}
// Fall back to transforming the raw response only when the response shape
// is not JSON-LD-wrapped.
return this.transformEvent(response);
}
/**
* Returns a single adopted text by document ID.
* **EP API Endpoint:** `GET /adopted-texts/{doc-id}`
*
* **Content-pending detection:** The EP Open Data Portal will sometimes respond
* with HTTP 200 for a document that is indexed in the feed but whose detail
* enrichment has not yet completed — every transformable field comes back empty.
* Returning that shape to callers would emit a response that passes JSON-schema
* validation but carries no data, leading to blank titles/dates/references being
* rendered downstream. We treat this sentinel as a 404 so callers get the same
* error semantics they would for a truly missing document, and we also evict
* the cached empty payload so availability recovers as soon as the upstream
* document is enriched (instead of blocking for the full cache TTL).
*
* @throws {APIError} 400 when `docId` is empty or whitespace.
* @throws {APIError} 404 in two cases:
* - the upstream returns HTTP 404 because no document exists for `docId`
* (re-thrown by {@link BaseEPClient.get}); or
* - the upstream returns HTTP 200 but every transformable field is empty
* (the indexed-but-content-pending sentinel detected here).
*/
async getAdoptedTextById(docId: string): Promise<AdoptedText> {
if (docId.trim() === '') throw new APIError('Document ID is required', 400);
const endpoint = `adopted-texts/${docId}`;
const params = { format: 'application/ld+json' };
const response = await this.get<Record<string, unknown>>(endpoint, params);
const transformed = this.transformAdoptedText(response);
if (isEmptyAdoptedText(transformed)) {
// Evict the empty payload so a retry after upstream enrichment gets the
// real document instead of the cached sentinel for the remainder of the
// cache TTL.
this.evictFromCache(endpoint, params);
throw new APIError(
`Adopted text "${docId}": document indexed but content not yet available`,
404
);
}
return transformed;
}
}
/**
* Returns `true` when every string field of an {@link AdoptedText} is empty —
* the upstream content-pending sentinel that must not be surfaced to callers.
*
* Iterates over `Object.values` so the check stays correct if new fields are
* added to {@link AdoptedText} (all current fields are `string`).
*
* @internal
*/
function isEmptyAdoptedText(text: AdoptedText): boolean {
return Object.values(text).every((v) => typeof v === 'string' && v === '');
}
|