@ordinatio/scheduling-api 0.5.1 → 0.7.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/CHANGELOG.md +18 -0
- package/README.md +89 -1
- package/dist/agent/index.d.mts +1 -1
- package/dist/agent/index.d.ts +1 -1
- package/dist/agent/index.js +77 -0
- package/dist/agent/index.mjs +77 -0
- package/dist/{chunk-WZ5KO7IW.mjs → chunk-IW6AN5WE.mjs} +10 -1
- package/dist/index.d.mts +308 -5
- package/dist/index.d.ts +308 -5
- package/dist/index.js +1095 -90
- package/dist/index.mjs +998 -26
- package/dist/{routes-CM-ezlv2.d.mts → routes-LaFljBCF.d.mts} +61 -2
- package/dist/{routes-CM-ezlv2.d.ts → routes-LaFljBCF.d.ts} +61 -2
- package/dist/schemas/index.d.mts +7 -1
- package/dist/schemas/index.d.ts +7 -1
- package/dist/schemas/index.js +10 -0
- package/dist/schemas/index.mjs +3 -1
- package/package.json +4 -3
package/dist/index.js
CHANGED
|
@@ -67,9 +67,12 @@ __export(index_exports, {
|
|
|
67
67
|
RouteClientSchema: () => RouteClientSchema,
|
|
68
68
|
SLOT_GRANULARITY_DEFAULT: () => SLOT_GRANULARITY_DEFAULT,
|
|
69
69
|
SLOT_GRANULARITY_OPTIONS: () => SLOT_GRANULARITY_OPTIONS,
|
|
70
|
+
SmsSendError: () => SmsSendError,
|
|
70
71
|
TERMINAL_SUCCESS_STATUSES: () => TERMINAL_SUCCESS_STATUSES,
|
|
71
72
|
TOKEN_TTL_DAYS: () => TOKEN_TTL_DAYS,
|
|
73
|
+
TelnyxSendError: () => SmsSendError,
|
|
72
74
|
TestRoutingFormSchema: () => TestRoutingFormSchema,
|
|
75
|
+
TextSettingsSchema: () => TextSettingsSchema,
|
|
73
76
|
UnverifiedPaymentError: () => UnverifiedPaymentError,
|
|
74
77
|
UpdateAppointmentCategorySchema: () => UpdateAppointmentCategorySchema,
|
|
75
78
|
UpdateAppointmentTypeSchema: () => UpdateAppointmentTypeSchema,
|
|
@@ -80,7 +83,13 @@ __export(index_exports, {
|
|
|
80
83
|
UpdatePackagePurchaseSchema: () => UpdatePackagePurchaseSchema,
|
|
81
84
|
UpdateRoutingFormSchema: () => UpdateRoutingFormSchema,
|
|
82
85
|
UpdateServicePackageSchema: () => UpdateServicePackageSchema,
|
|
86
|
+
assertStripeTestKey: () => assertStripeTestKey,
|
|
83
87
|
attemptLegRefund: () => attemptLegRefund,
|
|
88
|
+
calendarVisibilityFilter: () => calendarVisibilityFilter,
|
|
89
|
+
canSeeAppointmentInScope: () => canSeeAppointmentInScope,
|
|
90
|
+
canSeeCalendarInScope: () => canSeeCalendarInScope,
|
|
91
|
+
checkSendingDomain: () => checkSendingDomain,
|
|
92
|
+
classifyReply: () => classifyReply,
|
|
84
93
|
createBalanceIntent: () => createBalanceIntent,
|
|
85
94
|
createBearerStaffResolver: () => createBearerStaffResolver,
|
|
86
95
|
createMemoryAvailabilityCache: () => createMemoryAvailabilityCache,
|
|
@@ -89,22 +98,39 @@ __export(index_exports, {
|
|
|
89
98
|
createNoBalancePaymentControl: () => createNoBalancePaymentControl,
|
|
90
99
|
createNoPaymentAdapter: () => createNoPaymentAdapter,
|
|
91
100
|
createNodeListener: () => createNodeListener,
|
|
101
|
+
createOutlookCalendarSync: () => createOutlookCalendarSync,
|
|
102
|
+
createPerBusinessSmsAdapter: () => createPerBusinessSmsAdapter,
|
|
92
103
|
createSchedulingApi: () => createSchedulingApi,
|
|
104
|
+
createScopedVisibility: () => createScopedVisibility,
|
|
105
|
+
createSendingDomainVerifier: () => createSendingDomainVerifier,
|
|
93
106
|
createSingleOrganizationDirectory: () => createSingleOrganizationDirectory,
|
|
94
107
|
createSingleOrganizationResolver: () => createSingleOrganizationResolver,
|
|
95
108
|
createStaffContext: () => createStaffContext,
|
|
109
|
+
createStripePaymentAdapter: () => createStripePaymentAdapter,
|
|
110
|
+
createTelnyxSmsAdapter: () => createTelnyxSmsAdapter,
|
|
111
|
+
createTextSettingsResolver: () => createTextSettingsResolver,
|
|
112
|
+
createTwilioSmsAdapter: () => createTwilioSmsAdapter,
|
|
96
113
|
decimalToCents: () => decimalToCents,
|
|
97
114
|
defaultCorsHeaders: () => defaultCorsHeaders,
|
|
98
115
|
getErrorCode: () => getErrorCode,
|
|
99
116
|
getErrorMessage: () => getErrorMessage,
|
|
100
117
|
getErrorRef: () => getErrorRef,
|
|
118
|
+
handleTelnyxWebhook: () => handleTelnyxWebhook,
|
|
119
|
+
handleTwilioWebhook: () => handleTwilioWebhook,
|
|
120
|
+
isCalendarVisibleInScope: () => isCalendarVisibleInScope,
|
|
101
121
|
isSchedulingServiceError: () => isSchedulingServiceError,
|
|
122
|
+
isSupportedCurrency: () => isSupportedCurrency,
|
|
102
123
|
isTokenExpired: () => isTokenExpired,
|
|
124
|
+
normalizePhoneNumber: () => normalizePhoneNumber,
|
|
125
|
+
normalizeSendingDomain: () => normalizeSendingDomain,
|
|
103
126
|
parsePagination: () => parsePagination,
|
|
104
127
|
persistRefundOutcome: () => persistRefundOutcome,
|
|
105
128
|
recordBalanceIntent: () => recordBalanceIntent,
|
|
106
129
|
runCalendarRemoveWithoutBlocking: () => runCalendarRemoveWithoutBlocking,
|
|
107
|
-
runCalendarSyncWithoutBlocking: () => runCalendarSyncWithoutBlocking
|
|
130
|
+
runCalendarSyncWithoutBlocking: () => runCalendarSyncWithoutBlocking,
|
|
131
|
+
verifyTelnyxSignature: () => verifyTelnyxSignature,
|
|
132
|
+
verifyTwilioSignature: () => verifyTwilioSignature,
|
|
133
|
+
visibleCalendarIdsInScope: () => visibleCalendarIdsInScope
|
|
108
134
|
});
|
|
109
135
|
module.exports = __toCommonJS(index_exports);
|
|
110
136
|
|
|
@@ -1765,9 +1791,9 @@ function invalid(error) {
|
|
|
1765
1791
|
details: error.issues.map((e) => ({ field: e.path.join("."), message: e.message }))
|
|
1766
1792
|
}, { status: 400 });
|
|
1767
1793
|
}
|
|
1768
|
-
function failure(
|
|
1794
|
+
function failure(label2, error, fallback) {
|
|
1769
1795
|
const ref = getErrorRef(error);
|
|
1770
|
-
console.error(`[${
|
|
1796
|
+
console.error(`[${label2}]`, ref, error instanceof Error ? error.message : error);
|
|
1771
1797
|
return Response.json({ error: getErrorMessage(error, fallback), ...ref && { ref } }, { status: 500 });
|
|
1772
1798
|
}
|
|
1773
1799
|
async function updateLocation(request, { host, params }) {
|
|
@@ -2523,16 +2549,16 @@ async function attemptLegRefund(payments, paymentIntentId, idempotencyKeySuffix,
|
|
|
2523
2549
|
return failedLeg(errorCode, logLabel, appointmentId, paymentIntentId, idempotencyKey, retriedAfterReplay, { error: result.error, message: result.error ?? result.code ?? "no reason given", requestId: result.requestId });
|
|
2524
2550
|
}
|
|
2525
2551
|
}
|
|
2526
|
-
function failedLeg(errorCode, logLabel, appointmentId, paymentIntentId, idempotencyKey, retriedAfterReplay,
|
|
2527
|
-
const diagnostic = (0, import_scheduling24.schedError)(errorCode, { error:
|
|
2552
|
+
function failedLeg(errorCode, logLabel, appointmentId, paymentIntentId, idempotencyKey, retriedAfterReplay, failure4) {
|
|
2553
|
+
const diagnostic = (0, import_scheduling24.schedError)(errorCode, { error: failure4.error, appointmentId, paymentIntentId });
|
|
2528
2554
|
console.error(
|
|
2529
2555
|
`[resolve-refund] ${logLabel} refund failed${retriedAfterReplay ? " (after a fresh-key re-attempt)" : ""} \u2014 manual refund may be required:`,
|
|
2530
2556
|
diagnostic.ref,
|
|
2531
2557
|
appointmentId,
|
|
2532
2558
|
paymentIntentId,
|
|
2533
|
-
`requestId=${
|
|
2559
|
+
`requestId=${failure4.requestId}`,
|
|
2534
2560
|
`idempotencyKey=${idempotencyKey}`,
|
|
2535
|
-
|
|
2561
|
+
failure4.message
|
|
2536
2562
|
);
|
|
2537
2563
|
return { succeeded: false, amountCents: null };
|
|
2538
2564
|
}
|
|
@@ -3378,6 +3404,14 @@ var BrandSchema = import_zod14.z.object({
|
|
|
3378
3404
|
fromEmail: optionalText(400)
|
|
3379
3405
|
}).strict();
|
|
3380
3406
|
|
|
3407
|
+
// src/schemas/text-settings.schema.ts
|
|
3408
|
+
var import_zod15 = require("zod");
|
|
3409
|
+
var TextSettingsSchema = import_zod15.z.object({
|
|
3410
|
+
provider: import_zod15.z.string().max(40),
|
|
3411
|
+
fromNumber: import_zod15.z.string().max(40),
|
|
3412
|
+
enabled: import_zod15.z.boolean().optional()
|
|
3413
|
+
}).strict();
|
|
3414
|
+
|
|
3381
3415
|
// src/pagination.ts
|
|
3382
3416
|
var DEFAULT_LIMIT = 50;
|
|
3383
3417
|
var MAX_LIMIT = 200;
|
|
@@ -3399,12 +3433,12 @@ function parsePagination(request, maxLimit = MAX_LIMIT, defaultLimit = DEFAULT_L
|
|
|
3399
3433
|
}
|
|
3400
3434
|
|
|
3401
3435
|
// src/validation.ts
|
|
3402
|
-
var
|
|
3436
|
+
var import_zod16 = require("zod");
|
|
3403
3437
|
async function parseBody(request, schema) {
|
|
3404
3438
|
try {
|
|
3405
3439
|
return { success: true, data: schema.parse(await request.json()) };
|
|
3406
3440
|
} catch (error) {
|
|
3407
|
-
if (error instanceof
|
|
3441
|
+
if (error instanceof import_zod16.ZodError) {
|
|
3408
3442
|
const details = error.issues.map((issue) => ({ field: issue.path.join("."), message: issue.message }));
|
|
3409
3443
|
return { success: false, response: Response.json({ error: "Validation failed", details }, { status: 400 }) };
|
|
3410
3444
|
}
|
|
@@ -3418,7 +3452,7 @@ function validateData(data, schema) {
|
|
|
3418
3452
|
try {
|
|
3419
3453
|
return { success: true, data: schema.parse(data) };
|
|
3420
3454
|
} catch (error) {
|
|
3421
|
-
if (error instanceof
|
|
3455
|
+
if (error instanceof import_zod16.ZodError) {
|
|
3422
3456
|
return { success: false, errors: error.issues.map((issue) => ({ field: issue.path.join("."), message: issue.message })) };
|
|
3423
3457
|
}
|
|
3424
3458
|
return { success: false, errors: [{ field: "", message: "Validation failed" }] };
|
|
@@ -3949,24 +3983,24 @@ var import_scheduling29 = require("@ordinatio/scheduling");
|
|
|
3949
3983
|
// src/recurring/failure-collector.ts
|
|
3950
3984
|
function createFailureCollector() {
|
|
3951
3985
|
const problems = /* @__PURE__ */ new Map();
|
|
3952
|
-
const record = (
|
|
3986
|
+
const record = (label2, error) => {
|
|
3953
3987
|
const message = error instanceof Error ? error.message : String(error);
|
|
3954
|
-
const key = `${
|
|
3988
|
+
const key = `${label2}\0${message}`;
|
|
3955
3989
|
const known = problems.get(key);
|
|
3956
3990
|
if (known) known.count += 1;
|
|
3957
|
-
else problems.set(key, { label, message, count: 1 });
|
|
3991
|
+
else problems.set(key, { label: label2, message, count: 1 });
|
|
3958
3992
|
};
|
|
3959
|
-
const attempt = async (
|
|
3993
|
+
const attempt = async (label2, work) => {
|
|
3960
3994
|
try {
|
|
3961
3995
|
await work();
|
|
3962
3996
|
return true;
|
|
3963
3997
|
} catch (error) {
|
|
3964
|
-
record(
|
|
3998
|
+
record(label2, error);
|
|
3965
3999
|
return false;
|
|
3966
4000
|
}
|
|
3967
4001
|
};
|
|
3968
4002
|
const lines = () => [...problems.values()].map(
|
|
3969
|
-
({ label, message, count }) => count === 1 ? `${
|
|
4003
|
+
({ label: label2, message, count }) => count === 1 ? `${label2} failed: ${message}` : `${label2} failed for ${count} visits: ${message}`
|
|
3970
4004
|
);
|
|
3971
4005
|
return { record, attempt, lines };
|
|
3972
4006
|
}
|
|
@@ -4516,9 +4550,9 @@ async function businessName(host, db, organizationId) {
|
|
|
4516
4550
|
|
|
4517
4551
|
// src/handlers/appointment-messages.ts
|
|
4518
4552
|
var NOT_FOUND4 = () => Response.json({ error: "Appointment not found" }, { status: 404 });
|
|
4519
|
-
function failure2(
|
|
4553
|
+
function failure2(label2, error, fallback) {
|
|
4520
4554
|
const ref = getErrorRef(error);
|
|
4521
|
-
console.error(`[${
|
|
4555
|
+
console.error(`[${label2}]`, ref, error instanceof Error ? error.message : error);
|
|
4522
4556
|
return Response.json({ error: getErrorMessage(error, fallback), ...ref && { ref } }, { status: 500 });
|
|
4523
4557
|
}
|
|
4524
4558
|
async function sendFollowup(request, { host, params }) {
|
|
@@ -6201,7 +6235,7 @@ async function deliverWebhooks(request, { host }) {
|
|
|
6201
6235
|
|
|
6202
6236
|
// src/handlers/waitlist-join.ts
|
|
6203
6237
|
var import_scheduling53 = require("@ordinatio/scheduling");
|
|
6204
|
-
var
|
|
6238
|
+
var import_zod17 = require("zod");
|
|
6205
6239
|
|
|
6206
6240
|
// src/waitlist/waitlist-http.ts
|
|
6207
6241
|
var import_scheduling52 = require("@ordinatio/scheduling");
|
|
@@ -6234,15 +6268,15 @@ async function requireWaitlistAdmin(host, request, options) {
|
|
|
6234
6268
|
}
|
|
6235
6269
|
|
|
6236
6270
|
// src/handlers/waitlist-join.ts
|
|
6237
|
-
var JoinWaitlistSchema =
|
|
6238
|
-
orgSlug:
|
|
6239
|
-
typeId:
|
|
6240
|
-
calendarId:
|
|
6241
|
-
day:
|
|
6242
|
-
slotStart:
|
|
6243
|
-
clientName:
|
|
6244
|
-
clientEmail:
|
|
6245
|
-
clientPhone:
|
|
6271
|
+
var JoinWaitlistSchema = import_zod17.z.object({
|
|
6272
|
+
orgSlug: import_zod17.z.string().min(1).max(100).optional(),
|
|
6273
|
+
typeId: import_zod17.z.string().min(1),
|
|
6274
|
+
calendarId: import_zod17.z.string().min(1).optional(),
|
|
6275
|
+
day: import_zod17.z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Day must be YYYY-MM-DD"),
|
|
6276
|
+
slotStart: import_zod17.z.string().datetime({ message: "Invalid date/time format" }).optional(),
|
|
6277
|
+
clientName: import_zod17.z.string().trim().min(1, "Name is required").max(200),
|
|
6278
|
+
clientEmail: import_zod17.z.string().email("Invalid email").max(254),
|
|
6279
|
+
clientPhone: import_zod17.z.string().max(30).optional()
|
|
6246
6280
|
});
|
|
6247
6281
|
async function joinWaitlistRoute(request, { host }) {
|
|
6248
6282
|
const cors = host.cors(request);
|
|
@@ -6300,35 +6334,35 @@ async function leaveWaitlistRoute(request, { host }) {
|
|
|
6300
6334
|
|
|
6301
6335
|
// src/handlers/waitlist-offer.ts
|
|
6302
6336
|
var import_scheduling58 = require("@ordinatio/scheduling");
|
|
6303
|
-
var
|
|
6337
|
+
var import_zod19 = require("zod");
|
|
6304
6338
|
|
|
6305
6339
|
// src/handlers/appointments-book.ts
|
|
6306
6340
|
var import_scheduling57 = require("@ordinatio/scheduling");
|
|
6307
6341
|
|
|
6308
6342
|
// src/booking/booking-schema.ts
|
|
6309
|
-
var
|
|
6310
|
-
var BookingSchema =
|
|
6311
|
-
calendarId:
|
|
6312
|
-
preferredCalendarId:
|
|
6313
|
-
typeId:
|
|
6314
|
-
startTime:
|
|
6315
|
-
timezone:
|
|
6316
|
-
clientName:
|
|
6317
|
-
clientEmail:
|
|
6318
|
-
clientPhone:
|
|
6343
|
+
var import_zod18 = require("zod");
|
|
6344
|
+
var BookingSchema = import_zod18.z.object({
|
|
6345
|
+
calendarId: import_zod18.z.string().min(1).optional(),
|
|
6346
|
+
preferredCalendarId: import_zod18.z.string().min(1).optional(),
|
|
6347
|
+
typeId: import_zod18.z.string().min(1),
|
|
6348
|
+
startTime: import_zod18.z.string().datetime({ message: "Invalid date/time format" }),
|
|
6349
|
+
timezone: import_zod18.z.string().max(50).optional(),
|
|
6350
|
+
clientName: import_zod18.z.string().trim().min(1, "Name is required").max(200),
|
|
6351
|
+
clientEmail: import_zod18.z.string().email("Invalid email").max(254),
|
|
6352
|
+
clientPhone: import_zod18.z.string().max(30).optional(),
|
|
6319
6353
|
// Untrusted: the host's client resolver decides whether to honor it.
|
|
6320
|
-
clientId:
|
|
6321
|
-
notes:
|
|
6354
|
+
clientId: import_zod18.z.string().optional(),
|
|
6355
|
+
notes: import_zod18.z.string().max(1e3).optional(),
|
|
6322
6356
|
// Only the primitive types a form field produces; z.unknown() would accept anything.
|
|
6323
|
-
intakeResponses:
|
|
6324
|
-
|
|
6325
|
-
|
|
6357
|
+
intakeResponses: import_zod18.z.record(
|
|
6358
|
+
import_zod18.z.string(),
|
|
6359
|
+
import_zod18.z.union([import_zod18.z.string().max(1e3), import_zod18.z.number(), import_zod18.z.boolean(), import_zod18.z.null()])
|
|
6326
6360
|
).optional(),
|
|
6327
|
-
paymentId:
|
|
6328
|
-
couponCode:
|
|
6329
|
-
packagePurchaseId:
|
|
6361
|
+
paymentId: import_zod18.z.string().optional(),
|
|
6362
|
+
couponCode: import_zod18.z.string().min(1).max(50).transform((value) => value.trim().toUpperCase()).optional(),
|
|
6363
|
+
packagePurchaseId: import_zod18.z.string().optional(),
|
|
6330
6364
|
// Names the organization, so the calendar and type lookups can run against its own database.
|
|
6331
|
-
orgSlug:
|
|
6365
|
+
orgSlug: import_zod18.z.string().min(1).max(100).optional()
|
|
6332
6366
|
});
|
|
6333
6367
|
|
|
6334
6368
|
// src/booking/finalize-booking.ts
|
|
@@ -6818,7 +6852,7 @@ async function getWaitlistOfferRoute(request, { host }) {
|
|
|
6818
6852
|
return waitlistErrorResponse(cors, error, "Failed to read the offer");
|
|
6819
6853
|
}
|
|
6820
6854
|
}
|
|
6821
|
-
var AcceptSchema =
|
|
6855
|
+
var AcceptSchema = import_zod19.z.object({ token: import_zod19.z.string().min(1).max(200), orgSlug: import_zod19.z.string().min(1).max(100).optional() });
|
|
6822
6856
|
async function acceptWaitlistOfferRoute(request, context) {
|
|
6823
6857
|
const { host } = context;
|
|
6824
6858
|
const cors = host.cors(request);
|
|
@@ -7109,15 +7143,138 @@ async function deleteBrandRoute(request, { host }) {
|
|
|
7109
7143
|
}
|
|
7110
7144
|
}
|
|
7111
7145
|
|
|
7146
|
+
// src/handlers/admin-text-settings.ts
|
|
7147
|
+
var import_scheduling66 = require("@ordinatio/scheduling");
|
|
7148
|
+
var NOT_ENABLED4 = { error: "Text-message settings are not enabled on this server" };
|
|
7149
|
+
function failure3(error, fallback) {
|
|
7150
|
+
if (error instanceof import_scheduling66.SchedulingValidationError) {
|
|
7151
|
+
const details = error.context.errors;
|
|
7152
|
+
return Response.json({ error: error.message, code: error.code, ref: getErrorRef(error), ...details ? { details } : {} }, { status: 400 });
|
|
7153
|
+
}
|
|
7154
|
+
console.error("[text-settings]", error);
|
|
7155
|
+
return Response.json({ error: fallback }, { status: 500 });
|
|
7156
|
+
}
|
|
7157
|
+
async function requireTextAdmin(host, request, options) {
|
|
7158
|
+
const staff = await requireAdminStaff(host, request, options);
|
|
7159
|
+
if (staff instanceof Response) return staff;
|
|
7160
|
+
if (!host.textMessages) return Response.json(NOT_ENABLED4, { status: 501 });
|
|
7161
|
+
return staff;
|
|
7162
|
+
}
|
|
7163
|
+
async function getTextSettingsRoute(request, { host }) {
|
|
7164
|
+
try {
|
|
7165
|
+
const staff = await requireTextAdmin(host, request, { action: "admin-text-settings-get", tier: "GENERAL" });
|
|
7166
|
+
if (staff instanceof Response) return staff;
|
|
7167
|
+
return Response.json({ settings: await (0, import_scheduling66.getTextSettings)(staff.db, staff.organizationId), providers: host.textMessages?.providers ?? ["TELNYX", "TWILIO"] });
|
|
7168
|
+
} catch (error) {
|
|
7169
|
+
return failure3(error, "Failed to read the text-message settings");
|
|
7170
|
+
}
|
|
7171
|
+
}
|
|
7172
|
+
async function saveTextSettingsRoute(request, { host }) {
|
|
7173
|
+
try {
|
|
7174
|
+
const staff = await requireTextAdmin(host, request, { action: "admin-text-settings-save", tier: "UPDATE" });
|
|
7175
|
+
if (staff instanceof Response) return staff;
|
|
7176
|
+
const validation = await parseBody(request, TextSettingsSchema);
|
|
7177
|
+
if (!validation.success) return validation.response;
|
|
7178
|
+
const settings = await (0, import_scheduling66.saveTextSettings)(staff.db, staff.organizationId, validation.data, { providers: host.textMessages?.providers });
|
|
7179
|
+
await host.activity.log(staff.db, {
|
|
7180
|
+
action: "scheduling.text_settings_saved",
|
|
7181
|
+
description: "changed the text-message settings",
|
|
7182
|
+
metadata: { provider: settings.provider, enabled: settings.enabled }
|
|
7183
|
+
});
|
|
7184
|
+
return Response.json({ settings });
|
|
7185
|
+
} catch (error) {
|
|
7186
|
+
return failure3(error, "Failed to save the text-message settings");
|
|
7187
|
+
}
|
|
7188
|
+
}
|
|
7189
|
+
async function deleteTextSettingsRoute(request, { host }) {
|
|
7190
|
+
try {
|
|
7191
|
+
const staff = await requireTextAdmin(host, request, { action: "admin-text-settings-delete", tier: "DELETE" });
|
|
7192
|
+
if (staff instanceof Response) return staff;
|
|
7193
|
+
const removed = await (0, import_scheduling66.deleteTextSettings)(staff.db, staff.organizationId);
|
|
7194
|
+
if (removed) await host.activity.log(staff.db, { action: "scheduling.text_settings_removed", description: "removed the text-message settings", metadata: {} });
|
|
7195
|
+
return Response.json({ removed });
|
|
7196
|
+
} catch (error) {
|
|
7197
|
+
return failure3(error, "Failed to remove the text-message settings");
|
|
7198
|
+
}
|
|
7199
|
+
}
|
|
7200
|
+
|
|
7201
|
+
// src/sending-domain/check-sending-domain.ts
|
|
7202
|
+
function recordsFor(records, domain) {
|
|
7203
|
+
return typeof records === "function" ? records(domain) : records;
|
|
7204
|
+
}
|
|
7205
|
+
var DOMAIN_PATTERN = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
|
|
7206
|
+
var NOT_FOUND_CODES = /* @__PURE__ */ new Set(["ENODATA", "ENOTFOUND"]);
|
|
7207
|
+
function normalizeSendingDomain(raw) {
|
|
7208
|
+
const domain = raw.trim().toLowerCase().replace(/\.$/, "");
|
|
7209
|
+
return DOMAIN_PATTERN.test(domain) ? domain : null;
|
|
7210
|
+
}
|
|
7211
|
+
function recordHost(record, domain) {
|
|
7212
|
+
return record.name === "@" ? domain : `${record.name}.${domain}`;
|
|
7213
|
+
}
|
|
7214
|
+
var clean = (value) => value.trim().replace(/\.$/, "").toLowerCase();
|
|
7215
|
+
function matches(record, published) {
|
|
7216
|
+
if (record.type === "CNAME") return clean(published) === clean(record.value);
|
|
7217
|
+
const fold = (value) => record.purpose === "dkim" ? value.trim() : value.trim().toLowerCase();
|
|
7218
|
+
if (record.match !== "contains") return fold(published) === fold(record.value);
|
|
7219
|
+
const terms = fold(published).split(/\s+/);
|
|
7220
|
+
return fold(record.value).split(/\s+/).every((term) => terms.includes(term));
|
|
7221
|
+
}
|
|
7222
|
+
async function lookUp(resolver, record, host) {
|
|
7223
|
+
if (record.type === "CNAME") return await resolver.resolveCname(host);
|
|
7224
|
+
return (await resolver.resolveTxt(host)).map((chunks) => chunks.join(""));
|
|
7225
|
+
}
|
|
7226
|
+
var label = { spf: "SPF", dkim: "DKIM", dmarc: "DMARC", other: "This" };
|
|
7227
|
+
async function checkRecord(resolver, record, domain) {
|
|
7228
|
+
const host = recordHost(record, domain);
|
|
7229
|
+
const who = label[record.purpose];
|
|
7230
|
+
try {
|
|
7231
|
+
const published = await lookUp(resolver, record, host);
|
|
7232
|
+
if (published.some((value) => matches(record, value))) {
|
|
7233
|
+
return { record, host, status: "found", message: `${who} record is in place.` };
|
|
7234
|
+
}
|
|
7235
|
+
const hint = published.length === 0 ? "is empty" : "does not match";
|
|
7236
|
+
return { record, host, status: "wrong", message: `${who} record at ${host} ${hint}. Replace it with the value shown.` };
|
|
7237
|
+
} catch (error) {
|
|
7238
|
+
const code = error?.code;
|
|
7239
|
+
if (code && NOT_FOUND_CODES.has(code)) {
|
|
7240
|
+
return { record, host, status: "missing", message: `${who} record not found at ${host}. Add it at your domain host. New records can take up to a day to appear.` };
|
|
7241
|
+
}
|
|
7242
|
+
return { record, host, status: "unknown", message: `${who} record could not be checked just now. Try again in a few minutes.` };
|
|
7243
|
+
}
|
|
7244
|
+
}
|
|
7245
|
+
async function checkSendingDomain(config, rawDomain) {
|
|
7246
|
+
const domain = normalizeSendingDomain(rawDomain);
|
|
7247
|
+
if (!domain) return { domain: rawDomain, verified: false, records: [] };
|
|
7248
|
+
const records = await Promise.all(recordsFor(config.records, domain).map((record) => checkRecord(config.resolver, record, domain)));
|
|
7249
|
+
const required = records.filter((check) => check.record.required !== false);
|
|
7250
|
+
const verified = required.length > 0 && required.every((check) => check.status === "found");
|
|
7251
|
+
return { domain, verified, records };
|
|
7252
|
+
}
|
|
7253
|
+
|
|
7254
|
+
// src/handlers/admin-brand-domain-check.ts
|
|
7255
|
+
async function checkSendingDomainRoute(request, { host }) {
|
|
7256
|
+
try {
|
|
7257
|
+
const staff = await requireBrandAdmin(host, request, { action: "admin-brand-domain-check", tier: "SETTINGS" });
|
|
7258
|
+
if (staff instanceof Response) return staff;
|
|
7259
|
+
const check = host.brand?.checkSendingDomain;
|
|
7260
|
+
if (!check) return Response.json({ error: "Sending-domain checking is not set up on this server" }, { status: 501 });
|
|
7261
|
+
const domain = normalizeSendingDomain(new URL(request.url).searchParams.get("domain") ?? "");
|
|
7262
|
+
if (!domain) return Response.json({ error: "Enter a domain such as mail.acme.com" }, { status: 400 });
|
|
7263
|
+
return Response.json({ check: await check.call(host.brand, domain, staff.organizationId) });
|
|
7264
|
+
} catch (error) {
|
|
7265
|
+
return brandErrorResponse(error, "Failed to check the sending domain");
|
|
7266
|
+
}
|
|
7267
|
+
}
|
|
7268
|
+
|
|
7112
7269
|
// src/handlers/admin-privacy.ts
|
|
7113
|
-
var
|
|
7270
|
+
var import_scheduling68 = require("@ordinatio/scheduling");
|
|
7114
7271
|
|
|
7115
7272
|
// src/privacy/privacy-http.ts
|
|
7116
|
-
var
|
|
7117
|
-
var
|
|
7273
|
+
var import_scheduling67 = require("@ordinatio/scheduling");
|
|
7274
|
+
var NOT_ENABLED5 = { error: "Data export and erasure are not enabled on this server" };
|
|
7118
7275
|
var STATUS_BY_CODE3 = { SCHED_1300: 400, SCHED_1301: 409 };
|
|
7119
7276
|
function privacyErrorResponse(error, fallback) {
|
|
7120
|
-
if (error instanceof
|
|
7277
|
+
if (error instanceof import_scheduling67.SchedulingValidationError) {
|
|
7121
7278
|
return Response.json(
|
|
7122
7279
|
{ error: error.message, code: error.code, ref: getErrorRef(error), details: error.context },
|
|
7123
7280
|
{ status: STATUS_BY_CODE3[error.code] ?? 400 }
|
|
@@ -7129,7 +7286,7 @@ function privacyErrorResponse(error, fallback) {
|
|
|
7129
7286
|
async function requirePrivacyAdmin(host, request, options) {
|
|
7130
7287
|
const staff = await requireAdminStaff(host, request, options);
|
|
7131
7288
|
if (staff instanceof Response) return staff;
|
|
7132
|
-
if (!host.privacy) return Response.json(
|
|
7289
|
+
if (!host.privacy) return Response.json(NOT_ENABLED5, { status: 501 });
|
|
7133
7290
|
return staff;
|
|
7134
7291
|
}
|
|
7135
7292
|
|
|
@@ -7147,7 +7304,7 @@ async function exportPrivacyRoute(request, { host }) {
|
|
|
7147
7304
|
if (staff instanceof Response) return staff;
|
|
7148
7305
|
const validation = await parseBody(request, PrivacySubjectSchema);
|
|
7149
7306
|
if (!validation.success) return validation.response;
|
|
7150
|
-
const result = await (0,
|
|
7307
|
+
const result = await (0, import_scheduling68.exportSubject)(staff.db, { organizationId: staff.organizationId, requestedBy: staff.userId, ...validation.data });
|
|
7151
7308
|
await logQuietly(host, staff.db, {
|
|
7152
7309
|
action: "scheduling.privacy_export",
|
|
7153
7310
|
description: "exported the data held about one person",
|
|
@@ -7174,10 +7331,10 @@ async function erasePrivacyRoute(request, { host }) {
|
|
|
7174
7331
|
if (!validation.success) return validation.response;
|
|
7175
7332
|
const { confirm, ...subject2 } = validation.data;
|
|
7176
7333
|
if (confirm !== true) {
|
|
7177
|
-
const preview = await (0,
|
|
7334
|
+
const preview = await (0, import_scheduling68.previewErase)(staff.db, { organizationId: staff.organizationId, ...subject2 });
|
|
7178
7335
|
return Response.json({ erased: false, preview }, { headers: { "cache-control": "no-store" } });
|
|
7179
7336
|
}
|
|
7180
|
-
const { counts } = await (0,
|
|
7337
|
+
const { counts } = await (0, import_scheduling68.eraseSubject)(staff.db, { organizationId: staff.organizationId, requestedBy: staff.userId, ...subject2 });
|
|
7181
7338
|
await logQuietly(host, staff.db, {
|
|
7182
7339
|
action: "scheduling.privacy_erase",
|
|
7183
7340
|
description: "erased the data held about one person",
|
|
@@ -7193,7 +7350,7 @@ async function listPrivacyRequestsRoute(request, { host }) {
|
|
|
7193
7350
|
const staff = await requirePrivacyAdmin(host, request, { action: "admin-privacy-requests", tier: "GENERAL" });
|
|
7194
7351
|
if (staff instanceof Response) return staff;
|
|
7195
7352
|
const { limit, offset } = parsePagination(request);
|
|
7196
|
-
const { requests, total } = await (0,
|
|
7353
|
+
const { requests, total } = await (0, import_scheduling68.listPrivacyRequests)(staff.db, { organizationId: staff.organizationId, limit, offset });
|
|
7197
7354
|
return Response.json({ requests, total, hasMore: offset + requests.length < total });
|
|
7198
7355
|
} catch (error) {
|
|
7199
7356
|
return privacyErrorResponse(error, "Failed to list the requests");
|
|
@@ -7201,12 +7358,12 @@ async function listPrivacyRequestsRoute(request, { host }) {
|
|
|
7201
7358
|
}
|
|
7202
7359
|
|
|
7203
7360
|
// src/handlers/admin-routing-form-detail.ts
|
|
7204
|
-
var
|
|
7361
|
+
var import_scheduling69 = require("@ordinatio/scheduling");
|
|
7205
7362
|
async function getRoutingFormAdminRoute(request, { host, params }) {
|
|
7206
7363
|
try {
|
|
7207
7364
|
const staff = await requireRoutingAdmin(host, request, { action: "admin-routing-forms-get", tier: "GENERAL" });
|
|
7208
7365
|
if (staff instanceof Response) return staff;
|
|
7209
|
-
return Response.json({ form: await (0,
|
|
7366
|
+
return Response.json({ form: await (0, import_scheduling69.getRoutingForm)(staff.db, staff.organizationId, params.id) });
|
|
7210
7367
|
} catch (error) {
|
|
7211
7368
|
return routingErrorResponse(error, "Failed to read the form");
|
|
7212
7369
|
}
|
|
@@ -7217,7 +7374,7 @@ async function updateRoutingFormRoute(request, { host, params }) {
|
|
|
7217
7374
|
if (staff instanceof Response) return staff;
|
|
7218
7375
|
const validation = await parseBody(request, UpdateRoutingFormSchema);
|
|
7219
7376
|
if (!validation.success) return validation.response;
|
|
7220
|
-
const form = await (0,
|
|
7377
|
+
const form = await (0, import_scheduling69.updateRoutingForm)(staff.db, staff.organizationId, params.id, validation.data);
|
|
7221
7378
|
await host.activity.log(staff.db, {
|
|
7222
7379
|
action: "scheduling.routing_form_updated",
|
|
7223
7380
|
description: `changed routing form "${form.name}"`,
|
|
@@ -7232,7 +7389,7 @@ async function deleteRoutingFormRoute(request, { host, params }) {
|
|
|
7232
7389
|
try {
|
|
7233
7390
|
const staff = await requireRoutingAdmin(host, request, { action: "admin-routing-forms-delete", tier: "DELETE" });
|
|
7234
7391
|
if (staff instanceof Response) return staff;
|
|
7235
|
-
await (0,
|
|
7392
|
+
await (0, import_scheduling69.deleteRoutingForm)(staff.db, staff.organizationId, params.id);
|
|
7236
7393
|
await host.activity.log(staff.db, { action: "scheduling.routing_form_deleted", description: "removed a routing form", metadata: { formId: params.id } });
|
|
7237
7394
|
return Response.json({ success: true });
|
|
7238
7395
|
} catch (error) {
|
|
@@ -7245,14 +7402,14 @@ async function testRoutingFormRoute(request, { host, params }) {
|
|
|
7245
7402
|
if (staff instanceof Response) return staff;
|
|
7246
7403
|
const validation = await parseBody(request, TestRoutingFormSchema);
|
|
7247
7404
|
if (!validation.success) return validation.response;
|
|
7248
|
-
return Response.json(await (0,
|
|
7405
|
+
return Response.json(await (0, import_scheduling69.testRoutingForm)(staff.db, { organizationId: staff.organizationId, id: params.id, answers: validation.data.answers }));
|
|
7249
7406
|
} catch (error) {
|
|
7250
7407
|
return routingErrorResponse(error, "Failed to test the form");
|
|
7251
7408
|
}
|
|
7252
7409
|
}
|
|
7253
7410
|
|
|
7254
7411
|
// src/handlers/appointments-list.ts
|
|
7255
|
-
var
|
|
7412
|
+
var import_scheduling70 = require("@ordinatio/scheduling");
|
|
7256
7413
|
var DEFAULT_LIMIT2 = 50;
|
|
7257
7414
|
var MAX_LIMIT2 = 500;
|
|
7258
7415
|
async function listAppointments(request, { host }) {
|
|
@@ -7264,7 +7421,7 @@ async function listAppointments(request, { host }) {
|
|
|
7264
7421
|
const clientId = params.get("clientId") || void 0;
|
|
7265
7422
|
const status = params.get("status") || void 0;
|
|
7266
7423
|
if (!clientId && !staff.isAdmin) {
|
|
7267
|
-
const err = (0,
|
|
7424
|
+
const err = (0, import_scheduling70.schedError)("SCHED_900", { role: staff.role });
|
|
7268
7425
|
return Response.json({ error: "Forbidden", ref: err.ref }, { status: 403 });
|
|
7269
7426
|
}
|
|
7270
7427
|
const startDate = params.get("startDate");
|
|
@@ -7275,7 +7432,7 @@ async function listAppointments(request, { host }) {
|
|
|
7275
7432
|
MAX_LIMIT2
|
|
7276
7433
|
);
|
|
7277
7434
|
const visibility = await staff.visibleCalendars();
|
|
7278
|
-
const where = (0,
|
|
7435
|
+
const where = (0, import_scheduling70.withOrganization)({
|
|
7279
7436
|
...visibility ? { calendar: visibility } : {},
|
|
7280
7437
|
...calendarId ? { calendarId } : {},
|
|
7281
7438
|
...clientId ? { clientId } : {},
|
|
@@ -7344,7 +7501,7 @@ async function listAppointments(request, { host }) {
|
|
|
7344
7501
|
}
|
|
7345
7502
|
|
|
7346
7503
|
// src/handlers/availability.ts
|
|
7347
|
-
var
|
|
7504
|
+
var import_scheduling71 = require("@ordinatio/scheduling");
|
|
7348
7505
|
|
|
7349
7506
|
// src/availability/picked-day.ts
|
|
7350
7507
|
var CALENDAR_DAY_SHAPE = /^\d{4}-\d{2}-\d{2}$/;
|
|
@@ -7457,7 +7614,7 @@ async function getAvailability(request, { host }) {
|
|
|
7457
7614
|
const cached = await readCache(host.availabilityCache, calendarId, cacheDay, typeDuration);
|
|
7458
7615
|
if (cached != null) return corsJson(cors, cached);
|
|
7459
7616
|
}
|
|
7460
|
-
const result = await (0,
|
|
7617
|
+
const result = await (0, import_scheduling71.getAvailableSlots)(db, {
|
|
7461
7618
|
calendarId,
|
|
7462
7619
|
date: dateObj,
|
|
7463
7620
|
localDate: pickedDay,
|
|
@@ -7478,7 +7635,7 @@ async function getAvailability(request, { host }) {
|
|
|
7478
7635
|
}
|
|
7479
7636
|
|
|
7480
7637
|
// src/handlers/availability-team.ts
|
|
7481
|
-
var
|
|
7638
|
+
var import_scheduling72 = require("@ordinatio/scheduling");
|
|
7482
7639
|
|
|
7483
7640
|
// src/loaders/team-type.ts
|
|
7484
7641
|
async function loadTeamType(db, typeId, organizationId) {
|
|
@@ -7526,7 +7683,7 @@ async function getTeamAvailability(request, { host }) {
|
|
|
7526
7683
|
{ status: 400 }
|
|
7527
7684
|
);
|
|
7528
7685
|
}
|
|
7529
|
-
const result = await (0,
|
|
7686
|
+
const result = await (0, import_scheduling72.getTeamAvailableSlots)(db, {
|
|
7530
7687
|
typeId,
|
|
7531
7688
|
date: dateObj,
|
|
7532
7689
|
localDate: pickedCalendarDay(date),
|
|
@@ -7549,7 +7706,7 @@ async function getTeamAvailability(request, { host }) {
|
|
|
7549
7706
|
}
|
|
7550
7707
|
|
|
7551
7708
|
// src/handlers/appointment-types.ts
|
|
7552
|
-
var
|
|
7709
|
+
var import_scheduling73 = require("@ordinatio/scheduling");
|
|
7553
7710
|
|
|
7554
7711
|
// src/loaders/types-by-calendar.ts
|
|
7555
7712
|
function loadTypesByCalendarSlug(cache, db, organizationId, calendarSlug) {
|
|
@@ -7623,19 +7780,19 @@ async function getAppointmentTypes(request, { host }) {
|
|
|
7623
7780
|
}));
|
|
7624
7781
|
return corsJson(cors, response, { headers: WIDGET_CACHE_HEADERS });
|
|
7625
7782
|
} catch (error) {
|
|
7626
|
-
const diagnostic = (0,
|
|
7783
|
+
const diagnostic = (0, import_scheduling73.schedError)("SCHED_202", { error });
|
|
7627
7784
|
console.error("[appointment-types]", diagnostic.ref, error);
|
|
7628
7785
|
return corsJson(cors, { error: "Failed to fetch appointment types", ref: diagnostic.ref }, { status: 500 });
|
|
7629
7786
|
}
|
|
7630
7787
|
}
|
|
7631
7788
|
|
|
7632
7789
|
// src/handlers/coupons-validate.ts
|
|
7633
|
-
var
|
|
7634
|
-
var
|
|
7635
|
-
var Schema4 =
|
|
7636
|
-
code:
|
|
7637
|
-
calendarId:
|
|
7638
|
-
price:
|
|
7790
|
+
var import_zod20 = require("zod");
|
|
7791
|
+
var import_scheduling74 = require("@ordinatio/scheduling");
|
|
7792
|
+
var Schema4 = import_zod20.z.object({
|
|
7793
|
+
code: import_zod20.z.string().min(1).max(50).transform((v) => v.trim().toUpperCase()),
|
|
7794
|
+
calendarId: import_zod20.z.string().min(1),
|
|
7795
|
+
price: import_zod20.z.number().positive()
|
|
7639
7796
|
});
|
|
7640
7797
|
function calculateDiscount(price, discountType, discountValue) {
|
|
7641
7798
|
if (discountType === "PERCENTAGE") {
|
|
@@ -7693,7 +7850,7 @@ async function validateCoupon(request, { host }) {
|
|
|
7693
7850
|
{ headers: host.cors(request) }
|
|
7694
7851
|
);
|
|
7695
7852
|
} catch (error) {
|
|
7696
|
-
const err = (0,
|
|
7853
|
+
const err = (0, import_scheduling74.schedError)("SCHED_408", {
|
|
7697
7854
|
calendarId,
|
|
7698
7855
|
error: error instanceof Error ? error.message : String(error)
|
|
7699
7856
|
});
|
|
@@ -7747,8 +7904,33 @@ async function getPublicCalendar(request, { host }) {
|
|
|
7747
7904
|
}
|
|
7748
7905
|
}
|
|
7749
7906
|
|
|
7907
|
+
// src/handlers/calendars-active.ts
|
|
7908
|
+
async function listActiveCalendars(request, { host }) {
|
|
7909
|
+
try {
|
|
7910
|
+
const staff = await requireAdminStaff(host, request, {
|
|
7911
|
+
action: "admin-calendars-list",
|
|
7912
|
+
tier: "GENERAL",
|
|
7913
|
+
allowAnyRole: true,
|
|
7914
|
+
ignoreSchedulingSwitch: true
|
|
7915
|
+
});
|
|
7916
|
+
if (staff instanceof Response) return staff;
|
|
7917
|
+
const { db, organizationId } = staff;
|
|
7918
|
+
const visibility = await staff.visibleCalendars();
|
|
7919
|
+
const calendars = await db.schedulingCalendar.findMany({
|
|
7920
|
+
// organizationId comes last so a filter can never widen the list beyond this organization.
|
|
7921
|
+
where: { isActive: true, ...visibility, organizationId },
|
|
7922
|
+
select: { id: true, name: true, slug: true, staffName: true },
|
|
7923
|
+
orderBy: { name: "asc" }
|
|
7924
|
+
});
|
|
7925
|
+
return Response.json(calendars);
|
|
7926
|
+
} catch (error) {
|
|
7927
|
+
console.warn("[calendars/active]", error instanceof Error ? error.message : error);
|
|
7928
|
+
return Response.json({ error: "Failed to fetch calendars" }, { status: 500 });
|
|
7929
|
+
}
|
|
7930
|
+
}
|
|
7931
|
+
|
|
7750
7932
|
// src/handlers/type.ts
|
|
7751
|
-
var
|
|
7933
|
+
var import_scheduling75 = require("@ordinatio/scheduling");
|
|
7752
7934
|
|
|
7753
7935
|
// src/loaders/type-by-slug.ts
|
|
7754
7936
|
function loadTypeBySlug(cache, db, organizationId, slug) {
|
|
@@ -7853,14 +8035,14 @@ async function getType(request, { host }) {
|
|
|
7853
8035
|
{ headers: WIDGET_CACHE_HEADERS }
|
|
7854
8036
|
);
|
|
7855
8037
|
} catch (error) {
|
|
7856
|
-
const diagnostic = (0,
|
|
8038
|
+
const diagnostic = (0, import_scheduling75.schedError)("SCHED_207", { error });
|
|
7857
8039
|
console.error("[type]", diagnostic.ref, error);
|
|
7858
8040
|
return corsJson(cors, { error: "Failed to fetch appointment type", ref: diagnostic.ref }, { status: 500 });
|
|
7859
8041
|
}
|
|
7860
8042
|
}
|
|
7861
8043
|
|
|
7862
8044
|
// src/handlers/widget-init.ts
|
|
7863
|
-
var
|
|
8045
|
+
var import_scheduling76 = require("@ordinatio/scheduling");
|
|
7864
8046
|
|
|
7865
8047
|
// src/loaders/widget-data.ts
|
|
7866
8048
|
function loadWidgetData(cache, db, organizationId, calendarSlug) {
|
|
@@ -7949,7 +8131,7 @@ async function getWidgetInit(request, { host }) {
|
|
|
7949
8131
|
}));
|
|
7950
8132
|
return corsJson(cors, { calendar, types: sanitizedTypes }, { headers: WIDGET_CACHE_HEADERS });
|
|
7951
8133
|
} catch (error) {
|
|
7952
|
-
const diagnostic = (0,
|
|
8134
|
+
const diagnostic = (0, import_scheduling76.schedError)("SCHED_206", { error });
|
|
7953
8135
|
console.error("[widget-init]", diagnostic.ref, error);
|
|
7954
8136
|
return corsJson(cors, { error: "Failed to load widget data", ref: diagnostic.ref }, { status: 500 });
|
|
7955
8137
|
}
|
|
@@ -7963,6 +8145,7 @@ var ROUTES = [
|
|
|
7963
8145
|
{ method: "GET", path: "/type", public: true, handler: getType },
|
|
7964
8146
|
{ method: "GET", path: "/appointment-types", public: true, handler: getAppointmentTypes },
|
|
7965
8147
|
{ method: "GET", path: "/calendars", public: true, handler: getPublicCalendar },
|
|
8148
|
+
{ method: "GET", path: "/calendars/active", public: false, handler: listActiveCalendars },
|
|
7966
8149
|
{ method: "GET", path: "/availability", public: true, handler: getAvailability },
|
|
7967
8150
|
{ method: "GET", path: "/availability/team", public: true, handler: getTeamAvailability },
|
|
7968
8151
|
{ method: "POST", path: "/appointments", public: true, handler: bookAppointmentRoute },
|
|
@@ -8023,6 +8206,10 @@ var ROUTES = [
|
|
|
8023
8206
|
{ method: "GET", path: "/admin/brand", public: false, handler: getBrandAdminRoute },
|
|
8024
8207
|
{ method: "PUT", path: "/admin/brand", public: false, handler: saveBrandRoute },
|
|
8025
8208
|
{ method: "DELETE", path: "/admin/brand", public: false, handler: deleteBrandRoute },
|
|
8209
|
+
{ method: "GET", path: "/admin/text-settings", public: false, handler: getTextSettingsRoute },
|
|
8210
|
+
{ method: "PUT", path: "/admin/text-settings", public: false, handler: saveTextSettingsRoute },
|
|
8211
|
+
{ method: "DELETE", path: "/admin/text-settings", public: false, handler: deleteTextSettingsRoute },
|
|
8212
|
+
{ method: "GET", path: "/admin/brand/sending-domain", public: false, handler: checkSendingDomainRoute },
|
|
8026
8213
|
{ method: "POST", path: "/admin/privacy/export", public: false, handler: exportPrivacyRoute },
|
|
8027
8214
|
{ method: "POST", path: "/admin/privacy/erase", public: false, handler: erasePrivacyRoute },
|
|
8028
8215
|
{ method: "GET", path: "/admin/privacy/requests", public: false, handler: listPrivacyRequestsRoute },
|
|
@@ -8117,6 +8304,7 @@ function createSchedulingApi(config) {
|
|
|
8117
8304
|
routingForms: config.host.routingForms ?? null,
|
|
8118
8305
|
privacy: config.host.privacy ?? null,
|
|
8119
8306
|
brand: config.host.brand ?? null,
|
|
8307
|
+
textMessages: config.host.textMessages ?? null,
|
|
8120
8308
|
icalUidDomain: config.host.icalUidDomain?.bind(config.host) ?? (() => null),
|
|
8121
8309
|
calendarSync: config.host.calendarSync ?? { upsertEvent: async () => ({}), removeEvent: async () => void 0 },
|
|
8122
8310
|
activity: config.host.activity ?? { log: async () => void 0, isOpen: async () => false, resolve: async () => void 0 },
|
|
@@ -8148,16 +8336,16 @@ function createSchedulingApi(config) {
|
|
|
8148
8336
|
const { pathname } = new URL(request.url);
|
|
8149
8337
|
if (pathname !== basePath && !pathname.startsWith(`${basePath}/`)) return notFound();
|
|
8150
8338
|
const relative = pathname.slice(basePath.length) || "/";
|
|
8151
|
-
const
|
|
8152
|
-
if (
|
|
8339
|
+
const matches2 = routes.map((route) => ({ route, params: matchPath(route.path, relative) })).filter((match) => match.params !== null);
|
|
8340
|
+
if (matches2.length === 0) return notFound();
|
|
8153
8341
|
const method = request.method.toUpperCase();
|
|
8154
|
-
if (method === "OPTIONS" &&
|
|
8342
|
+
if (method === "OPTIONS" && matches2.some((match) => match.route.public)) {
|
|
8155
8343
|
return new Response(null, { status: 204, headers: host.cors(request) });
|
|
8156
8344
|
}
|
|
8157
|
-
const hit =
|
|
8345
|
+
const hit = matches2.find((match) => match.route.method === method);
|
|
8158
8346
|
if (!hit) {
|
|
8159
|
-
const allowed = [...new Set(
|
|
8160
|
-
if (
|
|
8347
|
+
const allowed = [...new Set(matches2.map((match) => match.route.method))];
|
|
8348
|
+
if (matches2.some((match) => match.route.public)) allowed.push("OPTIONS");
|
|
8161
8349
|
return Response.json({ error: "Method not allowed" }, { status: 405, headers: { Allow: allowed.join(", ") } });
|
|
8162
8350
|
}
|
|
8163
8351
|
try {
|
|
@@ -8178,6 +8366,756 @@ function createSchedulingApi(config) {
|
|
|
8178
8366
|
return { routes, handle, handler };
|
|
8179
8367
|
}
|
|
8180
8368
|
|
|
8369
|
+
// src/payments/stripe/stripe-payments.ts
|
|
8370
|
+
var TWO_DECIMAL_CURRENCIES = ["usd", "eur", "gbp", "cad", "aud"];
|
|
8371
|
+
var REFUSAL_TYPES = ["StripeInvalidRequestError", "StripeCardError"];
|
|
8372
|
+
var IN_FLIGHT_CODES = ["idempotency_key_in_use", "lock_timeout"];
|
|
8373
|
+
function asStripeError(error) {
|
|
8374
|
+
if (typeof error !== "object" || error === null) return {};
|
|
8375
|
+
const shape = error;
|
|
8376
|
+
return shape.code === void 0 && shape.raw?.code !== void 0 ? { ...shape, code: shape.raw.code } : shape;
|
|
8377
|
+
}
|
|
8378
|
+
function isKeyMismatch(error) {
|
|
8379
|
+
return error.type === "StripeIdempotencyError" || error.raw?.type === "idempotency_error";
|
|
8380
|
+
}
|
|
8381
|
+
function isRefusal(error) {
|
|
8382
|
+
return error.type !== void 0 && REFUSAL_TYPES.includes(error.type);
|
|
8383
|
+
}
|
|
8384
|
+
function isReplayedFailure(error) {
|
|
8385
|
+
const header = Object.entries(error.headers ?? {}).find(([name]) => name.toLowerCase() === "idempotent-replayed");
|
|
8386
|
+
return header?.[1] === "true";
|
|
8387
|
+
}
|
|
8388
|
+
function isSupportedCurrency(currency) {
|
|
8389
|
+
return currency !== void 0 && TWO_DECIMAL_CURRENCIES.includes(currency.toLowerCase());
|
|
8390
|
+
}
|
|
8391
|
+
function toMinor(amount) {
|
|
8392
|
+
if (!Number.isFinite(amount) || amount <= 0) return null;
|
|
8393
|
+
const minor = Math.round(amount * 100);
|
|
8394
|
+
if (minor < 1 || !Number.isSafeInteger(minor)) return null;
|
|
8395
|
+
return Math.abs(amount * 100 - minor) < 1e-6 ? minor : null;
|
|
8396
|
+
}
|
|
8397
|
+
function toMajor(minor, currency) {
|
|
8398
|
+
return isSupportedCurrency(currency) ? minor / 100 : void 0;
|
|
8399
|
+
}
|
|
8400
|
+
function unsupportedCurrency(currency) {
|
|
8401
|
+
return `Currency ${currency.toUpperCase()} is not supported by this adapter (supported: ${TWO_DECIMAL_CURRENCIES.join(", ").toUpperCase()})`;
|
|
8402
|
+
}
|
|
8403
|
+
var BAD_AMOUNT = "amount must be greater than 0 and have at most 2 decimals";
|
|
8404
|
+
function createStripePaymentAdapter(client) {
|
|
8405
|
+
async function verifyPayment(paymentId) {
|
|
8406
|
+
let intent;
|
|
8407
|
+
try {
|
|
8408
|
+
intent = await client.paymentIntents.retrieve(paymentId, { expand: ["latest_charge"] });
|
|
8409
|
+
} catch (error) {
|
|
8410
|
+
if (asStripeError(error).code === "resource_missing") return { paid: false, status: "not_found" };
|
|
8411
|
+
throw error;
|
|
8412
|
+
}
|
|
8413
|
+
const charge = intent.latest_charge;
|
|
8414
|
+
const metadata = intent.metadata ?? {};
|
|
8415
|
+
const currency = intent.currency.toUpperCase();
|
|
8416
|
+
const amount = toMajor(intent.amount, intent.currency);
|
|
8417
|
+
if (intent.status === "succeeded" && (typeof charge !== "object" || charge === null)) {
|
|
8418
|
+
return { paid: false, amount, currency, status: "refund_state_unknown", metadata };
|
|
8419
|
+
}
|
|
8420
|
+
const refunded = typeof charge === "object" && charge !== null ? charge.amount_refunded ?? 0 : 0;
|
|
8421
|
+
const fullyRefunded = intent.status === "succeeded" && refunded >= intent.amount;
|
|
8422
|
+
return {
|
|
8423
|
+
paid: intent.status === "succeeded" && !fullyRefunded,
|
|
8424
|
+
amount,
|
|
8425
|
+
currency,
|
|
8426
|
+
status: fullyRefunded ? "refunded" : intent.status,
|
|
8427
|
+
metadata
|
|
8428
|
+
};
|
|
8429
|
+
}
|
|
8430
|
+
return {
|
|
8431
|
+
async charge(request) {
|
|
8432
|
+
const currency = request.currency.toLowerCase();
|
|
8433
|
+
if (!isSupportedCurrency(currency)) return { success: false, error: unsupportedCurrency(request.currency) };
|
|
8434
|
+
const amount = toMinor(request.amount);
|
|
8435
|
+
if (amount === null) return { success: false, error: BAD_AMOUNT };
|
|
8436
|
+
let intent;
|
|
8437
|
+
try {
|
|
8438
|
+
intent = await client.paymentIntents.create(
|
|
8439
|
+
{ amount, currency, ...request.metadata ? { metadata: request.metadata } : {} },
|
|
8440
|
+
request.idempotencyKey ? { idempotencyKey: request.idempotencyKey } : void 0
|
|
8441
|
+
);
|
|
8442
|
+
} catch (error) {
|
|
8443
|
+
const stripeError = asStripeError(error);
|
|
8444
|
+
if (stripeError.code && IN_FLIGHT_CODES.includes(stripeError.code)) return { success: false, code: "IN_PROGRESS", error: stripeError.message };
|
|
8445
|
+
if (isKeyMismatch(stripeError)) return { success: false, code: "KEY_REUSED", error: stripeError.message };
|
|
8446
|
+
if (isRefusal(stripeError)) return { success: false, error: stripeError.message };
|
|
8447
|
+
throw error;
|
|
8448
|
+
}
|
|
8449
|
+
let status = intent.status;
|
|
8450
|
+
if (request.idempotencyKey) {
|
|
8451
|
+
try {
|
|
8452
|
+
status = (await client.paymentIntents.retrieve(intent.id)).status;
|
|
8453
|
+
} catch (error) {
|
|
8454
|
+
throw new UnverifiedPaymentError(intent.id, error);
|
|
8455
|
+
}
|
|
8456
|
+
if (status === "canceled") return { success: false, code: "CANCELED", error: "the payment saved for this key was canceled; retry with a new key" };
|
|
8457
|
+
}
|
|
8458
|
+
return {
|
|
8459
|
+
success: true,
|
|
8460
|
+
paymentId: intent.id,
|
|
8461
|
+
status: status === "succeeded" ? "SUCCEEDED" : "REQUIRES_ACTION",
|
|
8462
|
+
clientSecret: intent.client_secret ?? void 0
|
|
8463
|
+
};
|
|
8464
|
+
},
|
|
8465
|
+
verify: verifyPayment,
|
|
8466
|
+
async refund(paymentId, options = {}) {
|
|
8467
|
+
let amountMinor;
|
|
8468
|
+
if (options.amount !== void 0) {
|
|
8469
|
+
if (!options.idempotencyKey) return { success: false, error: "a partial refund needs an idempotencyKey" };
|
|
8470
|
+
const minor = toMinor(options.amount);
|
|
8471
|
+
if (minor === null) return { success: false, error: BAD_AMOUNT };
|
|
8472
|
+
amountMinor = minor;
|
|
8473
|
+
const check = await verifyPayment(paymentId);
|
|
8474
|
+
if (check.status === "not_found") return { success: false, error: "unknown payment" };
|
|
8475
|
+
if (!isSupportedCurrency(check.currency)) return { success: false, error: unsupportedCurrency(check.currency ?? "unknown") };
|
|
8476
|
+
}
|
|
8477
|
+
try {
|
|
8478
|
+
const refund = await client.refunds.create(
|
|
8479
|
+
{ payment_intent: paymentId, ...amountMinor !== void 0 ? { amount: amountMinor } : {} },
|
|
8480
|
+
options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : void 0
|
|
8481
|
+
);
|
|
8482
|
+
const amount = toMajor(refund.amount, refund.currency);
|
|
8483
|
+
if (refund.status === "succeeded") return { success: true, refundId: refund.id, amount, status: "SUCCEEDED" };
|
|
8484
|
+
if (refund.status === "pending" || refund.status === "requires_action") {
|
|
8485
|
+
return { success: true, refundId: refund.id, amount, status: "PENDING" };
|
|
8486
|
+
}
|
|
8487
|
+
return { success: false, refundId: refund.id, error: `Stripe refund ${refund.status ?? "unknown"}` };
|
|
8488
|
+
} catch (error) {
|
|
8489
|
+
const stripeError = asStripeError(error);
|
|
8490
|
+
const requestId = stripeError.requestId;
|
|
8491
|
+
if (stripeError.code === "charge_already_refunded") return { success: false, error: stripeError.message, code: "ALREADY_REFUNDED", requestId };
|
|
8492
|
+
if (stripeError.code && IN_FLIGHT_CODES.includes(stripeError.code)) return { success: false, error: stripeError.message, code: "IN_PROGRESS", requestId };
|
|
8493
|
+
if (stripeError.code === "resource_missing") return { success: false, error: "unknown payment", requestId };
|
|
8494
|
+
if (isKeyMismatch(stripeError)) return { success: false, error: stripeError.message, code: "KEY_REUSED", requestId };
|
|
8495
|
+
if (isRefusal(stripeError)) {
|
|
8496
|
+
return { success: false, error: stripeError.message, requestId, ...isReplayedFailure(stripeError) ? { code: "REPLAYED_FAILURE" } : {} };
|
|
8497
|
+
}
|
|
8498
|
+
if (isReplayedFailure(stripeError)) return { success: false, error: stripeError.message, requestId, code: "REPLAYED_FAILURE" };
|
|
8499
|
+
throw error;
|
|
8500
|
+
}
|
|
8501
|
+
}
|
|
8502
|
+
};
|
|
8503
|
+
}
|
|
8504
|
+
|
|
8505
|
+
// src/payments/stripe/stripe-test-key.ts
|
|
8506
|
+
function assertStripeTestKey(raw) {
|
|
8507
|
+
const key = raw?.trim();
|
|
8508
|
+
if (!key) throw new Error("STRIPE_SECRET_KEY is not set");
|
|
8509
|
+
if (!key.startsWith("sk_test_")) throw new Error("STRIPE_SECRET_KEY is not a test-mode secret key (it must start with sk_test_)");
|
|
8510
|
+
return key;
|
|
8511
|
+
}
|
|
8512
|
+
|
|
8513
|
+
// src/sending-domain/create-sending-domain-verifier.ts
|
|
8514
|
+
function createSendingDomainVerifier(config) {
|
|
8515
|
+
const check = (domain) => checkSendingDomain(config, domain);
|
|
8516
|
+
return {
|
|
8517
|
+
isSendingDomainVerified: async (domain) => (await check(domain)).verified,
|
|
8518
|
+
check,
|
|
8519
|
+
instructions: (rawDomain) => {
|
|
8520
|
+
const domain = normalizeSendingDomain(rawDomain);
|
|
8521
|
+
return domain ? recordsFor(config.records, domain).map((record) => ({ record, host: recordHost(record, domain) })) : [];
|
|
8522
|
+
}
|
|
8523
|
+
};
|
|
8524
|
+
}
|
|
8525
|
+
|
|
8526
|
+
// src/sms/sms-common.ts
|
|
8527
|
+
var SmsSendError = class extends Error {
|
|
8528
|
+
constructor(message, retryable, outcomeUnknown, status, code) {
|
|
8529
|
+
super(message);
|
|
8530
|
+
this.retryable = retryable;
|
|
8531
|
+
this.outcomeUnknown = outcomeUnknown;
|
|
8532
|
+
this.status = status;
|
|
8533
|
+
this.code = code;
|
|
8534
|
+
this.name = "SmsSendError";
|
|
8535
|
+
}
|
|
8536
|
+
};
|
|
8537
|
+
function normalizePhoneNumber(raw) {
|
|
8538
|
+
const digits = raw.trim().replace(/[\s().-]/g, "");
|
|
8539
|
+
if (/^\+[1-9]\d{7,14}$/.test(digits)) return digits;
|
|
8540
|
+
if (/^\d{10}$/.test(digits)) return `+1${digits}`;
|
|
8541
|
+
if (/^1\d{10}$/.test(digits)) return `+${digits}`;
|
|
8542
|
+
return null;
|
|
8543
|
+
}
|
|
8544
|
+
function readHeader(headers, name) {
|
|
8545
|
+
if (typeof headers.get === "function") return headers.get(name) ?? void 0;
|
|
8546
|
+
const found = Object.entries(headers).find(([key]) => key.toLowerCase() === name);
|
|
8547
|
+
const value = found?.[1];
|
|
8548
|
+
return Array.isArray(value) ? value[0] : value;
|
|
8549
|
+
}
|
|
8550
|
+
var STOP_WORDS = ["STOP", "STOPALL", "UNSUBSCRIBE", "END", "QUIT"];
|
|
8551
|
+
var START_WORDS = ["START", "UNSTOP"];
|
|
8552
|
+
function classifyReply(text) {
|
|
8553
|
+
const word = text.trim().toUpperCase().replace(/[.!?,]+$/, "");
|
|
8554
|
+
return STOP_WORDS.includes(word) ? "opt-out" : START_WORDS.includes(word) ? "opt-in" : "reply";
|
|
8555
|
+
}
|
|
8556
|
+
|
|
8557
|
+
// src/telnyx/telnyx-sms.ts
|
|
8558
|
+
var TELNYX_MESSAGES_URL = "https://api.telnyx.com/v2/messages";
|
|
8559
|
+
var DEFAULT_TIMEOUT_MS = 1e4;
|
|
8560
|
+
var OPTED_OUT_CODE = "40300";
|
|
8561
|
+
function firstError(body) {
|
|
8562
|
+
const error = body?.errors?.[0];
|
|
8563
|
+
if (!error) return { text: "no detail given" };
|
|
8564
|
+
return { code: error.code === void 0 ? void 0 : String(error.code), text: error.detail ?? error.title ?? "no detail given" };
|
|
8565
|
+
}
|
|
8566
|
+
function createTelnyxSmsAdapter(config) {
|
|
8567
|
+
const apiKey = typeof config.apiKey === "string" ? config.apiKey.trim() : "";
|
|
8568
|
+
if (!apiKey) throw new Error("createTelnyxSmsAdapter needs an apiKey");
|
|
8569
|
+
const profileId = config.messagingProfileId?.trim() || void 0;
|
|
8570
|
+
const from = config.from ? normalizePhoneNumber(config.from) : null;
|
|
8571
|
+
if (config.from && !from) throw new Error('createTelnyxSmsAdapter: "from" must be a phone number such as +13135550100');
|
|
8572
|
+
if (!from && !profileId) throw new Error('createTelnyxSmsAdapter needs a sending number ("from"), a messagingProfileId, or both');
|
|
8573
|
+
const doFetch = config.fetch ?? fetch;
|
|
8574
|
+
const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
8575
|
+
return {
|
|
8576
|
+
async send(message) {
|
|
8577
|
+
if (message.channel !== "SMS") return { status: "SKIPPED", reason: "The Telnyx adapter only sends text messages" };
|
|
8578
|
+
const to = normalizePhoneNumber(message.to);
|
|
8579
|
+
if (!to) return { status: "SKIPPED", reason: "The recipient is not a valid phone number" };
|
|
8580
|
+
if (!message.body.trim()) return { status: "SKIPPED", reason: "The message is empty" };
|
|
8581
|
+
const controller = new AbortController();
|
|
8582
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
8583
|
+
let response;
|
|
8584
|
+
let body;
|
|
8585
|
+
try {
|
|
8586
|
+
response = await doFetch(TELNYX_MESSAGES_URL, {
|
|
8587
|
+
method: "POST",
|
|
8588
|
+
headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
|
|
8589
|
+
body: JSON.stringify({
|
|
8590
|
+
to,
|
|
8591
|
+
text: message.body,
|
|
8592
|
+
type: "SMS",
|
|
8593
|
+
...from ? { from } : {},
|
|
8594
|
+
...profileId ? { messaging_profile_id: profileId } : {}
|
|
8595
|
+
}),
|
|
8596
|
+
signal: controller.signal
|
|
8597
|
+
});
|
|
8598
|
+
body = await response.json().catch((error) => {
|
|
8599
|
+
if (controller.signal.aborted) throw error;
|
|
8600
|
+
return null;
|
|
8601
|
+
});
|
|
8602
|
+
} catch (error) {
|
|
8603
|
+
const reason = controller.signal.aborted ? `timed out after ${timeoutMs} ms` : error instanceof Error ? error.message : String(error);
|
|
8604
|
+
throw new SmsSendError(`Telnyx could not be reached (${reason}); the message may or may not have been sent`, true, true);
|
|
8605
|
+
} finally {
|
|
8606
|
+
clearTimeout(timer);
|
|
8607
|
+
}
|
|
8608
|
+
if (response.ok) {
|
|
8609
|
+
const id = body?.data?.id;
|
|
8610
|
+
return id ? { status: "SENT", id } : { status: "SENT" };
|
|
8611
|
+
}
|
|
8612
|
+
const { code, text } = firstError(body);
|
|
8613
|
+
if (code === OPTED_OUT_CODE) return { status: "SKIPPED", reason: "The recipient opted out of text messages" };
|
|
8614
|
+
const serverFault = response.status >= 500;
|
|
8615
|
+
const retryable = response.status === 429 || serverFault;
|
|
8616
|
+
throw new SmsSendError(
|
|
8617
|
+
`Telnyx refused the message (HTTP ${response.status}${code ? `, code ${code}` : ""}): ${text}`,
|
|
8618
|
+
retryable,
|
|
8619
|
+
serverFault,
|
|
8620
|
+
response.status,
|
|
8621
|
+
code
|
|
8622
|
+
);
|
|
8623
|
+
}
|
|
8624
|
+
};
|
|
8625
|
+
}
|
|
8626
|
+
|
|
8627
|
+
// src/telnyx/telnyx-inbound.ts
|
|
8628
|
+
var import_node_crypto3 = require("crypto");
|
|
8629
|
+
var ED25519_SPKI_PREFIX = Buffer.from("302a300506032b6570032100", "hex");
|
|
8630
|
+
var DEFAULT_TOLERANCE_SECONDS = 300;
|
|
8631
|
+
function verifyTelnyxSignature(rawBody, headers, options) {
|
|
8632
|
+
const signature = readHeader(headers, "telnyx-signature-ed25519");
|
|
8633
|
+
const timestamp = readHeader(headers, "telnyx-timestamp");
|
|
8634
|
+
if (!signature || !timestamp || !/^\d+$/.test(timestamp)) return false;
|
|
8635
|
+
const nowSeconds = Math.floor((options.now?.() ?? /* @__PURE__ */ new Date()).getTime() / 1e3);
|
|
8636
|
+
if (Math.abs(nowSeconds - Number(timestamp)) > (options.toleranceSeconds ?? DEFAULT_TOLERANCE_SECONDS)) return false;
|
|
8637
|
+
try {
|
|
8638
|
+
const raw = Buffer.from(options.publicKey.trim(), "base64");
|
|
8639
|
+
if (raw.length !== 32) return false;
|
|
8640
|
+
const key = (0, import_node_crypto3.createPublicKey)({ key: Buffer.concat([ED25519_SPKI_PREFIX, raw]), format: "der", type: "spki" });
|
|
8641
|
+
return (0, import_node_crypto3.verify)(null, Buffer.from(`${timestamp}|${rawBody}`), key, Buffer.from(signature, "base64"));
|
|
8642
|
+
} catch {
|
|
8643
|
+
return false;
|
|
8644
|
+
}
|
|
8645
|
+
}
|
|
8646
|
+
function handleTelnyxWebhook(rawBody, headers, options) {
|
|
8647
|
+
if (!verifyTelnyxSignature(rawBody, headers, options)) return { ok: false, status: 401, reason: "The signature is missing, wrong or too old" };
|
|
8648
|
+
let parsed;
|
|
8649
|
+
try {
|
|
8650
|
+
const value = JSON.parse(rawBody);
|
|
8651
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return { ok: false, status: 400, reason: "The body is not an event" };
|
|
8652
|
+
parsed = value;
|
|
8653
|
+
} catch {
|
|
8654
|
+
return { ok: false, status: 400, reason: "The body is not JSON" };
|
|
8655
|
+
}
|
|
8656
|
+
const eventType = parsed.data?.event_type ?? "";
|
|
8657
|
+
const payload = parsed.data?.payload;
|
|
8658
|
+
const id = payload?.id;
|
|
8659
|
+
const to = payload?.to?.[0]?.phone_number;
|
|
8660
|
+
if (eventType === "message.received") {
|
|
8661
|
+
const from = payload?.from?.phone_number;
|
|
8662
|
+
if (!id || !from || !to) return { ok: false, status: 400, reason: "The message is missing its id or phone numbers" };
|
|
8663
|
+
const text = typeof payload?.text === "string" ? payload.text : "";
|
|
8664
|
+
const type = classifyReply(text);
|
|
8665
|
+
return { ok: true, event: { type, id, from, to, text } };
|
|
8666
|
+
}
|
|
8667
|
+
if (eventType === "message.finalized" || eventType === "message.sent") {
|
|
8668
|
+
if (!id || !to) return { ok: false, status: 400, reason: "The delivery report is missing its id or number" };
|
|
8669
|
+
const status = payload?.to?.[0]?.status;
|
|
8670
|
+
if (eventType === "message.sent" || status !== "delivered" && status !== "delivery_failed" && status !== "sending_failed") {
|
|
8671
|
+
return { ok: true, event: { type: "ignored", eventType } };
|
|
8672
|
+
}
|
|
8673
|
+
const errorCode = payload?.errors?.[0]?.code;
|
|
8674
|
+
return {
|
|
8675
|
+
ok: true,
|
|
8676
|
+
event: { type: "delivery", id, to, status: status === "delivered" ? "delivered" : "failed", ...errorCode === void 0 ? {} : { errorCode: String(errorCode) } }
|
|
8677
|
+
};
|
|
8678
|
+
}
|
|
8679
|
+
return { ok: true, event: { type: "ignored", eventType } };
|
|
8680
|
+
}
|
|
8681
|
+
|
|
8682
|
+
// src/twilio/twilio-sms.ts
|
|
8683
|
+
var DEFAULT_TIMEOUT_MS2 = 1e4;
|
|
8684
|
+
var OPTED_OUT_CODE2 = "21610";
|
|
8685
|
+
function createTwilioSmsAdapter(config) {
|
|
8686
|
+
const accountSid = typeof config.accountSid === "string" ? config.accountSid.trim() : "";
|
|
8687
|
+
const authToken = typeof config.authToken === "string" ? config.authToken.trim() : "";
|
|
8688
|
+
if (!accountSid || !authToken) throw new Error("createTwilioSmsAdapter needs an accountSid and an authToken");
|
|
8689
|
+
const serviceSid = config.messagingServiceSid?.trim() || void 0;
|
|
8690
|
+
const from = config.from ? normalizePhoneNumber(config.from) : null;
|
|
8691
|
+
if (config.from && !from) throw new Error('createTwilioSmsAdapter: "from" must be a phone number such as +13135550100');
|
|
8692
|
+
if (!from && !serviceSid) throw new Error('createTwilioSmsAdapter needs a sending number ("from") or a messagingServiceSid');
|
|
8693
|
+
const doFetch = config.fetch ?? fetch;
|
|
8694
|
+
const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
|
|
8695
|
+
const url = `https://api.twilio.com/2010-04-01/Accounts/${encodeURIComponent(accountSid)}/Messages.json`;
|
|
8696
|
+
const authorization = `Basic ${Buffer.from(`${accountSid}:${authToken}`).toString("base64")}`;
|
|
8697
|
+
return {
|
|
8698
|
+
async send(message) {
|
|
8699
|
+
if (message.channel !== "SMS") return { status: "SKIPPED", reason: "The Twilio adapter only sends text messages" };
|
|
8700
|
+
const to = normalizePhoneNumber(message.to);
|
|
8701
|
+
if (!to) return { status: "SKIPPED", reason: "The recipient is not a valid phone number" };
|
|
8702
|
+
if (!message.body.trim()) return { status: "SKIPPED", reason: "The message is empty" };
|
|
8703
|
+
const form = new URLSearchParams({ To: to, Body: message.body });
|
|
8704
|
+
if (from) form.set("From", from);
|
|
8705
|
+
else if (serviceSid) form.set("MessagingServiceSid", serviceSid);
|
|
8706
|
+
const controller = new AbortController();
|
|
8707
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
8708
|
+
let response;
|
|
8709
|
+
let body;
|
|
8710
|
+
try {
|
|
8711
|
+
response = await doFetch(url, {
|
|
8712
|
+
method: "POST",
|
|
8713
|
+
headers: { Authorization: authorization, "Content-Type": "application/x-www-form-urlencoded" },
|
|
8714
|
+
body: form.toString(),
|
|
8715
|
+
signal: controller.signal
|
|
8716
|
+
});
|
|
8717
|
+
body = await response.json().catch((error2) => {
|
|
8718
|
+
if (controller.signal.aborted) throw error2;
|
|
8719
|
+
return null;
|
|
8720
|
+
});
|
|
8721
|
+
} catch (error2) {
|
|
8722
|
+
const reason = controller.signal.aborted ? `timed out after ${timeoutMs} ms` : error2 instanceof Error ? error2.message : String(error2);
|
|
8723
|
+
throw new SmsSendError(`Twilio could not be reached (${reason}); the message may or may not have been sent`, true, true);
|
|
8724
|
+
} finally {
|
|
8725
|
+
clearTimeout(timer);
|
|
8726
|
+
}
|
|
8727
|
+
if (response.ok) {
|
|
8728
|
+
const id = body?.sid;
|
|
8729
|
+
return id ? { status: "SENT", id } : { status: "SENT" };
|
|
8730
|
+
}
|
|
8731
|
+
const error = body ?? {};
|
|
8732
|
+
const code = error.code === void 0 ? void 0 : String(error.code);
|
|
8733
|
+
if (code === OPTED_OUT_CODE2) return { status: "SKIPPED", reason: "The recipient opted out of text messages" };
|
|
8734
|
+
const serverFault = response.status >= 500;
|
|
8735
|
+
throw new SmsSendError(
|
|
8736
|
+
`Twilio refused the message (HTTP ${response.status}${code ? `, code ${code}` : ""}): ${error.message ?? "no detail given"}`,
|
|
8737
|
+
response.status === 429 || serverFault,
|
|
8738
|
+
serverFault,
|
|
8739
|
+
response.status,
|
|
8740
|
+
code
|
|
8741
|
+
);
|
|
8742
|
+
}
|
|
8743
|
+
};
|
|
8744
|
+
}
|
|
8745
|
+
|
|
8746
|
+
// src/twilio/twilio-inbound.ts
|
|
8747
|
+
var import_node_crypto4 = require("crypto");
|
|
8748
|
+
function expectedSignature(params, options) {
|
|
8749
|
+
const keys = [...new Set(params.keys())].sort();
|
|
8750
|
+
const signed = keys.reduce((text, key) => text + key + params.getAll(key).join(""), options.url);
|
|
8751
|
+
return (0, import_node_crypto4.createHmac)("sha1", options.authToken.trim()).update(signed).digest("base64");
|
|
8752
|
+
}
|
|
8753
|
+
function verifyTwilioSignature(rawBody, headers, options) {
|
|
8754
|
+
const given = readHeader(headers, "x-twilio-signature");
|
|
8755
|
+
if (!given || !options.authToken.trim()) return false;
|
|
8756
|
+
const expected = Buffer.from(expectedSignature(new URLSearchParams(rawBody), options));
|
|
8757
|
+
const actual = Buffer.from(given);
|
|
8758
|
+
return expected.length === actual.length && (0, import_node_crypto4.timingSafeEqual)(expected, actual);
|
|
8759
|
+
}
|
|
8760
|
+
function handleTwilioWebhook(rawBody, headers, options) {
|
|
8761
|
+
if (!verifyTwilioSignature(rawBody, headers, options)) return { ok: false, status: 401, reason: "The signature is missing or wrong" };
|
|
8762
|
+
const params = new URLSearchParams(rawBody);
|
|
8763
|
+
const id = params.get("MessageSid") ?? params.get("SmsSid");
|
|
8764
|
+
const from = params.get("From");
|
|
8765
|
+
const to = params.get("To");
|
|
8766
|
+
if (params.has("MessageStatus") && !params.has("Body")) {
|
|
8767
|
+
const status = params.get("MessageStatus") ?? "";
|
|
8768
|
+
if (!id || !to) return { ok: false, status: 400, reason: "The status report is missing its id or number" };
|
|
8769
|
+
if (status !== "delivered" && status !== "undelivered" && status !== "failed") return { ok: true, event: { type: "ignored", eventType: `status.${status}` } };
|
|
8770
|
+
const errorCode = params.get("ErrorCode");
|
|
8771
|
+
return { ok: true, event: { type: "delivery", id, to, status: status === "delivered" ? "delivered" : "failed", ...errorCode ? { errorCode } : {} } };
|
|
8772
|
+
}
|
|
8773
|
+
if (params.has("Body")) {
|
|
8774
|
+
if (!id || !from || !to) return { ok: false, status: 400, reason: "The message is missing its id or phone numbers" };
|
|
8775
|
+
const text = params.get("Body") ?? "";
|
|
8776
|
+
return { ok: true, event: { type: classifyReply(text), id, from, to, text } };
|
|
8777
|
+
}
|
|
8778
|
+
return { ok: true, event: { type: "ignored", eventType: "unknown" } };
|
|
8779
|
+
}
|
|
8780
|
+
|
|
8781
|
+
// src/sms/per-business-sms.ts
|
|
8782
|
+
var DEFAULT_ADAPTER_TTL_MS = 5 * 6e4;
|
|
8783
|
+
var DEFAULT_NO_NUMBER_TTL_MS = 6e4;
|
|
8784
|
+
function createPerBusinessSmsAdapter(options) {
|
|
8785
|
+
const adapterTtl = options.adapterTtlMs ?? DEFAULT_ADAPTER_TTL_MS;
|
|
8786
|
+
const noNumberTtl = options.noNumberTtlMs ?? DEFAULT_NO_NUMBER_TTL_MS;
|
|
8787
|
+
const now = options.now ?? Date.now;
|
|
8788
|
+
const kept = /* @__PURE__ */ new Map();
|
|
8789
|
+
function adapterFor(organizationId) {
|
|
8790
|
+
const existing = kept.get(organizationId);
|
|
8791
|
+
if (existing && (existing.expiresAt === null || existing.expiresAt > now())) return existing.lookup;
|
|
8792
|
+
const entry = { lookup: Promise.resolve(options.resolve(organizationId)), expiresAt: null };
|
|
8793
|
+
kept.set(organizationId, entry);
|
|
8794
|
+
entry.lookup.then(
|
|
8795
|
+
(adapter) => {
|
|
8796
|
+
entry.expiresAt = now() + (adapter ? adapterTtl : noNumberTtl);
|
|
8797
|
+
},
|
|
8798
|
+
// A failed lookup is not kept; only this entry is removed, not a newer one.
|
|
8799
|
+
() => {
|
|
8800
|
+
if (kept.get(organizationId) === entry) kept.delete(organizationId);
|
|
8801
|
+
}
|
|
8802
|
+
);
|
|
8803
|
+
return entry.lookup;
|
|
8804
|
+
}
|
|
8805
|
+
return {
|
|
8806
|
+
async send(message) {
|
|
8807
|
+
if (message.channel !== "SMS") return { status: "SKIPPED", reason: "This adapter only sends text messages" };
|
|
8808
|
+
if (!message.organizationId) {
|
|
8809
|
+
return { status: "SKIPPED", reason: "The message names no business, so there is no number to send from (run the sender with organization: true)" };
|
|
8810
|
+
}
|
|
8811
|
+
const adapter = await adapterFor(message.organizationId);
|
|
8812
|
+
if (!adapter) return { status: "SKIPPED", reason: "This business has no text-message number set up" };
|
|
8813
|
+
return adapter.send(message);
|
|
8814
|
+
},
|
|
8815
|
+
forget(organizationId) {
|
|
8816
|
+
kept.delete(organizationId);
|
|
8817
|
+
}
|
|
8818
|
+
};
|
|
8819
|
+
}
|
|
8820
|
+
|
|
8821
|
+
// src/sms/text-settings-resolver.ts
|
|
8822
|
+
var import_scheduling77 = require("@ordinatio/scheduling");
|
|
8823
|
+
function createTextSettingsResolver(options) {
|
|
8824
|
+
return async (organizationId) => {
|
|
8825
|
+
const settings = await (0, import_scheduling77.getTextSettings)(await options.db(organizationId), organizationId);
|
|
8826
|
+
if (!settings || !settings.enabled) return null;
|
|
8827
|
+
try {
|
|
8828
|
+
if (settings.provider === "TELNYX" && options.telnyx?.apiKey?.trim()) {
|
|
8829
|
+
return createTelnyxSmsAdapter({ ...options.telnyx, from: settings.fromNumber, fetch: options.fetch });
|
|
8830
|
+
}
|
|
8831
|
+
if (settings.provider === "TWILIO" && options.twilio?.accountSid?.trim() && options.twilio.authToken?.trim()) {
|
|
8832
|
+
return createTwilioSmsAdapter({ ...options.twilio, from: settings.fromNumber, fetch: options.fetch });
|
|
8833
|
+
}
|
|
8834
|
+
} catch (error) {
|
|
8835
|
+
console.error(`[text-settings] could not build the ${settings.provider} sender for organization ${organizationId}:`, error instanceof Error ? error.message : error);
|
|
8836
|
+
return null;
|
|
8837
|
+
}
|
|
8838
|
+
if (settings.provider === "TELNYX" || settings.provider === "TWILIO") {
|
|
8839
|
+
console.error(`[text-settings] organization ${organizationId} chose ${settings.provider}, but this server has no usable ${settings.provider} account`);
|
|
8840
|
+
}
|
|
8841
|
+
return null;
|
|
8842
|
+
};
|
|
8843
|
+
}
|
|
8844
|
+
|
|
8845
|
+
// src/outlook-sync/outlook-config.ts
|
|
8846
|
+
var BLOCKED_TYPE_SLUG = "blocked";
|
|
8847
|
+
var GRAPH_BASE = "https://graph.microsoft.com/v1.0";
|
|
8848
|
+
var MICROSOFT_TOKEN_ENDPOINT = "https://login.microsoftonline.com/common/oauth2/v2.0/token";
|
|
8849
|
+
var OUTLOOK_CALENDAR_SCOPE = "https://graph.microsoft.com/Calendars.ReadWrite offline_access";
|
|
8850
|
+
function problem(config, message, context) {
|
|
8851
|
+
config.onProblem?.(message, context);
|
|
8852
|
+
}
|
|
8853
|
+
|
|
8854
|
+
// src/outlook-sync/outlook-access-token.ts
|
|
8855
|
+
var REFRESH_MARGIN_MS = 5 * 60 * 1e3;
|
|
8856
|
+
async function getOutlookAccessToken(config, calendarId) {
|
|
8857
|
+
const calendar = await config.db.schedulingCalendar.findUnique({
|
|
8858
|
+
where: { id: calendarId },
|
|
8859
|
+
select: {
|
|
8860
|
+
outlookCalendarId: true,
|
|
8861
|
+
outlookAccessToken: true,
|
|
8862
|
+
outlookRefreshToken: true,
|
|
8863
|
+
outlookTokenExpiresAt: true
|
|
8864
|
+
}
|
|
8865
|
+
});
|
|
8866
|
+
if (!calendar?.outlookCalendarId || !calendar.outlookRefreshToken) return null;
|
|
8867
|
+
const now = (config.now ?? (() => /* @__PURE__ */ new Date()))();
|
|
8868
|
+
const stillValid = calendar.outlookAccessToken && calendar.outlookTokenExpiresAt && calendar.outlookTokenExpiresAt.getTime() - now.getTime() >= REFRESH_MARGIN_MS;
|
|
8869
|
+
if (stillValid) return calendar.outlookAccessToken;
|
|
8870
|
+
try {
|
|
8871
|
+
const response = await (config.fetch ?? fetch)(MICROSOFT_TOKEN_ENDPOINT, {
|
|
8872
|
+
method: "POST",
|
|
8873
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
8874
|
+
body: new URLSearchParams({
|
|
8875
|
+
client_id: config.clientId.trim(),
|
|
8876
|
+
client_secret: config.clientSecret.trim(),
|
|
8877
|
+
refresh_token: calendar.outlookRefreshToken,
|
|
8878
|
+
grant_type: "refresh_token",
|
|
8879
|
+
scope: OUTLOOK_CALENDAR_SCOPE
|
|
8880
|
+
})
|
|
8881
|
+
});
|
|
8882
|
+
if (!response.ok) throw new Error(`Token refresh HTTP ${response.status}`);
|
|
8883
|
+
const data = await response.json();
|
|
8884
|
+
if (!data.access_token || typeof data.expires_in !== "number") throw new Error("Token refresh answered without a token");
|
|
8885
|
+
await config.db.schedulingCalendar.update({
|
|
8886
|
+
where: { id: calendarId },
|
|
8887
|
+
data: {
|
|
8888
|
+
outlookAccessToken: data.access_token,
|
|
8889
|
+
outlookRefreshToken: data.refresh_token ?? calendar.outlookRefreshToken,
|
|
8890
|
+
outlookTokenExpiresAt: new Date(now.getTime() + data.expires_in * 1e3)
|
|
8891
|
+
}
|
|
8892
|
+
});
|
|
8893
|
+
return data.access_token;
|
|
8894
|
+
} catch (error) {
|
|
8895
|
+
problem(config, "Outlook token refresh failed; the calendar must be reconnected", {
|
|
8896
|
+
calendarId,
|
|
8897
|
+
error: error instanceof Error ? error.message : String(error)
|
|
8898
|
+
});
|
|
8899
|
+
return null;
|
|
8900
|
+
}
|
|
8901
|
+
}
|
|
8902
|
+
|
|
8903
|
+
// src/outlook-sync/outlook-push.ts
|
|
8904
|
+
async function pushAppointmentToOutlook(config, appointmentId) {
|
|
8905
|
+
const appointment = await config.db.appointment.findUnique({
|
|
8906
|
+
where: { id: appointmentId },
|
|
8907
|
+
include: {
|
|
8908
|
+
type: { select: { name: true, slug: true } },
|
|
8909
|
+
calendar: { select: { id: true, outlookCalendarId: true } }
|
|
8910
|
+
}
|
|
8911
|
+
});
|
|
8912
|
+
if (!appointment?.calendar.outlookCalendarId) return null;
|
|
8913
|
+
if (appointment.type.slug === BLOCKED_TYPE_SLUG) return null;
|
|
8914
|
+
const accessToken = await getOutlookAccessToken(config, appointment.calendarId);
|
|
8915
|
+
if (!accessToken) return null;
|
|
8916
|
+
const body = {
|
|
8917
|
+
subject: `${appointment.type.name} \u2014 ${appointment.clientName}`,
|
|
8918
|
+
body: {
|
|
8919
|
+
contentType: "text",
|
|
8920
|
+
content: [
|
|
8921
|
+
`Service: ${appointment.type.name}`,
|
|
8922
|
+
`Duration: ${appointment.duration} min`,
|
|
8923
|
+
appointment.clientPhone ? `Phone: ${appointment.clientPhone}` : "",
|
|
8924
|
+
appointment.clientEmail ? `Email: ${appointment.clientEmail}` : ""
|
|
8925
|
+
].filter(Boolean).join("\n")
|
|
8926
|
+
},
|
|
8927
|
+
// UTC on both sides so the event lands at the stored instant whatever zone the Outlook calendar uses.
|
|
8928
|
+
start: { dateTime: appointment.startTime.toISOString(), timeZone: "UTC" },
|
|
8929
|
+
end: { dateTime: appointment.endTime.toISOString(), timeZone: "UTC" }
|
|
8930
|
+
};
|
|
8931
|
+
const calendarUrl = `${GRAPH_BASE}/me/calendars/${encodeURIComponent(appointment.calendar.outlookCalendarId)}/events`;
|
|
8932
|
+
const isUpdate = Boolean(appointment.outlookEventId);
|
|
8933
|
+
const method = isUpdate ? "PATCH" : "POST";
|
|
8934
|
+
const url = isUpdate ? `${calendarUrl}/${encodeURIComponent(appointment.outlookEventId)}` : calendarUrl;
|
|
8935
|
+
const response = await (config.fetch ?? fetch)(url, {
|
|
8936
|
+
method,
|
|
8937
|
+
headers: { Authorization: `Bearer ${accessToken}`, "Content-Type": "application/json" },
|
|
8938
|
+
body: JSON.stringify(body)
|
|
8939
|
+
});
|
|
8940
|
+
if (!response.ok) throw new Error(`Outlook ${method} event failed with HTTP ${response.status}`);
|
|
8941
|
+
const created = await response.json();
|
|
8942
|
+
if (!isUpdate && created.id) {
|
|
8943
|
+
try {
|
|
8944
|
+
await config.db.appointment.update({ where: { id: appointmentId }, data: { outlookEventId: created.id } });
|
|
8945
|
+
} catch (error) {
|
|
8946
|
+
const removed = await (config.fetch ?? fetch)(`${calendarUrl}/${encodeURIComponent(created.id)}`, {
|
|
8947
|
+
method: "DELETE",
|
|
8948
|
+
headers: { Authorization: `Bearer ${accessToken}` }
|
|
8949
|
+
}).then((r) => r.ok || r.status === 404, () => false);
|
|
8950
|
+
if (!removed) problem(config, "An Outlook event was created but its id could not be saved or the event removed", { appointmentId });
|
|
8951
|
+
throw error;
|
|
8952
|
+
}
|
|
8953
|
+
}
|
|
8954
|
+
return created.id ?? appointment.outlookEventId ?? null;
|
|
8955
|
+
}
|
|
8956
|
+
async function deleteOutlookEvent(config, appointmentId) {
|
|
8957
|
+
const appointment = await config.db.appointment.findUnique({
|
|
8958
|
+
where: { id: appointmentId },
|
|
8959
|
+
select: { outlookEventId: true, calendarId: true, calendar: { select: { outlookCalendarId: true } }, type: { select: { slug: true } } }
|
|
8960
|
+
});
|
|
8961
|
+
if (!appointment?.outlookEventId || !appointment.calendar.outlookCalendarId) return;
|
|
8962
|
+
if (appointment.type.slug === BLOCKED_TYPE_SLUG) return;
|
|
8963
|
+
const accessToken = await getOutlookAccessToken(config, appointment.calendarId);
|
|
8964
|
+
if (!accessToken) return;
|
|
8965
|
+
const response = await (config.fetch ?? fetch)(
|
|
8966
|
+
`${GRAPH_BASE}/me/calendars/${encodeURIComponent(appointment.calendar.outlookCalendarId)}/events/${encodeURIComponent(appointment.outlookEventId)}`,
|
|
8967
|
+
{ method: "DELETE", headers: { Authorization: `Bearer ${accessToken}` } }
|
|
8968
|
+
);
|
|
8969
|
+
if (!response.ok && response.status !== 404) throw new Error(`Outlook DELETE event failed with HTTP ${response.status}`);
|
|
8970
|
+
await config.db.appointment.update({ where: { id: appointmentId }, data: { outlookEventId: null } });
|
|
8971
|
+
}
|
|
8972
|
+
|
|
8973
|
+
// src/outlook-sync/outlook-pull.ts
|
|
8974
|
+
var MAX_PAGES = 200;
|
|
8975
|
+
var withZone = (dateTime) => dateTime.endsWith("Z") ? dateTime : `${dateTime}Z`;
|
|
8976
|
+
async function pullChangesFromOutlook(config, hooks, calendarId) {
|
|
8977
|
+
return pullOnce(config, hooks, calendarId, { isRestart: false, skipWindowCheck: false });
|
|
8978
|
+
}
|
|
8979
|
+
async function pullOnce(config, hooks, calendarId, mode) {
|
|
8980
|
+
const { isRestart } = mode;
|
|
8981
|
+
const { db } = config;
|
|
8982
|
+
const calendar = await db.schedulingCalendar.findUnique({ where: { id: calendarId } });
|
|
8983
|
+
if (!calendar?.outlookCalendarId) return { synced: 0 };
|
|
8984
|
+
const now = (config.now ?? (() => /* @__PURE__ */ new Date()))();
|
|
8985
|
+
const windowIsStale = calendar.lastSyncAt != null && calendar.lastSyncAt.getUTCMonth() !== now.getUTCMonth();
|
|
8986
|
+
if (calendar.outlookSyncToken && windowIsStale && !isRestart && !mode.skipWindowCheck) {
|
|
8987
|
+
if (!await getOutlookAccessToken(config, calendarId)) return { synced: 0 };
|
|
8988
|
+
const drained = await pullOnce(config, hooks, calendarId, { isRestart: false, skipWindowCheck: true });
|
|
8989
|
+
const fresh = await pullOnce(config, hooks, calendarId, { isRestart: true, skipWindowCheck: true, ignoreSavedLink: true });
|
|
8990
|
+
return { synced: drained.synced + fresh.synced };
|
|
8991
|
+
}
|
|
8992
|
+
const accessToken = await getOutlookAccessToken(config, calendarId);
|
|
8993
|
+
if (!accessToken) return { synced: 0 };
|
|
8994
|
+
const headers = { Authorization: `Bearer ${accessToken}`, Prefer: 'outlook.timezone="UTC"' };
|
|
8995
|
+
const horizon = new Date(now);
|
|
8996
|
+
horizon.setUTCFullYear(horizon.getUTCFullYear() + 1);
|
|
8997
|
+
const firstUrl = `${GRAPH_BASE}/me/calendars/${encodeURIComponent(calendar.outlookCalendarId)}/calendarView/delta?startDateTime=${now.toISOString()}&endDateTime=${horizon.toISOString()}`;
|
|
8998
|
+
let url = mode.ignoreSavedLink ? firstUrl : calendar.outlookSyncToken ?? firstUrl;
|
|
8999
|
+
let deltaLink = null;
|
|
9000
|
+
let synced = 0;
|
|
9001
|
+
let unhandled = null;
|
|
9002
|
+
let blockedType = null;
|
|
9003
|
+
for (let pageNumber = 0; url; pageNumber++) {
|
|
9004
|
+
if (pageNumber >= MAX_PAGES) throw new Error("Outlook delta query returned more pages than expected");
|
|
9005
|
+
if (!url.startsWith(`${GRAPH_BASE}/`)) throw new Error("Outlook delta link does not point at Microsoft Graph");
|
|
9006
|
+
const response = await (config.fetch ?? fetch)(url, { headers });
|
|
9007
|
+
if (response.status === 410) {
|
|
9008
|
+
if (isRestart) throw new Error("Outlook delta query was refused with HTTP 410 on a fresh start");
|
|
9009
|
+
problem(config, "Outlook delta link expired; starting a full sync", { calendarId });
|
|
9010
|
+
await db.schedulingCalendar.update({ where: { id: calendarId }, data: { outlookSyncToken: null } });
|
|
9011
|
+
return pullOnce(config, hooks, calendarId, { isRestart: true, skipWindowCheck: true });
|
|
9012
|
+
}
|
|
9013
|
+
if (!response.ok) throw new Error(`Outlook delta query failed with HTTP ${response.status}`);
|
|
9014
|
+
const page = await response.json();
|
|
9015
|
+
for (const event of page.value) {
|
|
9016
|
+
if (!event.id) continue;
|
|
9017
|
+
const existing = await db.appointment.findFirst({ where: { outlookEventId: event.id, calendarId } });
|
|
9018
|
+
if (event["@removed"]) {
|
|
9019
|
+
if (existing && existing.status !== "CANCELLED") {
|
|
9020
|
+
try {
|
|
9021
|
+
if (await hooks.cancelAppointment(existing.id)) synced++;
|
|
9022
|
+
else unhandled ??= new Error(`The host did not cancel appointment ${existing.id}`);
|
|
9023
|
+
} catch (error) {
|
|
9024
|
+
unhandled ??= error instanceof Error ? error : new Error(String(error));
|
|
9025
|
+
problem(config, "Cancelling an appointment deleted in Outlook failed", { appointmentId: existing.id, error: unhandled.message });
|
|
9026
|
+
}
|
|
9027
|
+
}
|
|
9028
|
+
continue;
|
|
9029
|
+
}
|
|
9030
|
+
if (!event.start?.dateTime || !event.end?.dateTime) continue;
|
|
9031
|
+
const startTime = new Date(withZone(event.start.dateTime));
|
|
9032
|
+
const endTime = new Date(withZone(event.end.dateTime));
|
|
9033
|
+
if (Number.isNaN(startTime.getTime()) || Number.isNaN(endTime.getTime()) || endTime <= startTime) continue;
|
|
9034
|
+
const duration = Math.round((endTime.getTime() - startTime.getTime()) / 6e4);
|
|
9035
|
+
if (existing) {
|
|
9036
|
+
if (existing.status === "CANCELLED") continue;
|
|
9037
|
+
const moved = existing.startTime.getTime() !== startTime.getTime() || existing.endTime.getTime() !== endTime.getTime();
|
|
9038
|
+
if (!moved) continue;
|
|
9039
|
+
try {
|
|
9040
|
+
await hooks.onAppointmentMoved?.({ appointmentId: existing.id, organizationId: calendar.organizationId, startTime, endTime });
|
|
9041
|
+
await db.appointment.update({ where: { id: existing.id }, data: { startTime, endTime, duration } });
|
|
9042
|
+
} catch (error) {
|
|
9043
|
+
unhandled ??= error instanceof Error ? error : new Error(String(error));
|
|
9044
|
+
problem(config, "Saving a time changed in Outlook failed", { appointmentId: existing.id, error: unhandled.message });
|
|
9045
|
+
continue;
|
|
9046
|
+
}
|
|
9047
|
+
synced++;
|
|
9048
|
+
continue;
|
|
9049
|
+
}
|
|
9050
|
+
blockedType ??= await findOrCreateBlockedType(config, calendar.organizationId);
|
|
9051
|
+
await db.appointment.create({
|
|
9052
|
+
data: {
|
|
9053
|
+
calendarId,
|
|
9054
|
+
typeId: blockedType.id,
|
|
9055
|
+
startTime,
|
|
9056
|
+
endTime,
|
|
9057
|
+
duration,
|
|
9058
|
+
timezone: calendar.timezone,
|
|
9059
|
+
status: "CONFIRMED",
|
|
9060
|
+
clientName: event.subject || "Blocked",
|
|
9061
|
+
clientEmail: "",
|
|
9062
|
+
outlookEventId: event.id
|
|
9063
|
+
}
|
|
9064
|
+
});
|
|
9065
|
+
synced++;
|
|
9066
|
+
}
|
|
9067
|
+
deltaLink = page["@odata.deltaLink"] ?? null;
|
|
9068
|
+
url = page["@odata.nextLink"] ?? "";
|
|
9069
|
+
}
|
|
9070
|
+
if (unhandled) throw unhandled;
|
|
9071
|
+
if (deltaLink) {
|
|
9072
|
+
const isDrain = mode.skipWindowCheck && !isRestart;
|
|
9073
|
+
await db.schedulingCalendar.update({
|
|
9074
|
+
where: { id: calendarId },
|
|
9075
|
+
data: isDrain ? { outlookSyncToken: deltaLink } : { outlookSyncToken: deltaLink, lastSyncAt: now }
|
|
9076
|
+
});
|
|
9077
|
+
}
|
|
9078
|
+
return { synced };
|
|
9079
|
+
}
|
|
9080
|
+
async function findOrCreateBlockedType(config, organizationId) {
|
|
9081
|
+
const find = () => config.db.appointmentType.findFirst({ where: { slug: BLOCKED_TYPE_SLUG, organizationId } });
|
|
9082
|
+
const found = await find();
|
|
9083
|
+
if (found) return found;
|
|
9084
|
+
try {
|
|
9085
|
+
return await config.db.appointmentType.create({
|
|
9086
|
+
data: {
|
|
9087
|
+
name: "Blocked",
|
|
9088
|
+
slug: BLOCKED_TYPE_SLUG,
|
|
9089
|
+
duration: 60,
|
|
9090
|
+
color: "#6B7280",
|
|
9091
|
+
isActive: false,
|
|
9092
|
+
// never offered for booking
|
|
9093
|
+
organizationId
|
|
9094
|
+
}
|
|
9095
|
+
});
|
|
9096
|
+
} catch (error) {
|
|
9097
|
+
const raced = await find();
|
|
9098
|
+
if (raced) return raced;
|
|
9099
|
+
throw error;
|
|
9100
|
+
}
|
|
9101
|
+
}
|
|
9102
|
+
|
|
9103
|
+
// src/outlook-sync/create-outlook-calendar-sync.ts
|
|
9104
|
+
function createOutlookCalendarSync(config, hooks) {
|
|
9105
|
+
return {
|
|
9106
|
+
adapter: {
|
|
9107
|
+
async upsertEvent(event) {
|
|
9108
|
+
const externalId = await pushAppointmentToOutlook(config, event.appointmentId);
|
|
9109
|
+
return externalId ? { externalId } : {};
|
|
9110
|
+
},
|
|
9111
|
+
async removeEvent(ref) {
|
|
9112
|
+
await deleteOutlookEvent(config, ref.appointmentId);
|
|
9113
|
+
}
|
|
9114
|
+
},
|
|
9115
|
+
pull: async (calendarId) => await pullChangesFromOutlook(config, hooks, calendarId)
|
|
9116
|
+
};
|
|
9117
|
+
}
|
|
9118
|
+
|
|
8181
9119
|
// src/staff/simple-staff.ts
|
|
8182
9120
|
var DEFAULT_ADMIN_ROLES = ["OWNER", "ADMIN", "MANAGER"];
|
|
8183
9121
|
function createStaffContext(input) {
|
|
@@ -8216,6 +9154,47 @@ function createBearerStaffResolver(input) {
|
|
|
8216
9154
|
};
|
|
8217
9155
|
}
|
|
8218
9156
|
|
|
9157
|
+
// src/staff/staff-scope.ts
|
|
9158
|
+
function isCalendarVisibleInScope(calendarUserId, scope) {
|
|
9159
|
+
if (calendarUserId === null) return true;
|
|
9160
|
+
if (scope.mode === "unrestricted") return true;
|
|
9161
|
+
return scope.visibleUserIds.includes(calendarUserId);
|
|
9162
|
+
}
|
|
9163
|
+
function calendarVisibilityFilter(scope) {
|
|
9164
|
+
if (scope.mode === "unrestricted") return void 0;
|
|
9165
|
+
return { OR: [{ userId: { in: scope.visibleUserIds } }, { userId: null }] };
|
|
9166
|
+
}
|
|
9167
|
+
async function visibleCalendarIdsInScope(db, scope) {
|
|
9168
|
+
if (scope.mode === "unrestricted") return void 0;
|
|
9169
|
+
const calendars = await db.schedulingCalendar.findMany({
|
|
9170
|
+
where: { userId: { in: scope.visibleUserIds } },
|
|
9171
|
+
select: { id: true }
|
|
9172
|
+
});
|
|
9173
|
+
return calendars.map((calendar) => calendar.id);
|
|
9174
|
+
}
|
|
9175
|
+
async function canSeeCalendarInScope(db, calendarId, scope) {
|
|
9176
|
+
const [resolved, calendar] = await Promise.all([
|
|
9177
|
+
scope,
|
|
9178
|
+
db.schedulingCalendar.findUnique({ where: { id: calendarId }, select: { userId: true } })
|
|
9179
|
+
]);
|
|
9180
|
+
return calendar != null && isCalendarVisibleInScope(calendar.userId, resolved);
|
|
9181
|
+
}
|
|
9182
|
+
async function canSeeAppointmentInScope(db, appointmentId, scope) {
|
|
9183
|
+
const [resolved, appointment] = await Promise.all([
|
|
9184
|
+
scope,
|
|
9185
|
+
db.appointment.findUnique({ where: { id: appointmentId }, select: { calendar: { select: { userId: true } } } })
|
|
9186
|
+
]);
|
|
9187
|
+
return appointment != null && isCalendarVisibleInScope(appointment.calendar.userId, resolved);
|
|
9188
|
+
}
|
|
9189
|
+
function createScopedVisibility(db, getScope) {
|
|
9190
|
+
return {
|
|
9191
|
+
visibleCalendars: async () => calendarVisibilityFilter(await getScope()) ?? null,
|
|
9192
|
+
visibleCalendarIds: async () => await visibleCalendarIdsInScope(db, await getScope()),
|
|
9193
|
+
canSeeCalendar: async (calendarId) => await canSeeCalendarInScope(db, calendarId, getScope()),
|
|
9194
|
+
canSeeAppointment: async (appointmentId) => await canSeeAppointmentInScope(db, appointmentId, getScope())
|
|
9195
|
+
};
|
|
9196
|
+
}
|
|
9197
|
+
|
|
8219
9198
|
// src/node/node-listener.ts
|
|
8220
9199
|
var CONNECTION_HEADERS = ["host", "connection", "content-length", "transfer-encoding", "keep-alive", "upgrade"];
|
|
8221
9200
|
var PROXY_HEADERS = ["x-forwarded-for", "x-real-ip"];
|
|
@@ -8326,9 +9305,12 @@ function createNodeListener(api, options) {
|
|
|
8326
9305
|
RouteClientSchema,
|
|
8327
9306
|
SLOT_GRANULARITY_DEFAULT,
|
|
8328
9307
|
SLOT_GRANULARITY_OPTIONS,
|
|
9308
|
+
SmsSendError,
|
|
8329
9309
|
TERMINAL_SUCCESS_STATUSES,
|
|
8330
9310
|
TOKEN_TTL_DAYS,
|
|
9311
|
+
TelnyxSendError,
|
|
8331
9312
|
TestRoutingFormSchema,
|
|
9313
|
+
TextSettingsSchema,
|
|
8332
9314
|
UnverifiedPaymentError,
|
|
8333
9315
|
UpdateAppointmentCategorySchema,
|
|
8334
9316
|
UpdateAppointmentTypeSchema,
|
|
@@ -8339,7 +9321,13 @@ function createNodeListener(api, options) {
|
|
|
8339
9321
|
UpdatePackagePurchaseSchema,
|
|
8340
9322
|
UpdateRoutingFormSchema,
|
|
8341
9323
|
UpdateServicePackageSchema,
|
|
9324
|
+
assertStripeTestKey,
|
|
8342
9325
|
attemptLegRefund,
|
|
9326
|
+
calendarVisibilityFilter,
|
|
9327
|
+
canSeeAppointmentInScope,
|
|
9328
|
+
canSeeCalendarInScope,
|
|
9329
|
+
checkSendingDomain,
|
|
9330
|
+
classifyReply,
|
|
8343
9331
|
createBalanceIntent,
|
|
8344
9332
|
createBearerStaffResolver,
|
|
8345
9333
|
createMemoryAvailabilityCache,
|
|
@@ -8348,20 +9336,37 @@ function createNodeListener(api, options) {
|
|
|
8348
9336
|
createNoBalancePaymentControl,
|
|
8349
9337
|
createNoPaymentAdapter,
|
|
8350
9338
|
createNodeListener,
|
|
9339
|
+
createOutlookCalendarSync,
|
|
9340
|
+
createPerBusinessSmsAdapter,
|
|
8351
9341
|
createSchedulingApi,
|
|
9342
|
+
createScopedVisibility,
|
|
9343
|
+
createSendingDomainVerifier,
|
|
8352
9344
|
createSingleOrganizationDirectory,
|
|
8353
9345
|
createSingleOrganizationResolver,
|
|
8354
9346
|
createStaffContext,
|
|
9347
|
+
createStripePaymentAdapter,
|
|
9348
|
+
createTelnyxSmsAdapter,
|
|
9349
|
+
createTextSettingsResolver,
|
|
9350
|
+
createTwilioSmsAdapter,
|
|
8355
9351
|
decimalToCents,
|
|
8356
9352
|
defaultCorsHeaders,
|
|
8357
9353
|
getErrorCode,
|
|
8358
9354
|
getErrorMessage,
|
|
8359
9355
|
getErrorRef,
|
|
9356
|
+
handleTelnyxWebhook,
|
|
9357
|
+
handleTwilioWebhook,
|
|
9358
|
+
isCalendarVisibleInScope,
|
|
8360
9359
|
isSchedulingServiceError,
|
|
9360
|
+
isSupportedCurrency,
|
|
8361
9361
|
isTokenExpired,
|
|
9362
|
+
normalizePhoneNumber,
|
|
9363
|
+
normalizeSendingDomain,
|
|
8362
9364
|
parsePagination,
|
|
8363
9365
|
persistRefundOutcome,
|
|
8364
9366
|
recordBalanceIntent,
|
|
8365
9367
|
runCalendarRemoveWithoutBlocking,
|
|
8366
|
-
runCalendarSyncWithoutBlocking
|
|
9368
|
+
runCalendarSyncWithoutBlocking,
|
|
9369
|
+
verifyTelnyxSignature,
|
|
9370
|
+
verifyTwilioSignature,
|
|
9371
|
+
visibleCalendarIdsInScope
|
|
8367
9372
|
});
|