@lovebowls/api 0.1.0 → 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/README.md CHANGED
@@ -1,7 +1,8 @@
1
1
  # @lovebowls/api
2
2
 
3
3
  JavaScript SDK for the [lovebowls](https://www.lovebowls.co.uk) Public API: your club's details,
4
- competitions, fixtures, results and league tables, for a website you build yourself.
4
+ competitions, fixtures, results and league tables, and (from 0.2) member login with the signed-in
5
+ member's own details and calendar, for a website you build yourself.
5
6
 
6
7
  Zero dependencies. Works in browsers and Node 18+ (it uses the global `fetch`). Written in TypeScript;
7
8
  the types are generated from the API's OpenAPI contract.
@@ -16,8 +17,8 @@ Or, with no build step, from jsDelivr:
16
17
 
17
18
  ```html
18
19
  <script type="module">
19
- import { LovebowlsClient } from "https://cdn.jsdelivr.net/npm/@lovebowls/api@0.1.0/+esm";
20
- // or: ".../npm/@lovebowls/api@0.1.0/dist/index.js"
20
+ import { LovebowlsClient } from "https://cdn.jsdelivr.net/npm/@lovebowls/api@0.2.0/+esm";
21
+ // or: ".../npm/@lovebowls/api@0.2.0/dist/index.js"
21
22
  </script>
22
23
  ```
23
24
 
@@ -26,7 +27,7 @@ Or, with no build step, from jsDelivr:
26
27
  ```html
27
28
  <ul id="fixtures"></ul>
28
29
  <script type="module">
29
- import { LovebowlsClient } from "https://cdn.jsdelivr.net/npm/@lovebowls/api@0.1.0/+esm";
30
+ import { LovebowlsClient } from "https://cdn.jsdelivr.net/npm/@lovebowls/api@0.2.0/+esm";
30
31
  const lb = new LovebowlsClient({ apiKey: "lb_pk_..." }); // your publishable key
31
32
  const page = await lb.listFixtures("YOUR-CLUB-ID", { limit: 10 });
32
33
  for (const f of page.items) {
@@ -64,6 +65,8 @@ environment variables.
64
65
  ```ts
65
66
  new LovebowlsClient({
66
67
  apiKey: "lb_pk_...", // required; sent as X-Api-Key
68
+ auth, // optional: a LovebowlsAuth, for member methods
69
+ memberToken, // optional: a token (or async function) you already hold
67
70
  baseUrl: "https://api.lovebowls.co.uk/v1", // optional, this is the default
68
71
  fetch: customFetch, // optional, default globalThis.fetch
69
72
  });
@@ -82,6 +85,8 @@ Method names are the API's `operationId`s. Every method returns a promise and th
82
85
  | `iterateFixtures(clubId, filters?)` | `AsyncIterable<Fixture>`, all pages |
83
86
  | `getFixture(clubId, fixtureId)` | `Fixture` |
84
87
  | `getLeague(leagueId)` | `League` with its table (leagues have no club id) |
88
+ | `getMe(clubId)` | `Me`: the signed-in member's own record. Needs a member token |
89
+ | `getMyCalendar(clubId, { from?, to? })` | `{ items: CalendarEntry[] }`: the member's own calendar. Needs a member token; `from`/`to` as for fixtures |
85
90
 
86
91
  Filters:
87
92
 
@@ -121,16 +126,18 @@ Every failure is a `LovebowlsApiError` (an `Error`) with:
121
126
  | `requestId` | quote it when asking for support |
122
127
  | `retryAfter` | seconds to wait, from `Retry-After` on 429 and 503; else `null` |
123
128
 
124
- `code` is the API's problem code, for example `api_key_invalid`, `origin_not_allowed`,
129
+ `code` is the API's problem code, for example `api_key_invalid`, `member_token_invalid`, `not_a_member`, `origin_not_allowed`,
125
130
  `server_key_in_browser`, `club_mismatch`, `feature_not_in_plan`, `invalid_request`, `invalid_cursor`,
126
131
  `club_not_found`, `fixture_not_found`, `league_not_found`, `rate_limited`, `upstream_error`
127
- (safe to retry). The SDK adds two of its own:
132
+ (safe to retry). The SDK adds some of its own:
128
133
 
129
134
  - `network_error`: no answer (offline, DNS failure, a blocked cross-origin call, an abort);
130
135
  - `invalid_response`: an answer that is not what the API sends (a non-JSON body, an error without a
131
- problem document, or a paging cursor that repeats).
136
+ problem document, or a paging cursor that repeats);
137
+ - `member_token_required`: a member method with no usable token, so no request was made (`status` 0);
138
+ - `login_failed`, `state_mismatch`: the sign-in did not complete (see Member login).
132
139
 
133
- The API key is never included in an error message.
140
+ Neither the API key nor a member token is ever included in an error message.
134
141
 
135
142
  ```js
136
143
  try {
@@ -142,10 +149,139 @@ try {
142
149
  }
143
150
  ```
144
151
 
152
+ ## Member login
153
+
154
+ Member methods (`getMe`, `getMyCalendar`) need a **member token**: the member signs in on the
155
+ lovebowls login page and your page receives a short-lived token. `LovebowlsAuth` does the whole OAuth
156
+ flow (authorization code with PKCE, plain `fetch`, no other library); `LovebowlsClient` then sends the
157
+ token as `Authorization: Bearer <token>` on member calls only. A page that never logs anyone in needs none
158
+ of this.
159
+
160
+ You need two things from lovebowls: your **OAuth client id**, and your page's **redirect URI** added to the
161
+ client's list. The redirect URI must match **exactly** (scheme, host, path, trailing slash); anything else is
162
+ refused by Wix at the login page. It is the page that calls `handleRedirect()`.
163
+
164
+ ### In a plain HTML page
165
+
166
+ Use one page as both the login button and the return page. Import from the copy the API serves (no CDN) or
167
+ from jsDelivr:
168
+
169
+ ```html
170
+ <button id="login">Log in</button> <button id="logout" hidden>Log out</button>
171
+ <pre id="me"></pre>
172
+ <script type="module">
173
+ import { LovebowlsClient, LovebowlsAuth } from "https://api.lovebowls.co.uk/docs/example/lovebowls-api.js";
174
+ // or: from "https://cdn.jsdelivr.net/npm/@lovebowls/api@0.2.0/+esm"
175
+
176
+ const auth = new LovebowlsAuth({
177
+ clientId: "YOUR-OAUTH-CLIENT-ID",
178
+ redirectUri: location.origin + location.pathname, // must be on the client's list, exactly
179
+ });
180
+ const lb = new LovebowlsClient({ apiKey: "lb_pk_...", auth });
181
+ const CLUB = "YOUR-CLUB-ID";
182
+ const out = document.getElementById("me");
183
+
184
+ async function show() {
185
+ const loggedIn = auth.isLoggedIn();
186
+ document.getElementById("login").hidden = loggedIn;
187
+ document.getElementById("logout").hidden = !loggedIn;
188
+ out.textContent = "";
189
+ if (!loggedIn) return;
190
+ try {
191
+ out.textContent = JSON.stringify(await lb.getMe(CLUB), null, 2);
192
+ } catch (e) {
193
+ if (e.code === "not_a_member") out.textContent = "You are not a member of this club.";
194
+ else if (e.code === "member_token_required" || e.code === "member_token_invalid") show(); // session ended: offer login
195
+ else throw e;
196
+ }
197
+ }
198
+
199
+ try { await auth.handleRedirect(); } catch (e) { console.error(e.code); } // true if we just came back from the login
200
+ auth.onChange(show);
201
+ document.getElementById("login").onclick = () => auth.login();
202
+ document.getElementById("logout").onclick = () => auth.logout();
203
+ show();
204
+ </script>
205
+ ```
206
+
207
+ `handleRedirect()` is safe to call on every page load: it returns `false` when the page is not a login
208
+ return. When it is, it checks the `state` it stored before leaving, exchanges the code, and removes
209
+ `#code=...&state=...` from the address bar.
210
+
211
+ ### Options
212
+
213
+ ```ts
214
+ new LovebowlsAuth({
215
+ clientId: "...", // required
216
+ redirectUri: "https://...", // required, exact match on the client's list
217
+ storage: "session", // "session" (default) | "local" | "memory" | your own { getItem, setItem, removeItem }
218
+ offlineAccess: false, // true: also get a refresh token (see below)
219
+ postLogoutUrl: redirectUri, // where Wix sends the browser after logout()
220
+ fetch: customFetch, // optional
221
+ });
222
+ ```
223
+
224
+ Methods: `login()`, `handleRedirect()`, `isLoggedIn()`, `getAccessToken()`, `logout({ redirect? })`,
225
+ `onChange(cb)` (returns an unsubscribe function; `cb(loggedIn)` also fires when an expired session is dropped).
226
+
227
+ ### Where the token lives
228
+
229
+ By default the login asks for **only an access token**, which Wix issues for **4 hours**. It is kept in
230
+ `sessionStorage` (gone when the tab closes) under the key `lovebowls.auth.tokens`; during the trip to the login
231
+ page the PKCE secret is in `sessionStorage` too (`lovebowls.auth.pkce`) and is deleted on return.
232
+ `storage: "local"` survives closing the browser. `storage: "memory"` keeps the token in the page only, so it is
233
+ lost on reload. Any script on your page can read browser storage, so do not load scripts you do not trust.
234
+
235
+ When the 4 hours pass, `isLoggedIn()` turns `false`, the stored token is removed, and member methods throw
236
+ `member_token_required` without making a request: show your login button again.
237
+
238
+ ### Refresh tokens: off by default, and why
239
+
240
+ `offlineAccess: true` asks Wix for a refresh token as well, stores it in the same storage, and renews the
241
+ access token silently (just before it expires, and once, with one retry, if the API answers
242
+ `member_token_invalid`). The cost is a long-lived credential in the browser. **Measured: a Wix logout revokes
243
+ neither the access token nor the refresh token, and Wix has no revoke endpoint.** A stolen refresh token keeps
244
+ working after the member has logged out. Turn it on only if your members really need to stay signed in for
245
+ days, and prefer `storage: "session"`.
246
+
247
+ ### Logout
248
+
249
+ `logout()` **always clears the stored tokens and login state first**, in this browser, then (unless
250
+ `redirect: false`) sends the browser to Wix's logout page, which returns to `postLogoutUrl`. That URL's origin
251
+ must be an allowed redirect domain on the OAuth client. Wix's logout does not revoke tokens already issued, so a
252
+ copy of the access token taken earlier stays valid until its 4 hours are up: logging out protects this browser,
253
+ not a token someone already copied.
254
+
255
+ ### Member errors
256
+
257
+ | `code` | Meaning | What to do |
258
+ |---|---|---|
259
+ | `member_token_required` | no usable token (never logged in, or the session ended); **no request was made** | offer login |
260
+ | `member_token_invalid` | the API refused the token (expired, revoked or not ours). With a refresh token the SDK tries once more first; otherwise the session is cleared | offer login |
261
+ | `not_a_member` (403) | a valid login, but not a member of this club | tell the person; logging in again will not help |
262
+ | `state_mismatch`, `login_failed` | thrown by `handleRedirect()` or `login()`: the return did not match, was refused, or Wix did not answer | start again |
263
+
264
+ ### Node and servers
265
+
266
+ If you already hold a member token, pass it. There is no `window` and no `LovebowlsAuth`:
267
+
268
+ ```js
269
+ import { LovebowlsClient } from "@lovebowls/api";
270
+
271
+ const lb = new LovebowlsClient({
272
+ apiKey: process.env.LOVEBOWLS_API_KEY,
273
+ memberToken: async () => myTokenStore.get(userId), // or a plain string
274
+ });
275
+ const me = await lb.getMe("YOUR-CLUB-ID");
276
+ ```
277
+
278
+ Importing the package never touches a browser global, so it is safe in Node. The client does not renew a
279
+ `memberToken` for you: on `member_token_invalid`, get a new one and call again.
280
+
145
281
  ## Types
146
282
 
147
- `Club`, `Competition`, `Fixture`, `Result`, `League`, `LeagueTableRow`, `Page<T>`, `Problem` and
148
- `FixtureFilters` are exported. They are generated from `openapi.yaml`. The API only adds fields within v1, so
283
+ `Club`, `Competition`, `Fixture`, `Result`, `League`, `LeagueTableRow`, `Me`, `CalendarEntry`,
284
+ `MyFixtureStatus`, `ClubRole`, `Page<T>`, `Problem` and `FixtureFilters` are exported. They are generated from `openapi.yaml`. The API only adds fields within v1, so
149
285
  ignore unknown fields and unknown enum values (a new `kind`, say) as normal.
150
286
 
151
287
  ## Development
package/dist/auth.d.ts ADDED
@@ -0,0 +1,66 @@
1
+ /** The part of `Storage` the SDK uses. */
2
+ export interface StorageLike {
3
+ getItem(key: string): string | null;
4
+ setItem(key: string, value: string): void;
5
+ removeItem(key: string): void;
6
+ }
7
+ /** The part of `window.location` the SDK uses. */
8
+ export interface LocationLike {
9
+ hash: string;
10
+ pathname: string;
11
+ search: string;
12
+ assign(url: string): void;
13
+ }
14
+ export type AuthStorage = "session" | "local" | "memory";
15
+ export interface LovebowlsAuthOptions {
16
+ /** The OAuth client id of your site's login (public). Ask lovebowls for it. */
17
+ clientId: string;
18
+ /** The page that handles the sign-in return. Must be on the OAuth client's list of redirect URIs, exactly. */
19
+ redirectUri: string;
20
+ /**
21
+ * Where the member token is kept: `"session"` (default, `sessionStorage`), `"local"`, `"memory"` (lost on
22
+ * reload), or your own `StorageLike`.
23
+ */
24
+ storage?: AuthStorage | StorageLike;
25
+ /** Also ask for a refresh token (silent renewal after the 4-hour access token). Off by default: see the README. */
26
+ offlineAccess?: boolean;
27
+ /** Where Wix sends the browser after `logout()`. Default `redirectUri`. Its origin must be an allowed redirect domain. */
28
+ postLogoutUrl?: string;
29
+ /** Default `globalThis.fetch`. */
30
+ fetch?: typeof fetch;
31
+ /** Default `window.location`. */
32
+ location?: LocationLike;
33
+ /** Default `window.history` (only `replaceState` is used, to clear the sign-in fragment). */
34
+ history?: {
35
+ replaceState(data: unknown, unused: string, url?: string | null): void;
36
+ };
37
+ }
38
+ export declare class LovebowlsAuth {
39
+ #private;
40
+ constructor(options: LovebowlsAuthOptions);
41
+ /** Drop the stored tokens and PKCE state and tell listeners. The client calls it when a token proves invalid. */
42
+ clearSession(): void;
43
+ /** Start the sign-in: builds PKCE and state, stores them, and sends the browser to Wix's login page. */
44
+ login(): Promise<void>;
45
+ /**
46
+ * Call once on page load at `redirectUri`. Returns `true` when it completed a sign-in, `false` when the page
47
+ * was not a sign-in return. Throws `state_mismatch` or `login_failed` (and clears the PKCE state) otherwise.
48
+ * The fragment (`#code=...`) is removed from the address bar either way.
49
+ */
50
+ handleRedirect(): Promise<boolean>;
51
+ /** `true` while a member token is held that has not expired (or can be refreshed). */
52
+ isLoggedIn(): boolean;
53
+ /** The current access token, refreshed first when it is about to expire and a refresh token is held; else `null`. */
54
+ getAccessToken(): Promise<string | null>;
55
+ /** Exchange the refresh token for a new access token. `false` when none is held or Wix refuses (a refusal clears the session). */
56
+ refresh(): Promise<boolean>;
57
+ /**
58
+ * Sign out. The stored tokens and PKCE state are cleared first, always. Then, unless `redirect: false`, the browser
59
+ * goes to Wix's logout URL and comes back to `postLogoutUrl`. Wix's logout does not revoke tokens already issued.
60
+ */
61
+ logout(options?: {
62
+ redirect?: boolean;
63
+ }): Promise<void>;
64
+ /** Listen for sign-in and sign-out (including an expired session being dropped). Returns the unsubscribe function. */
65
+ onChange(cb: (loggedIn: boolean) => void): () => void;
66
+ }
@@ -0,0 +1,33 @@
1
+ import type { components } from "./schema";
2
+ type Problem = components["schemas"]["Problem"];
3
+ export type { Problem };
4
+ /**
5
+ * Thrown for every failure. `code` is the gateway's stable problem code (for example
6
+ * `fixture_not_found`, `rate_limited`) or one the SDK raises itself:
7
+ * - `network_error`: the request never got an answer (offline, DNS, CORS, abort);
8
+ * - `invalid_response`: the answer was not what the API sends (non-JSON, wrong shape, a paging loop);
9
+ * - `member_token_required`: a member method with no usable member token (never logged in, or the session
10
+ * expired); no request was made. The API itself also sends this code;
11
+ * - `login_failed`, `state_mismatch`: raised by `LovebowlsAuth` when the sign-in did not complete.
12
+ * The API also sends `member_token_invalid` and `not_a_member` (403).
13
+ * `status` is 0 for `network_error` and the SDK-raised codes. Neither the API key nor a member token is ever
14
+ * part of the message.
15
+ */
16
+ export declare class LovebowlsApiError extends Error {
17
+ status: number;
18
+ code: string;
19
+ title: string;
20
+ detail: string | null;
21
+ requestId: string | null;
22
+ /** Seconds to wait, from `Retry-After` (429 and 503); `null` when absent. */
23
+ retryAfter: number | null;
24
+ constructor(init: {
25
+ status: number;
26
+ code: string;
27
+ title: string;
28
+ detail?: string | null;
29
+ requestId?: string | null;
30
+ retryAfter?: number | null;
31
+ cause?: unknown;
32
+ });
33
+ }
package/dist/index.cjs CHANGED
@@ -22,10 +22,12 @@ var index_exports = {};
22
22
  __export(index_exports, {
23
23
  API_BASE_URL: () => API_BASE_URL,
24
24
  LovebowlsApiError: () => LovebowlsApiError,
25
+ LovebowlsAuth: () => LovebowlsAuth,
25
26
  LovebowlsClient: () => LovebowlsClient
26
27
  });
27
28
  module.exports = __toCommonJS(index_exports);
28
- var API_BASE_URL = "https://api.lovebowls.co.uk/v1";
29
+
30
+ // src/errors.ts
29
31
  var LovebowlsApiError = class _LovebowlsApiError extends Error {
30
32
  status;
31
33
  code;
@@ -47,6 +49,312 @@ var LovebowlsApiError = class _LovebowlsApiError extends Error {
47
49
  Object.setPrototypeOf(this, _LovebowlsApiError.prototype);
48
50
  }
49
51
  };
52
+
53
+ // src/auth.ts
54
+ var WIX_TOKEN_URL = "https://www.wixapis.com/oauth2/token";
55
+ var WIX_SESSION_URL = "https://www.wixapis.com/_api/redirects-api/v1/redirect-session";
56
+ var TOKENS_KEY = "lovebowls.auth.tokens";
57
+ var PKCE_KEY = "lovebowls.auth.pkce";
58
+ var SKEW_MS = 6e4;
59
+ function memoryStorage() {
60
+ const m = /* @__PURE__ */ new Map();
61
+ return {
62
+ getItem: (k) => m.get(k) ?? null,
63
+ setItem: (k, v) => void m.set(k, v),
64
+ removeItem: (k) => void m.delete(k)
65
+ };
66
+ }
67
+ function b64url(bytes) {
68
+ let s = "";
69
+ for (const b of bytes) s += String.fromCharCode(b);
70
+ return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
71
+ }
72
+ function randomString(bytes) {
73
+ return b64url(globalThis.crypto.getRandomValues(new Uint8Array(bytes)));
74
+ }
75
+ async function s256(verifier) {
76
+ const d = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
77
+ return b64url(new Uint8Array(d));
78
+ }
79
+ function authError(code, title, detail, status = 0) {
80
+ return new LovebowlsApiError({ status, code, title, detail });
81
+ }
82
+ var LovebowlsAuth = class {
83
+ #clientId;
84
+ #redirectUri;
85
+ #offline;
86
+ #postLogout;
87
+ #fetchOpt;
88
+ #locationOpt;
89
+ #historyOpt;
90
+ #storageOpt;
91
+ #listeners = /* @__PURE__ */ new Set();
92
+ #store;
93
+ #pkceStore;
94
+ #refreshing;
95
+ constructor(options) {
96
+ if (!options || !options.clientId) throw new TypeError("LovebowlsAuth: clientId is required");
97
+ if (!options.redirectUri) throw new TypeError("LovebowlsAuth: redirectUri is required");
98
+ this.#clientId = options.clientId;
99
+ this.#redirectUri = options.redirectUri;
100
+ this.#offline = options.offlineAccess === true;
101
+ this.#postLogout = options.postLogoutUrl ?? options.redirectUri;
102
+ this.#fetchOpt = options.fetch;
103
+ this.#locationOpt = options.location;
104
+ this.#historyOpt = options.history;
105
+ this.#storageOpt = options.storage ?? "session";
106
+ }
107
+ // ---- environment, resolved lazily so import never touches a browser global
108
+ #fetch(input, init) {
109
+ return this.#fetchOpt ? this.#fetchOpt(input, init) : globalThis.fetch(input, init);
110
+ }
111
+ #location() {
112
+ return this.#locationOpt ?? globalThis.location;
113
+ }
114
+ #tokenStore() {
115
+ if (this.#store) return this.#store;
116
+ const o = this.#storageOpt;
117
+ let s;
118
+ if (typeof o === "object") s = o;
119
+ else if (o !== "memory") {
120
+ try {
121
+ const g = globalThis;
122
+ s = o === "local" ? g.localStorage : g.sessionStorage;
123
+ } catch {
124
+ }
125
+ }
126
+ return this.#store = s ?? memoryStorage();
127
+ }
128
+ /** 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. */
129
+ #pkce() {
130
+ if (this.#pkceStore) return this.#pkceStore;
131
+ let s;
132
+ if (typeof this.#storageOpt === "object") s = this.#storageOpt;
133
+ else {
134
+ try {
135
+ s = globalThis.sessionStorage;
136
+ } catch {
137
+ }
138
+ }
139
+ return this.#pkceStore = s ?? memoryStorage();
140
+ }
141
+ // ---- token storage
142
+ #read() {
143
+ try {
144
+ const raw = this.#tokenStore().getItem(TOKENS_KEY);
145
+ if (!raw) return null;
146
+ const t = JSON.parse(raw);
147
+ if (typeof t.access !== "string" || !t.access || typeof t.expiresAt !== "number") return null;
148
+ return { access: t.access, refresh: typeof t.refresh === "string" && t.refresh ? t.refresh : void 0, expiresAt: t.expiresAt };
149
+ } catch {
150
+ return null;
151
+ }
152
+ }
153
+ #write(t) {
154
+ try {
155
+ this.#tokenStore().setItem(TOKENS_KEY, JSON.stringify(t));
156
+ } catch {
157
+ }
158
+ }
159
+ #erase() {
160
+ try {
161
+ this.#tokenStore().removeItem(TOKENS_KEY);
162
+ } catch {
163
+ }
164
+ try {
165
+ this.#pkce().removeItem(PKCE_KEY);
166
+ } catch {
167
+ }
168
+ }
169
+ #emit(loggedIn) {
170
+ for (const cb of [...this.#listeners]) {
171
+ try {
172
+ cb(loggedIn);
173
+ } catch {
174
+ }
175
+ }
176
+ }
177
+ /** Drop the stored tokens and PKCE state and tell listeners. The client calls it when a token proves invalid. */
178
+ clearSession() {
179
+ const had = this.#read() !== null;
180
+ this.#erase();
181
+ if (had) this.#emit(false);
182
+ }
183
+ async #post(url, body, authorization) {
184
+ let res;
185
+ try {
186
+ res = await this.#fetch(url, {
187
+ method: "POST",
188
+ headers: { "Content-Type": "application/json", ...authorization ? { Authorization: authorization } : {} },
189
+ body: JSON.stringify(body)
190
+ });
191
+ } catch (cause) {
192
+ throw new LovebowlsApiError({
193
+ status: 0,
194
+ code: "network_error",
195
+ title: "Network error",
196
+ detail: "The sign-in request could not be completed.",
197
+ cause
198
+ });
199
+ }
200
+ let json;
201
+ try {
202
+ const v = JSON.parse(await res.text());
203
+ if (v && typeof v === "object") json = v;
204
+ } catch {
205
+ }
206
+ return { status: res.status, json };
207
+ }
208
+ async #anonymous() {
209
+ const r = await this.#post(WIX_TOKEN_URL, { clientId: this.#clientId, grantType: "anonymous" });
210
+ const t = r.json?.access_token;
211
+ if (typeof t !== "string" || !t) throw authError("login_failed", "Login failed", `Wix did not issue a visitor token (HTTP ${r.status}).`, r.status);
212
+ return t;
213
+ }
214
+ async #redirectSession(body, authorization) {
215
+ const r = await this.#post(WIX_SESSION_URL, body, authorization);
216
+ const url = r.json?.redirectSession?.fullUrl;
217
+ if (typeof url !== "string" || !url) throw authError("login_failed", "Login failed", `Wix did not create a redirect session (HTTP ${r.status}).`, r.status);
218
+ return url;
219
+ }
220
+ /** Start the sign-in: builds PKCE and state, stores them, and sends the browser to Wix's login page. */
221
+ async login() {
222
+ const verifier = randomString(48);
223
+ const state = randomString(16);
224
+ const challenge = await s256(verifier);
225
+ const url = await this.#redirectSession(
226
+ {
227
+ auth: {
228
+ authRequest: {
229
+ redirectUri: this.#redirectUri,
230
+ clientId: this.#clientId,
231
+ codeChallenge: challenge,
232
+ codeChallengeMethod: "S256",
233
+ responseMode: "fragment",
234
+ responseType: "code",
235
+ // No scope at all unless the site opts in: an empty scope was never measured (F-283).
236
+ ...this.#offline ? { scope: "offline_access" } : {},
237
+ state
238
+ },
239
+ // As the measured login (probe-member-token.mjs): always show Wix's login box.
240
+ prompt: "login"
241
+ }
242
+ },
243
+ await this.#anonymous()
244
+ );
245
+ this.#pkce().setItem(PKCE_KEY, JSON.stringify({ verifier, state }));
246
+ this.#location().assign(url);
247
+ }
248
+ /**
249
+ * Call once on page load at `redirectUri`. Returns `true` when it completed a sign-in, `false` when the page
250
+ * was not a sign-in return. Throws `state_mismatch` or `login_failed` (and clears the PKCE state) otherwise.
251
+ * The fragment (`#code=...`) is removed from the address bar either way.
252
+ */
253
+ async handleRedirect() {
254
+ const loc = this.#location();
255
+ const frag = new URLSearchParams(String(loc.hash || "").replace(/^#/, ""));
256
+ const code = frag.get("code");
257
+ const state = frag.get("state");
258
+ const err = frag.get("error");
259
+ if (!code && !err) return false;
260
+ let saved = {};
261
+ try {
262
+ saved = JSON.parse(this.#pkce().getItem(PKCE_KEY) ?? "{}");
263
+ } catch {
264
+ }
265
+ this.#pkce().removeItem(PKCE_KEY);
266
+ try {
267
+ const h = this.#historyOpt ?? globalThis.history;
268
+ h?.replaceState(null, "", loc.pathname + loc.search);
269
+ } catch {
270
+ }
271
+ if (err) throw authError("login_failed", "Login failed", `The sign-in was refused: ${err.replace(/[^\w .-]/g, "").slice(0, 80)}.`);
272
+ if (!saved.verifier || !saved.state || state !== saved.state) {
273
+ throw authError("state_mismatch", "Login failed", "The sign-in response did not match the request that started it. Try again.");
274
+ }
275
+ const r = await this.#post(WIX_TOKEN_URL, {
276
+ clientId: this.#clientId,
277
+ grantType: "authorization_code",
278
+ code,
279
+ codeVerifier: saved.verifier,
280
+ redirectUri: this.#redirectUri
281
+ });
282
+ this.#storeGrant(r.json, void 0);
283
+ if (!this.#read()) throw authError("login_failed", "Login failed", `Wix did not issue a token for the code (HTTP ${r.status}).`, r.status);
284
+ this.#emit(true);
285
+ return true;
286
+ }
287
+ #storeGrant(json, previousRefresh) {
288
+ const access = json?.access_token;
289
+ if (typeof access !== "string" || !access) return;
290
+ const ttl = typeof json?.expires_in === "number" && json.expires_in > 0 ? json.expires_in : 14400;
291
+ const rt = json?.refresh_token;
292
+ const refresh = this.#offline ? typeof rt === "string" && rt ? rt : previousRefresh : void 0;
293
+ this.#write({ access, refresh, expiresAt: Date.now() + ttl * 1e3 });
294
+ }
295
+ /** `true` while a member token is held that has not expired (or can be refreshed). */
296
+ isLoggedIn() {
297
+ const t = this.#read();
298
+ if (!t) return false;
299
+ if (t.expiresAt - SKEW_MS > Date.now() || t.refresh) return true;
300
+ this.clearSession();
301
+ return false;
302
+ }
303
+ /** The current access token, refreshed first when it is about to expire and a refresh token is held; else `null`. */
304
+ async getAccessToken() {
305
+ const t = this.#read();
306
+ if (!t) return null;
307
+ if (t.expiresAt - SKEW_MS > Date.now()) return t.access;
308
+ if (t.refresh && await this.refresh()) return this.#read()?.access ?? null;
309
+ this.clearSession();
310
+ return null;
311
+ }
312
+ /** Exchange the refresh token for a new access token. `false` when none is held or Wix refuses (a refusal clears the session). */
313
+ refresh() {
314
+ return this.#refreshing ??= this.#doRefresh().finally(() => {
315
+ this.#refreshing = void 0;
316
+ });
317
+ }
318
+ async #doRefresh() {
319
+ const t = this.#read();
320
+ if (!t?.refresh) return false;
321
+ let r;
322
+ try {
323
+ r = await this.#post(WIX_TOKEN_URL, { clientId: this.#clientId, grantType: "refresh_token", refreshToken: t.refresh });
324
+ } catch {
325
+ return false;
326
+ }
327
+ if (typeof r.json?.access_token !== "string") {
328
+ if (r.status >= 400 && r.status < 500) this.clearSession();
329
+ return false;
330
+ }
331
+ this.#storeGrant(r.json, t.refresh);
332
+ return true;
333
+ }
334
+ /**
335
+ * Sign out. The stored tokens and PKCE state are cleared first, always. Then, unless `redirect: false`, the browser
336
+ * goes to Wix's logout URL and comes back to `postLogoutUrl`. Wix's logout does not revoke tokens already issued.
337
+ */
338
+ async logout(options = {}) {
339
+ const held = this.#read();
340
+ this.#erase();
341
+ if (held) this.#emit(false);
342
+ if (options.redirect === false) return;
343
+ const url = await this.#redirectSession(
344
+ { logout: { clientId: this.#clientId }, callbacks: { postFlowUrl: this.#postLogout } },
345
+ held?.access ?? await this.#anonymous()
346
+ );
347
+ this.#location().assign(url);
348
+ }
349
+ /** Listen for sign-in and sign-out (including an expired session being dropped). Returns the unsubscribe function. */
350
+ onChange(cb) {
351
+ this.#listeners.add(cb);
352
+ return () => void this.#listeners.delete(cb);
353
+ }
354
+ };
355
+
356
+ // src/index.ts
357
+ var API_BASE_URL = "https://api.lovebowls.co.uk/v1";
50
358
  function toIso(name, v) {
51
359
  if (v instanceof Date) {
52
360
  if (Number.isNaN(v.getTime())) throw new TypeError(`${name} is an invalid Date`);
@@ -74,6 +382,8 @@ var LovebowlsClient = class {
74
382
  #apiKey;
75
383
  #baseUrl;
76
384
  #fetch;
385
+ #auth;
386
+ #memberToken;
77
387
  constructor(options) {
78
388
  if (!options || typeof options.apiKey !== "string" || !options.apiKey) {
79
389
  throw new TypeError("LovebowlsClient: apiKey is required");
@@ -81,6 +391,23 @@ var LovebowlsClient = class {
81
391
  this.#apiKey = options.apiKey;
82
392
  this.#baseUrl = (options.baseUrl ?? API_BASE_URL).replace(/\/+$/, "");
83
393
  this.#fetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
394
+ this.#auth = options.auth;
395
+ this.#memberToken = options.memberToken;
396
+ }
397
+ /** The signed-in member's own record in this club. Needs a member token (`auth` or `memberToken`). */
398
+ getMe(clubId) {
399
+ return this.#get(`/clubs/${enc(clubId)}/me`, "", true);
400
+ }
401
+ /** The member's own calendar. With no `from`/`to`, the club's current season. */
402
+ getMyCalendar(clubId, options = {}) {
403
+ return this.#get(
404
+ `/clubs/${enc(clubId)}/me/calendar`,
405
+ query(
406
+ ["from", options.from === void 0 ? void 0 : toIso("from", options.from)],
407
+ ["to", options.to === void 0 ? void 0 : toIso("to", options.to)]
408
+ ),
409
+ true
410
+ );
84
411
  }
85
412
  getClub(clubId) {
86
413
  return this.#get(`/clubs/${enc(clubId)}`);
@@ -128,13 +455,47 @@ var LovebowlsClient = class {
128
455
  getLeague(leagueId) {
129
456
  return this.#get(`/leagues/${enc(leagueId)}`);
130
457
  }
131
- async #get(path, search = "") {
458
+ async #token() {
459
+ let t;
460
+ if (this.#auth) t = await this.#auth.getAccessToken();
461
+ else if (typeof this.#memberToken === "function") t = await this.#memberToken();
462
+ else t = this.#memberToken;
463
+ if (!t) {
464
+ throw new LovebowlsApiError({
465
+ status: 0,
466
+ code: "member_token_required",
467
+ title: "Member token required",
468
+ detail: "Log in first (LovebowlsAuth), or give the client a memberToken."
469
+ });
470
+ }
471
+ return t;
472
+ }
473
+ async #get(path, search = "", member = false) {
474
+ if (!member) return this.#send(path, search, void 0);
475
+ const first = await this.#token();
476
+ try {
477
+ return await this.#send(path, search, first);
478
+ } catch (e) {
479
+ if (!(e instanceof LovebowlsApiError) || e.code !== "member_token_invalid" || !this.#auth) throw e;
480
+ const next = await this.#auth.refresh() ? await this.#auth.getAccessToken() : null;
481
+ if (!next) {
482
+ this.#auth.clearSession();
483
+ throw e;
484
+ }
485
+ try {
486
+ return await this.#send(path, search, next);
487
+ } catch (e2) {
488
+ if (e2 instanceof LovebowlsApiError && e2.code === "member_token_invalid") this.#auth.clearSession();
489
+ throw e2;
490
+ }
491
+ }
492
+ }
493
+ async #send(path, search, token) {
132
494
  let res;
133
495
  try {
134
- res = await this.#fetch(this.#baseUrl + path + search, {
135
- method: "GET",
136
- headers: { "X-Api-Key": this.#apiKey, Accept: "application/json" }
137
- });
496
+ const headers = { "X-Api-Key": this.#apiKey, Accept: "application/json" };
497
+ if (token) headers.Authorization = `Bearer ${token}`;
498
+ res = await this.#fetch(this.#baseUrl + path + search, { method: "GET", headers });
138
499
  } catch (cause) {
139
500
  throw new LovebowlsApiError({
140
501
  status: 0,
package/dist/index.d.ts CHANGED
@@ -4,6 +4,11 @@
4
4
  * Types come from ./schema.ts, generated from the contract by `npm run generate`.
5
5
  */
6
6
  import type { components, operations } from "./schema";
7
+ import { LovebowlsApiError, type Problem } from "./errors";
8
+ import { LovebowlsAuth } from "./auth";
9
+ export { LovebowlsApiError, type Problem };
10
+ export { LovebowlsAuth };
11
+ export type { LovebowlsAuthOptions, AuthStorage, StorageLike, LocationLike } from "./auth";
7
12
  export declare const API_BASE_URL = "https://api.lovebowls.co.uk/v1";
8
13
  type Schemas = components["schemas"];
9
14
  export type Club = Schemas["Club"];
@@ -12,9 +17,16 @@ export type CompetitionSummary = Schemas["CompetitionSummary"];
12
17
  export type Fixture = Schemas["Fixture"];
13
18
  export type FixtureKind = Schemas["FixtureKind"];
14
19
  export type Result = Schemas["Result"];
20
+ export type Me = Schemas["Me"];
21
+ export type CalendarEntry = Schemas["CalendarEntry"];
22
+ export type MyFixtureStatus = Schemas["MyFixtureStatus"];
23
+ export type ClubRole = Schemas["ClubRole"];
24
+ /** What `getMyCalendar` returns: not paged, so just the items. */
25
+ export type CalendarList = {
26
+ items: CalendarEntry[];
27
+ };
15
28
  export type League = Schemas["League"];
16
29
  export type LeagueTableRow = Schemas["LeagueTableRow"];
17
- export type Problem = Schemas["Problem"];
18
30
  /** One page of a paged list. `nextCursor` is `null` on the last page. */
19
31
  export type Page<T> = Omit<Schemas["Page"], "items"> & {
20
32
  items: T[];
@@ -45,6 +57,14 @@ export interface ListFixturesOptions extends FixtureFilters {
45
57
  export interface ListCompetitionsOptions {
46
58
  kind?: FixtureKind;
47
59
  }
60
+ export interface MyCalendarOptions {
61
+ /** Start of the range, inclusive. Send both `from` and `to`, or neither (the club's current season). */
62
+ from?: DateInput;
63
+ /** End of the range, exclusive. At most 400 days after `from`. */
64
+ to?: DateInput;
65
+ }
66
+ /** A member token for Node or server code that already holds one (no login flow, no `window`). */
67
+ export type MemberTokenSource = string | (() => string | undefined | null | Promise<string | undefined | null>);
48
68
  export interface LovebowlsClientOptions {
49
69
  /** Your API key (`lb_pk_...` in a browser). Sent as `X-Api-Key`. */
50
70
  apiKey: string;
@@ -52,36 +72,19 @@ export interface LovebowlsClientOptions {
52
72
  baseUrl?: string;
53
73
  /** Default `globalThis.fetch`. */
54
74
  fetch?: typeof fetch;
75
+ /** A `LovebowlsAuth` (browser login). Member methods take their token from it. */
76
+ auth?: LovebowlsAuth;
77
+ /** A member token you already hold (Node/server), or a function returning one. Ignored if `auth` is set. */
78
+ memberToken?: MemberTokenSource;
55
79
  }
56
- export type OperationId = keyof Pick<operations, "getClub" | "listCompetitions" | "listFixtures" | "getFixture" | "getLeague">;
57
- /**
58
- * Thrown for every failure. `code` is the gateway's stable problem code (for example
59
- * `fixture_not_found`, `rate_limited`) or one the SDK raises itself:
60
- * - `network_error`: the request never got an answer (offline, DNS, CORS, abort);
61
- * - `invalid_response`: the answer was not what the API sends (non-JSON, wrong shape, a paging loop).
62
- * `status` is 0 for `network_error`. The API key is never part of the message.
63
- */
64
- export declare class LovebowlsApiError extends Error {
65
- status: number;
66
- code: string;
67
- title: string;
68
- detail: string | null;
69
- requestId: string | null;
70
- /** Seconds to wait, from `Retry-After` (429 and 503); `null` when absent. */
71
- retryAfter: number | null;
72
- constructor(init: {
73
- status: number;
74
- code: string;
75
- title: string;
76
- detail?: string | null;
77
- requestId?: string | null;
78
- retryAfter?: number | null;
79
- cause?: unknown;
80
- });
81
- }
80
+ export type OperationId = keyof Pick<operations, "getClub" | "listCompetitions" | "listFixtures" | "getFixture" | "getLeague" | "getMe" | "getMyCalendar">;
82
81
  export declare class LovebowlsClient {
83
82
  #private;
84
83
  constructor(options: LovebowlsClientOptions);
84
+ /** The signed-in member's own record in this club. Needs a member token (`auth` or `memberToken`). */
85
+ getMe(clubId: string): Promise<Me>;
86
+ /** The member's own calendar. With no `from`/`to`, the club's current season. */
87
+ getMyCalendar(clubId: string, options?: MyCalendarOptions): Promise<CalendarList>;
85
88
  getClub(clubId: string): Promise<Club>;
86
89
  listCompetitions(clubId: string, options?: ListCompetitionsOptions): Promise<CompetitionList>;
87
90
  listFixtures(clubId: string, options?: ListFixturesOptions): Promise<Page<Fixture>>;
@@ -92,4 +95,3 @@ export declare class LovebowlsClient {
92
95
  getFixture(clubId: string, fixtureId: string): Promise<Fixture>;
93
96
  getLeague(leagueId: string): Promise<League>;
94
97
  }
95
- export {};
package/dist/index.js CHANGED
@@ -1,5 +1,4 @@
1
- // src/index.ts
2
- var API_BASE_URL = "https://api.lovebowls.co.uk/v1";
1
+ // src/errors.ts
3
2
  var LovebowlsApiError = class _LovebowlsApiError extends Error {
4
3
  status;
5
4
  code;
@@ -21,6 +20,312 @@ var LovebowlsApiError = class _LovebowlsApiError extends Error {
21
20
  Object.setPrototypeOf(this, _LovebowlsApiError.prototype);
22
21
  }
23
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";
24
329
  function toIso(name, v) {
25
330
  if (v instanceof Date) {
26
331
  if (Number.isNaN(v.getTime())) throw new TypeError(`${name} is an invalid Date`);
@@ -48,6 +353,8 @@ var LovebowlsClient = class {
48
353
  #apiKey;
49
354
  #baseUrl;
50
355
  #fetch;
356
+ #auth;
357
+ #memberToken;
51
358
  constructor(options) {
52
359
  if (!options || typeof options.apiKey !== "string" || !options.apiKey) {
53
360
  throw new TypeError("LovebowlsClient: apiKey is required");
@@ -55,6 +362,23 @@ var LovebowlsClient = class {
55
362
  this.#apiKey = options.apiKey;
56
363
  this.#baseUrl = (options.baseUrl ?? API_BASE_URL).replace(/\/+$/, "");
57
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
+ );
58
382
  }
59
383
  getClub(clubId) {
60
384
  return this.#get(`/clubs/${enc(clubId)}`);
@@ -102,13 +426,47 @@ var LovebowlsClient = class {
102
426
  getLeague(leagueId) {
103
427
  return this.#get(`/leagues/${enc(leagueId)}`);
104
428
  }
105
- async #get(path, search = "") {
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) {
106
465
  let res;
107
466
  try {
108
- res = await this.#fetch(this.#baseUrl + path + search, {
109
- method: "GET",
110
- headers: { "X-Api-Key": this.#apiKey, Accept: "application/json" }
111
- });
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 });
112
470
  } catch (cause) {
113
471
  throw new LovebowlsApiError({
114
472
  status: 0,
@@ -176,5 +534,6 @@ var LovebowlsClient = class {
176
534
  export {
177
535
  API_BASE_URL,
178
536
  LovebowlsApiError,
537
+ LovebowlsAuth,
179
538
  LovebowlsClient
180
539
  };
package/dist/schema.d.ts CHANGED
@@ -1285,6 +1285,8 @@ export interface operations {
1285
1285
  /** @description The calendar. */
1286
1286
  200: {
1287
1287
  headers: {
1288
+ /** @example private, no-store */
1289
+ "Cache-Control"?: string;
1288
1290
  [name: string]: unknown;
1289
1291
  };
1290
1292
  content: {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@lovebowls/api",
3
- "version": "0.1.0",
4
- "description": "JavaScript SDK for the lovebowls Public API: club, competitions, fixtures, results and league tables. Zero dependencies; browsers and Node 18+.",
3
+ "version": "0.2.0",
4
+ "description": "JavaScript SDK for the lovebowls Public API: club, competitions, fixtures, results and league tables, and member login with the member's own details and calendar. Zero dependencies; browsers and Node 18+.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
7
7
  "module": "./dist/index.js",
@@ -31,7 +31,9 @@
31
31
  "club",
32
32
  "fixtures",
33
33
  "api",
34
- "sdk"
34
+ "sdk",
35
+ "login",
36
+ "oauth"
35
37
  ],
36
38
  "homepage": "https://api.lovebowls.co.uk/docs",
37
39
  "author": "lovebowls.co.uk",