@bowlos/reservations 0.1.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.
@@ -0,0 +1,367 @@
1
+ /**
2
+ * Core types for the BowlOS Reservations SDK client.
3
+ */
4
+ /** The customer session token pair returned by the auth relay. */
5
+ interface Tokens {
6
+ token: string;
7
+ refreshToken: string;
8
+ }
9
+ /**
10
+ * Where the client persists the customer's session. Defaults to in-memory.
11
+ * Browser apps pass `localStorageTokenStore()`; SSR / native pass their own.
12
+ *
13
+ * Sync for the web-first scaffold. Async stores (e.g. secure storage) are a
14
+ * follow-up — they will widen these to `| Promise<...>`.
15
+ */
16
+ interface TokenStore {
17
+ get(): Tokens | null;
18
+ set(tokens: Tokens | null): void;
19
+ }
20
+ /** Minimal fetch surface the client needs — injectable for tests / SSR. */
21
+ type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
22
+ interface BowlosClientConfig {
23
+ /** Brand publishable API key, sent as `X-BowlOS-Api-Key` on every request. */
24
+ apiKey: string;
25
+ /**
26
+ * Gateway base URL, including the version prefix, e.g.
27
+ * `https://<deployment>.convex.site/api/public/v1`. A trailing slash is fine.
28
+ */
29
+ baseUrl: string;
30
+ /** Session persistence. Defaults to an in-memory store (lost on reload). */
31
+ tokenStore?: TokenStore;
32
+ /** Override `fetch` (tests, SSR polyfills). Defaults to `globalThis.fetch`. */
33
+ fetch?: FetchLike;
34
+ }
35
+ /** The signed-in customer, as returned by `/auth/me`. Extra fields are passed
36
+ * through so the shape can grow server-side without an SDK release. */
37
+ interface Customer {
38
+ _id: string;
39
+ brandId: string;
40
+ displayId: string;
41
+ fullName: string;
42
+ email: string;
43
+ mobile?: string | null;
44
+ marketingOptIn?: boolean;
45
+ preferredCenterId?: string | null;
46
+ [key: string]: unknown;
47
+ }
48
+ /** Result of `/auth/probe` — the three-state session bootstrap. */
49
+ type AuthState = "unauthenticated" | "authed_no_customer" | "linked";
50
+ /** Result of `GET /ping` — a cheap health + key-validity probe. `mode` reports
51
+ * whether this is a `live` or `test` key; `authenticated` is true when a valid
52
+ * customer bearer happened to be attached. */
53
+ interface PingResult {
54
+ service: string;
55
+ version: string;
56
+ brandId: string;
57
+ mode: "live" | "test";
58
+ authenticated: boolean;
59
+ }
60
+ /** Profile fields collected when linking a freshly-signed-up auth user to a
61
+ * customer record (the second half of sign-up). */
62
+ interface LinkProfile {
63
+ fullName: string;
64
+ email: string;
65
+ mobile?: string;
66
+ marketingOptIn?: boolean;
67
+ }
68
+
69
+ /**
70
+ * BowlosClient — the framework-agnostic core of the Reservations SDK.
71
+ *
72
+ * It is a thin, typed client for the public API gateway (`/api/public/v1/*`):
73
+ * - sends the brand API key (`X-BowlOS-Api-Key`) on every request,
74
+ * - attaches the customer bearer token on authenticated calls,
75
+ * - parses the `{ ok, data | error }` envelope and throws a typed
76
+ * `BowlosApiError` on failure,
77
+ * - owns the customer session: sign-in / sign-up / link / sign-out, plus
78
+ * a transparent refresh-and-retry-once when a session has expired.
79
+ *
80
+ * The React layer (hooks + components) wraps this; nothing here imports React.
81
+ */
82
+
83
+ /** A `TokenStore` backed by `localStorage` for browser apps. No-ops under SSR
84
+ * / environments without `localStorage`. */
85
+ declare function localStorageTokenStore(storageKey?: string): TokenStore;
86
+ declare class BowlosClient {
87
+ private readonly apiKey;
88
+ private readonly baseUrl;
89
+ private readonly store;
90
+ private readonly fetchFn;
91
+ constructor(config: BowlosClientConfig);
92
+ /** Is there a stored session right now? (Does not validate it server-side.) */
93
+ isAuthenticated(): boolean;
94
+ /** The current token pair, if any (rarely needed directly). */
95
+ getTokens(): Tokens | null;
96
+ /**
97
+ * Health + key-validity probe (`GET /ping`). Resolves with the gateway's
98
+ * service info when the API key is accepted; throws a `BowlosApiError` whose
99
+ * `.code` distinguishes the failure (`NETWORK_ERROR`, `API_KEY_INVALID`,
100
+ * `ORIGIN_NOT_ALLOWED`, `RATE_LIMITED`, …). Cheap enough to call on boot, and
101
+ * the basis for `runDoctor`.
102
+ */
103
+ ping(): Promise<PingResult>;
104
+ private request;
105
+ /**
106
+ * Call a gateway route by name (`POST /api/public/v1/<name>`), returning the
107
+ * unwrapped `data`. Set `{ auth: true }` to attach the bearer token and
108
+ * enable refresh-and-retry on an expired session.
109
+ */
110
+ call<T = unknown>(name: string, args?: Record<string, unknown>, opts?: {
111
+ auth?: boolean;
112
+ method?: "GET" | "POST";
113
+ }): Promise<T>;
114
+ private callInternal;
115
+ /** Exchange the stored refresh token for a fresh pair. Clears the session if
116
+ * the refresh token is itself invalid/expired. Returns success. */
117
+ private tryRefresh;
118
+ /** Sign an existing customer in; stores the session on success. */
119
+ signIn(email: string, password: string): Promise<Tokens>;
120
+ /** Create a login (the auth half of sign-up); stores the session. Follow with
121
+ * `link()` to attach the customer profile. */
122
+ signUp(email: string, password: string): Promise<Tokens>;
123
+ /** Link the signed-in auth user to a customer profile at the brand. */
124
+ link(profile: LinkProfile): Promise<unknown>;
125
+ /** End the session (best-effort server call; always clears locally). */
126
+ signOut(): Promise<void>;
127
+ /** Session bootstrap: unauthenticated / authed-no-customer / linked.
128
+ * GET — matches the gateway's `GET /auth/probe` route. */
129
+ probe(): Promise<AuthState>;
130
+ /** The signed-in customer's profile, or null.
131
+ * GET — matches the gateway's `GET /auth/me` route. */
132
+ me(): Promise<Customer | null>;
133
+ }
134
+ /** Create a configured client. */
135
+ declare function createBowlosClient(config: BowlosClientConfig): BowlosClient;
136
+
137
+ /**
138
+ * Error model for the BowlOS Reservations SDK.
139
+ *
140
+ * Every failed gateway call surfaces as a single `BowlosApiError` carrying a
141
+ * stable `code` (string), the HTTP `status`, and — for rate limits — a
142
+ * `retryAfterSeconds`. The gateway normalizes the backend's two error
143
+ * conventions (thrown ConvexError + `{ ok:false }` envelopes) into one JSON
144
+ * shape; this class is the client-side mirror of that shape, so consumers
145
+ * branch on `error.code`, never on message text.
146
+ */
147
+ /** Stable error codes the gateway / backend can return. Open set — treat
148
+ * `code` as a string and match against these for known cases. */
149
+ declare const BOWLOS_ERROR_CODES: {
150
+ readonly API_KEY_MISSING: "API_KEY_MISSING";
151
+ readonly API_KEY_INVALID: "API_KEY_INVALID";
152
+ readonly ORIGIN_NOT_ALLOWED: "ORIGIN_NOT_ALLOWED";
153
+ readonly RATE_LIMITED: "RATE_LIMITED";
154
+ readonly INVALID_CREDENTIALS: "INVALID_CREDENTIALS";
155
+ readonly SIGNUP_FAILED: "SIGNUP_FAILED";
156
+ readonly VALIDATION_FAILED: "VALIDATION_FAILED";
157
+ readonly PERMISSION_DENIED: "PERMISSION_DENIED";
158
+ readonly SCOPE_REVOKED: "SCOPE_REVOKED";
159
+ readonly NOT_FOUND: "NOT_FOUND";
160
+ readonly VERSION_CONFLICT: "VERSION_CONFLICT";
161
+ readonly PRICING_SNAPSHOT_STALE: "PRICING_SNAPSHOT_STALE";
162
+ readonly PAYMENTS_NOT_CONNECTED: "PAYMENTS_NOT_CONNECTED";
163
+ readonly CONNECT_ACCOUNT_RESTRICTED: "CONNECT_ACCOUNT_RESTRICTED";
164
+ readonly CHECKOUT_EXPIRED: "CHECKOUT_EXPIRED";
165
+ readonly NETWORK_ERROR: "NETWORK_ERROR";
166
+ readonly UNKNOWN: "ERROR";
167
+ };
168
+ type BowlosErrorCode = (typeof BOWLOS_ERROR_CODES)[keyof typeof BOWLOS_ERROR_CODES] | (string & {});
169
+ interface BowlosApiErrorOptions {
170
+ retryAfterSeconds?: number;
171
+ cause?: unknown;
172
+ }
173
+ declare class BowlosApiError extends Error {
174
+ /** Stable, machine-readable code. Branch on this, not on `message`. */
175
+ readonly code: BowlosErrorCode;
176
+ /** HTTP status (0 for a network failure before any response). */
177
+ readonly status: number;
178
+ /** Seconds to wait before retrying — present only on `RATE_LIMITED`. */
179
+ readonly retryAfterSeconds?: number;
180
+ constructor(code: BowlosErrorCode, message: string, status: number, options?: BowlosApiErrorOptions);
181
+ /** Too many requests — caller should back off `retryAfterSeconds`. */
182
+ get isRateLimited(): boolean;
183
+ /** Bad/expired login. The session could not be established or has lapsed. */
184
+ get isAuthError(): boolean;
185
+ /** Wrong/missing API key or a disallowed origin — a site-config problem,
186
+ * not something the end customer can fix. */
187
+ get isConfigError(): boolean;
188
+ }
189
+
190
+ /**
191
+ * Typed data surface for @bowlos/reservations — booking-funnel reads.
192
+ *
193
+ * Arg shapes mirror the gateway functions; result shapes type the headline
194
+ * fields and pass the rest through (`[key: string]: unknown`), so the backend's
195
+ * full breakdown can grow without an SDK release. Each read has a
196
+ * framework-agnostic function here and a React hook in `hooks.tsx`, sharing
197
+ * these types.
198
+ *
199
+ * This file is React-free, so it's exported from the core entry. The hooks
200
+ * (React) live in `hooks.tsx` under the React entry.
201
+ */
202
+
203
+ /** Inputs for `checkAvailability`. Times are minutes-of-day in the Center's tz. */
204
+ type AvailabilityArgs = {
205
+ productId: string;
206
+ dateISO: string;
207
+ startMinuteOfDay: number;
208
+ endMinuteOfDay: number;
209
+ };
210
+ interface AvailabilityResult {
211
+ totalUnits: number;
212
+ busyUnitIds: string[];
213
+ }
214
+ type PricingMode = "per_unit_per_hour" | "per_person_per_hour" | "per_game";
215
+ type BookingAddonSelection = {
216
+ addonId: string;
217
+ quantity: number;
218
+ };
219
+ /** Inputs for `bookingPreview` (the authoritative price quote). */
220
+ type BookingPreviewArgs = {
221
+ centerId: string;
222
+ productId: string;
223
+ dateISO: string;
224
+ startMinuteOfDay: number;
225
+ endMinuteOfDay: number;
226
+ mode: PricingMode;
227
+ units?: number;
228
+ persons?: number;
229
+ games?: number;
230
+ addons?: BookingAddonSelection[];
231
+ shareToken?: string;
232
+ subtypeId?: string;
233
+ };
234
+ /** The price quote. Headline fields are typed; the engine's full breakdown
235
+ * (line items, discounts, tax, credit) is passed through. */
236
+ interface BookingQuote {
237
+ reservationFee: Record<string, unknown> | null;
238
+ totalCentsPerPlan: Array<{
239
+ pricePlanId: string;
240
+ totalCents: number;
241
+ }>;
242
+ [key: string]: unknown;
243
+ }
244
+ /** Free units for a product/date/time window (anonymous). */
245
+ declare function checkAvailability(client: BowlosClient, args: AvailabilityArgs): Promise<AvailabilityResult>;
246
+ /** Authoritative price quote for the chosen inputs (anonymous; a signed-in
247
+ * session unlocks member rates + account credit). */
248
+ declare function bookingPreview(client: BowlosClient, args: BookingPreviewArgs): Promise<BookingQuote>;
249
+ /** Convenience: free units = total minus the busy set (never negative). */
250
+ declare function availableUnitCount(availability: AvailabilityResult): number;
251
+ /** Customer identity for a booking (collected in the booking form; the server
252
+ * links/creates the customer per the booking-flow-only signup rule). */
253
+ type BookingCustomer = {
254
+ fullName: string;
255
+ email: string;
256
+ mobile?: string;
257
+ marketingOptIn: boolean;
258
+ };
259
+ /** Inputs for `createAnonymousBooking` — places the inventory hold. */
260
+ type CreateBookingArgs = {
261
+ centerId: string;
262
+ productId: string;
263
+ dateISO: string;
264
+ startMinuteOfDay: number;
265
+ endMinuteOfDay: number;
266
+ mode: PricingMode;
267
+ units?: number;
268
+ persons?: number;
269
+ games?: number;
270
+ addons?: BookingAddonSelection[];
271
+ customer: BookingCustomer;
272
+ /** Apply account credit (requires a signed-in customer). */
273
+ applyCredit?: boolean;
274
+ /** Idempotency key for the create. The SDK generates one if omitted. */
275
+ idempotencyKey?: string;
276
+ shareToken?: string;
277
+ subtypeId?: string;
278
+ };
279
+ /** Result of placing a booking. The hold→pay path returns `checkoutRefToken`
280
+ * with `requiresPayment: true`; a credit-covered / $0 booking returns the
281
+ * materialized `reservationId` + `reservationDisplayId` with
282
+ * `requiresPayment: false`. Headline fields typed; the rest passes through. */
283
+ interface BookingHold {
284
+ checkoutRefToken?: string;
285
+ reservationId?: string | null;
286
+ reservationDisplayId?: string | null;
287
+ requiresPayment: boolean;
288
+ finalCents: number;
289
+ appliedCreditCents: number;
290
+ paidCents?: number;
291
+ holdExpiresAt?: number;
292
+ replayed?: boolean;
293
+ [key: string]: unknown;
294
+ }
295
+ type CheckoutStatus = "not_found" | "pending_payment" | "paid_materialized" | "expired" | "payment_failed_retryable" | "abandoned";
296
+ interface CheckoutStatusResult {
297
+ status: CheckoutStatus;
298
+ reservationDisplayId: string | null;
299
+ reservationId: string | null;
300
+ }
301
+ /** Stripe (Connect) PaymentIntent data for the UI layer to render Elements.
302
+ * The SDK does NOT load Stripe.js — initialize it with `connectedAccountId`
303
+ * (the operator's connected account) + `clientSecret`. */
304
+ interface PaymentIntentInfo {
305
+ paymentIntentId: string;
306
+ clientSecret: string;
307
+ amountCents: number;
308
+ customerId: string;
309
+ ephemeralKey: string;
310
+ customerSessionClientSecret: string;
311
+ connectedAccountId: string;
312
+ }
313
+ /** Browser/Node-safe idempotency key for booking creates. */
314
+ declare function generateIdempotencyKey(): string;
315
+ /** Place the inventory hold + open a checkout. Sends the session when present
316
+ * (member rates + account credit); falls back to anonymous. */
317
+ declare function createBooking(client: BowlosClient, args: CreateBookingArgs): Promise<BookingHold>;
318
+ /** Mint the Stripe Connect PaymentIntent for a held checkout (by refToken). */
319
+ declare function createCheckoutPaymentIntent(client: BowlosClient, refToken: string): Promise<PaymentIntentInfo>;
320
+ /** Poll the hold→pay→materialize state for a checkout (by refToken). */
321
+ declare function getCheckoutStatus(client: BowlosClient, refToken: string): Promise<CheckoutStatusResult>;
322
+ /** Release the hold + cancel the checkout (the "Back" button). */
323
+ declare function abandonCheckout(client: BowlosClient, refToken: string): Promise<{
324
+ ok: boolean;
325
+ }>;
326
+
327
+ /**
328
+ * Typed account + flash reads for @bowlos/reservations.
329
+ *
330
+ * Session-scoped account reads (require a signed-in customer) and the
331
+ * session-aware flash-sale reads. Args are typed precisely — every account read
332
+ * is brand-scoped. Results are generic (`<T = unknown>`): parameterize with your
333
+ * own shape, or read `unknown` and narrow. (The backend return shapes are rich
334
+ * and evolving; the SDK doesn't pin them here.) Each read has a framework-agnostic
335
+ * function here and a React hook in `hooks.tsx`.
336
+ */
337
+
338
+ /** Every account read is scoped to the customer's Brand. */
339
+ type BrandScoped = {
340
+ brandId: string;
341
+ };
342
+ type ReservationDetailArgs = {
343
+ brandId: string;
344
+ displayId: string;
345
+ };
346
+ type MembershipDetailArgs = {
347
+ brandId: string;
348
+ membershipId: string;
349
+ };
350
+ type FlashSaleArgs = {
351
+ slug: string;
352
+ };
353
+ type FlashBookingOptionsArgs = {
354
+ slug: string;
355
+ itemId: string;
356
+ };
357
+ declare function getMyReservations<T = unknown>(client: BowlosClient, args: BrandScoped): Promise<T>;
358
+ declare function getMyReservationDetail<T = unknown>(client: BowlosClient, args: ReservationDetailArgs): Promise<T>;
359
+ declare function getMyMemberships<T = unknown>(client: BowlosClient, args: BrandScoped): Promise<T>;
360
+ declare function getMyMembershipDetail<T = unknown>(client: BowlosClient, args: MembershipDetailArgs): Promise<T>;
361
+ declare function getMyLoyalty<T = unknown>(client: BowlosClient, args: BrandScoped): Promise<T>;
362
+ declare function getMyCredits<T = unknown>(client: BowlosClient, args: BrandScoped): Promise<T>;
363
+ declare function getMyPasses<T = unknown>(client: BowlosClient, args: BrandScoped): Promise<T>;
364
+ declare function getFlashSale<T = unknown>(client: BowlosClient, args: FlashSaleArgs): Promise<T>;
365
+ declare function getFlashSaleBookingOptions<T = unknown>(client: BowlosClient, args: FlashBookingOptionsArgs): Promise<T>;
366
+
367
+ export { type AuthState as A, BOWLOS_ERROR_CODES as B, type CheckoutStatus as C, createBowlosClient as D, createCheckoutPaymentIntent as E, type FetchLike as F, generateIdempotencyKey as G, getCheckoutStatus as H, getFlashSale as I, getFlashSaleBookingOptions as J, getMyCredits as K, type LinkProfile as L, type MembershipDetailArgs as M, getMyLoyalty as N, getMyMembershipDetail as O, type PaymentIntentInfo as P, getMyMemberships as Q, type ReservationDetailArgs as R, getMyPasses as S, type TokenStore as T, getMyReservationDetail as U, getMyReservations as V, localStorageTokenStore as W, type AvailabilityArgs as a, type AvailabilityResult as b, type BookingAddonSelection as c, type BookingCustomer as d, type BookingHold as e, type BookingPreviewArgs as f, type BookingQuote as g, BowlosApiError as h, type BowlosApiErrorOptions as i, BowlosClient as j, type BowlosClientConfig as k, type BowlosErrorCode as l, type BrandScoped as m, type CheckoutStatusResult as n, type CreateBookingArgs as o, type Customer as p, type FlashBookingOptionsArgs as q, type FlashSaleArgs as r, type PingResult as s, type PricingMode as t, type Tokens as u, abandonCheckout as v, availableUnitCount as w, bookingPreview as x, checkAvailability as y, createBooking as z };
@@ -0,0 +1,174 @@
1
+ import { createBowlosClient, BOWLOS_ERROR_CODES, BowlosApiError } from './chunk-TCYTNCUL.js';
2
+
3
+ // src/doctor.ts
4
+ var GATEWAY_SUFFIX = "/api/public/v1";
5
+ async function runDoctor(options) {
6
+ const checks = [];
7
+ const report = { ok: true, checks, baseUrl: options.baseUrl };
8
+ const configIssues = [];
9
+ if (!options.apiKey) configIssues.push("`apiKey` is empty");
10
+ let parsedUrl = null;
11
+ try {
12
+ parsedUrl = new URL(options.baseUrl);
13
+ } catch {
14
+ configIssues.push("`baseUrl` is not a valid URL");
15
+ }
16
+ if (configIssues.length > 0) {
17
+ checks.push({
18
+ id: "config",
19
+ title: "Client configuration",
20
+ status: "fail",
21
+ detail: `${configIssues.join("; ")}.`,
22
+ fix: "Pass a brand API key and the gateway base URL, e.g. https://<deployment>.convex.site/api/public/v1"
23
+ });
24
+ report.ok = false;
25
+ return report;
26
+ }
27
+ const urlMisaimed = parsedUrl !== null && !parsedUrl.pathname.replace(/\/+$/, "").endsWith(GATEWAY_SUFFIX);
28
+ checks.push({
29
+ id: "config",
30
+ title: "Client configuration",
31
+ status: urlMisaimed ? "warn" : "pass",
32
+ detail: urlMisaimed ? `baseUrl "${options.baseUrl}" doesn't end with ${GATEWAY_SUFFIX} \u2014 it should point at the gateway, not the site root.` : "API key present; base URL well-formed.",
33
+ fix: urlMisaimed ? `Use the gateway URL, e.g. ${parsedUrl?.origin}${GATEWAY_SUFFIX}` : void 0
34
+ });
35
+ const client = createBowlosClient({
36
+ apiKey: options.apiKey,
37
+ baseUrl: options.baseUrl,
38
+ fetch: options.fetch
39
+ });
40
+ let ping = null;
41
+ try {
42
+ ping = await client.ping();
43
+ report.brandId = ping.brandId;
44
+ report.mode = ping.mode;
45
+ checks.push({
46
+ id: "gateway",
47
+ title: "Gateway reachable",
48
+ status: "pass",
49
+ detail: `Reached ${options.baseUrl} (service "${ping.service}", ${ping.version}).`
50
+ });
51
+ checks.push({
52
+ id: "api-key",
53
+ title: "API key accepted",
54
+ status: "pass",
55
+ detail: `Key valid for brand ${ping.brandId} \u2014 mode: ${ping.mode}.`
56
+ });
57
+ } catch (e) {
58
+ const err = e instanceof BowlosApiError ? e : null;
59
+ const code = err?.code ?? BOWLOS_ERROR_CODES.UNKNOWN;
60
+ const reached = err !== null && err.status !== 0 && code !== BOWLOS_ERROR_CODES.NETWORK_ERROR && code !== BOWLOS_ERROR_CODES.NOT_FOUND;
61
+ checks.push({
62
+ id: "gateway",
63
+ title: "Gateway reachable",
64
+ status: reached ? "pass" : "fail",
65
+ detail: reached ? `Reached ${options.baseUrl}.` : code === BOWLOS_ERROR_CODES.NETWORK_ERROR ? `Could not reach ${options.baseUrl} (network error).` : `No public-API gateway responded at ${options.baseUrl}.`,
66
+ fix: reached ? void 0 : "Check the base URL, that the Convex deployment is live, and that the public-API routes are deployed."
67
+ });
68
+ if (code === BOWLOS_ERROR_CODES.RATE_LIMITED) {
69
+ checks.push({
70
+ id: "api-key",
71
+ title: "API key accepted",
72
+ status: "pass",
73
+ detail: "Key accepted (this probe was rate-limited)."
74
+ });
75
+ checks.push({
76
+ id: "rate-limit",
77
+ title: "Rate-limit headroom",
78
+ status: "warn",
79
+ detail: `Currently rate-limited${err?.retryAfterSeconds ? ` \u2014 retry after ${err.retryAfterSeconds}s` : ""}.`,
80
+ fix: "Back off and retry; raise the key's per-minute limit if your real traffic is higher."
81
+ });
82
+ } else if (code === BOWLOS_ERROR_CODES.ORIGIN_NOT_ALLOWED) {
83
+ checks.push({
84
+ id: "api-key",
85
+ title: "API key accepted",
86
+ status: "pass",
87
+ detail: "Key accepted; the request was blocked on origin."
88
+ });
89
+ checks.push({
90
+ id: "origin",
91
+ title: "Origin allow-listed",
92
+ status: "fail",
93
+ detail: "The request origin is not on the key's allow-list.",
94
+ fix: `Add your site origin${options.origin ? ` (${options.origin})` : ""} to the API key's allowed origins.`
95
+ });
96
+ } else if (reached) {
97
+ checks.push({
98
+ id: "api-key",
99
+ title: "API key accepted",
100
+ status: "fail",
101
+ detail: code === BOWLOS_ERROR_CODES.API_KEY_INVALID || code === BOWLOS_ERROR_CODES.API_KEY_MISSING ? "The gateway rejected the API key." : `The gateway returned ${code}.`,
102
+ fix: "Mint or rotate a brand API key in the operator admin (Super-Admin \u2192 API keys) and use that value."
103
+ });
104
+ } else {
105
+ checks.push({
106
+ id: "api-key",
107
+ title: "API key accepted",
108
+ status: "skip",
109
+ detail: "Skipped \u2014 the gateway wasn't reachable."
110
+ });
111
+ }
112
+ }
113
+ if (!checks.some((c) => c.id === "origin")) {
114
+ const browserOrigin = typeof window !== "undefined" && typeof window.location?.origin === "string" ? window.location.origin : null;
115
+ if (ping !== null && browserOrigin !== null) {
116
+ checks.push({
117
+ id: "origin",
118
+ title: "Origin allow-listed",
119
+ status: "pass",
120
+ detail: `This origin (${browserOrigin}) is allow-listed for the key.`
121
+ });
122
+ } else {
123
+ checks.push({
124
+ id: "origin",
125
+ title: "Origin allow-listed",
126
+ status: "skip",
127
+ detail: "Origin allow-listing is enforced only for browser requests, so it can't be verified from a CLI.",
128
+ fix: `Ensure your deployed site origin${options.origin ? ` (${options.origin})` : ""} is on the key's allowed-origins list; load the site and watch for ORIGIN_NOT_ALLOWED.`
129
+ });
130
+ }
131
+ }
132
+ if (ping !== null && options.skipDataRead !== true) {
133
+ try {
134
+ const data = await client.call("listPublicCenters", { brandId: ping.brandId });
135
+ const innerError = typeof data === "object" && data !== null && data.ok === false;
136
+ checks.push({
137
+ id: "data-read",
138
+ title: "Data passthrough",
139
+ status: innerError ? "warn" : "pass",
140
+ detail: innerError ? "Reached the data plane, but listPublicCenters returned an error envelope." : "Anonymous read (listPublicCenters) succeeded \u2014 gateway \u2192 query passthrough works.",
141
+ fix: innerError ? "Confirm the brand has at least one published center." : void 0
142
+ });
143
+ } catch (e) {
144
+ const err = e instanceof BowlosApiError ? e : null;
145
+ checks.push({
146
+ id: "data-read",
147
+ title: "Data passthrough",
148
+ status: "warn",
149
+ detail: `An anonymous read failed${err ? ` (${err.code})` : ""}.`,
150
+ fix: "Key + gateway are fine; this read may need a published center or differ by brand. Safe to ignore if your booking reads work."
151
+ });
152
+ }
153
+ } else if (ping === null) {
154
+ checks.push({
155
+ id: "data-read",
156
+ title: "Data passthrough",
157
+ status: "skip",
158
+ detail: "Skipped \u2014 needs a reachable gateway."
159
+ });
160
+ }
161
+ checks.push({
162
+ id: "payments",
163
+ title: "Payments connected",
164
+ status: "skip",
165
+ detail: "Stripe Connect status isn't exposed over the public API yet, so the doctor can't verify it here.",
166
+ fix: "Confirm the operator's Stripe account is connected + charges-enabled in the admin (Payments \u2192 Connect)."
167
+ });
168
+ report.ok = !checks.some((c) => c.status === "fail");
169
+ return report;
170
+ }
171
+
172
+ export { runDoctor };
173
+ //# sourceMappingURL=chunk-T5DDHWEC.js.map
174
+ //# sourceMappingURL=chunk-T5DDHWEC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/doctor.ts"],"names":[],"mappings":";;;AA0DA,IAAM,cAAA,GAAiB,gBAAA;AAIvB,eAAsB,UAAU,OAAA,EAA+C;AAC7E,EAAA,MAAM,SAAwB,EAAC;AAC/B,EAAA,MAAM,SAAuB,EAAE,EAAA,EAAI,MAAM,MAAA,EAAQ,OAAA,EAAS,QAAQ,OAAA,EAAQ;AAG1E,EAAA,MAAM,eAAyB,EAAC;AAChC,EAAA,IAAI,CAAC,OAAA,CAAQ,MAAA,EAAQ,YAAA,CAAa,KAAK,mBAAmB,CAAA;AAC1D,EAAA,IAAI,SAAA,GAAwB,IAAA;AAC5B,EAAA,IAAI;AACF,IAAA,SAAA,GAAY,IAAI,GAAA,CAAI,OAAA,CAAQ,OAAO,CAAA;AAAA,EACrC,CAAA,CAAA,MAAQ;AACN,IAAA,YAA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,EAAQ,MAAA;AAAA,MACR,MAAA,EAAQ;AAAA,KACT,CAAA;AAAA,EACH;AAIA,EAAA,MAAA,CAAO,IAAA,CAAK;AAAA,IACV,EAAA,EAAI,UAAA;AAAA,IACJ,KAAA,EAAO,oBAAA;AAAA,IACP,MAAA,EAAQ,MAAA;AAAA,IACR,MAAA,EAAQ,kGAAA;AAAA,IACR,GAAA,EAAK;AAAA,GACN,CAAA;AAED,EAAA,MAAA,CAAO,EAAA,GAAK,CAAC,MAAA,CAAO,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,WAAW,MAAM,CAAA;AACnD,EAAA,OAAO,MAAA;AACT","file":"chunk-T5DDHWEC.js","sourcesContent":["/**\n * `runDoctor` — a setup-readiness oracle for a site built on @bowlos/reservations.\n *\n * It runs a short sequence of checks against a configured gateway + API key and\n * returns a structured report (pass / warn / fail / skip), each with a one-line\n * fix when it isn't a pass. The point is to make per-site setup self-debuggable\n * — it walks the failure modes a new center site actually hits, in order:\n * config → gateway reachable → API key valid → origin allow-listed → data plane.\n *\n * Framework-agnostic and dependency-free: it builds a `BowlosClient`, leans on\n * `client.ping()` (one call covers reachability + key + origin + rate-limit),\n * and reports honestly — checks it can't run from the current environment are\n * `skip`ped with guidance rather than faked. The `bowlos doctor` CLI is a thin\n * wrapper that pretty-prints the report.\n */\nimport { createBowlosClient } from \"./client\";\nimport { BowlosApiError, BOWLOS_ERROR_CODES } from \"./errors\";\nimport type { FetchLike, PingResult } from \"./types\";\n\nexport type DoctorCheckStatus = \"pass\" | \"warn\" | \"fail\" | \"skip\";\n\nexport interface DoctorCheck {\n /** Stable id (`config` | `gateway` | `api-key` | `origin` | `rate-limit` | `data-read` | `payments`). */\n id: string;\n title: string;\n status: DoctorCheckStatus;\n detail: string;\n /** One-line remediation, present when `status` isn't `pass`. */\n fix?: string;\n}\n\nexport interface DoctorReport {\n /** True when no check failed (warnings and skips are tolerated). */\n ok: boolean;\n checks: DoctorCheck[];\n /** Echoed back so the CLI can show what it probed. */\n baseUrl: string;\n /** From a successful ping — the key's brand + mode. */\n brandId?: string;\n mode?: \"live\" | \"test\";\n}\n\nexport interface DoctorOptions {\n apiKey: string;\n baseUrl: string;\n /**\n * The deployed site origin. Origin allow-listing is enforced by the gateway\n * only for browser requests (Origin is a forbidden header from Node), so this\n * can be actively verified only in a browser; from Node it informs the\n * skip-guidance message.\n */\n origin?: string;\n /** Skip the (anonymous) data-plane read even when a brand is known. */\n skipDataRead?: boolean;\n /** Injectable transport (tests / SSR polyfills). */\n fetch?: FetchLike;\n}\n\nconst GATEWAY_SUFFIX = \"/api/public/v1\";\n\n/** Run the readiness checks and return a structured report. Never throws — every\n * failure mode is captured as a check. */\nexport async function runDoctor(options: DoctorOptions): Promise<DoctorReport> {\n const checks: DoctorCheck[] = [];\n const report: DoctorReport = { ok: true, checks, baseUrl: options.baseUrl };\n\n // 1) config — can we even build a client?\n const configIssues: string[] = [];\n if (!options.apiKey) configIssues.push(\"`apiKey` is empty\");\n let parsedUrl: URL | null = null;\n try {\n parsedUrl = new URL(options.baseUrl);\n } catch {\n configIssues.push(\"`baseUrl` is not a valid URL\");\n }\n if (configIssues.length > 0) {\n checks.push({\n id: \"config\",\n title: \"Client configuration\",\n status: \"fail\",\n detail: `${configIssues.join(\"; \")}.`,\n fix: \"Pass a brand API key and the gateway base URL, e.g. https://<deployment>.convex.site/api/public/v1\",\n });\n report.ok = false;\n return report; // can't probe without a valid client config\n }\n\n const urlMisaimed =\n parsedUrl !== null && !parsedUrl.pathname.replace(/\\/+$/, \"\").endsWith(GATEWAY_SUFFIX);\n checks.push({\n id: \"config\",\n title: \"Client configuration\",\n status: urlMisaimed ? \"warn\" : \"pass\",\n detail: urlMisaimed\n ? `baseUrl \"${options.baseUrl}\" doesn't end with ${GATEWAY_SUFFIX} — it should point at the gateway, not the site root.`\n : \"API key present; base URL well-formed.\",\n fix: urlMisaimed ? `Use the gateway URL, e.g. ${parsedUrl?.origin}${GATEWAY_SUFFIX}` : undefined,\n });\n\n const client = createBowlosClient({\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n fetch: options.fetch,\n });\n\n // 2) one ping covers: gateway reachable + key valid + (browser) origin + rate-limit.\n let ping: PingResult | null = null;\n try {\n ping = await client.ping();\n report.brandId = ping.brandId;\n report.mode = ping.mode;\n checks.push({\n id: \"gateway\",\n title: \"Gateway reachable\",\n status: \"pass\",\n detail: `Reached ${options.baseUrl} (service \"${ping.service}\", ${ping.version}).`,\n });\n checks.push({\n id: \"api-key\",\n title: \"API key accepted\",\n status: \"pass\",\n detail: `Key valid for brand ${ping.brandId} — mode: ${ping.mode}.`,\n });\n } catch (e) {\n const err = e instanceof BowlosApiError ? e : null;\n const code = err?.code ?? BOWLOS_ERROR_CODES.UNKNOWN;\n // A network error (status 0) or a router 404 means no real gateway answered;\n // any other coded envelope means the gateway responded (and judged the key).\n const reached =\n err !== null && err.status !== 0 && code !== BOWLOS_ERROR_CODES.NETWORK_ERROR && code !== BOWLOS_ERROR_CODES.NOT_FOUND;\n\n checks.push({\n id: \"gateway\",\n title: \"Gateway reachable\",\n status: reached ? \"pass\" : \"fail\",\n detail: reached\n ? `Reached ${options.baseUrl}.`\n : code === BOWLOS_ERROR_CODES.NETWORK_ERROR\n ? `Could not reach ${options.baseUrl} (network error).`\n : `No public-API gateway responded at ${options.baseUrl}.`,\n fix: reached\n ? undefined\n : \"Check the base URL, that the Convex deployment is live, and that the public-API routes are deployed.\",\n });\n\n if (code === BOWLOS_ERROR_CODES.RATE_LIMITED) {\n checks.push({\n id: \"api-key\",\n title: \"API key accepted\",\n status: \"pass\",\n detail: \"Key accepted (this probe was rate-limited).\",\n });\n checks.push({\n id: \"rate-limit\",\n title: \"Rate-limit headroom\",\n status: \"warn\",\n detail: `Currently rate-limited${err?.retryAfterSeconds ? ` — retry after ${err.retryAfterSeconds}s` : \"\"}.`,\n fix: \"Back off and retry; raise the key's per-minute limit if your real traffic is higher.\",\n });\n } else if (code === BOWLOS_ERROR_CODES.ORIGIN_NOT_ALLOWED) {\n checks.push({\n id: \"api-key\",\n title: \"API key accepted\",\n status: \"pass\",\n detail: \"Key accepted; the request was blocked on origin.\",\n });\n checks.push({\n id: \"origin\",\n title: \"Origin allow-listed\",\n status: \"fail\",\n detail: \"The request origin is not on the key's allow-list.\",\n fix: `Add your site origin${options.origin ? ` (${options.origin})` : \"\"} to the API key's allowed origins.`,\n });\n } else if (reached) {\n checks.push({\n id: \"api-key\",\n title: \"API key accepted\",\n status: \"fail\",\n detail:\n code === BOWLOS_ERROR_CODES.API_KEY_INVALID || code === BOWLOS_ERROR_CODES.API_KEY_MISSING\n ? \"The gateway rejected the API key.\"\n : `The gateway returned ${code}.`,\n fix: \"Mint or rotate a brand API key in the operator admin (Super-Admin → API keys) and use that value.\",\n });\n } else {\n checks.push({\n id: \"api-key\",\n title: \"API key accepted\",\n status: \"skip\",\n detail: \"Skipped — the gateway wasn't reachable.\",\n });\n }\n }\n\n // 3) origin — only actively verifiable in a browser (Origin is a forbidden\n // header from Node). A successful ping in a browser means the current\n // origin IS allow-listed; otherwise skip with guidance.\n if (!checks.some((c) => c.id === \"origin\")) {\n const browserOrigin =\n typeof window !== \"undefined\" && typeof window.location?.origin === \"string\"\n ? window.location.origin\n : null;\n if (ping !== null && browserOrigin !== null) {\n checks.push({\n id: \"origin\",\n title: \"Origin allow-listed\",\n status: \"pass\",\n detail: `This origin (${browserOrigin}) is allow-listed for the key.`,\n });\n } else {\n checks.push({\n id: \"origin\",\n title: \"Origin allow-listed\",\n status: \"skip\",\n detail: \"Origin allow-listing is enforced only for browser requests, so it can't be verified from a CLI.\",\n fix: `Ensure your deployed site origin${options.origin ? ` (${options.origin})` : \"\"} is on the key's allowed-origins list; load the site and watch for ORIGIN_NOT_ALLOWED.`,\n });\n }\n }\n\n // 4) data plane — a cheap anonymous read proves gateway → manifest → query → scope.\n if (ping !== null && options.skipDataRead !== true) {\n try {\n const data = await client.call<unknown>(\"listPublicCenters\", { brandId: ping.brandId });\n const innerError = typeof data === \"object\" && data !== null && (data as { ok?: boolean }).ok === false;\n checks.push({\n id: \"data-read\",\n title: \"Data passthrough\",\n status: innerError ? \"warn\" : \"pass\",\n detail: innerError\n ? \"Reached the data plane, but listPublicCenters returned an error envelope.\"\n : \"Anonymous read (listPublicCenters) succeeded — gateway → query passthrough works.\",\n fix: innerError ? \"Confirm the brand has at least one published center.\" : undefined,\n });\n } catch (e) {\n const err = e instanceof BowlosApiError ? e : null;\n checks.push({\n id: \"data-read\",\n title: \"Data passthrough\",\n status: \"warn\",\n detail: `An anonymous read failed${err ? ` (${err.code})` : \"\"}.`,\n fix: \"Key + gateway are fine; this read may need a published center or differ by brand. Safe to ignore if your booking reads work.\",\n });\n }\n } else if (ping === null) {\n checks.push({\n id: \"data-read\",\n title: \"Data passthrough\",\n status: \"skip\",\n detail: \"Skipped — needs a reachable gateway.\",\n });\n }\n\n // 5) payments — Stripe Connect status isn't exposed over the public API yet.\n // Honest skip (no faked pass) so the operator knows to verify it elsewhere.\n checks.push({\n id: \"payments\",\n title: \"Payments connected\",\n status: \"skip\",\n detail: \"Stripe Connect status isn't exposed over the public API yet, so the doctor can't verify it here.\",\n fix: \"Confirm the operator's Stripe account is connected + charges-enabled in the admin (Payments → Connect).\",\n });\n\n report.ok = !checks.some((c) => c.status === \"fail\");\n return report;\n}\n"]}