@ordinatio/scheduling-api 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import {
2
+ ApiKeySchema,
2
3
  BookingPageConfigSchema,
3
4
  BookingPageThemeSchema,
4
5
  BrandSchema,
@@ -16,6 +17,9 @@ import {
16
17
  CreateServicePackageSchema,
17
18
  CreateWebhookEndpointSchema,
18
19
  DEFAULT_CANCELLATION_POLICY,
20
+ GiftCertificateCheckSchema,
21
+ GiftCertificateRestoreSchema,
22
+ GiftCertificateSchema,
19
23
  IntakeFormFieldSchema,
20
24
  NoShowPreventionActionSchema,
21
25
  NotificationChannelSchema,
@@ -38,7 +42,7 @@ import {
38
42
  UpdatePackagePurchaseSchema,
39
43
  UpdateRoutingFormSchema,
40
44
  UpdateServicePackageSchema
41
- } from "./chunk-IW6AN5WE.mjs";
45
+ } from "./chunk-W3SY2DAU.mjs";
42
46
 
43
47
  // src/create-api.ts
44
48
  import * as engine from "@ordinatio/scheduling";
@@ -54,6 +58,82 @@ function defaultCorsHeaders() {
54
58
  };
55
59
  }
56
60
 
61
+ // src/api-keys/api-key-host.ts
62
+ import { verifyApiKey } from "@ordinatio/scheduling";
63
+
64
+ // src/staff/simple-staff.ts
65
+ var DEFAULT_ADMIN_ROLES = ["OWNER", "ADMIN", "MANAGER"];
66
+ function createStaffContext(input) {
67
+ const adminRoles = (input.adminRoles ?? DEFAULT_ADMIN_ROLES).map((role) => role.toUpperCase());
68
+ const { db, organizationId } = input;
69
+ return {
70
+ userId: input.userId,
71
+ organizationId,
72
+ role: input.role,
73
+ isAdmin: adminRoles.includes(input.role.toUpperCase()),
74
+ schedulingEnabled: input.schedulingEnabled ?? true,
75
+ db,
76
+ visibleCalendars: async () => null,
77
+ visibleCalendarIds: async () => void 0,
78
+ canSeeCalendar: async (calendarId) => Boolean(await db.schedulingCalendar.findFirst({ where: { id: calendarId, organizationId }, select: { id: true } })),
79
+ canSeeAppointment: async (appointmentId) => Boolean(await db.appointment.findFirst({ where: { id: appointmentId, calendar: { organizationId } }, select: { id: true } })),
80
+ // The package has no client table, so there is no preference to read.
81
+ preferredLocationOf: async () => null
82
+ };
83
+ }
84
+ var BEARER = /^bearer\s+(\S+)$/i;
85
+ function createBearerStaffResolver(input) {
86
+ return {
87
+ async resolve(request) {
88
+ const token = BEARER.exec(request.headers.get("authorization") ?? "")?.[1];
89
+ if (!token) return null;
90
+ const person = await input.authenticate(token, request);
91
+ if (!person) return null;
92
+ return createStaffContext({
93
+ ...person,
94
+ db: await input.db(person),
95
+ adminRoles: input.adminRoles,
96
+ schedulingEnabled: input.schedulingEnabled ? await input.schedulingEnabled(person) : void 0
97
+ });
98
+ }
99
+ };
100
+ }
101
+
102
+ // src/api-keys/api-key-host.ts
103
+ var API_KEY_ROLE_PREFIX = "API_KEY_";
104
+ var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
105
+ function bearerKeyOf(request) {
106
+ const header = request.headers.get("authorization");
107
+ if (!header) return null;
108
+ const match = /^[Bb][Ee][Aa][Rr][Ee][Rr]\s+(osk_\S+)$/.exec(header.trim());
109
+ return match ? match[1] : null;
110
+ }
111
+ function contextOf(key, db, schedulingEnabled) {
112
+ return createStaffContext({
113
+ // The key, not the person who made it, is what the rate limit counts.
114
+ userId: `api-key:${key.id}`,
115
+ organizationId: key.organizationId,
116
+ role: `${API_KEY_ROLE_PREFIX}${key.access}`,
117
+ adminRoles: [`${API_KEY_ROLE_PREFIX}READ`, `${API_KEY_ROLE_PREFIX}FULL`],
118
+ schedulingEnabled,
119
+ db
120
+ });
121
+ }
122
+ async function hostForRequest(host, request, route) {
123
+ if (route.public || !host.apiKeys) return host;
124
+ const secret = bearerKeyOf(request);
125
+ if (secret === null) return host;
126
+ const db = await host.apiKeys.db();
127
+ const key = await verifyApiKey(db, secret);
128
+ if (!key) return Response.json({ error: "Unauthorized" }, { status: 401 });
129
+ if (route.personOnly) return Response.json({ error: "This needs a person signed in at a browser, not an API key" }, { status: 403 });
130
+ if (key.access === "READ" && !SAFE_METHODS.has(request.method.toUpperCase())) {
131
+ return Response.json({ error: "This API key is read-only" }, { status: 403 });
132
+ }
133
+ const context = contextOf(key, db, await host.schedulingEnabledFor(key.organizationId));
134
+ return { ...host, staff: { resolve: async () => context } };
135
+ }
136
+
57
137
  // src/availability/memory-availability-cache.ts
58
138
  var TTL_MS = 6e4;
59
139
  var DEFAULT_MAX_ENTRIES = 2e3;
@@ -2473,16 +2553,16 @@ async function attemptLegRefund(payments, paymentIntentId, idempotencyKeySuffix,
2473
2553
  return failedLeg(errorCode, logLabel, appointmentId, paymentIntentId, idempotencyKey, retriedAfterReplay, { error: result.error, message: result.error ?? result.code ?? "no reason given", requestId: result.requestId });
2474
2554
  }
2475
2555
  }
2476
- function failedLeg(errorCode, logLabel, appointmentId, paymentIntentId, idempotencyKey, retriedAfterReplay, failure4) {
2477
- const diagnostic = schedError14(errorCode, { error: failure4.error, appointmentId, paymentIntentId });
2556
+ function failedLeg(errorCode, logLabel, appointmentId, paymentIntentId, idempotencyKey, retriedAfterReplay, failure5) {
2557
+ const diagnostic = schedError14(errorCode, { error: failure5.error, appointmentId, paymentIntentId });
2478
2558
  console.error(
2479
2559
  `[resolve-refund] ${logLabel} refund failed${retriedAfterReplay ? " (after a fresh-key re-attempt)" : ""} \u2014 manual refund may be required:`,
2480
2560
  diagnostic.ref,
2481
2561
  appointmentId,
2482
2562
  paymentIntentId,
2483
- `requestId=${failure4.requestId}`,
2563
+ `requestId=${failure5.requestId}`,
2484
2564
  `idempotencyKey=${idempotencyKey}`,
2485
- failure4.message
2565
+ failure5.message
2486
2566
  );
2487
2567
  return { succeeded: false, amountCents: null };
2488
2568
  }
@@ -6654,21 +6734,221 @@ async function deleteBrandRoute(request, { host }) {
6654
6734
  }
6655
6735
  }
6656
6736
 
6657
- // src/handlers/admin-text-settings.ts
6658
- import { deleteTextSettings, getTextSettings, saveTextSettings, SchedulingValidationError as SchedulingValidationError12 } from "@ordinatio/scheduling";
6659
- var NOT_ENABLED4 = { error: "Text-message settings are not enabled on this server" };
6737
+ // src/handlers/admin-api-keys.ts
6738
+ import { createApiKey, listApiKeys, revokeApiKey, SchedulingValidationError as SchedulingValidationError12 } from "@ordinatio/scheduling";
6739
+ var NOT_ENABLED4 = { error: "API keys are not enabled on this server" };
6660
6740
  function failure3(error, fallback) {
6661
6741
  if (error instanceof SchedulingValidationError12) {
6662
6742
  const details = error.context.errors;
6663
6743
  return Response.json({ error: error.message, code: error.code, ref: getErrorRef(error), ...details ? { details } : {} }, { status: 400 });
6664
6744
  }
6745
+ console.error("[api-keys]", error);
6746
+ return Response.json({ error: fallback }, { status: 500 });
6747
+ }
6748
+ async function requireKeyAdmin(host, request, options) {
6749
+ const staff = await requireAdminStaff(host, request, options);
6750
+ if (staff instanceof Response) return staff;
6751
+ if (!host.apiKeys) return Response.json(NOT_ENABLED4, { status: 501 });
6752
+ if (staff.role.startsWith(API_KEY_ROLE_PREFIX)) return Response.json({ error: "API keys are managed by a signed-in person, not with an API key" }, { status: 403 });
6753
+ return staff;
6754
+ }
6755
+ async function listApiKeysRoute(request, { host }) {
6756
+ try {
6757
+ const staff = await requireKeyAdmin(host, request, { action: "admin-api-keys-list", tier: "GENERAL" });
6758
+ if (staff instanceof Response) return staff;
6759
+ return Response.json({ keys: await listApiKeys(staff.db, staff.organizationId) });
6760
+ } catch (error) {
6761
+ return failure3(error, "Failed to list the API keys");
6762
+ }
6763
+ }
6764
+ async function createApiKeyRoute(request, { host }) {
6765
+ try {
6766
+ const staff = await requireKeyAdmin(host, request, { action: "admin-api-keys-create", tier: "SETTINGS" });
6767
+ if (staff instanceof Response) return staff;
6768
+ const validation = await parseBody(request, ApiKeySchema);
6769
+ if (!validation.success) return validation.response;
6770
+ const { key, view } = await createApiKey(staff.db, staff.organizationId, validation.data, staff.userId);
6771
+ await host.activity.log(staff.db, { action: "scheduling.api_key_created", description: `made the API key "${view.name}"`, metadata: { keyId: view.id, access: view.access } }).catch((error) => {
6772
+ console.error("[api-keys] could not record the new key in the activity log", error);
6773
+ });
6774
+ return Response.json({ key, apiKey: view }, { status: 201, headers: { "Cache-Control": "no-store" } });
6775
+ } catch (error) {
6776
+ return failure3(error, "Failed to make the API key");
6777
+ }
6778
+ }
6779
+ async function revokeApiKeyRoute(request, { host, params }) {
6780
+ try {
6781
+ const staff = await requireKeyAdmin(host, request, { action: "admin-api-keys-revoke", tier: "DELETE" });
6782
+ if (staff instanceof Response) return staff;
6783
+ const revoked = await revokeApiKey(staff.db, staff.organizationId, params.id);
6784
+ if (revoked) await host.activity.log(staff.db, { action: "scheduling.api_key_revoked", description: "revoked an API key", metadata: { keyId: params.id } });
6785
+ return Response.json({ revoked });
6786
+ } catch (error) {
6787
+ return failure3(error, "Failed to revoke the API key");
6788
+ }
6789
+ }
6790
+
6791
+ // src/handlers/admin-gift-certificates.ts
6792
+ import { issueGiftCertificateOnce, listGiftCertificates } from "@ordinatio/scheduling";
6793
+
6794
+ // src/gift-certificates/gift-http.ts
6795
+ import { SchedulingNotFoundError as SchedulingNotFoundError11, SchedulingValidationError as SchedulingValidationError13 } from "@ordinatio/scheduling";
6796
+ var NOT_ENABLED5 = { error: "Gift certificates are not enabled on this server" };
6797
+ var BAD_REQUEST = /* @__PURE__ */ new Set(["SCHED_1700", "SCHED_1706", "SCHED_1709"]);
6798
+ var CONFLICT = /* @__PURE__ */ new Set(["SCHED_1702", "SCHED_1703", "SCHED_1704", "SCHED_1707", "SCHED_1708", "SCHED_1710"]);
6799
+ var CODE_SHAPE = /\b[A-Za-z0-9]{4}[- ]?[A-Za-z0-9]{4}[- ]?[A-Za-z0-9]{4}\b/g;
6800
+ function safeErrorText(error) {
6801
+ if (!(error instanceof Error)) return "unknown error";
6802
+ const code = error.code;
6803
+ return `${error.name}${typeof code === "string" ? ` ${code}` : ""}: ${error.message.replace(CODE_SHAPE, "[code]").slice(0, 300)}`;
6804
+ }
6805
+ function forCaller(staff, certificate) {
6806
+ if (!staff.role.startsWith(API_KEY_ROLE_PREFIX) || staff.role === `${API_KEY_ROLE_PREFIX}FULL`) return certificate;
6807
+ return { ...certificate, code: `\u2026${certificate.code.slice(-4)}`, codeHidden: true };
6808
+ }
6809
+ function noStoreJson(body, init = {}) {
6810
+ return Response.json(body, { status: init.status ?? 200, headers: { "Cache-Control": "no-store" } });
6811
+ }
6812
+ function giftFailure(error, fallback) {
6813
+ if (error instanceof SchedulingNotFoundError11) return Response.json({ error: error.message, code: error.code, ref: getErrorRef(error) }, { status: 404 });
6814
+ if (error instanceof SchedulingValidationError13) {
6815
+ const status = BAD_REQUEST.has(error.code) ? 400 : CONFLICT.has(error.code) ? 409 : 500;
6816
+ if (status !== 500) {
6817
+ const details = error.context?.errors;
6818
+ return Response.json({ error: error.message, code: error.code, ref: getErrorRef(error), ...details ? { details } : {} }, { status });
6819
+ }
6820
+ }
6821
+ console.error("[gift-certificates]", safeErrorText(error));
6822
+ return Response.json({ error: fallback }, { status: 500 });
6823
+ }
6824
+ async function recordGiftActivity(host, staff, entry) {
6825
+ await host.activity.log(staff.db, entry).catch((error) => {
6826
+ console.error("[gift-certificates] could not record the activity", safeErrorText(error));
6827
+ });
6828
+ }
6829
+ async function requireGiftAdmin(host, request, options) {
6830
+ const staff = await requireAdminStaff(host, request, options);
6831
+ if (staff instanceof Response) return staff;
6832
+ if (!host.giftCertificates) return Response.json(NOT_ENABLED5, { status: 501 });
6833
+ return staff;
6834
+ }
6835
+
6836
+ // src/handlers/admin-gift-certificates.ts
6837
+ async function listGiftCertificatesRoute(request, { host }) {
6838
+ try {
6839
+ const staff = await requireGiftAdmin(host, request, { action: "admin-gift-certificates-list", tier: "GENERAL" });
6840
+ if (staff instanceof Response) return staff;
6841
+ const params = new URL(request.url).searchParams;
6842
+ const status = params.get("status");
6843
+ if (status !== null && status !== "ACTIVE" && status !== "VOID") return Response.json({ error: "status must be ACTIVE or VOID" }, { status: 400 });
6844
+ const limit = params.get("limit");
6845
+ const certificates = await listGiftCertificates(staff.db, staff.organizationId, { ...status ? { status } : {}, ...limit ? { limit: Number(limit) } : {} });
6846
+ return noStoreJson({ certificates: certificates.map((certificate) => forCaller(staff, certificate)) });
6847
+ } catch (error) {
6848
+ return giftFailure(error, "Failed to list the gift certificates");
6849
+ }
6850
+ }
6851
+ async function issueGiftCertificateRoute(request, { host }) {
6852
+ try {
6853
+ const staff = await requireGiftAdmin(host, request, { action: "admin-gift-certificates-issue", tier: "CREATE" });
6854
+ if (staff instanceof Response) return staff;
6855
+ const validation = await parseBody(request, GiftCertificateSchema);
6856
+ if (!validation.success) return validation.response;
6857
+ const { certificate, created } = await issueGiftCertificateOnce(staff.db, staff.organizationId, validation.data, staff.userId);
6858
+ if (!created) return noStoreJson({ certificate: forCaller(staff, certificate) });
6859
+ await recordGiftActivity(host, staff, {
6860
+ action: "scheduling.gift_certificate_issued",
6861
+ description: "issued a gift certificate",
6862
+ metadata: { certificateId: certificate.id, amountCents: certificate.initialCents, currency: certificate.currency }
6863
+ });
6864
+ return noStoreJson({ certificate: forCaller(staff, certificate) }, { status: 201 });
6865
+ } catch (error) {
6866
+ return giftFailure(error, "Failed to issue the gift certificate");
6867
+ }
6868
+ }
6869
+
6870
+ // src/handlers/admin-gift-certificate-detail.ts
6871
+ import { getGiftCertificate, restoreGiftCertificate, voidGiftCertificate } from "@ordinatio/scheduling";
6872
+ async function getGiftCertificateRoute(request, { host, params }) {
6873
+ try {
6874
+ const staff = await requireGiftAdmin(host, request, { action: "admin-gift-certificate-get", tier: "GENERAL" });
6875
+ if (staff instanceof Response) return staff;
6876
+ const found = await getGiftCertificate(staff.db, staff.organizationId, params.id);
6877
+ return noStoreJson({ ...found, certificate: forCaller(staff, found.certificate) });
6878
+ } catch (error) {
6879
+ return giftFailure(error, "Failed to read the gift certificate");
6880
+ }
6881
+ }
6882
+ async function voidGiftCertificateRoute(request, { host, params }) {
6883
+ try {
6884
+ const staff = await requireGiftAdmin(host, request, { action: "admin-gift-certificate-void", tier: "DELETE" });
6885
+ if (staff instanceof Response) return staff;
6886
+ const voided = await voidGiftCertificate(staff.db, staff.organizationId, params.id, staff.userId);
6887
+ if (!voided) return Response.json({ error: "Gift certificate not found, or already void" }, { status: 404 });
6888
+ await recordGiftActivity(host, staff, { action: "scheduling.gift_certificate_voided", description: "voided a gift certificate", metadata: { certificateId: params.id } });
6889
+ return noStoreJson({ voided: true });
6890
+ } catch (error) {
6891
+ return giftFailure(error, "Failed to void the gift certificate");
6892
+ }
6893
+ }
6894
+ async function restoreGiftCertificateRoute(request, { host, params }) {
6895
+ try {
6896
+ const staff = await requireGiftAdmin(host, request, { action: "admin-gift-certificate-restore", tier: "UPDATE" });
6897
+ if (staff instanceof Response) return staff;
6898
+ const validation = await parseBody(request, GiftCertificateRestoreSchema);
6899
+ if (!validation.success) return validation.response;
6900
+ const restored = await restoreGiftCertificate(staff.db, staff.organizationId, params.id, validation.data, staff.userId);
6901
+ await recordGiftActivity(host, staff, {
6902
+ action: "scheduling.gift_certificate_restored",
6903
+ description: "gave value back to a gift certificate",
6904
+ metadata: { certificateId: params.id, amountCents: restored.restoredCents, ...validation.data.appointmentId ? { appointmentId: validation.data.appointmentId } : {} }
6905
+ });
6906
+ return noStoreJson({ restored });
6907
+ } catch (error) {
6908
+ return giftFailure(error, "Failed to give value back to the gift certificate");
6909
+ }
6910
+ }
6911
+
6912
+ // src/handlers/gift-certificates-check.ts
6913
+ import { checkGiftCertificate, schedError as schedError28 } from "@ordinatio/scheduling";
6914
+ async function checkGiftCertificateRoute(request, { host }) {
6915
+ const cors = host.cors(request);
6916
+ const headers = { ...cors, "Cache-Control": "no-store" };
6917
+ if (!host.giftCertificates) return Response.json(NOT_ENABLED5, { status: 501, headers });
6918
+ const limited = await host.rateLimit(`gift-check:${clientAddress(request)}`, "PUBLIC_BOOKING");
6919
+ if (limited) return limited;
6920
+ const parsed = validateData(await request.json().catch(() => null), GiftCertificateCheckSchema);
6921
+ if (!parsed.success) return Response.json({ error: "Validation failed" }, { status: 400, headers });
6922
+ const { code, calendarId } = parsed.data;
6923
+ try {
6924
+ const db = await host.publicDb();
6925
+ const calendar = await db.schedulingCalendar.findUnique({ where: { id: calendarId }, select: { organizationId: true } });
6926
+ const found = calendar?.organizationId ? await checkGiftCertificate(db, calendar.organizationId, code) : null;
6927
+ if (!found) return Response.json({ valid: false, reason: "not_found" }, { headers });
6928
+ if (found.state !== "ACTIVE") return Response.json({ valid: false, reason: found.state.toLowerCase() }, { headers });
6929
+ return Response.json({ valid: true, balanceCents: found.balanceCents, currency: found.currency, expiresAt: found.expiresAt }, { headers });
6930
+ } catch (error) {
6931
+ const err = schedError28("SCHED_408", { calendarId, error: safeErrorText(error) });
6932
+ console.error(`[${err.ref}] gift certificate check failed:`, safeErrorText(error));
6933
+ return Response.json({ valid: false, reason: "error", error: err.description, ref: err.ref }, { status: 500, headers });
6934
+ }
6935
+ }
6936
+
6937
+ // src/handlers/admin-text-settings.ts
6938
+ import { deleteTextSettings, getTextSettings, saveTextSettings, SchedulingValidationError as SchedulingValidationError14 } from "@ordinatio/scheduling";
6939
+ var NOT_ENABLED6 = { error: "Text-message settings are not enabled on this server" };
6940
+ function failure4(error, fallback) {
6941
+ if (error instanceof SchedulingValidationError14) {
6942
+ const details = error.context.errors;
6943
+ return Response.json({ error: error.message, code: error.code, ref: getErrorRef(error), ...details ? { details } : {} }, { status: 400 });
6944
+ }
6665
6945
  console.error("[text-settings]", error);
6666
6946
  return Response.json({ error: fallback }, { status: 500 });
6667
6947
  }
6668
6948
  async function requireTextAdmin(host, request, options) {
6669
6949
  const staff = await requireAdminStaff(host, request, options);
6670
6950
  if (staff instanceof Response) return staff;
6671
- if (!host.textMessages) return Response.json(NOT_ENABLED4, { status: 501 });
6951
+ if (!host.textMessages) return Response.json(NOT_ENABLED6, { status: 501 });
6672
6952
  return staff;
6673
6953
  }
6674
6954
  async function getTextSettingsRoute(request, { host }) {
@@ -6677,7 +6957,7 @@ async function getTextSettingsRoute(request, { host }) {
6677
6957
  if (staff instanceof Response) return staff;
6678
6958
  return Response.json({ settings: await getTextSettings(staff.db, staff.organizationId), providers: host.textMessages?.providers ?? ["TELNYX", "TWILIO"] });
6679
6959
  } catch (error) {
6680
- return failure3(error, "Failed to read the text-message settings");
6960
+ return failure4(error, "Failed to read the text-message settings");
6681
6961
  }
6682
6962
  }
6683
6963
  async function saveTextSettingsRoute(request, { host }) {
@@ -6694,7 +6974,7 @@ async function saveTextSettingsRoute(request, { host }) {
6694
6974
  });
6695
6975
  return Response.json({ settings });
6696
6976
  } catch (error) {
6697
- return failure3(error, "Failed to save the text-message settings");
6977
+ return failure4(error, "Failed to save the text-message settings");
6698
6978
  }
6699
6979
  }
6700
6980
  async function deleteTextSettingsRoute(request, { host }) {
@@ -6705,7 +6985,7 @@ async function deleteTextSettingsRoute(request, { host }) {
6705
6985
  if (removed) await host.activity.log(staff.db, { action: "scheduling.text_settings_removed", description: "removed the text-message settings", metadata: {} });
6706
6986
  return Response.json({ removed });
6707
6987
  } catch (error) {
6708
- return failure3(error, "Failed to remove the text-message settings");
6988
+ return failure4(error, "Failed to remove the text-message settings");
6709
6989
  }
6710
6990
  }
6711
6991
 
@@ -6781,11 +7061,11 @@ async function checkSendingDomainRoute(request, { host }) {
6781
7061
  import { eraseSubject, exportSubject, listPrivacyRequests, previewErase } from "@ordinatio/scheduling";
6782
7062
 
6783
7063
  // src/privacy/privacy-http.ts
6784
- import { SchedulingValidationError as SchedulingValidationError13 } from "@ordinatio/scheduling";
6785
- var NOT_ENABLED5 = { error: "Data export and erasure are not enabled on this server" };
7064
+ import { SchedulingValidationError as SchedulingValidationError15 } from "@ordinatio/scheduling";
7065
+ var NOT_ENABLED7 = { error: "Data export and erasure are not enabled on this server" };
6786
7066
  var STATUS_BY_CODE3 = { SCHED_1300: 400, SCHED_1301: 409 };
6787
7067
  function privacyErrorResponse(error, fallback) {
6788
- if (error instanceof SchedulingValidationError13) {
7068
+ if (error instanceof SchedulingValidationError15) {
6789
7069
  return Response.json(
6790
7070
  { error: error.message, code: error.code, ref: getErrorRef(error), details: error.context },
6791
7071
  { status: STATUS_BY_CODE3[error.code] ?? 400 }
@@ -6797,7 +7077,7 @@ function privacyErrorResponse(error, fallback) {
6797
7077
  async function requirePrivacyAdmin(host, request, options) {
6798
7078
  const staff = await requireAdminStaff(host, request, options);
6799
7079
  if (staff instanceof Response) return staff;
6800
- if (!host.privacy) return Response.json(NOT_ENABLED5, { status: 501 });
7080
+ if (!host.privacy) return Response.json(NOT_ENABLED7, { status: 501 });
6801
7081
  return staff;
6802
7082
  }
6803
7083
 
@@ -6920,7 +7200,7 @@ async function testRoutingFormRoute(request, { host, params }) {
6920
7200
  }
6921
7201
 
6922
7202
  // src/handlers/appointments-list.ts
6923
- import { schedError as schedError28, withOrganization } from "@ordinatio/scheduling";
7203
+ import { schedError as schedError29, withOrganization } from "@ordinatio/scheduling";
6924
7204
  var DEFAULT_LIMIT2 = 50;
6925
7205
  var MAX_LIMIT2 = 500;
6926
7206
  async function listAppointments(request, { host }) {
@@ -6932,7 +7212,7 @@ async function listAppointments(request, { host }) {
6932
7212
  const clientId = params.get("clientId") || void 0;
6933
7213
  const status = params.get("status") || void 0;
6934
7214
  if (!clientId && !staff.isAdmin) {
6935
- const err = schedError28("SCHED_900", { role: staff.role });
7215
+ const err = schedError29("SCHED_900", { role: staff.role });
6936
7216
  return Response.json({ error: "Forbidden", ref: err.ref }, { status: 403 });
6937
7217
  }
6938
7218
  const startDate = params.get("startDate");
@@ -7217,7 +7497,7 @@ async function getTeamAvailability(request, { host }) {
7217
7497
  }
7218
7498
 
7219
7499
  // src/handlers/appointment-types.ts
7220
- import { schedError as schedError29 } from "@ordinatio/scheduling";
7500
+ import { schedError as schedError30 } from "@ordinatio/scheduling";
7221
7501
 
7222
7502
  // src/loaders/types-by-calendar.ts
7223
7503
  function loadTypesByCalendarSlug(cache, db, organizationId, calendarSlug) {
@@ -7291,7 +7571,7 @@ async function getAppointmentTypes(request, { host }) {
7291
7571
  }));
7292
7572
  return corsJson(cors, response, { headers: WIDGET_CACHE_HEADERS });
7293
7573
  } catch (error) {
7294
- const diagnostic = schedError29("SCHED_202", { error });
7574
+ const diagnostic = schedError30("SCHED_202", { error });
7295
7575
  console.error("[appointment-types]", diagnostic.ref, error);
7296
7576
  return corsJson(cors, { error: "Failed to fetch appointment types", ref: diagnostic.ref }, { status: 500 });
7297
7577
  }
@@ -7299,7 +7579,7 @@ async function getAppointmentTypes(request, { host }) {
7299
7579
 
7300
7580
  // src/handlers/coupons-validate.ts
7301
7581
  import { z as z10 } from "zod";
7302
- import { schedError as schedError30 } from "@ordinatio/scheduling";
7582
+ import { schedError as schedError31 } from "@ordinatio/scheduling";
7303
7583
  var Schema4 = z10.object({
7304
7584
  code: z10.string().min(1).max(50).transform((v) => v.trim().toUpperCase()),
7305
7585
  calendarId: z10.string().min(1),
@@ -7361,7 +7641,7 @@ async function validateCoupon(request, { host }) {
7361
7641
  { headers: host.cors(request) }
7362
7642
  );
7363
7643
  } catch (error) {
7364
- const err = schedError30("SCHED_408", {
7644
+ const err = schedError31("SCHED_408", {
7365
7645
  calendarId,
7366
7646
  error: error instanceof Error ? error.message : String(error)
7367
7647
  });
@@ -7441,7 +7721,7 @@ async function listActiveCalendars(request, { host }) {
7441
7721
  }
7442
7722
 
7443
7723
  // src/handlers/type.ts
7444
- import { schedError as schedError31 } from "@ordinatio/scheduling";
7724
+ import { schedError as schedError32 } from "@ordinatio/scheduling";
7445
7725
 
7446
7726
  // src/loaders/type-by-slug.ts
7447
7727
  function loadTypeBySlug(cache, db, organizationId, slug) {
@@ -7546,14 +7826,14 @@ async function getType(request, { host }) {
7546
7826
  { headers: WIDGET_CACHE_HEADERS }
7547
7827
  );
7548
7828
  } catch (error) {
7549
- const diagnostic = schedError31("SCHED_207", { error });
7829
+ const diagnostic = schedError32("SCHED_207", { error });
7550
7830
  console.error("[type]", diagnostic.ref, error);
7551
7831
  return corsJson(cors, { error: "Failed to fetch appointment type", ref: diagnostic.ref }, { status: 500 });
7552
7832
  }
7553
7833
  }
7554
7834
 
7555
7835
  // src/handlers/widget-init.ts
7556
- import { schedError as schedError32 } from "@ordinatio/scheduling";
7836
+ import { schedError as schedError33 } from "@ordinatio/scheduling";
7557
7837
 
7558
7838
  // src/loaders/widget-data.ts
7559
7839
  function loadWidgetData(cache, db, organizationId, calendarSlug) {
@@ -7642,7 +7922,7 @@ async function getWidgetInit(request, { host }) {
7642
7922
  }));
7643
7923
  return corsJson(cors, { calendar, types: sanitizedTypes }, { headers: WIDGET_CACHE_HEADERS });
7644
7924
  } catch (error) {
7645
- const diagnostic = schedError32("SCHED_206", { error });
7925
+ const diagnostic = schedError33("SCHED_206", { error });
7646
7926
  console.error("[widget-init]", diagnostic.ref, error);
7647
7927
  return corsJson(cors, { error: "Failed to load widget data", ref: diagnostic.ref }, { status: 500 });
7648
7928
  }
@@ -7651,6 +7931,7 @@ async function getWidgetInit(request, { host }) {
7651
7931
  // src/routes.ts
7652
7932
  var ROUTES = [
7653
7933
  { method: "POST", path: "/coupons/validate", public: true, handler: validateCoupon },
7934
+ { method: "POST", path: "/gift-certificates/check", public: true, handler: checkGiftCertificateRoute },
7654
7935
  { method: "POST", path: "/payments/intent", public: true, handler: createPaymentIntentRoute },
7655
7936
  { method: "GET", path: "/widget-init", public: true, handler: getWidgetInit },
7656
7937
  { method: "GET", path: "/type", public: true, handler: getType },
@@ -7720,6 +8001,14 @@ var ROUTES = [
7720
8001
  { method: "GET", path: "/admin/text-settings", public: false, handler: getTextSettingsRoute },
7721
8002
  { method: "PUT", path: "/admin/text-settings", public: false, handler: saveTextSettingsRoute },
7722
8003
  { method: "DELETE", path: "/admin/text-settings", public: false, handler: deleteTextSettingsRoute },
8004
+ { method: "GET", path: "/admin/api-keys", public: false, handler: listApiKeysRoute },
8005
+ { method: "POST", path: "/admin/api-keys", public: false, handler: createApiKeyRoute },
8006
+ { method: "DELETE", path: "/admin/api-keys/[id]", public: false, handler: revokeApiKeyRoute },
8007
+ { method: "GET", path: "/admin/gift-certificates", public: false, handler: listGiftCertificatesRoute },
8008
+ { method: "POST", path: "/admin/gift-certificates", public: false, handler: issueGiftCertificateRoute },
8009
+ { method: "GET", path: "/admin/gift-certificates/[id]", public: false, handler: getGiftCertificateRoute },
8010
+ { method: "POST", path: "/admin/gift-certificates/[id]/void", public: false, handler: voidGiftCertificateRoute },
8011
+ { method: "POST", path: "/admin/gift-certificates/[id]/restore", public: false, handler: restoreGiftCertificateRoute },
7723
8012
  { method: "GET", path: "/admin/brand/sending-domain", public: false, handler: checkSendingDomainRoute },
7724
8013
  { method: "POST", path: "/admin/privacy/export", public: false, handler: exportPrivacyRoute },
7725
8014
  { method: "POST", path: "/admin/privacy/erase", public: false, handler: erasePrivacyRoute },
@@ -7754,11 +8043,11 @@ var ROUTES = [
7754
8043
  { method: "POST", path: "/appointments/[id]/followup", public: false, handler: sendFollowup },
7755
8044
  { method: "POST", path: "/appointments/[id]/remind", public: false, handler: sendReminder },
7756
8045
  { method: "POST", path: "/appointments/[id]/cancel", public: false, handler: cancelByStaff },
7757
- { method: "GET", path: "/calendars/connect-google", public: false, handler: startGoogleConnection },
7758
- { method: "POST", path: "/calendars/connect-google", public: false, handler: setGoogleCalendar },
7759
- { method: "GET", path: "/calendars/connect-google/callback", public: false, handler: finishGoogleConnection },
7760
- { method: "GET", path: "/calendars/connect-outlook", public: false, handler: startOutlookConnection },
7761
- { method: "GET", path: "/calendars/connect-outlook/callback", public: false, handler: finishOutlookConnection },
8046
+ { method: "GET", path: "/calendars/connect-google", public: false, personOnly: true, handler: startGoogleConnection },
8047
+ { method: "POST", path: "/calendars/connect-google", public: false, personOnly: true, handler: setGoogleCalendar },
8048
+ { method: "GET", path: "/calendars/connect-google/callback", public: false, personOnly: true, handler: finishGoogleConnection },
8049
+ { method: "GET", path: "/calendars/connect-outlook", public: false, personOnly: true, handler: startOutlookConnection },
8050
+ { method: "GET", path: "/calendars/connect-outlook/callback", public: false, personOnly: true, handler: finishOutlookConnection },
7762
8051
  { method: "POST", path: "/appointments/[id]/cancel-sync", public: false, handler: cancelFromCalendarSync },
7763
8052
  { method: "POST", path: "/appointments/[id]/approve", public: false, handler: approveOrReject },
7764
8053
  { method: "POST", path: "/appointments/[id]/reschedule", public: false, handler: rescheduleByStaff },
@@ -7816,6 +8105,8 @@ function createSchedulingApi(config) {
7816
8105
  privacy: config.host.privacy ?? null,
7817
8106
  brand: config.host.brand ?? null,
7818
8107
  textMessages: config.host.textMessages ?? null,
8108
+ apiKeys: config.host.apiKeys ?? null,
8109
+ giftCertificates: config.host.giftCertificates ?? null,
7819
8110
  icalUidDomain: config.host.icalUidDomain?.bind(config.host) ?? (() => null),
7820
8111
  calendarSync: config.host.calendarSync ?? { upsertEvent: async () => ({}), removeEvent: async () => void 0 },
7821
8112
  activity: config.host.activity ?? { log: async () => void 0, isOpen: async () => false, resolve: async () => void 0 },
@@ -7843,6 +8134,14 @@ function createSchedulingApi(config) {
7843
8134
  cors: config.host.cors?.bind(config.host) ?? defaultCorsHeaders
7844
8135
  };
7845
8136
  host.events = withWebhooks(withWaitlist(config.host.events ?? { emit: async () => void 0 }, host), host);
8137
+ async function hostForRoute(route, request) {
8138
+ try {
8139
+ return await hostForRequest(host, request, route);
8140
+ } catch (error) {
8141
+ console.error("[scheduling-api] could not check the API key:", error);
8142
+ return Response.json({ error: "Internal error" }, { status: 500 });
8143
+ }
8144
+ }
7846
8145
  async function handle(request) {
7847
8146
  const { pathname } = new URL(request.url);
7848
8147
  if (pathname !== basePath && !pathname.startsWith(`${basePath}/`)) return notFound();
@@ -7860,7 +8159,9 @@ function createSchedulingApi(config) {
7860
8159
  return Response.json({ error: "Method not allowed" }, { status: 405, headers: { Allow: allowed.join(", ") } });
7861
8160
  }
7862
8161
  try {
7863
- return await hit.route.handler(request, { host, params: hit.params });
8162
+ const runHost = await hostForRoute(hit.route, request);
8163
+ if (runHost instanceof Response) return runHost;
8164
+ return await hit.route.handler(request, { host: runHost, params: hit.params });
7864
8165
  } catch (error) {
7865
8166
  console.error("[scheduling-api] unhandled error:", error);
7866
8167
  return Response.json({ error: "Internal error" }, { status: 500 });
@@ -7871,7 +8172,9 @@ function createSchedulingApi(config) {
7871
8172
  if (!route) throw new Error(`No route ${method} ${path}`);
7872
8173
  return async (request, context) => {
7873
8174
  const params = await context?.params ?? {};
7874
- return route.handler(request, { host, params });
8175
+ const runHost = await hostForRoute(route, request);
8176
+ if (runHost instanceof Response) return runHost;
8177
+ return route.handler(request, { host: runHost, params });
7875
8178
  };
7876
8179
  }
7877
8180
  return { routes, handle, handler };
@@ -8627,44 +8930,6 @@ function createOutlookCalendarSync(config, hooks) {
8627
8930
  };
8628
8931
  }
8629
8932
 
8630
- // src/staff/simple-staff.ts
8631
- var DEFAULT_ADMIN_ROLES = ["OWNER", "ADMIN", "MANAGER"];
8632
- function createStaffContext(input) {
8633
- const adminRoles = (input.adminRoles ?? DEFAULT_ADMIN_ROLES).map((role) => role.toUpperCase());
8634
- const { db, organizationId } = input;
8635
- return {
8636
- userId: input.userId,
8637
- organizationId,
8638
- role: input.role,
8639
- isAdmin: adminRoles.includes(input.role.toUpperCase()),
8640
- schedulingEnabled: input.schedulingEnabled ?? true,
8641
- db,
8642
- visibleCalendars: async () => null,
8643
- visibleCalendarIds: async () => void 0,
8644
- canSeeCalendar: async (calendarId) => Boolean(await db.schedulingCalendar.findFirst({ where: { id: calendarId, organizationId }, select: { id: true } })),
8645
- canSeeAppointment: async (appointmentId) => Boolean(await db.appointment.findFirst({ where: { id: appointmentId, calendar: { organizationId } }, select: { id: true } })),
8646
- // The package has no client table, so there is no preference to read.
8647
- preferredLocationOf: async () => null
8648
- };
8649
- }
8650
- var BEARER = /^bearer\s+(\S+)$/i;
8651
- function createBearerStaffResolver(input) {
8652
- return {
8653
- async resolve(request) {
8654
- const token = BEARER.exec(request.headers.get("authorization") ?? "")?.[1];
8655
- if (!token) return null;
8656
- const person = await input.authenticate(token, request);
8657
- if (!person) return null;
8658
- return createStaffContext({
8659
- ...person,
8660
- db: await input.db(person),
8661
- adminRoles: input.adminRoles,
8662
- schedulingEnabled: input.schedulingEnabled ? await input.schedulingEnabled(person) : void 0
8663
- });
8664
- }
8665
- };
8666
- }
8667
-
8668
8933
  // src/staff/staff-scope.ts
8669
8934
  function isCalendarVisibleInScope(calendarUserId, scope) {
8670
8935
  if (calendarUserId === null) return true;
@@ -8779,6 +9044,7 @@ function createNodeListener(api, options) {
8779
9044
  }
8780
9045
  export {
8781
9046
  ALL_REFUND_STATUSES,
9047
+ ApiKeySchema,
8782
9048
  BALANCE_APPOINTMENT_SELECT,
8783
9049
  BALANCE_BLOCKED_APPOINTMENT_STATUS,
8784
9050
  BALANCE_REQUIRED_PAYMENT_STATUS,
@@ -8802,6 +9068,9 @@ export {
8802
9068
  CreateServicePackageSchema,
8803
9069
  CreateWebhookEndpointSchema,
8804
9070
  DEFAULT_CANCELLATION_POLICY,
9071
+ GiftCertificateCheckSchema,
9072
+ GiftCertificateRestoreSchema,
9073
+ GiftCertificateSchema,
8805
9074
  IntakeFormFieldSchema,
8806
9075
  NoShowPreventionActionSchema,
8807
9076
  NotificationChannelSchema,
@@ -8833,6 +9102,7 @@ export {
8833
9102
  UpdateServicePackageSchema,
8834
9103
  assertStripeTestKey,
8835
9104
  attemptLegRefund,
9105
+ bearerKeyOf,
8836
9106
  calendarVisibilityFilter,
8837
9107
  canSeeAppointmentInScope,
8838
9108
  canSeeCalendarInScope,