@ordinatio/scheduling 0.2.1 → 0.3.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 +16 -0
- package/README.md +56 -2
- package/dist/index.d.mts +196 -2
- package/dist/index.d.ts +196 -2
- package/dist/index.js +657 -1
- package/dist/index.mjs +626 -3
- package/package.json +1 -1
- package/prisma/migrations/20261027000000_webhooks/migration.sql +75 -0
- package/prisma/schema.prisma +62 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.3.0
|
|
4
|
+
|
|
5
|
+
- **Outbound webhooks.** An organization can register web addresses that are told when a booking is made,
|
|
6
|
+
moved, cancelled, marked no-show, or when a reminder is sent. Each delivery is signed (HMAC-SHA256 over a
|
|
7
|
+
timestamp and the exact body), retried with growing waits (1 minute, 5, 30, 2 hours, 6 hours), moved to a
|
|
8
|
+
dead-letter list after the last try, and logged. New tables: `WebhookEndpoint`, `WebhookDelivery`,
|
|
9
|
+
`WebhookAttempt` (migration `20261027000000_webhooks`; run `prisma migrate deploy` after updating). New
|
|
10
|
+
functions: `createWebhookEndpoint`, `listWebhookEndpoints`, `deleteWebhookEndpoint`, `enqueueWebhookEvent`,
|
|
11
|
+
`deliverDueWebhooks`, `sendTestWebhook`, `listWebhookDeliveries`, `retryWebhookDelivery`,
|
|
12
|
+
`verifyWebhookSignature` (for the receiver) and `signWebhook`.
|
|
13
|
+
- Webhook addresses must be `https` and public. Addresses on a private network are refused when the endpoint is
|
|
14
|
+
added and again when a connection is made, so a name that later points at a private address is still refused.
|
|
15
|
+
- `processPendingNotifications` takes `webhooks: true` to queue `reminder.sent` for each reminder it sends.
|
|
16
|
+
Off by default.
|
|
17
|
+
- New error codes `SCHED_1000` to `SCHED_1006`.
|
|
18
|
+
|
|
3
19
|
## 0.2.1
|
|
4
20
|
|
|
5
21
|
- **Upcoming bookings on the dashboard.** `getAppointmentDashboard` now also returns `upcoming` (bookings after
|
package/README.md
CHANGED
|
@@ -3,8 +3,8 @@
|
|
|
3
3
|
A booking engine. It finds open times, books one, and refuses a second booking for the same time. It keeps
|
|
4
4
|
its data in your own Postgres database.
|
|
5
5
|
|
|
6
|
-
**Status:** version 0.
|
|
7
|
-
`examples/scheduling-starter` in this repository.
|
|
6
|
+
**Status:** version 0.3.0, on npm. A runnable starter that installs it from a packed tarball is in
|
|
7
|
+
`examples/scheduling-starter` in this repository.
|
|
8
8
|
|
|
9
9
|
## Words used here
|
|
10
10
|
|
|
@@ -253,3 +253,57 @@ Available: `checkClockContract`, `checkNotificationContract`, `checkPaymentContr
|
|
|
253
253
|
the payment check makes a real charge and refund (use the provider's test mode), the notification check sends a real message to
|
|
254
254
|
`contract@example.com`, and the calendar check creates and removes a real event. Pass valid
|
|
255
255
|
credentials as the second argument to `checkAuthContract`, or it cannot check that valid sign-ins work.
|
|
256
|
+
|
|
257
|
+
## Webhooks
|
|
258
|
+
|
|
259
|
+
An organization can register web addresses that are told when something happens to a booking. The events are
|
|
260
|
+
`appointment.booked`, `appointment.rescheduled`, `appointment.cancelled`, `appointment.no_show` and
|
|
261
|
+
`reminder.sent`. Run `prisma migrate deploy` after updating: webhooks need the `WebhookEndpoint`,
|
|
262
|
+
`WebhookDelivery` and `WebhookAttempt` tables.
|
|
263
|
+
|
|
264
|
+
```ts
|
|
265
|
+
import {
|
|
266
|
+
createWebhookEndpoint, enqueueAppointmentWebhook, deliverDueWebhooks,
|
|
267
|
+
} from '@ordinatio/scheduling';
|
|
268
|
+
|
|
269
|
+
// 1. Add an address. The secret is returned once; store it where the receiver can read it.
|
|
270
|
+
const { endpoint, secret } = await createWebhookEndpoint(db, {
|
|
271
|
+
organizationId, url: 'https://example.com/hooks/scheduling', eventTypes: ['appointment.booked', 'appointment.cancelled'],
|
|
272
|
+
});
|
|
273
|
+
|
|
274
|
+
// 2. When something happens, queue it. This never throws; the booking is already saved.
|
|
275
|
+
await enqueueAppointmentWebhook(db, { organizationId, type: 'appointment.booked', appointmentId });
|
|
276
|
+
|
|
277
|
+
// 3. On a timer, send what is due. Two callers at once never send the same delivery twice.
|
|
278
|
+
setInterval(() => {
|
|
279
|
+
deliverDueWebhooks(db).catch((error) => console.error('Webhook delivery failed:', error));
|
|
280
|
+
}, 10_000);
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
A delivery that fails is tried again after 1 minute, 5 minutes, 30 minutes, 2 hours and 6 hours. After the sixth
|
|
284
|
+
failure it is `DEAD_LETTER`; `retryWebhookDelivery` puts it back. Any `2xx` answer counts as delivered. A redirect
|
|
285
|
+
counts as a failure and is not followed. Every try is kept in `WebhookAttempt`.
|
|
286
|
+
|
|
287
|
+
**On the receiving side**, check the signature on the raw body before trusting it:
|
|
288
|
+
|
|
289
|
+
```ts
|
|
290
|
+
import { verifyWebhookSignature } from '@ordinatio/scheduling';
|
|
291
|
+
|
|
292
|
+
const ok = verifyWebhookSignature({
|
|
293
|
+
secret, // the whsec_... value from step 1
|
|
294
|
+
header: String(request.headers['x-scheduling-signature'] ?? ''), // t=<seconds>,v1=<hex>
|
|
295
|
+
body: rawBody, // the exact text received, not re-serialized JSON
|
|
296
|
+
});
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
The header carries a timestamp and the check refuses anything more than 5 minutes old, so a captured delivery
|
|
300
|
+
cannot be replayed later. The same event can arrive more than once (a retry after a timeout the receiver did
|
|
301
|
+
answer), so act on `id` once. Each delivery also carries `x-scheduling-event` and `x-scheduling-delivery`.
|
|
302
|
+
|
|
303
|
+
**Safety.** Addresses must be `https` and public; `localhost`, private networks and cloud metadata addresses are
|
|
304
|
+
refused when the endpoint is added, and again at the moment of connecting. Pass `allowInsecureTargets: true` to
|
|
305
|
+
`createWebhookEndpoint` and `deliverDueWebhooks` only in local development. The secret is stored readable,
|
|
306
|
+
because signing needs it; protect database backups as you would any key. To rotate a secret, add a new endpoint
|
|
307
|
+
and remove the old one.
|
|
308
|
+
|
|
309
|
+
To also queue `reminder.sent`, call `processPendingNotifications(db, sender, { webhooks: true })`.
|
package/dist/index.d.mts
CHANGED
|
@@ -10,7 +10,7 @@ import { ErrorRegistry } from '@ordinatio/errors';
|
|
|
10
10
|
* interface (minus $transaction itself) so code inside transactions
|
|
11
11
|
* is fully typed without `as any` casts.
|
|
12
12
|
*/
|
|
13
|
-
type SchedulingDb = Pick<PrismaClient, 'schedulingCalendar' | 'availabilityRule' | 'appointmentType' | 'appointmentTypeCalendar' | 'appointmentCategory' | 'appointment' | 'scheduledNotification' | 'notificationTemplate' | 'servicePackage' | 'packagePurchase' | 'couponCode' | 'recurringSeries' | 'roundRobinState' | 'organization' | '$transaction' | '$executeRaw' | '$queryRaw'>;
|
|
13
|
+
type SchedulingDb = Pick<PrismaClient, 'schedulingCalendar' | 'availabilityRule' | 'appointmentType' | 'appointmentTypeCalendar' | 'appointmentCategory' | 'appointment' | 'scheduledNotification' | 'notificationTemplate' | 'servicePackage' | 'packagePurchase' | 'couponCode' | 'recurringSeries' | 'roundRobinState' | 'webhookEndpoint' | 'webhookDelivery' | 'webhookAttempt' | 'organization' | '$transaction' | '$executeRaw' | '$queryRaw'>;
|
|
14
14
|
/**
|
|
15
15
|
* Branded subtype of SchedulingDb for transaction clients produced by withTransaction().
|
|
16
16
|
* selectCalendarForBooking() requires this type to enforce that its RoundRobinState
|
|
@@ -1607,6 +1607,8 @@ declare function processPendingNotifications(db: SchedulingDb, sender: Notificat
|
|
|
1607
1607
|
workerId?: string;
|
|
1608
1608
|
staleThresholdMs?: number;
|
|
1609
1609
|
maxOverdueMs?: number;
|
|
1610
|
+
/** Queue a `reminder.sent` webhook for each reminder that was sent. Off by default; needs the webhook tables. */
|
|
1611
|
+
webhooks?: boolean;
|
|
1610
1612
|
}): Promise<{
|
|
1611
1613
|
sent: number;
|
|
1612
1614
|
failed: number;
|
|
@@ -1898,4 +1900,196 @@ declare function getTeamAvailableSlots(db: SchedulingDb, query: TeamAvailability
|
|
|
1898
1900
|
*/
|
|
1899
1901
|
declare function localToUTC(dateStr: string, timeStr: string, tz: string): Date;
|
|
1900
1902
|
|
|
1901
|
-
|
|
1903
|
+
declare const WEBHOOK_EVENT_TYPES: readonly ["appointment.booked", "appointment.rescheduled", "appointment.cancelled", "appointment.no_show", "reminder.sent"];
|
|
1904
|
+
type WebhookEventType = (typeof WEBHOOK_EVENT_TYPES)[number];
|
|
1905
|
+
/** Sent only by the "test" action; no endpoint subscribes to it. */
|
|
1906
|
+
declare const WEBHOOK_TEST_EVENT = "webhook.test";
|
|
1907
|
+
interface WebhookEnvelope {
|
|
1908
|
+
id: string;
|
|
1909
|
+
type: string;
|
|
1910
|
+
createdAt: string;
|
|
1911
|
+
organizationId: string;
|
|
1912
|
+
data: Record<string, unknown>;
|
|
1913
|
+
}
|
|
1914
|
+
|
|
1915
|
+
declare const SIGNATURE_HEADER = "x-scheduling-signature";
|
|
1916
|
+
declare function generateWebhookSecret(): string;
|
|
1917
|
+
/** The header value: `t=<unix seconds>,v1=<hex hmac-sha256 of "<t>.<body>">`. */
|
|
1918
|
+
declare function signWebhook(args: {
|
|
1919
|
+
secret: string;
|
|
1920
|
+
body: string;
|
|
1921
|
+
now: Date;
|
|
1922
|
+
}): string;
|
|
1923
|
+
/**
|
|
1924
|
+
* True only when the header was made with this secret for exactly this body, and its timestamp is within
|
|
1925
|
+
* `toleranceSeconds` of now (default 5 minutes, both directions). Never throws on a malformed header.
|
|
1926
|
+
*/
|
|
1927
|
+
declare function verifyWebhookSignature(args: {
|
|
1928
|
+
secret: string;
|
|
1929
|
+
header: string | null | undefined;
|
|
1930
|
+
body: string;
|
|
1931
|
+
toleranceSeconds?: number;
|
|
1932
|
+
now?: Date;
|
|
1933
|
+
}): boolean;
|
|
1934
|
+
|
|
1935
|
+
interface UrlCheckOptions {
|
|
1936
|
+
/** Allows http and addresses on this machine or a private network. For local development and tests only. */
|
|
1937
|
+
allowInsecureTargets?: boolean;
|
|
1938
|
+
}
|
|
1939
|
+
type UrlCheck = {
|
|
1940
|
+
ok: true;
|
|
1941
|
+
url: URL;
|
|
1942
|
+
} | {
|
|
1943
|
+
ok: false;
|
|
1944
|
+
reason: string;
|
|
1945
|
+
};
|
|
1946
|
+
/** True for loopback, private, link-local, carrier-grade NAT, multicast and unspecified addresses. */
|
|
1947
|
+
declare function isPrivateAddress(ip: string): boolean;
|
|
1948
|
+
declare function checkWebhookUrl(raw: string, options?: UrlCheckOptions): UrlCheck;
|
|
1949
|
+
|
|
1950
|
+
interface TransportRequest {
|
|
1951
|
+
url: URL;
|
|
1952
|
+
headers: Record<string, string>;
|
|
1953
|
+
body: string;
|
|
1954
|
+
timeoutMs: number;
|
|
1955
|
+
}
|
|
1956
|
+
/** The status the receiver answered with. Rejects on a network failure, a timeout or a blocked target. */
|
|
1957
|
+
type WebhookTransport = (request: TransportRequest) => Promise<{
|
|
1958
|
+
status: number;
|
|
1959
|
+
}>;
|
|
1960
|
+
declare class BlockedTargetError extends Error {
|
|
1961
|
+
constructor(hostname: string);
|
|
1962
|
+
}
|
|
1963
|
+
declare function createNodeTransport(options?: {
|
|
1964
|
+
allowInsecureTargets?: boolean;
|
|
1965
|
+
}): WebhookTransport;
|
|
1966
|
+
|
|
1967
|
+
declare const MAX_ENDPOINTS_PER_ORGANIZATION = 20;
|
|
1968
|
+
/** An endpoint as the outside world sees it. The secret is never part of it. */
|
|
1969
|
+
interface WebhookEndpointView {
|
|
1970
|
+
id: string;
|
|
1971
|
+
url: string;
|
|
1972
|
+
description: string | null;
|
|
1973
|
+
eventTypes: string[];
|
|
1974
|
+
isActive: boolean;
|
|
1975
|
+
createdAt: Date;
|
|
1976
|
+
}
|
|
1977
|
+
declare function createWebhookEndpoint(db: SchedulingDb, input: {
|
|
1978
|
+
organizationId: string;
|
|
1979
|
+
url: string;
|
|
1980
|
+
eventTypes: unknown;
|
|
1981
|
+
description?: string | null;
|
|
1982
|
+
}, options?: UrlCheckOptions): Promise<{
|
|
1983
|
+
endpoint: WebhookEndpointView;
|
|
1984
|
+
secret: string;
|
|
1985
|
+
}>;
|
|
1986
|
+
declare function listWebhookEndpoints(db: SchedulingDb, organizationId: string): Promise<WebhookEndpointView[]>;
|
|
1987
|
+
/** Removes the endpoint and, with it, its deliveries and their log. */
|
|
1988
|
+
declare function deleteWebhookEndpoint(db: SchedulingDb, organizationId: string, endpointId: string): Promise<void>;
|
|
1989
|
+
|
|
1990
|
+
/** What a receiver is told about an appointment. Payment details are left out on purpose. */
|
|
1991
|
+
declare function appointmentWebhookData(db: SchedulingDb, organizationId: string, appointmentId: string): Promise<Record<string, unknown>>;
|
|
1992
|
+
/** Queues the event for every active endpoint of the organization that subscribes to it. Returns how many were queued. */
|
|
1993
|
+
declare function enqueueWebhookEvent(db: SchedulingDb, input: {
|
|
1994
|
+
organizationId: string;
|
|
1995
|
+
type: string;
|
|
1996
|
+
data: Record<string, unknown>;
|
|
1997
|
+
eventId?: string;
|
|
1998
|
+
now?: Date;
|
|
1999
|
+
}): Promise<{
|
|
2000
|
+
queued: number;
|
|
2001
|
+
}>;
|
|
2002
|
+
/**
|
|
2003
|
+
* Queues an event for an appointment and never throws: the booking is already saved, and a webhook problem must
|
|
2004
|
+
* not undo or hide that. The failure is logged with a reference.
|
|
2005
|
+
*/
|
|
2006
|
+
declare function enqueueAppointmentWebhook(db: SchedulingDb, input: {
|
|
2007
|
+
organizationId: string;
|
|
2008
|
+
type: string;
|
|
2009
|
+
appointmentId: string;
|
|
2010
|
+
extra?: Record<string, unknown>;
|
|
2011
|
+
eventId?: string;
|
|
2012
|
+
}): Promise<void>;
|
|
2013
|
+
/** Queues `reminder.sent` for a reminder the engine just sent. The organization comes from the appointment's calendar. */
|
|
2014
|
+
declare function enqueueReminderSent(db: SchedulingDb, notification: {
|
|
2015
|
+
id: string;
|
|
2016
|
+
appointmentId: string;
|
|
2017
|
+
channel: string;
|
|
2018
|
+
trigger: string;
|
|
2019
|
+
}): Promise<void>;
|
|
2020
|
+
|
|
2021
|
+
/** Seconds to wait after the 1st, 2nd, ... failed try. The delivery goes to the dead-letter list after one more failure. */
|
|
2022
|
+
declare const DEFAULT_BACKOFF_SECONDS: number[];
|
|
2023
|
+
interface AttemptOptions {
|
|
2024
|
+
transport?: WebhookTransport;
|
|
2025
|
+
now?: () => Date;
|
|
2026
|
+
timeoutMs?: number;
|
|
2027
|
+
backoffSeconds?: number[];
|
|
2028
|
+
/** Tries before dead-letter. Default: one more than the back-off list is long (6). */
|
|
2029
|
+
maxAttempts?: number;
|
|
2030
|
+
allowInsecureTargets?: boolean;
|
|
2031
|
+
}
|
|
2032
|
+
|
|
2033
|
+
interface DeliverOptions extends AttemptOptions {
|
|
2034
|
+
/** How many deliveries one call picks up. Default 20. */
|
|
2035
|
+
batchSize?: number;
|
|
2036
|
+
/** How many are sent at the same moment. Default 5. */
|
|
2037
|
+
concurrency?: number;
|
|
2038
|
+
workerId?: string;
|
|
2039
|
+
/** A claim older than this is taken to belong to a crashed worker and is reclaimed. Default 5 minutes. */
|
|
2040
|
+
staleClaimMs?: number;
|
|
2041
|
+
}
|
|
2042
|
+
interface DeliverSummary {
|
|
2043
|
+
succeeded: number;
|
|
2044
|
+
retried: number;
|
|
2045
|
+
deadLettered: number;
|
|
2046
|
+
/** Deliveries another worker finished first. */
|
|
2047
|
+
lostClaim: number;
|
|
2048
|
+
}
|
|
2049
|
+
declare function deliverDueWebhooks(db: SchedulingDb, options?: DeliverOptions): Promise<DeliverSummary>;
|
|
2050
|
+
|
|
2051
|
+
interface TestSendResult {
|
|
2052
|
+
deliveryId: string;
|
|
2053
|
+
ok: boolean;
|
|
2054
|
+
statusCode: number | null;
|
|
2055
|
+
error: string | null;
|
|
2056
|
+
}
|
|
2057
|
+
declare function sendTestWebhook(db: SchedulingDb, input: {
|
|
2058
|
+
organizationId: string;
|
|
2059
|
+
endpointId: string;
|
|
2060
|
+
}, options?: AttemptOptions): Promise<TestSendResult>;
|
|
2061
|
+
|
|
2062
|
+
interface WebhookDeliveryView {
|
|
2063
|
+
id: string;
|
|
2064
|
+
endpointId: string;
|
|
2065
|
+
eventId: string;
|
|
2066
|
+
eventType: string;
|
|
2067
|
+
status: string;
|
|
2068
|
+
attempts: number;
|
|
2069
|
+
nextAttemptAt: Date;
|
|
2070
|
+
lastStatusCode: number | null;
|
|
2071
|
+
lastError: string | null;
|
|
2072
|
+
deliveredAt: Date | null;
|
|
2073
|
+
createdAt: Date;
|
|
2074
|
+
attemptLog: Array<{
|
|
2075
|
+
attemptNumber: number;
|
|
2076
|
+
statusCode: number | null;
|
|
2077
|
+
error: string | null;
|
|
2078
|
+
durationMs: number;
|
|
2079
|
+
createdAt: Date;
|
|
2080
|
+
}>;
|
|
2081
|
+
}
|
|
2082
|
+
declare function listWebhookDeliveries(db: SchedulingDb, input: {
|
|
2083
|
+
organizationId: string;
|
|
2084
|
+
endpointId?: string;
|
|
2085
|
+
status?: string;
|
|
2086
|
+
limit?: number;
|
|
2087
|
+
offset?: number;
|
|
2088
|
+
}): Promise<{
|
|
2089
|
+
deliveries: WebhookDeliveryView[];
|
|
2090
|
+
total: number;
|
|
2091
|
+
}>;
|
|
2092
|
+
/** Puts a dead-lettered delivery back in the queue with a fresh set of tries. The log of earlier tries stays. */
|
|
2093
|
+
declare function retryWebhookDelivery(db: SchedulingDb, organizationId: string, deliveryId: string, now?: Date): Promise<void>;
|
|
2094
|
+
|
|
2095
|
+
export { type AddTimeBlockInput, type AppointmentDashboardData, type AppointmentDashboardItem, type AppointmentDashboardStats, type AppointmentLocationType, type AppointmentStatus, type AppointmentWithDetails, type AssignmentStrategy, type AttemptOptions, type AuthAdapter, type AuthContext, type AvailabilityQuery, type AvailabilityResult, type AvailabilityRuleInput, BlockedTargetError, type BookAppointmentInput, type BookingAnalytics, type CalendarEvent, type CalendarEventRef, type CalendarSyncAdapter, type CalendarType, type CancelInput, type CancelRecurringScope, type CancellationFeeConfig, type CancellationFeeResult, type ChargeRequest, type ChargeResult, type Clock, type CreateAppointmentTypeInput, type CreateCalendarInput, DEFAULT_BACKOFF_SECONDS, type DashboardQuery, type DayAppointment, type DeliverOptions, type DeliverSummary, type GroupCapacityResult, type GroupSession, type GroupSessionAttendee, type InMemoryClockControl, type InMemoryOptions, type InMemoryRecords, type IntakeFormField, MAX_ENDPOINTS_PER_ORGANIZATION, type MarkNoShowInput, type NotificationAdapter, type NotificationChannel, type NotificationContext, type NotificationSender, type NotificationTrigger, type OrgCancellationPolicy, type OutboundMessage, type PaymentAdapter, type PaymentCheck, type PaymentContractOptions, type PaymentProcessor, type PaymentResult, RECURRING_MAX_OCCURRENCES, type RecurringFrequency, type RefundOptions, type RefundResult, type RescheduleInput, type RetryConfig, SCHEDULING_ERRORS, SIGNATURE_HEADER, type SchedulingAdapters, type SchedulingCallbacks, type SchedulingDb, SchedulingNotFoundError, SchedulingValidationError, type SendResult, type TeamAvailabilityQuery, type TeamAvailabilityResult, type TestSendResult, type TimeSlot, type TransportRequest, USER_DAY_LIMIT, type UpdateCalendarInput, type UrlCheckOptions, type UserDayInput, type UserDayResult, WEBHOOK_EVENT_TYPES, WEBHOOK_TEST_EVENT, type WebhookDeliveryView, type WebhookEndpointView, type WebhookEnvelope, type WebhookEventType, type WebhookTransport, adaptersToCallbacks, addDateOverride, addTimeBlock, appointmentWebhookData, archiveCalendar, bookAppointment, buildJitsiUrl, buildNotificationContext, buildOccurrenceStartTime, buildRecurringSlots, calculateCancellationFee, cancelAppointment, cancelPendingNotifications, checkAuthContract, checkCalendarSyncContract, checkClockContract, checkNotificationContract, checkPaymentContract, checkWebhookUrl, createAppointmentType, createCalendar, createInMemoryAdapters, createNodeTransport, createNotificationTemplate, createWebhookEndpoint, deleteCalendar, deleteNotificationTemplate, deleteWebhookEndpoint, deliverDueWebhooks, enqueueAppointmentWebhook, enqueueReminderSent, enqueueWebhookEvent, generateOccurrenceDates, generateWebhookSecret, getAppointment, getAppointmentDashboard, getAppointmentType, getAppointmentsForRange, getAvailableDates, getAvailableSlots, getBookingAnalytics, getCalendar, getGroupCapacity, getGroupSessions, getNotificationTemplate, getTeamAvailableSlots, getUserDayAppointments, isPrivateAddress, isSlotAvailable, isVirtualMeeting, listAppointmentTypes, listAppointments, listAvailabilityRules, listCalendars, listNotificationTemplates, listWebhookDeliveries, listWebhookEndpoints, localToUTC, markNoShow, parseTimeLocal, processPendingNotifications, queueImmediateNotification, queueStaffNotification, removeDateOverride, renderTemplate, rescheduleAppointment, resolveLocation, retryWebhookDelivery, schedError, scheduleNotifications, selectCalendarForBooking, sendTestWebhook, setWeeklyAvailability, signWebhook, updateAppointmentType, updateCalendar, updateNotificationTemplate, verifyWebhookSignature, withCalendarVisibility };
|
package/dist/index.d.ts
CHANGED
|
@@ -10,7 +10,7 @@ import { ErrorRegistry } from '@ordinatio/errors';
|
|
|
10
10
|
* interface (minus $transaction itself) so code inside transactions
|
|
11
11
|
* is fully typed without `as any` casts.
|
|
12
12
|
*/
|
|
13
|
-
type SchedulingDb = Pick<PrismaClient, 'schedulingCalendar' | 'availabilityRule' | 'appointmentType' | 'appointmentTypeCalendar' | 'appointmentCategory' | 'appointment' | 'scheduledNotification' | 'notificationTemplate' | 'servicePackage' | 'packagePurchase' | 'couponCode' | 'recurringSeries' | 'roundRobinState' | 'organization' | '$transaction' | '$executeRaw' | '$queryRaw'>;
|
|
13
|
+
type SchedulingDb = Pick<PrismaClient, 'schedulingCalendar' | 'availabilityRule' | 'appointmentType' | 'appointmentTypeCalendar' | 'appointmentCategory' | 'appointment' | 'scheduledNotification' | 'notificationTemplate' | 'servicePackage' | 'packagePurchase' | 'couponCode' | 'recurringSeries' | 'roundRobinState' | 'webhookEndpoint' | 'webhookDelivery' | 'webhookAttempt' | 'organization' | '$transaction' | '$executeRaw' | '$queryRaw'>;
|
|
14
14
|
/**
|
|
15
15
|
* Branded subtype of SchedulingDb for transaction clients produced by withTransaction().
|
|
16
16
|
* selectCalendarForBooking() requires this type to enforce that its RoundRobinState
|
|
@@ -1607,6 +1607,8 @@ declare function processPendingNotifications(db: SchedulingDb, sender: Notificat
|
|
|
1607
1607
|
workerId?: string;
|
|
1608
1608
|
staleThresholdMs?: number;
|
|
1609
1609
|
maxOverdueMs?: number;
|
|
1610
|
+
/** Queue a `reminder.sent` webhook for each reminder that was sent. Off by default; needs the webhook tables. */
|
|
1611
|
+
webhooks?: boolean;
|
|
1610
1612
|
}): Promise<{
|
|
1611
1613
|
sent: number;
|
|
1612
1614
|
failed: number;
|
|
@@ -1898,4 +1900,196 @@ declare function getTeamAvailableSlots(db: SchedulingDb, query: TeamAvailability
|
|
|
1898
1900
|
*/
|
|
1899
1901
|
declare function localToUTC(dateStr: string, timeStr: string, tz: string): Date;
|
|
1900
1902
|
|
|
1901
|
-
|
|
1903
|
+
declare const WEBHOOK_EVENT_TYPES: readonly ["appointment.booked", "appointment.rescheduled", "appointment.cancelled", "appointment.no_show", "reminder.sent"];
|
|
1904
|
+
type WebhookEventType = (typeof WEBHOOK_EVENT_TYPES)[number];
|
|
1905
|
+
/** Sent only by the "test" action; no endpoint subscribes to it. */
|
|
1906
|
+
declare const WEBHOOK_TEST_EVENT = "webhook.test";
|
|
1907
|
+
interface WebhookEnvelope {
|
|
1908
|
+
id: string;
|
|
1909
|
+
type: string;
|
|
1910
|
+
createdAt: string;
|
|
1911
|
+
organizationId: string;
|
|
1912
|
+
data: Record<string, unknown>;
|
|
1913
|
+
}
|
|
1914
|
+
|
|
1915
|
+
declare const SIGNATURE_HEADER = "x-scheduling-signature";
|
|
1916
|
+
declare function generateWebhookSecret(): string;
|
|
1917
|
+
/** The header value: `t=<unix seconds>,v1=<hex hmac-sha256 of "<t>.<body>">`. */
|
|
1918
|
+
declare function signWebhook(args: {
|
|
1919
|
+
secret: string;
|
|
1920
|
+
body: string;
|
|
1921
|
+
now: Date;
|
|
1922
|
+
}): string;
|
|
1923
|
+
/**
|
|
1924
|
+
* True only when the header was made with this secret for exactly this body, and its timestamp is within
|
|
1925
|
+
* `toleranceSeconds` of now (default 5 minutes, both directions). Never throws on a malformed header.
|
|
1926
|
+
*/
|
|
1927
|
+
declare function verifyWebhookSignature(args: {
|
|
1928
|
+
secret: string;
|
|
1929
|
+
header: string | null | undefined;
|
|
1930
|
+
body: string;
|
|
1931
|
+
toleranceSeconds?: number;
|
|
1932
|
+
now?: Date;
|
|
1933
|
+
}): boolean;
|
|
1934
|
+
|
|
1935
|
+
interface UrlCheckOptions {
|
|
1936
|
+
/** Allows http and addresses on this machine or a private network. For local development and tests only. */
|
|
1937
|
+
allowInsecureTargets?: boolean;
|
|
1938
|
+
}
|
|
1939
|
+
type UrlCheck = {
|
|
1940
|
+
ok: true;
|
|
1941
|
+
url: URL;
|
|
1942
|
+
} | {
|
|
1943
|
+
ok: false;
|
|
1944
|
+
reason: string;
|
|
1945
|
+
};
|
|
1946
|
+
/** True for loopback, private, link-local, carrier-grade NAT, multicast and unspecified addresses. */
|
|
1947
|
+
declare function isPrivateAddress(ip: string): boolean;
|
|
1948
|
+
declare function checkWebhookUrl(raw: string, options?: UrlCheckOptions): UrlCheck;
|
|
1949
|
+
|
|
1950
|
+
interface TransportRequest {
|
|
1951
|
+
url: URL;
|
|
1952
|
+
headers: Record<string, string>;
|
|
1953
|
+
body: string;
|
|
1954
|
+
timeoutMs: number;
|
|
1955
|
+
}
|
|
1956
|
+
/** The status the receiver answered with. Rejects on a network failure, a timeout or a blocked target. */
|
|
1957
|
+
type WebhookTransport = (request: TransportRequest) => Promise<{
|
|
1958
|
+
status: number;
|
|
1959
|
+
}>;
|
|
1960
|
+
declare class BlockedTargetError extends Error {
|
|
1961
|
+
constructor(hostname: string);
|
|
1962
|
+
}
|
|
1963
|
+
declare function createNodeTransport(options?: {
|
|
1964
|
+
allowInsecureTargets?: boolean;
|
|
1965
|
+
}): WebhookTransport;
|
|
1966
|
+
|
|
1967
|
+
declare const MAX_ENDPOINTS_PER_ORGANIZATION = 20;
|
|
1968
|
+
/** An endpoint as the outside world sees it. The secret is never part of it. */
|
|
1969
|
+
interface WebhookEndpointView {
|
|
1970
|
+
id: string;
|
|
1971
|
+
url: string;
|
|
1972
|
+
description: string | null;
|
|
1973
|
+
eventTypes: string[];
|
|
1974
|
+
isActive: boolean;
|
|
1975
|
+
createdAt: Date;
|
|
1976
|
+
}
|
|
1977
|
+
declare function createWebhookEndpoint(db: SchedulingDb, input: {
|
|
1978
|
+
organizationId: string;
|
|
1979
|
+
url: string;
|
|
1980
|
+
eventTypes: unknown;
|
|
1981
|
+
description?: string | null;
|
|
1982
|
+
}, options?: UrlCheckOptions): Promise<{
|
|
1983
|
+
endpoint: WebhookEndpointView;
|
|
1984
|
+
secret: string;
|
|
1985
|
+
}>;
|
|
1986
|
+
declare function listWebhookEndpoints(db: SchedulingDb, organizationId: string): Promise<WebhookEndpointView[]>;
|
|
1987
|
+
/** Removes the endpoint and, with it, its deliveries and their log. */
|
|
1988
|
+
declare function deleteWebhookEndpoint(db: SchedulingDb, organizationId: string, endpointId: string): Promise<void>;
|
|
1989
|
+
|
|
1990
|
+
/** What a receiver is told about an appointment. Payment details are left out on purpose. */
|
|
1991
|
+
declare function appointmentWebhookData(db: SchedulingDb, organizationId: string, appointmentId: string): Promise<Record<string, unknown>>;
|
|
1992
|
+
/** Queues the event for every active endpoint of the organization that subscribes to it. Returns how many were queued. */
|
|
1993
|
+
declare function enqueueWebhookEvent(db: SchedulingDb, input: {
|
|
1994
|
+
organizationId: string;
|
|
1995
|
+
type: string;
|
|
1996
|
+
data: Record<string, unknown>;
|
|
1997
|
+
eventId?: string;
|
|
1998
|
+
now?: Date;
|
|
1999
|
+
}): Promise<{
|
|
2000
|
+
queued: number;
|
|
2001
|
+
}>;
|
|
2002
|
+
/**
|
|
2003
|
+
* Queues an event for an appointment and never throws: the booking is already saved, and a webhook problem must
|
|
2004
|
+
* not undo or hide that. The failure is logged with a reference.
|
|
2005
|
+
*/
|
|
2006
|
+
declare function enqueueAppointmentWebhook(db: SchedulingDb, input: {
|
|
2007
|
+
organizationId: string;
|
|
2008
|
+
type: string;
|
|
2009
|
+
appointmentId: string;
|
|
2010
|
+
extra?: Record<string, unknown>;
|
|
2011
|
+
eventId?: string;
|
|
2012
|
+
}): Promise<void>;
|
|
2013
|
+
/** Queues `reminder.sent` for a reminder the engine just sent. The organization comes from the appointment's calendar. */
|
|
2014
|
+
declare function enqueueReminderSent(db: SchedulingDb, notification: {
|
|
2015
|
+
id: string;
|
|
2016
|
+
appointmentId: string;
|
|
2017
|
+
channel: string;
|
|
2018
|
+
trigger: string;
|
|
2019
|
+
}): Promise<void>;
|
|
2020
|
+
|
|
2021
|
+
/** Seconds to wait after the 1st, 2nd, ... failed try. The delivery goes to the dead-letter list after one more failure. */
|
|
2022
|
+
declare const DEFAULT_BACKOFF_SECONDS: number[];
|
|
2023
|
+
interface AttemptOptions {
|
|
2024
|
+
transport?: WebhookTransport;
|
|
2025
|
+
now?: () => Date;
|
|
2026
|
+
timeoutMs?: number;
|
|
2027
|
+
backoffSeconds?: number[];
|
|
2028
|
+
/** Tries before dead-letter. Default: one more than the back-off list is long (6). */
|
|
2029
|
+
maxAttempts?: number;
|
|
2030
|
+
allowInsecureTargets?: boolean;
|
|
2031
|
+
}
|
|
2032
|
+
|
|
2033
|
+
interface DeliverOptions extends AttemptOptions {
|
|
2034
|
+
/** How many deliveries one call picks up. Default 20. */
|
|
2035
|
+
batchSize?: number;
|
|
2036
|
+
/** How many are sent at the same moment. Default 5. */
|
|
2037
|
+
concurrency?: number;
|
|
2038
|
+
workerId?: string;
|
|
2039
|
+
/** A claim older than this is taken to belong to a crashed worker and is reclaimed. Default 5 minutes. */
|
|
2040
|
+
staleClaimMs?: number;
|
|
2041
|
+
}
|
|
2042
|
+
interface DeliverSummary {
|
|
2043
|
+
succeeded: number;
|
|
2044
|
+
retried: number;
|
|
2045
|
+
deadLettered: number;
|
|
2046
|
+
/** Deliveries another worker finished first. */
|
|
2047
|
+
lostClaim: number;
|
|
2048
|
+
}
|
|
2049
|
+
declare function deliverDueWebhooks(db: SchedulingDb, options?: DeliverOptions): Promise<DeliverSummary>;
|
|
2050
|
+
|
|
2051
|
+
interface TestSendResult {
|
|
2052
|
+
deliveryId: string;
|
|
2053
|
+
ok: boolean;
|
|
2054
|
+
statusCode: number | null;
|
|
2055
|
+
error: string | null;
|
|
2056
|
+
}
|
|
2057
|
+
declare function sendTestWebhook(db: SchedulingDb, input: {
|
|
2058
|
+
organizationId: string;
|
|
2059
|
+
endpointId: string;
|
|
2060
|
+
}, options?: AttemptOptions): Promise<TestSendResult>;
|
|
2061
|
+
|
|
2062
|
+
interface WebhookDeliveryView {
|
|
2063
|
+
id: string;
|
|
2064
|
+
endpointId: string;
|
|
2065
|
+
eventId: string;
|
|
2066
|
+
eventType: string;
|
|
2067
|
+
status: string;
|
|
2068
|
+
attempts: number;
|
|
2069
|
+
nextAttemptAt: Date;
|
|
2070
|
+
lastStatusCode: number | null;
|
|
2071
|
+
lastError: string | null;
|
|
2072
|
+
deliveredAt: Date | null;
|
|
2073
|
+
createdAt: Date;
|
|
2074
|
+
attemptLog: Array<{
|
|
2075
|
+
attemptNumber: number;
|
|
2076
|
+
statusCode: number | null;
|
|
2077
|
+
error: string | null;
|
|
2078
|
+
durationMs: number;
|
|
2079
|
+
createdAt: Date;
|
|
2080
|
+
}>;
|
|
2081
|
+
}
|
|
2082
|
+
declare function listWebhookDeliveries(db: SchedulingDb, input: {
|
|
2083
|
+
organizationId: string;
|
|
2084
|
+
endpointId?: string;
|
|
2085
|
+
status?: string;
|
|
2086
|
+
limit?: number;
|
|
2087
|
+
offset?: number;
|
|
2088
|
+
}): Promise<{
|
|
2089
|
+
deliveries: WebhookDeliveryView[];
|
|
2090
|
+
total: number;
|
|
2091
|
+
}>;
|
|
2092
|
+
/** Puts a dead-lettered delivery back in the queue with a fresh set of tries. The log of earlier tries stays. */
|
|
2093
|
+
declare function retryWebhookDelivery(db: SchedulingDb, organizationId: string, deliveryId: string, now?: Date): Promise<void>;
|
|
2094
|
+
|
|
2095
|
+
export { type AddTimeBlockInput, type AppointmentDashboardData, type AppointmentDashboardItem, type AppointmentDashboardStats, type AppointmentLocationType, type AppointmentStatus, type AppointmentWithDetails, type AssignmentStrategy, type AttemptOptions, type AuthAdapter, type AuthContext, type AvailabilityQuery, type AvailabilityResult, type AvailabilityRuleInput, BlockedTargetError, type BookAppointmentInput, type BookingAnalytics, type CalendarEvent, type CalendarEventRef, type CalendarSyncAdapter, type CalendarType, type CancelInput, type CancelRecurringScope, type CancellationFeeConfig, type CancellationFeeResult, type ChargeRequest, type ChargeResult, type Clock, type CreateAppointmentTypeInput, type CreateCalendarInput, DEFAULT_BACKOFF_SECONDS, type DashboardQuery, type DayAppointment, type DeliverOptions, type DeliverSummary, type GroupCapacityResult, type GroupSession, type GroupSessionAttendee, type InMemoryClockControl, type InMemoryOptions, type InMemoryRecords, type IntakeFormField, MAX_ENDPOINTS_PER_ORGANIZATION, type MarkNoShowInput, type NotificationAdapter, type NotificationChannel, type NotificationContext, type NotificationSender, type NotificationTrigger, type OrgCancellationPolicy, type OutboundMessage, type PaymentAdapter, type PaymentCheck, type PaymentContractOptions, type PaymentProcessor, type PaymentResult, RECURRING_MAX_OCCURRENCES, type RecurringFrequency, type RefundOptions, type RefundResult, type RescheduleInput, type RetryConfig, SCHEDULING_ERRORS, SIGNATURE_HEADER, type SchedulingAdapters, type SchedulingCallbacks, type SchedulingDb, SchedulingNotFoundError, SchedulingValidationError, type SendResult, type TeamAvailabilityQuery, type TeamAvailabilityResult, type TestSendResult, type TimeSlot, type TransportRequest, USER_DAY_LIMIT, type UpdateCalendarInput, type UrlCheckOptions, type UserDayInput, type UserDayResult, WEBHOOK_EVENT_TYPES, WEBHOOK_TEST_EVENT, type WebhookDeliveryView, type WebhookEndpointView, type WebhookEnvelope, type WebhookEventType, type WebhookTransport, adaptersToCallbacks, addDateOverride, addTimeBlock, appointmentWebhookData, archiveCalendar, bookAppointment, buildJitsiUrl, buildNotificationContext, buildOccurrenceStartTime, buildRecurringSlots, calculateCancellationFee, cancelAppointment, cancelPendingNotifications, checkAuthContract, checkCalendarSyncContract, checkClockContract, checkNotificationContract, checkPaymentContract, checkWebhookUrl, createAppointmentType, createCalendar, createInMemoryAdapters, createNodeTransport, createNotificationTemplate, createWebhookEndpoint, deleteCalendar, deleteNotificationTemplate, deleteWebhookEndpoint, deliverDueWebhooks, enqueueAppointmentWebhook, enqueueReminderSent, enqueueWebhookEvent, generateOccurrenceDates, generateWebhookSecret, getAppointment, getAppointmentDashboard, getAppointmentType, getAppointmentsForRange, getAvailableDates, getAvailableSlots, getBookingAnalytics, getCalendar, getGroupCapacity, getGroupSessions, getNotificationTemplate, getTeamAvailableSlots, getUserDayAppointments, isPrivateAddress, isSlotAvailable, isVirtualMeeting, listAppointmentTypes, listAppointments, listAvailabilityRules, listCalendars, listNotificationTemplates, listWebhookDeliveries, listWebhookEndpoints, localToUTC, markNoShow, parseTimeLocal, processPendingNotifications, queueImmediateNotification, queueStaffNotification, removeDateOverride, renderTemplate, rescheduleAppointment, resolveLocation, retryWebhookDelivery, schedError, scheduleNotifications, selectCalendarForBooking, sendTestWebhook, setWeeklyAvailability, signWebhook, updateAppointmentType, updateCalendar, updateNotificationTemplate, verifyWebhookSignature, withCalendarVisibility };
|