@lovebowls/api 0.0.0-stage → 0.2.0

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.
package/dist/index.js ADDED
@@ -0,0 +1,539 @@
1
+ // src/errors.ts
2
+ var LovebowlsApiError = class _LovebowlsApiError extends Error {
3
+ status;
4
+ code;
5
+ title;
6
+ detail;
7
+ requestId;
8
+ /** Seconds to wait, from `Retry-After` (429 and 503); `null` when absent. */
9
+ retryAfter;
10
+ constructor(init) {
11
+ super(init.detail ? `${init.title}: ${init.detail}` : init.title);
12
+ this.name = "LovebowlsApiError";
13
+ this.status = init.status;
14
+ this.code = init.code;
15
+ this.title = init.title;
16
+ this.detail = init.detail ?? null;
17
+ this.requestId = init.requestId ?? null;
18
+ this.retryAfter = init.retryAfter ?? null;
19
+ if (init.cause !== void 0) this.cause = init.cause;
20
+ Object.setPrototypeOf(this, _LovebowlsApiError.prototype);
21
+ }
22
+ };
23
+
24
+ // src/auth.ts
25
+ var WIX_TOKEN_URL = "https://www.wixapis.com/oauth2/token";
26
+ var WIX_SESSION_URL = "https://www.wixapis.com/_api/redirects-api/v1/redirect-session";
27
+ var TOKENS_KEY = "lovebowls.auth.tokens";
28
+ var PKCE_KEY = "lovebowls.auth.pkce";
29
+ var SKEW_MS = 6e4;
30
+ function memoryStorage() {
31
+ const m = /* @__PURE__ */ new Map();
32
+ return {
33
+ getItem: (k) => m.get(k) ?? null,
34
+ setItem: (k, v) => void m.set(k, v),
35
+ removeItem: (k) => void m.delete(k)
36
+ };
37
+ }
38
+ function b64url(bytes) {
39
+ let s = "";
40
+ for (const b of bytes) s += String.fromCharCode(b);
41
+ return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
42
+ }
43
+ function randomString(bytes) {
44
+ return b64url(globalThis.crypto.getRandomValues(new Uint8Array(bytes)));
45
+ }
46
+ async function s256(verifier) {
47
+ const d = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
48
+ return b64url(new Uint8Array(d));
49
+ }
50
+ function authError(code, title, detail, status = 0) {
51
+ return new LovebowlsApiError({ status, code, title, detail });
52
+ }
53
+ var LovebowlsAuth = class {
54
+ #clientId;
55
+ #redirectUri;
56
+ #offline;
57
+ #postLogout;
58
+ #fetchOpt;
59
+ #locationOpt;
60
+ #historyOpt;
61
+ #storageOpt;
62
+ #listeners = /* @__PURE__ */ new Set();
63
+ #store;
64
+ #pkceStore;
65
+ #refreshing;
66
+ constructor(options) {
67
+ if (!options || !options.clientId) throw new TypeError("LovebowlsAuth: clientId is required");
68
+ if (!options.redirectUri) throw new TypeError("LovebowlsAuth: redirectUri is required");
69
+ this.#clientId = options.clientId;
70
+ this.#redirectUri = options.redirectUri;
71
+ this.#offline = options.offlineAccess === true;
72
+ this.#postLogout = options.postLogoutUrl ?? options.redirectUri;
73
+ this.#fetchOpt = options.fetch;
74
+ this.#locationOpt = options.location;
75
+ this.#historyOpt = options.history;
76
+ this.#storageOpt = options.storage ?? "session";
77
+ }
78
+ // ---- environment, resolved lazily so import never touches a browser global
79
+ #fetch(input, init) {
80
+ return this.#fetchOpt ? this.#fetchOpt(input, init) : globalThis.fetch(input, init);
81
+ }
82
+ #location() {
83
+ return this.#locationOpt ?? globalThis.location;
84
+ }
85
+ #tokenStore() {
86
+ if (this.#store) return this.#store;
87
+ const o = this.#storageOpt;
88
+ let s;
89
+ if (typeof o === "object") s = o;
90
+ else if (o !== "memory") {
91
+ try {
92
+ const g = globalThis;
93
+ s = o === "local" ? g.localStorage : g.sessionStorage;
94
+ } catch {
95
+ }
96
+ }
97
+ return this.#store = s ?? memoryStorage();
98
+ }
99
+ /** PKCE state must survive the trip to Wix and back, so it is in `sessionStorage` (or your own storage), never plain memory when a browser is there. */
100
+ #pkce() {
101
+ if (this.#pkceStore) return this.#pkceStore;
102
+ let s;
103
+ if (typeof this.#storageOpt === "object") s = this.#storageOpt;
104
+ else {
105
+ try {
106
+ s = globalThis.sessionStorage;
107
+ } catch {
108
+ }
109
+ }
110
+ return this.#pkceStore = s ?? memoryStorage();
111
+ }
112
+ // ---- token storage
113
+ #read() {
114
+ try {
115
+ const raw = this.#tokenStore().getItem(TOKENS_KEY);
116
+ if (!raw) return null;
117
+ const t = JSON.parse(raw);
118
+ if (typeof t.access !== "string" || !t.access || typeof t.expiresAt !== "number") return null;
119
+ return { access: t.access, refresh: typeof t.refresh === "string" && t.refresh ? t.refresh : void 0, expiresAt: t.expiresAt };
120
+ } catch {
121
+ return null;
122
+ }
123
+ }
124
+ #write(t) {
125
+ try {
126
+ this.#tokenStore().setItem(TOKENS_KEY, JSON.stringify(t));
127
+ } catch {
128
+ }
129
+ }
130
+ #erase() {
131
+ try {
132
+ this.#tokenStore().removeItem(TOKENS_KEY);
133
+ } catch {
134
+ }
135
+ try {
136
+ this.#pkce().removeItem(PKCE_KEY);
137
+ } catch {
138
+ }
139
+ }
140
+ #emit(loggedIn) {
141
+ for (const cb of [...this.#listeners]) {
142
+ try {
143
+ cb(loggedIn);
144
+ } catch {
145
+ }
146
+ }
147
+ }
148
+ /** Drop the stored tokens and PKCE state and tell listeners. The client calls it when a token proves invalid. */
149
+ clearSession() {
150
+ const had = this.#read() !== null;
151
+ this.#erase();
152
+ if (had) this.#emit(false);
153
+ }
154
+ async #post(url, body, authorization) {
155
+ let res;
156
+ try {
157
+ res = await this.#fetch(url, {
158
+ method: "POST",
159
+ headers: { "Content-Type": "application/json", ...authorization ? { Authorization: authorization } : {} },
160
+ body: JSON.stringify(body)
161
+ });
162
+ } catch (cause) {
163
+ throw new LovebowlsApiError({
164
+ status: 0,
165
+ code: "network_error",
166
+ title: "Network error",
167
+ detail: "The sign-in request could not be completed.",
168
+ cause
169
+ });
170
+ }
171
+ let json;
172
+ try {
173
+ const v = JSON.parse(await res.text());
174
+ if (v && typeof v === "object") json = v;
175
+ } catch {
176
+ }
177
+ return { status: res.status, json };
178
+ }
179
+ async #anonymous() {
180
+ const r = await this.#post(WIX_TOKEN_URL, { clientId: this.#clientId, grantType: "anonymous" });
181
+ const t = r.json?.access_token;
182
+ if (typeof t !== "string" || !t) throw authError("login_failed", "Login failed", `Wix did not issue a visitor token (HTTP ${r.status}).`, r.status);
183
+ return t;
184
+ }
185
+ async #redirectSession(body, authorization) {
186
+ const r = await this.#post(WIX_SESSION_URL, body, authorization);
187
+ const url = r.json?.redirectSession?.fullUrl;
188
+ if (typeof url !== "string" || !url) throw authError("login_failed", "Login failed", `Wix did not create a redirect session (HTTP ${r.status}).`, r.status);
189
+ return url;
190
+ }
191
+ /** Start the sign-in: builds PKCE and state, stores them, and sends the browser to Wix's login page. */
192
+ async login() {
193
+ const verifier = randomString(48);
194
+ const state = randomString(16);
195
+ const challenge = await s256(verifier);
196
+ const url = await this.#redirectSession(
197
+ {
198
+ auth: {
199
+ authRequest: {
200
+ redirectUri: this.#redirectUri,
201
+ clientId: this.#clientId,
202
+ codeChallenge: challenge,
203
+ codeChallengeMethod: "S256",
204
+ responseMode: "fragment",
205
+ responseType: "code",
206
+ // No scope at all unless the site opts in: an empty scope was never measured (F-283).
207
+ ...this.#offline ? { scope: "offline_access" } : {},
208
+ state
209
+ },
210
+ // As the measured login (probe-member-token.mjs): always show Wix's login box.
211
+ prompt: "login"
212
+ }
213
+ },
214
+ await this.#anonymous()
215
+ );
216
+ this.#pkce().setItem(PKCE_KEY, JSON.stringify({ verifier, state }));
217
+ this.#location().assign(url);
218
+ }
219
+ /**
220
+ * Call once on page load at `redirectUri`. Returns `true` when it completed a sign-in, `false` when the page
221
+ * was not a sign-in return. Throws `state_mismatch` or `login_failed` (and clears the PKCE state) otherwise.
222
+ * The fragment (`#code=...`) is removed from the address bar either way.
223
+ */
224
+ async handleRedirect() {
225
+ const loc = this.#location();
226
+ const frag = new URLSearchParams(String(loc.hash || "").replace(/^#/, ""));
227
+ const code = frag.get("code");
228
+ const state = frag.get("state");
229
+ const err = frag.get("error");
230
+ if (!code && !err) return false;
231
+ let saved = {};
232
+ try {
233
+ saved = JSON.parse(this.#pkce().getItem(PKCE_KEY) ?? "{}");
234
+ } catch {
235
+ }
236
+ this.#pkce().removeItem(PKCE_KEY);
237
+ try {
238
+ const h = this.#historyOpt ?? globalThis.history;
239
+ h?.replaceState(null, "", loc.pathname + loc.search);
240
+ } catch {
241
+ }
242
+ if (err) throw authError("login_failed", "Login failed", `The sign-in was refused: ${err.replace(/[^\w .-]/g, "").slice(0, 80)}.`);
243
+ if (!saved.verifier || !saved.state || state !== saved.state) {
244
+ throw authError("state_mismatch", "Login failed", "The sign-in response did not match the request that started it. Try again.");
245
+ }
246
+ const r = await this.#post(WIX_TOKEN_URL, {
247
+ clientId: this.#clientId,
248
+ grantType: "authorization_code",
249
+ code,
250
+ codeVerifier: saved.verifier,
251
+ redirectUri: this.#redirectUri
252
+ });
253
+ this.#storeGrant(r.json, void 0);
254
+ if (!this.#read()) throw authError("login_failed", "Login failed", `Wix did not issue a token for the code (HTTP ${r.status}).`, r.status);
255
+ this.#emit(true);
256
+ return true;
257
+ }
258
+ #storeGrant(json, previousRefresh) {
259
+ const access = json?.access_token;
260
+ if (typeof access !== "string" || !access) return;
261
+ const ttl = typeof json?.expires_in === "number" && json.expires_in > 0 ? json.expires_in : 14400;
262
+ const rt = json?.refresh_token;
263
+ const refresh = this.#offline ? typeof rt === "string" && rt ? rt : previousRefresh : void 0;
264
+ this.#write({ access, refresh, expiresAt: Date.now() + ttl * 1e3 });
265
+ }
266
+ /** `true` while a member token is held that has not expired (or can be refreshed). */
267
+ isLoggedIn() {
268
+ const t = this.#read();
269
+ if (!t) return false;
270
+ if (t.expiresAt - SKEW_MS > Date.now() || t.refresh) return true;
271
+ this.clearSession();
272
+ return false;
273
+ }
274
+ /** The current access token, refreshed first when it is about to expire and a refresh token is held; else `null`. */
275
+ async getAccessToken() {
276
+ const t = this.#read();
277
+ if (!t) return null;
278
+ if (t.expiresAt - SKEW_MS > Date.now()) return t.access;
279
+ if (t.refresh && await this.refresh()) return this.#read()?.access ?? null;
280
+ this.clearSession();
281
+ return null;
282
+ }
283
+ /** Exchange the refresh token for a new access token. `false` when none is held or Wix refuses (a refusal clears the session). */
284
+ refresh() {
285
+ return this.#refreshing ??= this.#doRefresh().finally(() => {
286
+ this.#refreshing = void 0;
287
+ });
288
+ }
289
+ async #doRefresh() {
290
+ const t = this.#read();
291
+ if (!t?.refresh) return false;
292
+ let r;
293
+ try {
294
+ r = await this.#post(WIX_TOKEN_URL, { clientId: this.#clientId, grantType: "refresh_token", refreshToken: t.refresh });
295
+ } catch {
296
+ return false;
297
+ }
298
+ if (typeof r.json?.access_token !== "string") {
299
+ if (r.status >= 400 && r.status < 500) this.clearSession();
300
+ return false;
301
+ }
302
+ this.#storeGrant(r.json, t.refresh);
303
+ return true;
304
+ }
305
+ /**
306
+ * Sign out. The stored tokens and PKCE state are cleared first, always. Then, unless `redirect: false`, the browser
307
+ * goes to Wix's logout URL and comes back to `postLogoutUrl`. Wix's logout does not revoke tokens already issued.
308
+ */
309
+ async logout(options = {}) {
310
+ const held = this.#read();
311
+ this.#erase();
312
+ if (held) this.#emit(false);
313
+ if (options.redirect === false) return;
314
+ const url = await this.#redirectSession(
315
+ { logout: { clientId: this.#clientId }, callbacks: { postFlowUrl: this.#postLogout } },
316
+ held?.access ?? await this.#anonymous()
317
+ );
318
+ this.#location().assign(url);
319
+ }
320
+ /** Listen for sign-in and sign-out (including an expired session being dropped). Returns the unsubscribe function. */
321
+ onChange(cb) {
322
+ this.#listeners.add(cb);
323
+ return () => void this.#listeners.delete(cb);
324
+ }
325
+ };
326
+
327
+ // src/index.ts
328
+ var API_BASE_URL = "https://api.lovebowls.co.uk/v1";
329
+ function toIso(name, v) {
330
+ if (v instanceof Date) {
331
+ if (Number.isNaN(v.getTime())) throw new TypeError(`${name} is an invalid Date`);
332
+ return v.toISOString();
333
+ }
334
+ return String(v);
335
+ }
336
+ function parseRetryAfter(h) {
337
+ if (!h) return null;
338
+ const s = h.trim();
339
+ if (/^\d+$/.test(s)) return Number(s);
340
+ const t = Date.parse(s);
341
+ return Number.isNaN(t) ? null : Math.max(0, Math.ceil((t - Date.now()) / 1e3));
342
+ }
343
+ function enc(id) {
344
+ return encodeURIComponent(String(id));
345
+ }
346
+ function query(...pairs) {
347
+ const usp = new URLSearchParams();
348
+ for (const [k, v] of pairs) if (v !== void 0) usp.append(k, v);
349
+ const s = usp.toString();
350
+ return s ? `?${s}` : "";
351
+ }
352
+ var LovebowlsClient = class {
353
+ #apiKey;
354
+ #baseUrl;
355
+ #fetch;
356
+ #auth;
357
+ #memberToken;
358
+ constructor(options) {
359
+ if (!options || typeof options.apiKey !== "string" || !options.apiKey) {
360
+ throw new TypeError("LovebowlsClient: apiKey is required");
361
+ }
362
+ this.#apiKey = options.apiKey;
363
+ this.#baseUrl = (options.baseUrl ?? API_BASE_URL).replace(/\/+$/, "");
364
+ this.#fetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
365
+ this.#auth = options.auth;
366
+ this.#memberToken = options.memberToken;
367
+ }
368
+ /** The signed-in member's own record in this club. Needs a member token (`auth` or `memberToken`). */
369
+ getMe(clubId) {
370
+ return this.#get(`/clubs/${enc(clubId)}/me`, "", true);
371
+ }
372
+ /** The member's own calendar. With no `from`/`to`, the club's current season. */
373
+ getMyCalendar(clubId, options = {}) {
374
+ return this.#get(
375
+ `/clubs/${enc(clubId)}/me/calendar`,
376
+ query(
377
+ ["from", options.from === void 0 ? void 0 : toIso("from", options.from)],
378
+ ["to", options.to === void 0 ? void 0 : toIso("to", options.to)]
379
+ ),
380
+ true
381
+ );
382
+ }
383
+ getClub(clubId) {
384
+ return this.#get(`/clubs/${enc(clubId)}`);
385
+ }
386
+ listCompetitions(clubId, options = {}) {
387
+ return this.#get(`/clubs/${enc(clubId)}/competitions`, query(["kind", options.kind]));
388
+ }
389
+ listFixtures(clubId, options = {}) {
390
+ const comp = options.competition === void 0 ? [] : [].concat(options.competition);
391
+ return this.#get(
392
+ `/clubs/${enc(clubId)}/fixtures`,
393
+ query(
394
+ ["from", options.from === void 0 ? void 0 : toIso("from", options.from)],
395
+ ["to", options.to === void 0 ? void 0 : toIso("to", options.to)],
396
+ ...comp.map((c) => ["competition", c]),
397
+ ["team", options.team],
398
+ ["kind", options.kind],
399
+ ["limit", options.limit === void 0 ? void 0 : String(options.limit)],
400
+ ["cursor", options.cursor]
401
+ )
402
+ );
403
+ }
404
+ /** Every fixture matching the filters, fetching pages (via `nextCursor`) as you iterate. */
405
+ async *iterateFixtures(clubId, filters = {}) {
406
+ let cursor;
407
+ for (; ; ) {
408
+ const page = await this.listFixtures(clubId, { ...filters, cursor });
409
+ for (const item of page.items) yield item;
410
+ const next = page.nextCursor;
411
+ if (next === null || next === void 0) return;
412
+ if (next === cursor) {
413
+ throw new LovebowlsApiError({
414
+ status: 200,
415
+ code: "invalid_response",
416
+ title: "Invalid response",
417
+ detail: "The API returned the same paging cursor twice."
418
+ });
419
+ }
420
+ cursor = next;
421
+ }
422
+ }
423
+ getFixture(clubId, fixtureId) {
424
+ return this.#get(`/clubs/${enc(clubId)}/fixtures/${enc(fixtureId)}`);
425
+ }
426
+ getLeague(leagueId) {
427
+ return this.#get(`/leagues/${enc(leagueId)}`);
428
+ }
429
+ async #token() {
430
+ let t;
431
+ if (this.#auth) t = await this.#auth.getAccessToken();
432
+ else if (typeof this.#memberToken === "function") t = await this.#memberToken();
433
+ else t = this.#memberToken;
434
+ if (!t) {
435
+ throw new LovebowlsApiError({
436
+ status: 0,
437
+ code: "member_token_required",
438
+ title: "Member token required",
439
+ detail: "Log in first (LovebowlsAuth), or give the client a memberToken."
440
+ });
441
+ }
442
+ return t;
443
+ }
444
+ async #get(path, search = "", member = false) {
445
+ if (!member) return this.#send(path, search, void 0);
446
+ const first = await this.#token();
447
+ try {
448
+ return await this.#send(path, search, first);
449
+ } catch (e) {
450
+ if (!(e instanceof LovebowlsApiError) || e.code !== "member_token_invalid" || !this.#auth) throw e;
451
+ const next = await this.#auth.refresh() ? await this.#auth.getAccessToken() : null;
452
+ if (!next) {
453
+ this.#auth.clearSession();
454
+ throw e;
455
+ }
456
+ try {
457
+ return await this.#send(path, search, next);
458
+ } catch (e2) {
459
+ if (e2 instanceof LovebowlsApiError && e2.code === "member_token_invalid") this.#auth.clearSession();
460
+ throw e2;
461
+ }
462
+ }
463
+ }
464
+ async #send(path, search, token) {
465
+ let res;
466
+ try {
467
+ const headers = { "X-Api-Key": this.#apiKey, Accept: "application/json" };
468
+ if (token) headers.Authorization = `Bearer ${token}`;
469
+ res = await this.#fetch(this.#baseUrl + path + search, { method: "GET", headers });
470
+ } catch (cause) {
471
+ throw new LovebowlsApiError({
472
+ status: 0,
473
+ code: "network_error",
474
+ title: "Network error",
475
+ detail: "The request could not be completed.",
476
+ cause
477
+ });
478
+ }
479
+ const requestId = res.headers.get("X-Request-Id");
480
+ let text = "";
481
+ try {
482
+ text = await res.text();
483
+ } catch (cause) {
484
+ throw new LovebowlsApiError({
485
+ status: res.status,
486
+ code: "network_error",
487
+ title: "Network error",
488
+ detail: "The response could not be read.",
489
+ requestId,
490
+ cause
491
+ });
492
+ }
493
+ let body;
494
+ let parsed = false;
495
+ try {
496
+ body = JSON.parse(text);
497
+ parsed = true;
498
+ } catch {
499
+ }
500
+ if (res.ok) {
501
+ if (!parsed) {
502
+ throw new LovebowlsApiError({
503
+ status: res.status,
504
+ code: "invalid_response",
505
+ title: "Invalid response",
506
+ detail: "The response was not JSON.",
507
+ requestId
508
+ });
509
+ }
510
+ return body;
511
+ }
512
+ const retryAfter = parseRetryAfter(res.headers.get("Retry-After"));
513
+ const p = parsed && body && typeof body === "object" ? body : null;
514
+ if (p && typeof p.code === "string") {
515
+ throw new LovebowlsApiError({
516
+ status: res.status,
517
+ code: p.code,
518
+ title: typeof p.title === "string" ? p.title : res.statusText || "Error",
519
+ detail: typeof p.detail === "string" ? p.detail : null,
520
+ requestId: typeof p.requestId === "string" ? p.requestId : requestId,
521
+ retryAfter
522
+ });
523
+ }
524
+ throw new LovebowlsApiError({
525
+ status: res.status,
526
+ code: "invalid_response",
527
+ title: res.statusText || "Error",
528
+ detail: `The API answered ${res.status} with a body that was not a problem document.`,
529
+ requestId,
530
+ retryAfter
531
+ });
532
+ }
533
+ };
534
+ export {
535
+ API_BASE_URL,
536
+ LovebowlsApiError,
537
+ LovebowlsAuth,
538
+ LovebowlsClient
539
+ };