@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.
package/dist/cli.js ADDED
@@ -0,0 +1,106 @@
1
+ #!/usr/bin/env node
2
+ import { runDoctor } from './chunk-T5DDHWEC.js';
3
+ import './chunk-TCYTNCUL.js';
4
+
5
+ // src/cli.ts
6
+ function parseArgs(argv) {
7
+ const out = {};
8
+ for (let i = 0; i < argv.length; i++) {
9
+ const a = argv[i];
10
+ if (a === void 0) continue;
11
+ if (a.startsWith("--")) {
12
+ const key = a.slice(2);
13
+ const next = argv[i + 1];
14
+ if (next !== void 0 && !next.startsWith("--")) {
15
+ out[key] = next;
16
+ i++;
17
+ } else {
18
+ out[key] = true;
19
+ }
20
+ } else if (out._command === void 0) {
21
+ out._command = a;
22
+ }
23
+ }
24
+ return out;
25
+ }
26
+ var ICON = {
27
+ pass: "\u2713",
28
+ // ✓
29
+ warn: "\u26A0",
30
+ // ⚠
31
+ fail: "\u2717",
32
+ // ✗
33
+ skip: "\xB7"
34
+ // ·
35
+ };
36
+ function render(report) {
37
+ const lines = ["", `bowlos doctor \u2014 ${report.baseUrl}`];
38
+ if (report.brandId) lines.push(`brand ${report.brandId} \xB7 mode ${report.mode}`);
39
+ lines.push("");
40
+ for (const c of report.checks) {
41
+ lines.push(` ${ICON[c.status]} ${c.title}: ${c.detail}`);
42
+ if (c.fix && c.status !== "pass") lines.push(` \u2192 ${c.fix}`);
43
+ }
44
+ const fails = report.checks.filter((c) => c.status === "fail").length;
45
+ const warns = report.checks.filter((c) => c.status === "warn").length;
46
+ lines.push(
47
+ "",
48
+ report.ok ? warns > 0 ? `Ready, with ${warns} warning(s).` : "All checks passed \u2014 ready." : `${fails} check(s) failed \u2014 not ready.`,
49
+ ""
50
+ );
51
+ return lines.join("\n");
52
+ }
53
+ var HELP = [
54
+ "Usage: bowlos doctor [options]",
55
+ "",
56
+ "Validates a @bowlos/reservations setup against the gateway + API key.",
57
+ "",
58
+ "Options:",
59
+ " --api-key <key> Brand API key (or env BOWLOS_API_KEY)",
60
+ " --base-url <url> Gateway base URL (or env BOWLOS_BASE_URL)",
61
+ " --origin <url> Your deployed site origin (informs the allow-list note)",
62
+ " --skip-data-read Skip the anonymous data-plane read",
63
+ " --json Print the raw JSON report instead of the table",
64
+ " --help Show this help",
65
+ ""
66
+ ].join("\n");
67
+ async function main() {
68
+ const args = parseArgs(process.argv.slice(2));
69
+ const command = args._command ?? "doctor";
70
+ if (args.help === true || command === "help") {
71
+ process.stdout.write(`${HELP}
72
+ `);
73
+ return;
74
+ }
75
+ if (command !== "doctor") {
76
+ process.stderr.write(`Unknown command "${command}". Try: bowlos doctor --help
77
+ `);
78
+ process.exitCode = 1;
79
+ return;
80
+ }
81
+ const apiKey = (typeof args["api-key"] === "string" ? args["api-key"] : void 0) ?? process.env.BOWLOS_API_KEY ?? "";
82
+ const baseUrl = (typeof args["base-url"] === "string" ? args["base-url"] : void 0) ?? process.env.BOWLOS_BASE_URL ?? "";
83
+ if (!apiKey || !baseUrl) {
84
+ process.stderr.write(
85
+ "Missing --api-key / --base-url (or BOWLOS_API_KEY / BOWLOS_BASE_URL).\nRun `bowlos doctor --help`.\n"
86
+ );
87
+ process.exitCode = 1;
88
+ return;
89
+ }
90
+ const report = await runDoctor({
91
+ apiKey,
92
+ baseUrl,
93
+ origin: typeof args.origin === "string" ? args.origin : void 0,
94
+ skipDataRead: args["skip-data-read"] === true
95
+ });
96
+ process.stdout.write(args.json === true ? `${JSON.stringify(report, null, 2)}
97
+ ` : render(report));
98
+ if (!report.ok) process.exitCode = 1;
99
+ }
100
+ main().catch((e) => {
101
+ process.stderr.write(`bowlos doctor crashed: ${e instanceof Error ? e.message : String(e)}
102
+ `);
103
+ process.exitCode = 1;
104
+ });
105
+ //# sourceMappingURL=cli.js.map
106
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli.ts"],"names":[],"mappings":";;;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,OAAO,IAAA,CAAK,MAAA,KAAW,QAAA,GAAW,KAAK,MAAA,GAAS,MAAA;AAAA,IACxD,YAAA,EAAc,IAAA,CAAK,gBAAgB,CAAA,KAAM;AAAA,GAC1C,CAAA;AAED,EAAA,OAAA,CAAQ,MAAA,CAAO,KAAA,CAAM,IAAA,CAAK,IAAA,KAAS,IAAA,GAAO,CAAA,EAAG,IAAA,CAAK,SAAA,CAAU,MAAA,EAAQ,IAAA,EAAM,CAAC,CAAC;AAAA,CAAA,GAAO,MAAA,CAAO,MAAM,CAAC,CAAA;AACjG,EAAA,IAAI,CAAC,MAAA,CAAO,EAAA,EAAI,OAAA,CAAQ,QAAA,GAAW,CAAA;AACrC;AAEA,IAAA,EAAK,CAAE,KAAA,CAAM,CAAC,CAAA,KAAe;AAC3B,EAAA,OAAA,CAAQ,MAAA,CAAO,MAAM,CAAA,uBAAA,EAA0B,CAAA,YAAa,QAAQ,CAAA,CAAE,OAAA,GAAU,MAAA,CAAO,CAAC,CAAC;AAAA,CAAI,CAAA;AAC7F,EAAA,OAAA,CAAQ,QAAA,GAAW,CAAA;AACrB,CAAC,CAAA","file":"cli.js","sourcesContent":["#!/usr/bin/env node\n/// <reference types=\"node\" />\n/**\n * `bowlos` CLI. One command today: `bowlos doctor` — validates a site's\n * @bowlos/reservations setup against a gateway + API key and prints a readiness\n * report. Reads flags or env vars; exits non-zero if any check failed (so it\n * drops into CI / a setup script). Dependency-free argv parsing.\n */\nimport { runDoctor, type DoctorCheck, type DoctorReport } from \"./doctor\";\n\ntype ParsedArgs = { _command?: string } & Record<string, string | boolean>;\n\nfunction parseArgs(argv: string[]): ParsedArgs {\n const out: ParsedArgs = {};\n for (let i = 0; i < argv.length; i++) {\n const a = argv[i];\n if (a === undefined) continue;\n if (a.startsWith(\"--\")) {\n const key = a.slice(2);\n const next = argv[i + 1];\n if (next !== undefined && !next.startsWith(\"--\")) {\n out[key] = next;\n i++;\n } else {\n out[key] = true;\n }\n } else if (out._command === undefined) {\n out._command = a;\n }\n }\n return out;\n}\n\nconst ICON: Record<DoctorCheck[\"status\"], string> = {\n pass: \"✓\", // ✓\n warn: \"⚠\", // ⚠\n fail: \"✗\", // ✗\n skip: \"·\", // ·\n};\n\nfunction render(report: DoctorReport): string {\n const lines: string[] = [\"\", `bowlos doctor — ${report.baseUrl}`];\n if (report.brandId) lines.push(`brand ${report.brandId} · mode ${report.mode}`);\n lines.push(\"\");\n for (const c of report.checks) {\n lines.push(` ${ICON[c.status]} ${c.title}: ${c.detail}`);\n if (c.fix && c.status !== \"pass\") lines.push(` → ${c.fix}`);\n }\n const fails = report.checks.filter((c) => c.status === \"fail\").length;\n const warns = report.checks.filter((c) => c.status === \"warn\").length;\n lines.push(\n \"\",\n report.ok\n ? warns > 0\n ? `Ready, with ${warns} warning(s).`\n : \"All checks passed — ready.\"\n : `${fails} check(s) failed — not ready.`,\n \"\",\n );\n return lines.join(\"\\n\");\n}\n\nconst HELP = [\n \"Usage: bowlos doctor [options]\",\n \"\",\n \"Validates a @bowlos/reservations setup against the gateway + API key.\",\n \"\",\n \"Options:\",\n \" --api-key <key> Brand API key (or env BOWLOS_API_KEY)\",\n \" --base-url <url> Gateway base URL (or env BOWLOS_BASE_URL)\",\n \" --origin <url> Your deployed site origin (informs the allow-list note)\",\n \" --skip-data-read Skip the anonymous data-plane read\",\n \" --json Print the raw JSON report instead of the table\",\n \" --help Show this help\",\n \"\",\n].join(\"\\n\");\n\nasync function main(): Promise<void> {\n const args = parseArgs(process.argv.slice(2));\n const command = args._command ?? \"doctor\";\n\n if (args.help === true || command === \"help\") {\n process.stdout.write(`${HELP}\\n`);\n return;\n }\n if (command !== \"doctor\") {\n process.stderr.write(`Unknown command \"${command}\". Try: bowlos doctor --help\\n`);\n process.exitCode = 1;\n return;\n }\n\n const apiKey = (typeof args[\"api-key\"] === \"string\" ? args[\"api-key\"] : undefined) ?? process.env.BOWLOS_API_KEY ?? \"\";\n const baseUrl = (typeof args[\"base-url\"] === \"string\" ? args[\"base-url\"] : undefined) ?? process.env.BOWLOS_BASE_URL ?? \"\";\n\n if (!apiKey || !baseUrl) {\n process.stderr.write(\n \"Missing --api-key / --base-url (or BOWLOS_API_KEY / BOWLOS_BASE_URL).\\nRun `bowlos doctor --help`.\\n\",\n );\n process.exitCode = 1;\n return;\n }\n\n const report = await runDoctor({\n apiKey,\n baseUrl,\n origin: typeof args.origin === \"string\" ? args.origin : undefined,\n skipDataRead: args[\"skip-data-read\"] === true,\n });\n\n process.stdout.write(args.json === true ? `${JSON.stringify(report, null, 2)}\\n` : render(report));\n if (!report.ok) process.exitCode = 1;\n}\n\nmain().catch((e: unknown) => {\n process.stderr.write(`bowlos doctor crashed: ${e instanceof Error ? e.message : String(e)}\\n`);\n process.exitCode = 1;\n});\n"]}
package/dist/index.cjs ADDED
@@ -0,0 +1,547 @@
1
+ 'use strict';
2
+
3
+ // src/errors.ts
4
+ var BOWLOS_ERROR_CODES = {
5
+ // Gateway front door
6
+ API_KEY_MISSING: "API_KEY_MISSING",
7
+ API_KEY_INVALID: "API_KEY_INVALID",
8
+ ORIGIN_NOT_ALLOWED: "ORIGIN_NOT_ALLOWED",
9
+ RATE_LIMITED: "RATE_LIMITED",
10
+ // Auth
11
+ INVALID_CREDENTIALS: "INVALID_CREDENTIALS",
12
+ SIGNUP_FAILED: "SIGNUP_FAILED",
13
+ // Shared backend codes
14
+ VALIDATION_FAILED: "VALIDATION_FAILED",
15
+ PERMISSION_DENIED: "PERMISSION_DENIED",
16
+ SCOPE_REVOKED: "SCOPE_REVOKED",
17
+ NOT_FOUND: "NOT_FOUND",
18
+ VERSION_CONFLICT: "VERSION_CONFLICT",
19
+ PRICING_SNAPSHOT_STALE: "PRICING_SNAPSHOT_STALE",
20
+ PAYMENTS_NOT_CONNECTED: "PAYMENTS_NOT_CONNECTED",
21
+ CONNECT_ACCOUNT_RESTRICTED: "CONNECT_ACCOUNT_RESTRICTED",
22
+ CHECKOUT_EXPIRED: "CHECKOUT_EXPIRED",
23
+ // Client-side
24
+ NETWORK_ERROR: "NETWORK_ERROR",
25
+ UNKNOWN: "ERROR"
26
+ };
27
+ var BowlosApiError = class _BowlosApiError extends Error {
28
+ /** Stable, machine-readable code. Branch on this, not on `message`. */
29
+ code;
30
+ /** HTTP status (0 for a network failure before any response). */
31
+ status;
32
+ /** Seconds to wait before retrying — present only on `RATE_LIMITED`. */
33
+ retryAfterSeconds;
34
+ constructor(code, message, status, options = {}) {
35
+ super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
36
+ this.name = "BowlosApiError";
37
+ this.code = code;
38
+ this.status = status;
39
+ this.retryAfterSeconds = options.retryAfterSeconds;
40
+ Object.setPrototypeOf(this, _BowlosApiError.prototype);
41
+ }
42
+ /** Too many requests — caller should back off `retryAfterSeconds`. */
43
+ get isRateLimited() {
44
+ return this.code === BOWLOS_ERROR_CODES.RATE_LIMITED;
45
+ }
46
+ /** Bad/expired login. The session could not be established or has lapsed. */
47
+ get isAuthError() {
48
+ return this.code === BOWLOS_ERROR_CODES.INVALID_CREDENTIALS || this.code === BOWLOS_ERROR_CODES.PERMISSION_DENIED || this.code === BOWLOS_ERROR_CODES.SCOPE_REVOKED;
49
+ }
50
+ /** Wrong/missing API key or a disallowed origin — a site-config problem,
51
+ * not something the end customer can fix. */
52
+ get isConfigError() {
53
+ return this.code === BOWLOS_ERROR_CODES.API_KEY_MISSING || this.code === BOWLOS_ERROR_CODES.API_KEY_INVALID || this.code === BOWLOS_ERROR_CODES.ORIGIN_NOT_ALLOWED;
54
+ }
55
+ };
56
+
57
+ // src/client.ts
58
+ var MemoryTokenStore = class {
59
+ tokens = null;
60
+ get() {
61
+ return this.tokens;
62
+ }
63
+ set(tokens) {
64
+ this.tokens = tokens;
65
+ }
66
+ };
67
+ function localStorageTokenStore(storageKey = "bowlos.tokens") {
68
+ return {
69
+ get() {
70
+ if (typeof localStorage === "undefined") return null;
71
+ const raw = localStorage.getItem(storageKey);
72
+ if (!raw) return null;
73
+ try {
74
+ const parsed = JSON.parse(raw);
75
+ return parsed.token && parsed.refreshToken ? { token: parsed.token, refreshToken: parsed.refreshToken } : null;
76
+ } catch {
77
+ return null;
78
+ }
79
+ },
80
+ set(tokens) {
81
+ if (typeof localStorage === "undefined") return;
82
+ if (tokens) localStorage.setItem(storageKey, JSON.stringify(tokens));
83
+ else localStorage.removeItem(storageKey);
84
+ }
85
+ };
86
+ }
87
+ function isConfigErrorCode(code) {
88
+ return code === BOWLOS_ERROR_CODES.API_KEY_MISSING || code === BOWLOS_ERROR_CODES.API_KEY_INVALID || code === BOWLOS_ERROR_CODES.ORIGIN_NOT_ALLOWED || code === BOWLOS_ERROR_CODES.RATE_LIMITED;
89
+ }
90
+ function looksLikeExpiredSession(status, code) {
91
+ if (isConfigErrorCode(code)) return false;
92
+ return status === 401 || code === BOWLOS_ERROR_CODES.PERMISSION_DENIED || code === BOWLOS_ERROR_CODES.SCOPE_REVOKED;
93
+ }
94
+ var BowlosClient = class {
95
+ apiKey;
96
+ baseUrl;
97
+ store;
98
+ fetchFn;
99
+ constructor(config) {
100
+ this.apiKey = config.apiKey;
101
+ this.baseUrl = config.baseUrl.replace(/\/+$/, "");
102
+ this.store = config.tokenStore ?? new MemoryTokenStore();
103
+ this.fetchFn = config.fetch ?? defaultFetch;
104
+ if (!this.apiKey) throw new Error("BowlosClient: `apiKey` is required.");
105
+ if (!this.baseUrl) throw new Error("BowlosClient: `baseUrl` is required.");
106
+ }
107
+ /** Is there a stored session right now? (Does not validate it server-side.) */
108
+ isAuthenticated() {
109
+ return this.store.get() !== null;
110
+ }
111
+ /** The current token pair, if any (rarely needed directly). */
112
+ getTokens() {
113
+ return this.store.get();
114
+ }
115
+ /**
116
+ * Health + key-validity probe (`GET /ping`). Resolves with the gateway's
117
+ * service info when the API key is accepted; throws a `BowlosApiError` whose
118
+ * `.code` distinguishes the failure (`NETWORK_ERROR`, `API_KEY_INVALID`,
119
+ * `ORIGIN_NOT_ALLOWED`, `RATE_LIMITED`, …). Cheap enough to call on boot, and
120
+ * the basis for `runDoctor`.
121
+ */
122
+ async ping() {
123
+ const { status, body, retryAfterSeconds } = await this.request(
124
+ "ping",
125
+ {},
126
+ this.store.get()?.token,
127
+ "GET"
128
+ );
129
+ const env = body ?? {};
130
+ if (env.ok === true) return env.data;
131
+ const code = env.error?.code ?? (status === 429 ? BOWLOS_ERROR_CODES.RATE_LIMITED : status === 404 ? BOWLOS_ERROR_CODES.NOT_FOUND : BOWLOS_ERROR_CODES.UNKNOWN);
132
+ throw new BowlosApiError(
133
+ code,
134
+ env.error?.message ?? `Health ping failed (HTTP ${status}).`,
135
+ status,
136
+ { retryAfterSeconds: code === BOWLOS_ERROR_CODES.RATE_LIMITED ? retryAfterSeconds : void 0 }
137
+ );
138
+ }
139
+ // ── low-level transport ────────────────────────────────────────────────
140
+ async request(name, args, bearer, method = "POST") {
141
+ const headers = {
142
+ "X-BowlOS-Api-Key": this.apiKey
143
+ };
144
+ if (method !== "GET") headers["Content-Type"] = "application/json";
145
+ if (bearer) headers["Authorization"] = `Bearer ${bearer}`;
146
+ const init = { method, headers };
147
+ if (method !== "GET") init.body = JSON.stringify(args);
148
+ let res;
149
+ try {
150
+ res = await this.fetchFn(`${this.baseUrl}/${name}`, init);
151
+ } catch (cause) {
152
+ throw new BowlosApiError(
153
+ BOWLOS_ERROR_CODES.NETWORK_ERROR,
154
+ `Network request to "${name}" failed.`,
155
+ 0,
156
+ { cause }
157
+ );
158
+ }
159
+ const retryHeader = res.headers.get("Retry-After");
160
+ const retryAfterSeconds = retryHeader ? Number(retryHeader) || void 0 : void 0;
161
+ let body = null;
162
+ const text = await res.text();
163
+ if (text) {
164
+ try {
165
+ body = JSON.parse(text);
166
+ } catch {
167
+ body = { ok: false, error: { code: BOWLOS_ERROR_CODES.NOT_FOUND, message: text.slice(0, 200) } };
168
+ }
169
+ }
170
+ return { status: res.status, body, retryAfterSeconds };
171
+ }
172
+ /**
173
+ * Call a gateway route by name (`POST /api/public/v1/<name>`), returning the
174
+ * unwrapped `data`. Set `{ auth: true }` to attach the bearer token and
175
+ * enable refresh-and-retry on an expired session.
176
+ */
177
+ async call(name, args = {}, opts = {}) {
178
+ return this.callInternal(name, args, opts.auth ?? false, false, opts.method ?? "POST");
179
+ }
180
+ async callInternal(name, args, auth, retried, method) {
181
+ const bearer = auth ? this.store.get()?.token : void 0;
182
+ const { status, body, retryAfterSeconds } = await this.request(name, args, bearer, method);
183
+ const env = body ?? {};
184
+ if (env.ok === true) {
185
+ const data = env.data;
186
+ if (data !== null && typeof data === "object" && "schema_version" in data && "ok" in data) {
187
+ const inner = data;
188
+ if (inner.ok === false) {
189
+ throw new BowlosApiError(
190
+ inner.error?.code ?? BOWLOS_ERROR_CODES.UNKNOWN,
191
+ inner.error?.message ?? `Request to "${name}" failed.`,
192
+ status
193
+ );
194
+ }
195
+ return inner.data;
196
+ }
197
+ return data;
198
+ }
199
+ const code = env.error?.code ?? (status === 429 ? BOWLOS_ERROR_CODES.RATE_LIMITED : status === 404 ? BOWLOS_ERROR_CODES.NOT_FOUND : BOWLOS_ERROR_CODES.UNKNOWN);
200
+ const message = env.error?.message ?? `Request to "${name}" failed (HTTP ${status}).`;
201
+ if (auth && !retried && this.store.get() && looksLikeExpiredSession(status, code)) {
202
+ const refreshed = await this.tryRefresh();
203
+ if (refreshed) return this.callInternal(name, args, auth, true, method);
204
+ }
205
+ throw new BowlosApiError(code, message, status, {
206
+ retryAfterSeconds: code === BOWLOS_ERROR_CODES.RATE_LIMITED ? retryAfterSeconds : void 0
207
+ });
208
+ }
209
+ /** Exchange the stored refresh token for a fresh pair. Clears the session if
210
+ * the refresh token is itself invalid/expired. Returns success. */
211
+ async tryRefresh() {
212
+ const current = this.store.get();
213
+ if (!current?.refreshToken) return false;
214
+ const { status, body } = await this.request("auth/refresh", {
215
+ refreshToken: current.refreshToken
216
+ });
217
+ const env = body ?? {};
218
+ if (status >= 200 && status < 300 && env.ok === true && env.data?.tokens) {
219
+ this.store.set(env.data.tokens);
220
+ return true;
221
+ }
222
+ this.store.set(null);
223
+ return false;
224
+ }
225
+ // ── auth lifecycle ───────────────────────────────────────────────────────
226
+ /** Sign an existing customer in; stores the session on success. */
227
+ async signIn(email, password) {
228
+ const { tokens } = await this.call("auth/signin", { email, password });
229
+ this.store.set(tokens);
230
+ return tokens;
231
+ }
232
+ /** Create a login (the auth half of sign-up); stores the session. Follow with
233
+ * `link()` to attach the customer profile. */
234
+ async signUp(email, password) {
235
+ const { tokens } = await this.call("auth/signup", { email, password });
236
+ this.store.set(tokens);
237
+ return tokens;
238
+ }
239
+ /** Link the signed-in auth user to a customer profile at the brand. */
240
+ async link(profile) {
241
+ return this.call("auth/link", { ...profile }, { auth: true });
242
+ }
243
+ /** End the session (best-effort server call; always clears locally). */
244
+ async signOut() {
245
+ try {
246
+ await this.call("auth/signout", {}, { auth: true });
247
+ } catch {
248
+ } finally {
249
+ this.store.set(null);
250
+ }
251
+ }
252
+ /** Session bootstrap: unauthenticated / authed-no-customer / linked.
253
+ * GET — matches the gateway's `GET /auth/probe` route. */
254
+ async probe() {
255
+ const { state } = await this.call(
256
+ "auth/probe",
257
+ {},
258
+ { auth: true, method: "GET" }
259
+ );
260
+ return state;
261
+ }
262
+ /** The signed-in customer's profile, or null.
263
+ * GET — matches the gateway's `GET /auth/me` route. */
264
+ async me() {
265
+ const { customer } = await this.call(
266
+ "auth/me",
267
+ {},
268
+ { auth: true, method: "GET" }
269
+ );
270
+ return customer;
271
+ }
272
+ };
273
+ var defaultFetch = (input, init) => {
274
+ if (typeof globalThis.fetch !== "function") {
275
+ throw new BowlosApiError(
276
+ BOWLOS_ERROR_CODES.NETWORK_ERROR,
277
+ "No global fetch available. Pass `config.fetch`.",
278
+ 0
279
+ );
280
+ }
281
+ return globalThis.fetch(input, init);
282
+ };
283
+ function createBowlosClient(config) {
284
+ return new BowlosClient(config);
285
+ }
286
+
287
+ // src/doctor.ts
288
+ var GATEWAY_SUFFIX = "/api/public/v1";
289
+ async function runDoctor(options) {
290
+ const checks = [];
291
+ const report = { ok: true, checks, baseUrl: options.baseUrl };
292
+ const configIssues = [];
293
+ if (!options.apiKey) configIssues.push("`apiKey` is empty");
294
+ let parsedUrl = null;
295
+ try {
296
+ parsedUrl = new URL(options.baseUrl);
297
+ } catch {
298
+ configIssues.push("`baseUrl` is not a valid URL");
299
+ }
300
+ if (configIssues.length > 0) {
301
+ checks.push({
302
+ id: "config",
303
+ title: "Client configuration",
304
+ status: "fail",
305
+ detail: `${configIssues.join("; ")}.`,
306
+ fix: "Pass a brand API key and the gateway base URL, e.g. https://<deployment>.convex.site/api/public/v1"
307
+ });
308
+ report.ok = false;
309
+ return report;
310
+ }
311
+ const urlMisaimed = parsedUrl !== null && !parsedUrl.pathname.replace(/\/+$/, "").endsWith(GATEWAY_SUFFIX);
312
+ checks.push({
313
+ id: "config",
314
+ title: "Client configuration",
315
+ status: urlMisaimed ? "warn" : "pass",
316
+ 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.",
317
+ fix: urlMisaimed ? `Use the gateway URL, e.g. ${parsedUrl?.origin}${GATEWAY_SUFFIX}` : void 0
318
+ });
319
+ const client = createBowlosClient({
320
+ apiKey: options.apiKey,
321
+ baseUrl: options.baseUrl,
322
+ fetch: options.fetch
323
+ });
324
+ let ping = null;
325
+ try {
326
+ ping = await client.ping();
327
+ report.brandId = ping.brandId;
328
+ report.mode = ping.mode;
329
+ checks.push({
330
+ id: "gateway",
331
+ title: "Gateway reachable",
332
+ status: "pass",
333
+ detail: `Reached ${options.baseUrl} (service "${ping.service}", ${ping.version}).`
334
+ });
335
+ checks.push({
336
+ id: "api-key",
337
+ title: "API key accepted",
338
+ status: "pass",
339
+ detail: `Key valid for brand ${ping.brandId} \u2014 mode: ${ping.mode}.`
340
+ });
341
+ } catch (e) {
342
+ const err = e instanceof BowlosApiError ? e : null;
343
+ const code = err?.code ?? BOWLOS_ERROR_CODES.UNKNOWN;
344
+ const reached = err !== null && err.status !== 0 && code !== BOWLOS_ERROR_CODES.NETWORK_ERROR && code !== BOWLOS_ERROR_CODES.NOT_FOUND;
345
+ checks.push({
346
+ id: "gateway",
347
+ title: "Gateway reachable",
348
+ status: reached ? "pass" : "fail",
349
+ 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}.`,
350
+ fix: reached ? void 0 : "Check the base URL, that the Convex deployment is live, and that the public-API routes are deployed."
351
+ });
352
+ if (code === BOWLOS_ERROR_CODES.RATE_LIMITED) {
353
+ checks.push({
354
+ id: "api-key",
355
+ title: "API key accepted",
356
+ status: "pass",
357
+ detail: "Key accepted (this probe was rate-limited)."
358
+ });
359
+ checks.push({
360
+ id: "rate-limit",
361
+ title: "Rate-limit headroom",
362
+ status: "warn",
363
+ detail: `Currently rate-limited${err?.retryAfterSeconds ? ` \u2014 retry after ${err.retryAfterSeconds}s` : ""}.`,
364
+ fix: "Back off and retry; raise the key's per-minute limit if your real traffic is higher."
365
+ });
366
+ } else if (code === BOWLOS_ERROR_CODES.ORIGIN_NOT_ALLOWED) {
367
+ checks.push({
368
+ id: "api-key",
369
+ title: "API key accepted",
370
+ status: "pass",
371
+ detail: "Key accepted; the request was blocked on origin."
372
+ });
373
+ checks.push({
374
+ id: "origin",
375
+ title: "Origin allow-listed",
376
+ status: "fail",
377
+ detail: "The request origin is not on the key's allow-list.",
378
+ fix: `Add your site origin${options.origin ? ` (${options.origin})` : ""} to the API key's allowed origins.`
379
+ });
380
+ } else if (reached) {
381
+ checks.push({
382
+ id: "api-key",
383
+ title: "API key accepted",
384
+ status: "fail",
385
+ 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}.`,
386
+ fix: "Mint or rotate a brand API key in the operator admin (Super-Admin \u2192 API keys) and use that value."
387
+ });
388
+ } else {
389
+ checks.push({
390
+ id: "api-key",
391
+ title: "API key accepted",
392
+ status: "skip",
393
+ detail: "Skipped \u2014 the gateway wasn't reachable."
394
+ });
395
+ }
396
+ }
397
+ if (!checks.some((c) => c.id === "origin")) {
398
+ const browserOrigin = typeof window !== "undefined" && typeof window.location?.origin === "string" ? window.location.origin : null;
399
+ if (ping !== null && browserOrigin !== null) {
400
+ checks.push({
401
+ id: "origin",
402
+ title: "Origin allow-listed",
403
+ status: "pass",
404
+ detail: `This origin (${browserOrigin}) is allow-listed for the key.`
405
+ });
406
+ } else {
407
+ checks.push({
408
+ id: "origin",
409
+ title: "Origin allow-listed",
410
+ status: "skip",
411
+ detail: "Origin allow-listing is enforced only for browser requests, so it can't be verified from a CLI.",
412
+ 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.`
413
+ });
414
+ }
415
+ }
416
+ if (ping !== null && options.skipDataRead !== true) {
417
+ try {
418
+ const data = await client.call("listPublicCenters", { brandId: ping.brandId });
419
+ const innerError = typeof data === "object" && data !== null && data.ok === false;
420
+ checks.push({
421
+ id: "data-read",
422
+ title: "Data passthrough",
423
+ status: innerError ? "warn" : "pass",
424
+ detail: innerError ? "Reached the data plane, but listPublicCenters returned an error envelope." : "Anonymous read (listPublicCenters) succeeded \u2014 gateway \u2192 query passthrough works.",
425
+ fix: innerError ? "Confirm the brand has at least one published center." : void 0
426
+ });
427
+ } catch (e) {
428
+ const err = e instanceof BowlosApiError ? e : null;
429
+ checks.push({
430
+ id: "data-read",
431
+ title: "Data passthrough",
432
+ status: "warn",
433
+ detail: `An anonymous read failed${err ? ` (${err.code})` : ""}.`,
434
+ fix: "Key + gateway are fine; this read may need a published center or differ by brand. Safe to ignore if your booking reads work."
435
+ });
436
+ }
437
+ } else if (ping === null) {
438
+ checks.push({
439
+ id: "data-read",
440
+ title: "Data passthrough",
441
+ status: "skip",
442
+ detail: "Skipped \u2014 needs a reachable gateway."
443
+ });
444
+ }
445
+ checks.push({
446
+ id: "payments",
447
+ title: "Payments connected",
448
+ status: "skip",
449
+ detail: "Stripe Connect status isn't exposed over the public API yet, so the doctor can't verify it here.",
450
+ fix: "Confirm the operator's Stripe account is connected + charges-enabled in the admin (Payments \u2192 Connect)."
451
+ });
452
+ report.ok = !checks.some((c) => c.status === "fail");
453
+ return report;
454
+ }
455
+
456
+ // src/data.ts
457
+ function checkAvailability(client, args) {
458
+ return client.call("checkAvailability", args);
459
+ }
460
+ function bookingPreview(client, args) {
461
+ return client.call("bookingPreview", args);
462
+ }
463
+ function availableUnitCount(availability) {
464
+ return Math.max(0, availability.totalUnits - availability.busyUnitIds.length);
465
+ }
466
+ function generateIdempotencyKey() {
467
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
468
+ return crypto.randomUUID();
469
+ }
470
+ return `idem_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
471
+ }
472
+ function createBooking(client, args) {
473
+ const idempotencyKey = args.idempotencyKey ?? generateIdempotencyKey();
474
+ return client.call(
475
+ "createAnonymousBooking",
476
+ { ...args, idempotencyKey },
477
+ { auth: true }
478
+ );
479
+ }
480
+ function createCheckoutPaymentIntent(client, refToken) {
481
+ return client.call(
482
+ "createCheckoutPaymentIntent",
483
+ { refToken },
484
+ { auth: true }
485
+ );
486
+ }
487
+ function getCheckoutStatus(client, refToken) {
488
+ return client.call("getCheckoutStatus", { refToken }, { auth: true });
489
+ }
490
+ function abandonCheckout(client, refToken) {
491
+ return client.call("abandonCheckout", { refToken }, { auth: true });
492
+ }
493
+
494
+ // src/account.ts
495
+ function getMyReservations(client, args) {
496
+ return client.call("listMyReservations", args, { auth: true });
497
+ }
498
+ function getMyReservationDetail(client, args) {
499
+ return client.call("getMyReservationDetail", args, { auth: true });
500
+ }
501
+ function getMyMemberships(client, args) {
502
+ return client.call("listMyMemberships", args, { auth: true });
503
+ }
504
+ function getMyMembershipDetail(client, args) {
505
+ return client.call("getMyMembershipDetail", args, { auth: true });
506
+ }
507
+ function getMyLoyalty(client, args) {
508
+ return client.call("getMyLoyalty", args, { auth: true });
509
+ }
510
+ function getMyCredits(client, args) {
511
+ return client.call("listMyCredits", args, { auth: true });
512
+ }
513
+ function getMyPasses(client, args) {
514
+ return client.call("listMyPasses", args, { auth: true });
515
+ }
516
+ function getFlashSale(client, args) {
517
+ return client.call("getPublicFlashSaleBySlug", args, { auth: true });
518
+ }
519
+ function getFlashSaleBookingOptions(client, args) {
520
+ return client.call("getFlashSaleBookingOptions", args, { auth: true });
521
+ }
522
+
523
+ exports.BOWLOS_ERROR_CODES = BOWLOS_ERROR_CODES;
524
+ exports.BowlosApiError = BowlosApiError;
525
+ exports.BowlosClient = BowlosClient;
526
+ exports.abandonCheckout = abandonCheckout;
527
+ exports.availableUnitCount = availableUnitCount;
528
+ exports.bookingPreview = bookingPreview;
529
+ exports.checkAvailability = checkAvailability;
530
+ exports.createBooking = createBooking;
531
+ exports.createBowlosClient = createBowlosClient;
532
+ exports.createCheckoutPaymentIntent = createCheckoutPaymentIntent;
533
+ exports.generateIdempotencyKey = generateIdempotencyKey;
534
+ exports.getCheckoutStatus = getCheckoutStatus;
535
+ exports.getFlashSale = getFlashSale;
536
+ exports.getFlashSaleBookingOptions = getFlashSaleBookingOptions;
537
+ exports.getMyCredits = getMyCredits;
538
+ exports.getMyLoyalty = getMyLoyalty;
539
+ exports.getMyMembershipDetail = getMyMembershipDetail;
540
+ exports.getMyMemberships = getMyMemberships;
541
+ exports.getMyPasses = getMyPasses;
542
+ exports.getMyReservationDetail = getMyReservationDetail;
543
+ exports.getMyReservations = getMyReservations;
544
+ exports.localStorageTokenStore = localStorageTokenStore;
545
+ exports.runDoctor = runDoctor;
546
+ //# sourceMappingURL=index.cjs.map
547
+ //# sourceMappingURL=index.cjs.map