1
2
3
4
5
6
7
8
9
10
11
12
13
14
15const SEARCH_URL = 'https://api.ted.europa.eu/v3/notices/search';
16
17
18export const MAX_LIMIT = 250;
19export const MAX_FIELDS_PER_PAGE = 10000;
20
21
22
23
24
25export const MAX_PAGE_NUMBER_NOTICES = 15000;
26
27
28
29
30
31export const FIELDS = [
32 'publication-number',
33 'publication-date',
34 'notice-type',
35 'notice-title',
36 'description-proc',
37 'buyer-name',
38 'buyer-country',
39 'classification-cpv',
40
41
42 'deadline',
43 'deadline-date-lot',
44 'deadline-receipt-request',
45 'deadline-receipt-request-date-lot',
46 'deadline-receipt-tender-date-lot',
47 'total-value',
48 'total-value-cur',
49 'estimated-value-proc',
50 'estimated-value-cur-proc',
51 'contract-nature',
52 'links',
53];
54
55
56
57
58
59export function pickLang(value, preferred = 'dan') {
60 if (value == null) return null;
61 if (typeof value === 'string') return value;
62 if (Array.isArray(value)) return value.length ? pickLang(value[0], preferred) : null;
63 if (typeof value !== 'object') return null;
64
65 for (const key of [preferred, 'eng', ...Object.keys(value)]) {
66 const hit = value[key];
67 if (hit == null) continue;
68 const text = Array.isArray(hit) ? hit.filter(Boolean).join(' ') : String(hit);
69 if (text.trim()) return text.trim();
70 }
71 return null;
72}
73
74
75export function pickLink(links, kind, preferred = 'DAN') {
76 const group = links?.[kind];
77 if (!group || typeof group !== 'object') return null;
78 for (const key of [preferred, 'ENG', 'MUL', ...Object.keys(group)]) {
79 if (group[key]) return group[key];
80 }
81 return null;
82}
83
84
85function first(value) {
86 if (Array.isArray(value)) return value.length ? value[0] : null;
87 return value ?? null;
88}
89
90
91
92
93
94
95
96
97export const DEADLINE_FIELDS = [
98 'deadline-receipt-tender-date-lot',
99 'deadline-receipt-request',
100 'deadline-receipt-request-date-lot',
101 'deadline',
102 'deadline-date-lot',
103];
104
105
106
107
108
109
110
111export const MAX_DEADLINE_HORIZON_DAYS = 730;
112
113
114
115
116
117
118
119
120
121
122export function resolveDeadline(notice, { today = new Date(), maxHorizonDays = MAX_DEADLINE_HORIZON_DAYS } = {}) {
123 const todayMs = Date.parse(`${today.toISOString().slice(0, 10)}T00:00:00Z`);
124 let rejected = null;
125
126 for (const field of DEADLINE_FIELDS) {
127 const value = notice?.[field];
128 if (value == null) continue;
129 const date = earliestDate(value);
130 if (!date) continue;
131
132 const aheadDays = Math.round((Date.parse(`${date}T00:00:00Z`) - todayMs) / 86400000);
133 if (aheadDays > maxHorizonDays) {
134 rejected = rejected ?? { date, source: field, aheadDays };
135 continue;
136 }
137 return { date, source: field, implausible: null };
138 }
139
140 return { date: null, source: null, implausible: rejected };
141}
142
143
144export function earliestDate(value) {
145 if (!Array.isArray(value)) return toIsoDate(value);
146 const dates = value
147 .map((v) => toIsoDate(v))
148 .filter((v) => v && /^\d{4}-\d{2}-\d{2}$/.test(v))
149 .sort();
150 return dates.length ? dates[0] : null;
151}
152
153
154export function toIsoDate(value) {
155 const raw = first(value);
156 if (!raw) return null;
157 const match = String(raw).match(/^(\d{4}-\d{2}-\d{2})/);
158 return match ? match[1] : String(raw);
159}
160
161
162
163
164
165
166export function normalizeNotice(notice, { language = 'dan' } = {}) {
167 const linkLang = language.slice(0, 3).toUpperCase();
168 const deadline = resolveDeadline(notice);
169 const cpv = Array.isArray(notice['classification-cpv'])
170 ? [...new Set(notice['classification-cpv'].filter(Boolean).map(String))]
171 : [];
172
173 const estimated = first(notice['estimated-value-proc']) ?? first(notice['total-value']);
174 const currency =
175 first(notice['estimated-value-cur-proc']) ?? first(notice['total-value-cur']) ?? null;
176
177 return {
178 publicationNumber: first(notice['publication-number']) ?? null,
179 publicationDate: toIsoDate(notice['publication-date']),
180 noticeType: first(notice['notice-type']) ?? null,
181 contractNature: first(notice['contract-nature']) ?? null,
182 title: pickLang(notice['notice-title'], language),
183 description: pickLang(notice['description-proc'], language),
184 buyerName: pickLang(notice['buyer-name'], language),
185 buyerCountry: first(notice['buyer-country']) ?? null,
186 cpvCodes: cpv,
187 deadline: deadline.date,
188
189
190 deadlineSource: deadline.source,
191
192
193 deadlineImplausible: deadline.implausible ?? null,
194 estimatedValue: estimated == null ? null : Number(estimated),
195 currency,
196 htmlUrl: pickLink(notice.links, 'html', linkLang),
197 pdfUrl: pickLink(notice.links, 'pdf', linkLang),
198 xmlUrl: pickLink(notice.links, 'xml', 'MUL'),
199 };
200}
201
202
203
204
205
206
207
208export function buildQuery({
209 countries = ['DNK'],
210 publishedSince = null,
211 publishedUntil = null,
212 cpvCodes = [],
213 noticeTypes = [],
214 keywords = [],
215} = {}) {
216 const clauses = [];
217
218 if (countries.length) {
219 clauses.push(`(${countries.map((c) => `buyer-country=${ted(c)}`).join(' OR ')})`);
220 }
221 if (publishedSince) clauses.push(`publication-date>=${compactDate(publishedSince)}`);
222 if (publishedUntil) clauses.push(`publication-date<=${compactDate(publishedUntil)}`);
223
224 if (cpvCodes.length) {
225 clauses.push(`(${cpvCodes.map((c) => `classification-cpv=${ted(c)}`).join(' OR ')})`);
226 }
227 if (noticeTypes.length) {
228 clauses.push(`(${noticeTypes.map((t) => `notice-type=${ted(t)}`).join(' OR ')})`);
229 }
230 if (keywords.length) {
231 const terms = keywords
232 .map((k) => `(notice-title~"${escapeQuotes(k)}" OR description-proc~"${escapeQuotes(k)}")`)
233 .join(' OR ');
234 clauses.push(`(${terms})`);
235 }
236
237 return clauses.join(' AND ');
238}
239
240
241function ted(code) {
242 const clean = String(code).trim();
243 if (!/^[A-Za-z0-9_-]+$/.test(clean)) {
244 throw new Error(`Unsafe value for a TED query: ${JSON.stringify(code)}`);
245 }
246 return clean;
247}
248
249function escapeQuotes(text) {
250 return String(text).replace(/["\\]/g, ' ').trim();
251}
252
253
254export function compactDate(value) {
255 const clean = String(value).trim();
256 if (/^\d{8}$/.test(clean)) return clean;
257 const match = clean.match(/^(\d{4})-(\d{2})-(\d{2})/);
258 if (!match) throw new Error(`Cannot read "${value}" as a date. Use YYYY-MM-DD.`);
259 return `${match[1]}${match[2]}${match[3]}`;
260}
261
262export function daysAgoIso(days) {
263 const d = new Date(Date.now() - days * 24 * 60 * 60 * 1000);
264 return d.toISOString().slice(0, 10);
265}
266
267
268export class IterationTokenError extends Error {}
269
270
271
272
273
274
275
276
277export async function searchPage({
278 query,
279 fields = FIELDS,
280 page = 1,
281 limit = 50,
282 scope = 'ALL',
283 onlyLatestVersions = true,
284 paginationMode = 'ITERATION',
285 iterationNextToken = null,
286 log = console,
287 fetchImpl = fetch,
288 maxAttempts = 4,
289} = {}) {
290 if (limit > MAX_LIMIT) throw new Error(`limit must be <= ${MAX_LIMIT}`);
291 if (fields.length * limit > MAX_FIELDS_PER_PAGE) {
292 throw new Error(
293 `fields.length * limit must be <= ${MAX_FIELDS_PER_PAGE} (got ${fields.length * limit})`,
294 );
295 }
296 if (paginationMode === 'PAGE_NUMBER' && page * limit > MAX_PAGE_NUMBER_NOTICES) {
297 throw new Error(
298 `PAGE_NUMBER cannot reach notice ${page * limit}; the ceiling is ` +
299 `${MAX_PAGE_NUMBER_NOTICES}. Use ITERATION instead.`,
300 );
301 }
302
303
304 if (paginationMode !== 'PAGE_NUMBER' && page !== 1) {
305 throw new Error(
306 `page=${page} has no effect in ${paginationMode} mode; it walks with ` +
307 'iterationNextToken. Pass paginationMode: "PAGE_NUMBER" to use page numbers.',
308 );
309 }
310
311 const request = { query, fields, limit, scope, paginationMode, onlyLatestVersions };
312 if (paginationMode === 'PAGE_NUMBER') {
313 request.page = page;
314 } else if (iterationNextToken) {
315
316 request.iterationNextToken = iterationNextToken;
317 }
318 const body = JSON.stringify(request);
319
320 let lastError;
321 for (let attempt = 1; attempt <= maxAttempts; attempt++) {
322 try {
323 const res = await fetchImpl(SEARCH_URL, {
324 method: 'POST',
325 headers: { 'content-type': 'application/json', accept: 'application/json' },
326 body,
327 });
328
329 if (res.status === 429 || res.status >= 500) {
330 throw new Error(`TED responded ${res.status}`);
331 }
332 if (!res.ok) {
333
334 const detail = await res.text().catch(() => '');
335
336
337 if (/iteration.?token/i.test(detail)) {
338 throw Object.assign(
339 new IterationTokenError(`TED rejected the iteration token: ${detail.slice(0, 200)}`),
340 { fatal: true },
341 );
342 }
343 throw Object.assign(
344 new Error(`TED rejected the query (${res.status}): ${detail.slice(0, 400)}`),
345 { fatal: true },
346 );
347 }
348 return await res.json();
349 } catch (err) {
350 if (err.fatal || attempt === maxAttempts) throw err;
351 lastError = err;
352 const waitMs = 800 * 2 ** (attempt - 1);
353 log.warning?.(`TED request failed (${err.message}). Retrying in ${waitMs}ms.`);
354 await new Promise((resolve) => setTimeout(resolve, waitMs));
355 }
356 }
357 throw lastError;
358}