odds-api-io 1.3.0 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +324 -249
  2. package/dist/cjs/client.d.ts +278 -0
  3. package/dist/cjs/client.js +536 -292
  4. package/dist/cjs/client.js.map +1 -1
  5. package/dist/cjs/errors.d.ts +63 -0
  6. package/dist/cjs/errors.js +54 -36
  7. package/dist/cjs/errors.js.map +1 -1
  8. package/dist/cjs/helpers.d.ts +5 -0
  9. package/dist/cjs/helpers.js +13 -0
  10. package/dist/cjs/helpers.js.map +1 -0
  11. package/dist/cjs/index.d.ts +15 -0
  12. package/dist/cjs/index.js +15 -3
  13. package/dist/cjs/index.js.map +1 -1
  14. package/dist/cjs/package.json +1 -0
  15. package/dist/cjs/types.d.ts +770 -0
  16. package/dist/cjs/types.js +4 -1
  17. package/dist/cjs/types.js.map +1 -1
  18. package/dist/cjs/version.d.ts +1 -0
  19. package/dist/cjs/version.js +5 -0
  20. package/dist/cjs/version.js.map +1 -0
  21. package/dist/cjs/websocket.d.ts +210 -0
  22. package/dist/cjs/websocket.js +405 -0
  23. package/dist/cjs/websocket.js.map +1 -0
  24. package/dist/esm/client.d.ts +278 -0
  25. package/dist/esm/client.js +537 -293
  26. package/dist/esm/client.js.map +1 -1
  27. package/dist/esm/errors.d.ts +63 -0
  28. package/dist/esm/errors.js +49 -34
  29. package/dist/esm/errors.js.map +1 -1
  30. package/dist/esm/helpers.d.ts +5 -0
  31. package/dist/esm/helpers.js +9 -0
  32. package/dist/esm/helpers.js.map +1 -0
  33. package/dist/esm/index.d.ts +15 -0
  34. package/dist/esm/index.js +5 -2
  35. package/dist/esm/index.js.map +1 -1
  36. package/dist/esm/package.json +1 -0
  37. package/dist/esm/types.d.ts +770 -0
  38. package/dist/esm/types.js +4 -1
  39. package/dist/esm/types.js.map +1 -1
  40. package/dist/esm/version.d.ts +1 -0
  41. package/dist/esm/version.js +2 -0
  42. package/dist/esm/version.js.map +1 -0
  43. package/dist/esm/websocket.d.ts +210 -0
  44. package/dist/esm/websocket.js +367 -0
  45. package/dist/esm/websocket.js.map +1 -0
  46. package/dist/types/client.d.ts +155 -195
  47. package/dist/types/client.d.ts.map +1 -1
  48. package/dist/types/errors.d.ts +48 -24
  49. package/dist/types/errors.d.ts.map +1 -1
  50. package/dist/types/helpers.d.ts +6 -0
  51. package/dist/types/helpers.d.ts.map +1 -0
  52. package/dist/types/index.d.ts +8 -3
  53. package/dist/types/index.d.ts.map +1 -1
  54. package/dist/types/types.d.ts +659 -187
  55. package/dist/types/types.d.ts.map +1 -1
  56. package/dist/types/version.d.ts +2 -0
  57. package/dist/types/version.d.ts.map +1 -0
  58. package/dist/types/websocket.d.ts +211 -0
  59. package/dist/types/websocket.d.ts.map +1 -0
  60. package/package.json +46 -16
@@ -1,475 +1,719 @@
1
- import { OddsAPIError, InvalidAPIKeyError, RateLimitExceededError, NotFoundError, TimeoutError, NetworkError, } from './errors.js';
2
- const DEFAULT_BASE_URL = 'https://api2.odds-api.io/v3';
1
+ import { OddsAPIError, BadRequestError, InvalidAPIKeyError, ForbiddenError, NotFoundError, RateLimitError, ServerError, TimeoutError, NetworkError, } from './errors.js';
2
+ import { VERSION } from './version.js';
3
+ const DEFAULT_BASE_URL = 'https://api.odds-api.io/v3';
3
4
  const DEFAULT_TIMEOUT = 10000;
5
+ const DEFAULT_MAX_RETRIES = 2;
6
+ const DEFAULT_MAX_RETRY_DELAY = 10000;
7
+ const HISTORICAL_SPAN_MS = 31 * 24 * 60 * 60 * 1000;
8
+ const SETTLEMENT_BATCH = 50;
9
+ function joinList(value) {
10
+ if (value === undefined || value === null)
11
+ return undefined;
12
+ return typeof value === 'string' ? value : value.join(',');
13
+ }
14
+ function splitList(value) {
15
+ const parts = typeof value === 'string' ? value.split(',') : value.map(String);
16
+ return parts.map((p) => p.trim()).filter(Boolean);
17
+ }
18
+ function numberHeader(headers, name) {
19
+ const raw = headers.get(name);
20
+ if (raw === null || raw.trim() === '')
21
+ return null;
22
+ const n = Number(raw);
23
+ return Number.isFinite(n) ? n : null;
24
+ }
25
+ function parseRateLimit(headers) {
26
+ const limit = numberHeader(headers, 'x-ratelimit-limit');
27
+ const remaining = numberHeader(headers, 'x-ratelimit-remaining');
28
+ const resetRaw = headers.get('x-ratelimit-reset');
29
+ if (limit === null && remaining === null && !resetRaw)
30
+ return undefined;
31
+ const reset = resetRaw ? new Date(resetRaw) : null;
32
+ return { limit, remaining, reset: reset && !isNaN(reset.getTime()) ? reset : null };
33
+ }
34
+ function retryAfterSeconds(headers, rateLimit) {
35
+ const header = headers.get('retry-after');
36
+ if (header) {
37
+ const secs = Number(header);
38
+ if (Number.isFinite(secs))
39
+ return Math.max(0, secs);
40
+ const date = Date.parse(header);
41
+ if (!isNaN(date))
42
+ return Math.max(0, Math.ceil((date - Date.now()) / 1000));
43
+ }
44
+ if (rateLimit?.remaining === 0 && rateLimit.reset) {
45
+ return Math.max(0, Math.ceil((rateLimit.reset.getTime() - Date.now()) / 1000));
46
+ }
47
+ return undefined;
48
+ }
49
+ function sleep(ms, signal) {
50
+ return new Promise((resolve) => {
51
+ if (signal?.aborted)
52
+ return resolve();
53
+ const timer = setTimeout(done, ms);
54
+ function done() {
55
+ clearTimeout(timer);
56
+ signal?.removeEventListener('abort', done);
57
+ resolve();
58
+ }
59
+ signal?.addEventListener('abort', done, { once: true });
60
+ });
61
+ }
4
62
  /**
5
- * Official Node.js client for Odds-API.io
63
+ * Official Node.js client for Odds-API.io.
6
64
  *
7
65
  * @example
8
66
  * ```typescript
9
67
  * import { OddsAPIClient } from 'odds-api-io';
10
68
  *
11
- * const client = new OddsAPIClient({ apiKey: 'your-api-key' });
69
+ * const client = new OddsAPIClient({ apiKey: process.env.ODDS_API_KEY! });
12
70
  * const sports = await client.getSports();
13
71
  * ```
14
72
  */
15
73
  export class OddsAPIClient {
16
74
  constructor(config) {
17
75
  this.apiKey = config.apiKey;
18
- this.baseUrl = config.baseUrl || DEFAULT_BASE_URL;
19
- this.timeout = config.timeout || DEFAULT_TIMEOUT;
76
+ this.baseUrl = (config.baseUrl || DEFAULT_BASE_URL).replace(/\/+$/, '');
77
+ this.timeout = config.timeout ?? DEFAULT_TIMEOUT;
78
+ this.maxRetries = Math.max(0, config.maxRetries ?? DEFAULT_MAX_RETRIES);
79
+ this.maxRetryDelay = config.maxRetryDelay ?? DEFAULT_MAX_RETRY_DELAY;
80
+ this.fetchImpl = config.fetch;
20
81
  }
21
- /**
22
- * Make a GET request to the API
23
- */
24
- async request(path, params = {}, requiresAuth = false) {
82
+ buildUrl(path, query = {}, auth = true) {
25
83
  const url = new URL(`${this.baseUrl}/${path}`);
26
- // Add query parameters
27
- if (requiresAuth) {
28
- params.apiKey = this.apiKey;
84
+ for (const [key, value] of Object.entries(query)) {
85
+ if (value === undefined || value === null)
86
+ continue;
87
+ const str = Array.isArray(value) ? value.join(',') : String(value);
88
+ url.searchParams.set(key, str);
29
89
  }
30
- Object.entries(params).forEach(([key, value]) => {
31
- if (value !== undefined && value !== null) {
32
- url.searchParams.append(key, String(value));
33
- }
34
- });
35
- const controller = new AbortController();
36
- const timeoutId = setTimeout(() => controller.abort(), this.timeout);
37
- try {
38
- const response = await fetch(url.toString(), {
39
- method: 'GET',
40
- signal: controller.signal,
41
- headers: {
42
- 'User-Agent': 'odds-api-io-node-sdk/1.0.0',
43
- },
44
- });
45
- clearTimeout(timeoutId);
46
- if (!response.ok) {
47
- await this.handleErrorResponse(response);
90
+ if (auth)
91
+ url.searchParams.set('apiKey', this.apiKey);
92
+ return url;
93
+ }
94
+ async send(path, options = {}) {
95
+ const method = options.method ?? 'GET';
96
+ const url = this.buildUrl(path, options.query, options.auth ?? true);
97
+ const retries = method === 'PUT' ? 0 : this.maxRetries;
98
+ const doFetch = this.fetchImpl ?? globalThis.fetch;
99
+ for (let attempt = 0;; attempt++) {
100
+ const controller = new AbortController();
101
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
102
+ let response;
103
+ try {
104
+ const headers = { 'User-Agent': `odds-api-io-node/${VERSION}` };
105
+ let body;
106
+ if (options.body !== undefined) {
107
+ headers['Content-Type'] = 'application/json';
108
+ body = JSON.stringify(options.body);
109
+ }
110
+ response = await doFetch(url.toString(), { method, headers, body, signal: controller.signal });
48
111
  }
49
- return (await response.json());
50
- }
51
- catch (error) {
52
- clearTimeout(timeoutId);
53
- if (error.name === 'AbortError') {
54
- throw new TimeoutError(`Request timeout after ${this.timeout}ms`);
112
+ catch (error) {
113
+ clearTimeout(timeoutId);
114
+ const err = error?.name === 'AbortError'
115
+ ? new TimeoutError(`Request timeout after ${this.timeout}ms`)
116
+ : new NetworkError(`Network request failed: ${error?.message ?? error}`);
117
+ if (attempt < retries) {
118
+ await sleep(this.backoff(attempt));
119
+ continue;
120
+ }
121
+ throw err;
55
122
  }
56
- if (error instanceof OddsAPIError) {
123
+ try {
124
+ const rateLimit = parseRateLimit(response.headers);
125
+ if (rateLimit)
126
+ this.lastRateLimit = rateLimit;
127
+ if (response.ok) {
128
+ const data = options.raw ? await response.arrayBuffer() : await response.json();
129
+ return { data: data, headers: response.headers };
130
+ }
131
+ const error = await this.toError(response, rateLimit);
132
+ const wait = this.retryDelay(error, attempt);
133
+ if (attempt < retries && wait !== null) {
134
+ await sleep(wait);
135
+ continue;
136
+ }
57
137
  throw error;
58
138
  }
59
- throw new NetworkError(`Network request failed: ${error.message}`);
60
- }
61
- }
62
- /**
63
- * Make a PUT request to the API
64
- */
65
- async requestPut(path, params = {}, requiresAuth = false) {
66
- const url = new URL(`${this.baseUrl}/${path}`);
67
- // Add query parameters
68
- if (requiresAuth) {
69
- params.apiKey = this.apiKey;
70
- }
71
- Object.entries(params).forEach(([key, value]) => {
72
- if (value !== undefined && value !== null) {
73
- url.searchParams.append(key, String(value));
139
+ catch (error) {
140
+ if (error instanceof OddsAPIError)
141
+ throw error;
142
+ if (error?.name === 'AbortError')
143
+ throw new TimeoutError(`Request timeout after ${this.timeout}ms`);
144
+ throw new NetworkError(`Failed to read response: ${error?.message ?? error}`);
74
145
  }
75
- });
76
- const controller = new AbortController();
77
- const timeoutId = setTimeout(() => controller.abort(), this.timeout);
78
- try {
79
- const response = await fetch(url.toString(), {
80
- method: 'PUT',
81
- signal: controller.signal,
82
- headers: {
83
- 'User-Agent': 'odds-api-io-node-sdk/1.0.0',
84
- },
85
- });
86
- clearTimeout(timeoutId);
87
- if (!response.ok) {
88
- await this.handleErrorResponse(response);
146
+ finally {
147
+ clearTimeout(timeoutId);
89
148
  }
90
- return (await response.json());
91
149
  }
92
- catch (error) {
93
- clearTimeout(timeoutId);
94
- if (error.name === 'AbortError') {
95
- throw new TimeoutError(`Request timeout after ${this.timeout}ms`);
96
- }
97
- if (error instanceof OddsAPIError) {
98
- throw error;
99
- }
100
- throw new NetworkError(`Network request failed: ${error.message}`);
150
+ }
151
+ backoff(attempt) {
152
+ const base = Math.min(this.maxRetryDelay, 500 * 2 ** attempt);
153
+ return Math.round(base * (0.75 + Math.random() * 0.25));
154
+ }
155
+ retryDelay(error, attempt) {
156
+ if (error instanceof RateLimitError) {
157
+ if (error.retryAfter === undefined)
158
+ return null;
159
+ const ms = error.retryAfter * 1000;
160
+ return ms <= this.maxRetryDelay ? ms : null;
161
+ }
162
+ if (error instanceof ServerError && [500, 502, 503, 504].includes(error.status ?? 0)) {
163
+ return error.retryAfter !== undefined
164
+ ? Math.min(error.retryAfter * 1000, this.maxRetryDelay)
165
+ : this.backoff(attempt);
101
166
  }
167
+ return null;
102
168
  }
103
- /**
104
- * Handle error responses from the API
105
- */
106
- async handleErrorResponse(response) {
169
+ async toError(response, rateLimit) {
107
170
  const status = response.status;
108
- let errorMessage;
171
+ let body = '';
109
172
  try {
110
- const errorBody = await response.text();
111
- errorMessage = errorBody || response.statusText;
173
+ body = await response.text();
112
174
  }
113
175
  catch {
114
- errorMessage = response.statusText;
176
+ body = '';
177
+ }
178
+ let message = body.trim() || response.statusText || `HTTP ${status}`;
179
+ try {
180
+ const parsed = JSON.parse(body);
181
+ if (parsed && typeof parsed.error === 'string')
182
+ message = parsed.error;
183
+ else if (parsed && typeof parsed.message === 'string')
184
+ message = parsed.message;
115
185
  }
186
+ catch {
187
+ // not JSON: keep the raw text
188
+ }
189
+ const details = { status, body, rateLimit };
116
190
  switch (status) {
191
+ case 400:
192
+ return new BadRequestError(message, details);
117
193
  case 401:
118
- throw new InvalidAPIKeyError('Invalid API key');
119
- case 429:
120
- throw new RateLimitExceededError('Rate limit exceeded - please wait before retrying');
194
+ return new InvalidAPIKeyError(message, details);
195
+ case 403:
196
+ return new ForbiddenError(message, details);
121
197
  case 404:
122
- throw new NotFoundError('Resource not found');
198
+ return new NotFoundError(message, details);
199
+ case 429:
200
+ return new RateLimitError(message, {
201
+ ...details,
202
+ retryAfter: retryAfterSeconds(response.headers, rateLimit),
203
+ });
123
204
  default:
124
- throw new OddsAPIError(`API error ${status}: ${errorMessage}`);
205
+ if (status >= 500) {
206
+ return new ServerError(message, { ...details, retryAfter: retryAfterSeconds(response.headers) });
207
+ }
208
+ return new OddsAPIError(message, details);
125
209
  }
126
210
  }
211
+ async get(path, query, auth = true) {
212
+ return (await this.send(path, { query, auth })).data;
213
+ }
127
214
  // ============================================================================
128
- // SPORTS & LEAGUES
215
+ // SPORTS, LEAGUES, MARKETS
129
216
  // ============================================================================
130
- /**
131
- * Get all available sports
132
- *
133
- * @returns List of available sports
134
- *
135
- * @example
136
- * ```typescript
137
- * const sports = await client.getSports();
138
- * console.log(`Found ${sports.length} sports`);
139
- * ```
140
- */
217
+ /** All sports. No API key needed. */
141
218
  async getSports() {
142
- return this.request('sports');
219
+ return this.get('sports', undefined, false);
143
220
  }
144
221
  /**
145
- * Get leagues for a specific sport
146
- *
147
- * @param sport - Sport identifier (e.g., 'basketball', 'football')
148
- * @returns List of leagues
222
+ * Leagues for a sport.
149
223
  *
150
224
  * @example
151
225
  * ```typescript
152
- * const leagues = await client.getLeagues('basketball');
226
+ * const leagues = await client.getLeagues('football');
153
227
  * ```
154
228
  */
155
- async getLeagues(sport) {
156
- return this.request('leagues', { sport }, true);
229
+ async getLeagues(sport, options = {}) {
230
+ return this.get('leagues', { sport, all: options.all });
231
+ }
232
+ async getMarkets(sport) {
233
+ return this.get('markets', { sport }, false);
157
234
  }
158
235
  // ============================================================================
159
236
  // EVENTS
160
237
  // ============================================================================
161
238
  /**
162
- * Get events with optional filters
163
- *
164
- * @param params - Event filter parameters
165
- * @returns List of events
239
+ * Events for a sport. Without `to` the window is the next 14 days; each
240
+ * response is capped at 5000 events (see `iterateEvents`).
166
241
  *
167
242
  * @example
168
243
  * ```typescript
169
- * const events = await client.getEvents({
170
- * sport: 'basketball',
171
- * league: 'usa-nba'
172
- * });
244
+ * const events = await client.getEvents({ sport: 'football', league: 'england-premier-league', status: 'pending,live' });
173
245
  * ```
174
246
  */
175
247
  async getEvents(params) {
176
- return this.request('events', params, true);
248
+ return this.get('events', { ...params, status: joinList(params.status) });
177
249
  }
178
250
  /**
179
- * Get a specific event by ID
180
- *
181
- * @param eventId - Event ID
182
- * @returns Event details
251
+ * Every event matching the filters, paging with limit and skip.
183
252
  *
184
253
  * @example
185
254
  * ```typescript
186
- * const event = await client.getEventById('62924717');
255
+ * for await (const event of client.iterateEvents({ sport: 'football', to: '2027-01-01T00:00:00Z' })) {
256
+ * console.log(event.home, event.away);
257
+ * }
187
258
  * ```
188
259
  */
260
+ async *iterateEvents(params, options = {}) {
261
+ const pageSize = options.pageSize ?? params.limit ?? 1000;
262
+ let skip = params.skip ?? 0;
263
+ for (let page = 0; options.maxPages === undefined || page < options.maxPages; page++) {
264
+ const events = await this.getEvents({ ...params, limit: pageSize, skip });
265
+ yield* events;
266
+ if (events.length < pageSize)
267
+ return;
268
+ skip += events.length;
269
+ }
270
+ }
271
+ /** One event by id. */
189
272
  async getEventById(eventId) {
190
- return this.request(`events/${eventId}`, {}, true);
273
+ return this.get(`events/${encodeURIComponent(String(eventId))}`);
191
274
  }
192
- /**
193
- * Get currently live events for a sport
194
- *
195
- * @param sport - Sport identifier
196
- * @returns List of live events
197
- *
198
- * @example
199
- * ```typescript
200
- * const liveEvents = await client.getLiveEvents('basketball');
201
- * ```
202
- */
275
+ /** Live events, optionally for one sport. Live events carry `clock`. */
203
276
  async getLiveEvents(sport) {
204
- return this.request('events/live', { sport }, true);
277
+ return this.get('events/live', { sport });
205
278
  }
206
279
  /**
207
- * Search for events by keyword
208
- *
209
- * @param query - Search query
210
- * @returns List of matching events
280
+ * Search events by team or league name (min 3 characters, up to 10 results).
211
281
  *
212
282
  * @example
213
283
  * ```typescript
214
- * const events = await client.searchEvents('Lakers');
284
+ * const live = await client.searchEvents('Liverpool', { status: 'live' });
215
285
  * ```
216
286
  */
217
- async searchEvents(query) {
218
- return this.request('events/search', { query }, true);
287
+ async searchEvents(query, options = {}) {
288
+ return this.get('events/search', { query, status: options.status });
219
289
  }
220
290
  // ============================================================================
221
291
  // HISTORICAL
222
292
  // ============================================================================
223
293
  /**
224
- * Get finished historical events within a date range
225
- *
226
- * @param params - Historical event filter parameters
227
- * @returns List of historical events
294
+ * Finished events for one league. The span from `from` to `to` is at most 31
295
+ * days; use `iterateHistoricalEvents` for longer ranges.
296
+ */
297
+ async getHistoricalEvents(params) {
298
+ return this.get('historical/events', { ...params });
299
+ }
300
+ /** Finished events for one league over any range, fetched in 31-day windows. */
301
+ async *iterateHistoricalEvents(params) {
302
+ const start = Date.parse(params.from);
303
+ const end = Date.parse(params.to);
304
+ if (isNaN(start) || isNaN(end))
305
+ throw new BadRequestError('from and to must be RFC 3339 dates');
306
+ const seen = new Set();
307
+ for (let windowStart = start; windowStart < end; windowStart += HISTORICAL_SPAN_MS) {
308
+ const windowEnd = Math.min(windowStart + HISTORICAL_SPAN_MS, end);
309
+ const events = await this.getHistoricalEvents({
310
+ ...params,
311
+ from: new Date(windowStart).toISOString().replace(/\.\d{3}Z$/, 'Z'),
312
+ to: new Date(windowEnd).toISOString().replace(/\.\d{3}Z$/, 'Z'),
313
+ });
314
+ for (const event of events) {
315
+ if (seen.has(event.id))
316
+ continue;
317
+ seen.add(event.id);
318
+ yield event;
319
+ }
320
+ }
321
+ }
322
+ /** Search finished events by team name, across leagues (31-day span, default the last 31 days). */
323
+ async searchHistoricalEvents(params) {
324
+ return this.get('historical/events/search', { ...params });
325
+ }
326
+ /**
327
+ * Odds for a finished event, in the `/odds` shape.
228
328
  *
229
329
  * @example
230
330
  * ```typescript
231
- * const events = await client.getHistoricalEvents({
232
- * sport: 'football',
233
- * league: 'england-premier-league',
234
- * from: '2026-01-01T00:00:00Z',
235
- * to: '2026-01-31T23:59:59Z'
236
- * });
331
+ * const odds = await client.getHistoricalOdds({ eventId: 67697888, bookmakers: ['Bet365', 'SingBet'], markets: ['ML'] });
237
332
  * ```
238
333
  */
239
- async getHistoricalEvents(params) {
240
- return this.request('historical/events', params, true);
334
+ async getHistoricalOdds(params) {
335
+ return this.get('historical/odds', {
336
+ ...params,
337
+ bookmakers: joinList(params.bookmakers),
338
+ markets: joinList(params.markets),
339
+ });
241
340
  }
242
341
  /**
243
- * Get closing odds for a historical event
244
- *
245
- * @param params - Historical odds query parameters
246
- * @returns Historical event odds data
342
+ * Closing odds for every settled event across up to 10 leagues (paid plans).
343
+ * Up to 366 days per call, 100 events per page (see `iterateClosingLines`).
247
344
  *
248
345
  * @example
249
346
  * ```typescript
250
- * const odds = await client.getHistoricalOdds({
251
- * eventId: '67697888',
252
- * bookmakers: 'singbet,bet365'
347
+ * const lines = await client.getClosingLines({
348
+ * sport: 'football',
349
+ * leagues: ['england-premier-league'],
350
+ * from: '2026-08-01T00:00:00Z',
351
+ * to: '2026-10-31T23:59:59Z',
352
+ * markets: ['ML', 'Totals'],
353
+ * bookmakers: ['Bet365'],
253
354
  * });
254
355
  * ```
255
356
  */
256
- async getHistoricalOdds(params) {
257
- return this.request('historical/odds', params, true);
357
+ async getClosingLines(params) {
358
+ return this.get('historical/closing-lines', {
359
+ ...params,
360
+ leagues: joinList(params.leagues),
361
+ markets: joinList(params.markets),
362
+ bookmakers: joinList(params.bookmakers),
363
+ });
364
+ }
365
+ /** Every closing line matching the filters, paging with limit and skip. */
366
+ async *iterateClosingLines(params, options = {}) {
367
+ const pageSize = Math.min(options.pageSize ?? params.limit ?? 100, 100);
368
+ let skip = params.skip ?? 0;
369
+ for (let page = 0; options.maxPages === undefined || page < options.maxPages; page++) {
370
+ const events = await this.getClosingLines({ ...params, limit: pageSize, skip });
371
+ yield* events;
372
+ if (events.length < pageSize)
373
+ return;
374
+ skip += events.length;
375
+ }
258
376
  }
259
377
  // ============================================================================
260
378
  // ODDS
261
379
  // ============================================================================
262
380
  /**
263
- * Get odds for a specific event
264
- *
265
- * @param params - Odds query parameters
266
- * @returns Event odds data
381
+ * Odds for one event. Pass `markets` to keep the response small.
267
382
  *
268
383
  * @example
269
384
  * ```typescript
270
- * const odds = await client.getEventOdds({
271
- * eventId: '62924717',
272
- * bookmakers: 'singbet,bet365'
273
- * });
385
+ * const odds = await client.getEventOdds({ eventId: 62924717, bookmakers: ['Bet365', 'SingBet'], markets: ['ML', 'Totals'] });
386
+ * const ml = odds.bookmakers['Bet365']?.find((m) => m.name === 'ML');
274
387
  * ```
275
388
  */
276
389
  async getEventOdds(params) {
277
- return this.request('odds', params, true);
390
+ return this.get('odds', {
391
+ ...params,
392
+ bookmakers: joinList(params.bookmakers),
393
+ markets: joinList(params.markets),
394
+ });
395
+ }
396
+ /** Odds for up to 10 events in one request. */
397
+ async getOddsForMultipleEvents(params) {
398
+ return this.get('odds/multi', this.multiOddsQuery(params));
278
399
  }
279
400
  /**
280
- * Track odds movements for an event
281
- *
282
- * @param params - Odds movement parameters
283
- * @returns Historical odds movements
401
+ * Odds for up to 10 events plus the WebSocket sequence at that moment.
402
+ * Rebuild state from `data`, then connect or reconnect with `lastSeq: seq`.
403
+ */
404
+ async getOddsSnapshot(params) {
405
+ const { data, headers } = await this.send('odds/multi', {
406
+ query: this.multiOddsQuery({ ...params, includeSeq: true }),
407
+ });
408
+ return { data, seq: numberHeader(headers, 'x-oddsapi-seq') };
409
+ }
410
+ multiOddsQuery(params) {
411
+ return {
412
+ ...params,
413
+ eventIds: joinList(params.eventIds),
414
+ bookmakers: joinList(params.bookmakers),
415
+ markets: joinList(params.markets),
416
+ };
417
+ }
418
+ /**
419
+ * Price history for one market at one bookmaker (prematch only).
284
420
  *
285
421
  * @example
286
422
  * ```typescript
287
- * const movements = await client.getOddsMovement({
288
- * eventId: '62924717',
289
- * bookmaker: 'singbet',
290
- * market: 'moneyline'
291
- * });
423
+ * const history = await client.getOddsMovement({ eventId: 62924717, bookmaker: 'Bet365', market: 'ML' });
292
424
  * ```
293
425
  */
294
426
  async getOddsMovement(params) {
295
- return this.request('odds/movements', params, true);
427
+ return this.get('odds/movements', { ...params });
296
428
  }
297
429
  /**
298
- * Get odds for multiple events at once
299
- *
300
- * @param params - Multi-event odds parameters
301
- * @returns Array of event odds
302
- *
303
- * @example
304
- * ```typescript
305
- * const odds = await client.getOddsForMultipleEvents({
306
- * eventIds: '12345,67890',
307
- * bookmakers: 'singbet,bet365'
308
- * });
309
- * ```
430
+ * Market groups changed since `since` for one bookmaker and sport. The result
431
+ * is a delta: merge it into what you hold, keyed by event and market.
432
+ * See `pollUpdatedOdds` for a loop that follows X-Next-Since.
310
433
  */
311
- async getOddsForMultipleEvents(params) {
312
- return this.request('odds/multi', params, true);
434
+ async getUpdatedOddsSince(params) {
435
+ return (await this.getUpdatedOddsSinceWithMeta(params)).data;
436
+ }
437
+ /** Like `getUpdatedOddsSince`, plus the X-Next-Since, X-Server-Time and X-Unknown-Markets headers. */
438
+ async getUpdatedOddsSinceWithMeta(params) {
439
+ const { data, headers } = await this.send('odds/updated', {
440
+ query: { ...params, markets: joinList(params.markets) },
441
+ });
442
+ const unknown = headers.get('x-unknown-markets');
443
+ return {
444
+ data,
445
+ nextSince: numberHeader(headers, 'x-next-since'),
446
+ serverTime: numberHeader(headers, 'x-server-time'),
447
+ unknownMarkets: unknown ? splitList(unknown) : [],
448
+ };
313
449
  }
314
450
  /**
315
- * Get odds updated since a given timestamp
316
- *
317
- * @param params - Updated odds parameters
318
- * @returns Array of updated event odds
451
+ * Polls `/odds/updated`, passing each X-Next-Since as the next `since`.
452
+ * A page cut short by `limit` is followed up at once.
319
453
  *
320
454
  * @example
321
455
  * ```typescript
322
- * const updatedOdds = await client.getUpdatedOddsSince({
323
- * since: Math.floor(Date.now() / 1000) - 20, // seconds, at most 90 old
324
- * bookmaker: 'Bet365',
325
- * sport: 'football',
326
- * markets: 'ML,Spread,Totals', // required from 15 October 2026
327
- * });
456
+ * const controller = new AbortController();
457
+ * for await (const batch of client.pollUpdatedOdds({ bookmaker: 'Bet365', sport: 'football', markets: ['ML'], signal: controller.signal })) {
458
+ * for (const event of batch.data) merge(event);
459
+ * }
328
460
  * ```
329
461
  */
330
- async getUpdatedOddsSince(params) {
331
- return this.request('odds/updated', params, true);
462
+ async *pollUpdatedOdds(params) {
463
+ const { intervalMs = 10000, signal, since: firstSince, ...query } = params;
464
+ let since = firstSince ?? Math.floor(Date.now() / 1000) - 20;
465
+ while (!signal?.aborted) {
466
+ const result = await this.getUpdatedOddsSinceWithMeta({ ...query, since });
467
+ yield result;
468
+ since = result.nextSince ?? (result.serverTime ?? Math.floor(Date.now() / 1000)) - 10;
469
+ const truncated = query.limit !== undefined && result.data.length >= query.limit;
470
+ if (!truncated)
471
+ await sleep(intervalMs, signal);
472
+ }
473
+ }
474
+ /**
475
+ * Best, average, median, worst and fair price per market line across
476
+ * bookmakers (Growth plans and above; lower plans get `demo: true`).
477
+ */
478
+ async getOddsSummary(params) {
479
+ return this.get('odds/summary', this.summaryQuery(params));
480
+ }
481
+ /** `getOddsSummary` for up to 10 events in one request. */
482
+ async getOddsSummaryMulti(params) {
483
+ return this.get('odds/summary/multi', {
484
+ ...this.summaryQuery(params),
485
+ eventIds: joinList(params.eventIds),
486
+ });
487
+ }
488
+ summaryQuery(params) {
489
+ return {
490
+ ...params,
491
+ markets: joinList(params.markets),
492
+ bookmakers: joinList(params.bookmakers),
493
+ };
332
494
  }
333
495
  // ============================================================================
334
496
  // PARTICIPANTS
335
497
  // ============================================================================
336
- /**
337
- * Get participants (teams/players) for a sport
338
- *
339
- * @param params - Participant query parameters
340
- * @returns List of participants
341
- *
342
- * @example
343
- * ```typescript
344
- * const participants = await client.getParticipants({
345
- * sport: 'basketball',
346
- * search: 'Warriors'
347
- * });
348
- * ```
349
- */
498
+ /** Teams and players for a sport. */
350
499
  async getParticipants(params) {
351
- return this.request('participants', params, true);
500
+ return this.get('participants', { ...params });
501
+ }
502
+ /** One participant by id. */
503
+ async getParticipantById(participantId) {
504
+ return this.get(`participants/${encodeURIComponent(String(participantId))}`);
352
505
  }
353
506
  /**
354
- * Get a specific participant by ID
355
- *
356
- * @param participantId - Participant ID
357
- * @returns Participant details
358
- *
359
- * @example
360
- * ```typescript
361
- * const participant = await client.getParticipantById(3428);
362
- * ```
507
+ * URL of a participant's PNG logo (use `homeId`/`awayId` from events).
508
+ * The URL carries your API key, so only hand it to a browser you trust;
509
+ * otherwise proxy it with `getParticipantLogo`.
363
510
  */
364
- async getParticipantById(participantId) {
365
- return this.request(`participants/${participantId}`, {}, true);
511
+ getParticipantLogoUrl(participantId) {
512
+ return this.buildUrl(`participants/${encodeURIComponent(String(participantId))}/logo`).toString();
513
+ }
514
+ /** A participant's logo as PNG bytes. Throws NotFoundError when there is none. */
515
+ async getParticipantLogo(participantId) {
516
+ const { data } = await this.send(`participants/${encodeURIComponent(String(participantId))}/logo`, { raw: true });
517
+ return data;
366
518
  }
367
519
  // ============================================================================
368
520
  // BOOKMAKERS
369
521
  // ============================================================================
522
+ /** All bookmakers with their current status. No API key needed. */
523
+ async getBookmakers() {
524
+ return this.get('bookmakers', undefined, false);
525
+ }
526
+ /** The bookmakers selected on your key. */
527
+ async getSelectedBookmakers() {
528
+ return this.get('bookmakers/selected');
529
+ }
530
+ /** Add bookmakers to your selection. */
531
+ async selectBookmakers(bookmakers) {
532
+ const { data } = await this.send('bookmakers/selected/select', {
533
+ method: 'PUT',
534
+ query: { bookmakers: joinList(bookmakers) },
535
+ });
536
+ return data;
537
+ }
538
+ /** Clear your selection. Allowed once every 12 hours. */
539
+ async clearSelectedBookmakers() {
540
+ const { data } = await this.send('bookmakers/selected/clear', { method: 'PUT' });
541
+ return data;
542
+ }
543
+ // ============================================================================
544
+ // BETTING ANALYSIS
545
+ // ============================================================================
370
546
  /**
371
- * Get all available bookmakers
372
- *
373
- * @returns List of bookmakers
547
+ * Price gaps across your bookmakers where the best prices imply under 100%
548
+ * (prematch only, refreshed every few seconds). Prices move and limits
549
+ * apply, so check every leg before acting.
374
550
  *
375
551
  * @example
376
552
  * ```typescript
377
- * const bookmakers = await client.getBookmakers();
553
+ * const arbs = await client.getArbitrageBets({ bookmakers: ['Bet365', 'SingBet'], sport: 'football', minProfit: 1 });
378
554
  * ```
379
555
  */
380
- async getBookmakers() {
381
- return this.request('bookmakers');
556
+ async getArbitrageBets(params) {
557
+ return this.get('arbitrage-bets', {
558
+ ...params,
559
+ bookmakers: joinList(params.bookmakers),
560
+ markets: joinList(params.markets),
561
+ });
562
+ }
563
+ /** Prices above a fair-odds estimate at one bookmaker. */
564
+ async getValueBets(params) {
565
+ return this.get('value-bets', { ...params });
382
566
  }
383
567
  /**
384
- * Get your selected bookmakers
385
- *
386
- * @returns List of selected bookmakers
568
+ * Dropping odds from sharp bookmakers (paid plans).
387
569
  *
388
570
  * @example
389
571
  * ```typescript
390
- * const selected = await client.getSelectedBookmakers();
572
+ * const drops = await client.getDroppingOdds({ sport: 'football', markets: ['ML'], minDrop: 10 });
391
573
  * ```
392
574
  */
393
- async getSelectedBookmakers() {
394
- return this.request('bookmakers/selected', {}, true);
575
+ async getDroppingOdds(params = {}) {
576
+ return (await this.getDroppingOddsPage(params)).data;
577
+ }
578
+ /** Like `getDroppingOdds`, plus the pagination headers. */
579
+ async getDroppingOddsPage(params = {}) {
580
+ const { market, ...rest } = params;
581
+ const { data, headers } = await this.send('dropping-odds', {
582
+ query: {
583
+ ...rest,
584
+ leagues: joinList(rest.leagues),
585
+ markets: joinList(rest.markets) ?? market,
586
+ },
587
+ });
588
+ return {
589
+ data,
590
+ total: numberHeader(headers, 'x-total-count'),
591
+ page: numberHeader(headers, 'x-page'),
592
+ perPage: numberHeader(headers, 'x-per-page'),
593
+ updatedAt: numberHeader(headers, 'x-updated-at'),
594
+ };
595
+ }
596
+ /** Every dropping-odds entry matching the filters, page by page. */
597
+ async *iterateDroppingOdds(params = {}, options = {}) {
598
+ const limit = options.pageSize ?? params.limit ?? 200;
599
+ let page = params.page ?? 1;
600
+ let seen = 0;
601
+ for (let n = 0; options.maxPages === undefined || n < options.maxPages; n++, page++) {
602
+ const result = await this.getDroppingOddsPage({ ...params, limit, page });
603
+ yield* result.data;
604
+ seen += result.data.length;
605
+ if (result.data.length < limit)
606
+ return;
607
+ if (result.total !== null && seen >= result.total)
608
+ return;
609
+ }
395
610
  }
611
+ // ============================================================================
612
+ // SETTLEMENT
613
+ // ============================================================================
396
614
  /**
397
- * Select specific bookmakers for your account
398
- *
399
- * @param bookmakers - Comma-separated bookmaker IDs
400
- * @returns Success response
615
+ * Settlement records (status, final flag, final scores) for events (paid plans).
616
+ * More than 50 ids are split into several requests.
401
617
  *
402
618
  * @example
403
619
  * ```typescript
404
- * await client.selectBookmakers('singbet,bet365');
620
+ * const { settlements, notFound } = await client.getSettlements([74919888, 73101436]);
405
621
  * ```
406
622
  */
407
- async selectBookmakers(bookmakers) {
408
- return this.requestPut('bookmakers/selected/select', { bookmakers }, true);
623
+ async getSettlements(eventIds) {
624
+ const ids = splitList(eventIds);
625
+ const result = { settlements: [], notFound: [] };
626
+ for (let i = 0; i < ids.length || i === 0; i += SETTLEMENT_BATCH) {
627
+ const page = await this.get('settlements', {
628
+ eventIds: ids.slice(i, i + SETTLEMENT_BATCH).join(','),
629
+ });
630
+ result.settlements.push(...(page.settlements ?? []));
631
+ result.notFound.push(...(page.notFound ?? []));
632
+ }
633
+ return result;
409
634
  }
410
635
  /**
411
- * Clear your selected bookmakers
412
- *
413
- * @returns Success response
636
+ * Grade bet selections against final results (paid plans). Returns one grade
637
+ * per selection, in order. More than 50 selections are sent in batches.
638
+ * Re-send selections that are not `final`, at most once a minute.
414
639
  *
415
640
  * @example
416
641
  * ```typescript
417
- * await client.clearSelectedBookmakers();
642
+ * const { grades } = await client.gradeBets([
643
+ * { ref: 'bet-1', eventId: 74919888, market: 'Spread', hdp: -0.75, side: 'home' },
644
+ * ]);
418
645
  * ```
419
646
  */
420
- async clearSelectedBookmakers() {
421
- return this.requestPut('bookmakers/selected/clear', {}, true);
647
+ async gradeBets(selections) {
648
+ const grades = [];
649
+ for (let i = 0; i < selections.length || i === 0; i += SETTLEMENT_BATCH) {
650
+ const { data } = await this.send('settlements/grade', {
651
+ method: 'POST',
652
+ body: { selections: selections.slice(i, i + SETTLEMENT_BATCH) },
653
+ });
654
+ grades.push(...(data.grades ?? []));
655
+ }
656
+ return { grades };
657
+ }
658
+ /** Same as `gradeBets` (the API operation is called GradeSelections). */
659
+ async gradeSelections(selections) {
660
+ return this.gradeBets(selections);
422
661
  }
423
662
  // ============================================================================
424
- // BETTING ANALYSIS
663
+ // OUTRIGHTS (paid add-on; a key without it gets ForbiddenError)
425
664
  // ============================================================================
426
665
  /**
427
- * Find arbitrage betting opportunities
428
- *
429
- * @param params - Arbitrage bet parameters
430
- * @returns List of arbitrage opportunities
666
+ * Tournaments for a sport (golf today), sorted by date.
431
667
  *
432
668
  * @example
433
669
  * ```typescript
434
- * const arbs = await client.getArbitrageBets({
435
- * bookmakers: 'singbet,bet365',
436
- * limit: 10,
437
- * includeEventDetails: true
438
- * });
670
+ * const tournaments = await client.getOutrights({ sport: 'golf', league: 'pga-tour' });
439
671
  * ```
440
672
  */
441
- async getArbitrageBets(params) {
442
- return this.request('arbitrage-bets', params, true);
673
+ async getOutrights(params) {
674
+ return this.get('outrights', { ...params, status: joinList(params.status) });
443
675
  }
444
676
  /**
445
- * Find value betting opportunities
446
- *
447
- * @param params - Value bet parameters
448
- * @returns List of value bets
677
+ * Prices for one tournament: Winner, Top 5/10/20, the "(Incl. Ties)"
678
+ * variants and Make Cut, per bookmaker.
449
679
  *
450
680
  * @example
451
681
  * ```typescript
452
- * const valueBets = await client.getValueBets({
453
- * bookmaker: 'singbet',
454
- * includeEventDetails: true
455
- * });
682
+ * const odds = await client.getOutrightOdds({ id: 1001, bookmakers: ['DraftKings', 'Betfair Exchange'] });
456
683
  * ```
457
684
  */
458
- async getValueBets(params) {
459
- return this.request('value-bets', params, true);
685
+ async getOutrightOdds(params) {
686
+ return this.get('outrights/odds', { ...params, bookmakers: joinList(params.bookmakers) });
687
+ }
688
+ /** Final positions and winners per market for one tournament. */
689
+ async getOutrightResults(id) {
690
+ return this.get('outrights/results', { id });
460
691
  }
692
+ // ============================================================================
693
+ // MAPPINGS
694
+ // ============================================================================
461
695
  /**
462
- * Get dropping odds from sharp bookmakers.
463
- * @example
464
- * const drops = await client.getDroppingOdds({
465
- * sport: 'football',
466
- * market: 'ML',
467
- * minDrop: 10,
468
- * includeEventDetails: true
469
- * });
696
+ * A bookmaker's own event, market and outcome ids for our events (paid plans).
697
+ * Without eventId(s), marketId(s) or outcomeId it is a bulk sync with a cursor.
470
698
  */
471
- async getDroppingOdds(params = {}) {
472
- return this.request('dropping-odds', params, true);
699
+ async getMappings(params) {
700
+ return this.get('mappings', {
701
+ ...params,
702
+ eventIds: joinList(params.eventIds),
703
+ marketIds: joinList(params.marketIds),
704
+ });
705
+ }
706
+ /** Every mapping row, following `nextCursor` until it is null. */
707
+ async *iterateMappings(params, options = {}) {
708
+ let cursor = params.cursor;
709
+ const limit = options.pageSize ?? params.limit;
710
+ for (let n = 0; options.maxPages === undefined || n < options.maxPages; n++) {
711
+ const page = await this.getMappings({ ...params, limit, cursor });
712
+ yield* page.data;
713
+ if (!page.nextCursor)
714
+ return;
715
+ cursor = page.nextCursor;
716
+ }
473
717
  }
474
718
  }
475
719
  //# sourceMappingURL=client.js.map