@ordinatio/scheduling-api 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts DELETED
@@ -1,597 +0,0 @@
1
- import { S as SchedulingHost, R as Route, H as HttpMethod, a as RateLimitTier, b as SchedulingCache, P as PublicBookingResolver, c as PublicOrganizationResolver, A as AvailabilityCache, B as BalancePaymentControl, d as SendingDomainCheck, e as SendingDomainRecord, f as SendingDomainRecords, D as DnsResolver, g as StaffResolver, h as StaffContext } from './routes-h90wEQuD.js';
2
- export { i as ActivityEntry, j as ActivityLog, k as ApiKeySettings, l as AppointmentEventSink, m as BookingClientResolver, n as BookingPolicy, o as BrandSettings, C as CacheOptions, p as CalendarConnectOutcome, q as CalendarConnector, r as CalendarConnectors, s as CalendarVisibility, I as InternalAccess, N as NoShowPolicy, t as PrivacySettings, u as PublicBookingContext, v as PublicBookingKind, w as PublicOrganization, x as RecordCheck, y as RecordStatus, z as ResolvedHost, E as RouteContext, F as RouteHandler, G as RoutingFormSettings, J as StaffDirectory, W as WaitlistSettings, K as WebhookSettings, L as WorkerCommands, M as checkSendingDomain, O as normalizeSendingDomain } from './routes-h90wEQuD.js';
3
- import { SchedulingDb, PaymentAdapter, NotificationAdapter, AppointmentStatus, CalendarSyncAdapter, CalendarEventRef, CalendarEvent } from '@ordinatio/scheduling';
4
- export { ApiKeySchema, BookingPageConfig, BookingPageConfigSchema, BookingPageTheme, BookingPageThemeSchema, BrandSchema, CancelRecurringScopeSchema, CancelRecurringSeriesInput, CancelRecurringSeriesSchema, CreateAppointmentCategoryInput, CreateAppointmentCategorySchema, CreateAppointmentTypeInput, CreateAppointmentTypeSchema, CreateAvailabilityRuleInput, CreateAvailabilityRuleSchema, CreateCalendarInput, CreateCalendarSchema, CreateCouponCodeInput, CreateCouponCodeSchema, CreateNotificationTemplateInput, CreateNotificationTemplateSchema, CreatePackagePurchaseInput, CreatePackagePurchaseSchema, CreateRecurringSeriesInput, CreateRecurringSeriesSchema, CreateRoutingFormInput, CreateRoutingFormSchema, CreateServicePackageInput, CreateServicePackageSchema, CreateWebhookEndpointInput, CreateWebhookEndpointSchema, DEFAULT_CANCELLATION_POLICY, GiftCertificateCheckSchema, GiftCertificateRestoreSchema, GiftCertificateSchema, IntakeFormFieldSchema, NoShowPrevention, NoShowPreventionAction, NoShowPreventionActionSchema, NotificationChannelSchema, NotificationTriggerSchema, OrgCancellationPolicy, OrgCancellationPolicySchema, PrivacyEraseSchema, PrivacySubjectSchema, RecurringFrequencySchema, RouteClientSchema, SLOT_GRANULARITY_DEFAULT, SLOT_GRANULARITY_OPTIONS, SlotGranularityMinutes, TestRoutingFormSchema, TextSettingsSchema, UpdateAppointmentCategoryInput, UpdateAppointmentCategorySchema, UpdateAppointmentTypeInput, UpdateAppointmentTypeSchema, UpdateBookingPageInput, UpdateBookingPageSchema, UpdateCalendarInput, UpdateCalendarSchema, UpdateCouponCodeInput, UpdateCouponCodeSchema, UpdateNotificationTemplateInput, UpdateNotificationTemplateSchema, UpdatePackagePurchaseInput, UpdatePackagePurchaseSchema, UpdateRoutingFormInput, UpdateRoutingFormSchema, UpdateServicePackageInput, UpdateServicePackageSchema } from './schemas/index.js';
5
- import { IncomingMessage, ServerResponse } from 'node:http';
6
- import 'zod';
7
-
8
- interface SchedulingApiConfig {
9
- host: SchedulingHost;
10
- /** Where the API is mounted. Default: /api/scheduling. */
11
- basePath?: string;
12
- /** Replaces the built-in route list. Meant for tests. */
13
- routes?: Route[];
14
- }
15
- /** What Next.js passes as the second argument of a route file's function. */
16
- interface NextStyleContext {
17
- params?: Promise<Record<string, string>> | Record<string, string>;
18
- }
19
- declare function createSchedulingApi(config: SchedulingApiConfig): {
20
- routes: Route[];
21
- handle: (request: Request) => Promise<Response>;
22
- handler: (method: HttpMethod, path: string) => (request: Request, context?: NextStyleContext) => Promise<Response>;
23
- };
24
- type SchedulingApi = ReturnType<typeof createSchedulingApi>;
25
-
26
- declare function createMemoryRateLimiter(options?: {
27
- now?: () => number;
28
- maxKeys?: number;
29
- }): ((key: string, tier: RateLimitTier) => Promise<Response | null>) & {
30
- readonly size: number;
31
- };
32
-
33
- declare function defaultCorsHeaders(): Record<string, string>;
34
-
35
- declare function createMemoryCache(options?: {
36
- now?: () => number;
37
- maxEntries?: number;
38
- }): SchedulingCache & {
39
- readonly size: number;
40
- };
41
-
42
- declare function createSingleOrganizationResolver(publicDb: () => Promise<SchedulingDb>): PublicBookingResolver;
43
-
44
- declare function createSingleOrganizationDirectory(publicDb: () => Promise<SchedulingDb>): PublicOrganizationResolver;
45
-
46
- declare function createMemoryAvailabilityCache(options?: {
47
- now?: () => number;
48
- maxEntries?: number;
49
- }): AvailabilityCache & {
50
- readonly size: number;
51
- };
52
-
53
- /** The string `code` of a caught value, such as SCHED_305, or undefined. */
54
- declare function getErrorCode(error: unknown): string | undefined;
55
- /** The timestamped diagnostic `ref` of a caught value, or undefined. */
56
- declare function getErrorRef(error: unknown): string | undefined;
57
- /** The fields of an error the engine made with schedError: a SCHED_ code and the HTTP status it maps to. */
58
- interface SchedulingServiceError {
59
- readonly code: string;
60
- readonly httpStatus: number;
61
- readonly description: string;
62
- readonly message: string;
63
- }
64
- /** True when the value carries both a string `code` and a numeric `httpStatus`, as every engine error does. */
65
- declare function isSchedulingServiceError(error: unknown): error is SchedulingServiceError;
66
- /** The message of a caught value, or `fallback` when it has none. */
67
- declare function getErrorMessage(error: unknown, fallback: string): string;
68
-
69
- interface Pagination {
70
- limit: number;
71
- offset: number;
72
- }
73
- /**
74
- * Missing, non-numeric, zero or negative values fall back to their defaults instead of rejecting the request,
75
- * because paging is a convenience and not required input. `limit` is capped at `maxLimit`, so nobody can ask for a
76
- * whole unbounded table. `defaultLimit` is higher for lists that feed a dropdown, which expects every row with no
77
- * parameters at all.
78
- */
79
- declare function parsePagination(request: Request, maxLimit?: number, defaultLimit?: number): Pagination;
80
-
81
- declare function createNoPaymentAdapter(): PaymentAdapter;
82
- /** The same fail-closed default for cancelling and reading a payment: both reject, so nothing is assumed canceled. */
83
- declare function createNoBalancePaymentControl(): BalancePaymentControl;
84
-
85
- declare class UnverifiedPaymentError extends Error {
86
- readonly paymentId: string;
87
- readonly cause: unknown;
88
- constructor(paymentId: string, cause: unknown);
89
- }
90
-
91
- /** The slice of the Stripe client this adapter uses, so tests can supply a fake. */
92
- interface StripeLike {
93
- paymentIntents: {
94
- create(params: {
95
- amount: number;
96
- currency: string;
97
- metadata?: Record<string, string>;
98
- }, options?: {
99
- idempotencyKey?: string;
100
- }): Promise<StripeIntent>;
101
- retrieve(id: string, params?: {
102
- expand?: string[];
103
- }): Promise<StripeIntent>;
104
- };
105
- refunds: {
106
- create(params: {
107
- payment_intent: string;
108
- amount?: number;
109
- }, options?: {
110
- idempotencyKey?: string;
111
- }): Promise<{
112
- id: string;
113
- amount: number;
114
- status: string | null;
115
- currency?: string;
116
- }>;
117
- };
118
- }
119
- interface StripeIntent {
120
- id: string;
121
- amount: number;
122
- currency: string;
123
- status: string;
124
- client_secret?: string | null;
125
- metadata?: Record<string, string> | null;
126
- latest_charge?: string | {
127
- amount_refunded?: number;
128
- } | null;
129
- }
130
- declare function isSupportedCurrency(currency: string | undefined): boolean;
131
- declare function createStripePaymentAdapter(client: StripeLike): PaymentAdapter;
132
-
133
- /** Returns the key when it is a Stripe test-mode secret key. A live key must never reach a script that creates and refunds payments. */
134
- declare function assertStripeTestKey(raw: string | undefined): string;
135
-
136
- interface SendingDomainVerifierConfig {
137
- /**
138
- * The records your mail provider asks for. Their values are provider-specific, so the host lists them. Records that are
139
- * the same for every domain only prove the provider was set up at the domain, not who is claiming it: when your provider
140
- * issues a token per domain or organization, pass a function that returns that domain's records.
141
- */
142
- records: SendingDomainRecords;
143
- resolver: DnsResolver;
144
- }
145
- interface SendingDomainVerifier {
146
- /** Pass to `saveBrand`: true only when every required record is published. */
147
- isSendingDomainVerified(domain: string): Promise<boolean>;
148
- /** The same check with a status and a plain sentence for each record. */
149
- check(domain: string): Promise<SendingDomainCheck>;
150
- /** What a business must add at its domain host, with the full name for each record. Empty for something that is not a domain. */
151
- instructions(domain: string): Array<{
152
- record: SendingDomainRecord;
153
- host: string;
154
- }>;
155
- }
156
- declare function createSendingDomainVerifier(config: SendingDomainVerifierConfig): SendingDomainVerifier;
157
-
158
- /**
159
- * Thrown when a provider did not confirm the message. `retryable` is true when trying again may work.
160
- * `outcomeUnknown` is true when the text may already have been sent (timeout, network failure, server error),
161
- * so a retry can duplicate it.
162
- */
163
- declare class SmsSendError extends Error {
164
- readonly retryable: boolean;
165
- readonly outcomeUnknown: boolean;
166
- readonly status?: number | undefined;
167
- readonly code?: string | undefined;
168
- constructor(message: string, retryable: boolean, outcomeUnknown: boolean, status?: number | undefined, code?: string | undefined);
169
- }
170
- /**
171
- * Returns the number in international format, or null when it cannot be one. Ten digits are read as a US
172
- * number; anything else must already start with a plus and country code.
173
- */
174
- declare function normalizePhoneNumber(raw: string): string | null;
175
- /** What a provider's webhook means, in the same words for every provider. */
176
- type SmsInboundEvent = {
177
- type: 'reply';
178
- id: string;
179
- from: string;
180
- to: string;
181
- text: string;
182
- } | {
183
- type: 'opt-out';
184
- id: string;
185
- from: string;
186
- to: string;
187
- text: string;
188
- } | {
189
- type: 'opt-in';
190
- id: string;
191
- from: string;
192
- to: string;
193
- text: string;
194
- } | {
195
- type: 'delivery';
196
- id: string;
197
- status: 'delivered' | 'failed';
198
- to: string;
199
- errorCode?: string;
200
- } | {
201
- type: 'ignored';
202
- eventType: string;
203
- };
204
- type SmsWebhookResult = {
205
- ok: true;
206
- event: SmsInboundEvent;
207
- } | {
208
- ok: false;
209
- status: 400 | 401;
210
- reason: string;
211
- };
212
- /** Plain header record (Node, Express) or a web `Headers` object (Fetch-style routes). */
213
- type WebhookHeaders = Record<string, string | string[] | undefined> | {
214
- get(name: string): string | null;
215
- };
216
- /** A message that is only a stop or start word counts as an opt-out or opt-in; anything else is a reply. */
217
- declare function classifyReply(text: string): 'reply' | 'opt-out' | 'opt-in';
218
-
219
- interface TelnyxSmsConfig {
220
- apiKey: string;
221
- /** The sending number in international format, such as +13135550100. */
222
- from?: string;
223
- /** A Telnyx messaging profile id. Used when no sending number is given, or alongside one. */
224
- messagingProfileId?: string;
225
- /** Replaces the global fetch, for tests. */
226
- fetch?: typeof fetch;
227
- timeoutMs?: number;
228
- }
229
-
230
- declare function createTelnyxSmsAdapter(config: TelnyxSmsConfig): NotificationAdapter;
231
-
232
- type TelnyxInboundEvent = SmsInboundEvent;
233
- type TelnyxWebhookResult = SmsWebhookResult;
234
- interface TelnyxWebhookOptions {
235
- /** The webhook public key from the Telnyx portal (base64). */
236
- publicKey: string;
237
- /** Replaces the clock, for tests. */
238
- now?: () => Date;
239
- toleranceSeconds?: number;
240
- }
241
- /** True when the body was signed by Telnyx's key and the timestamp is recent. */
242
- declare function verifyTelnyxSignature(rawBody: string, headers: WebhookHeaders, options: TelnyxWebhookOptions): boolean;
243
- /** Checks the signature and reads the event. Call it with the raw request body, exactly as received. */
244
- declare function handleTelnyxWebhook(rawBody: string, headers: WebhookHeaders, options: TelnyxWebhookOptions): TelnyxWebhookResult;
245
-
246
- interface TwilioSmsConfig {
247
- accountSid: string;
248
- authToken: string;
249
- /** The sending number in international format, such as +13135550100. */
250
- from?: string;
251
- /** A Twilio messaging service SID. Used when no sending number is given. */
252
- messagingServiceSid?: string;
253
- /** Replaces the global fetch, for tests. */
254
- fetch?: typeof fetch;
255
- timeoutMs?: number;
256
- }
257
- declare function createTwilioSmsAdapter(config: TwilioSmsConfig): NotificationAdapter;
258
-
259
- interface TwilioWebhookOptions {
260
- /** The Twilio auth token of the account that sends the webhooks. */
261
- authToken: string;
262
- /** The exact public address Twilio was told to call, including https and any query string. */
263
- url: string;
264
- }
265
- /** True when the form body was signed by Twilio for this address. Twilio sends no timestamp, so there is no age check. */
266
- declare function verifyTwilioSignature(rawBody: string, headers: WebhookHeaders, options: TwilioWebhookOptions): boolean;
267
- /** Checks the signature and reads the event. Pass the raw form body exactly as received. */
268
- declare function handleTwilioWebhook(rawBody: string, headers: WebhookHeaders, options: TwilioWebhookOptions): SmsWebhookResult;
269
-
270
- interface PerBusinessSmsOptions {
271
- /**
272
- * Returns the adapter for one business, or null when it has no text number. Build it with createTelnyxSmsAdapter or
273
- * createTwilioSmsAdapter. The answer is reused until it expires, so a changed number is picked up within `adapterTtlMs`
274
- * (or at once with `forget`) in every worker.
275
- */
276
- resolve(organizationId: string): Promise<NotificationAdapter | null> | NotificationAdapter | null;
277
- /** How long an adapter is reused. Default 5 minutes. */
278
- adapterTtlMs?: number;
279
- /** How long "no number" is reused, so a business that adds a number starts sending soon. Default 1 minute. */
280
- noNumberTtlMs?: number;
281
- /** Replaces the clock, for tests. */
282
- now?: () => number;
283
- }
284
- interface PerBusinessSmsAdapter extends NotificationAdapter {
285
- /** Drops the kept answer for a business, for when its number or provider changed. */
286
- forget(organizationId: string): void;
287
- }
288
- declare function createPerBusinessSmsAdapter(options: PerBusinessSmsOptions): PerBusinessSmsAdapter;
289
-
290
- interface TextSettingsResolverOptions {
291
- /** The database that holds the organization's settings. */
292
- db(organizationId: string): Promise<SchedulingDb> | SchedulingDb;
293
- /** The host's Telnyx account. Leave out when the server has none: a business that chose Telnyx then sends nothing. */
294
- telnyx?: {
295
- apiKey: string;
296
- messagingProfileId?: string;
297
- };
298
- /** The host's Twilio account. Leave out when the server has none. */
299
- twilio?: {
300
- accountSid: string;
301
- authToken: string;
302
- };
303
- /** Replaces the global fetch, for tests. */
304
- fetch?: typeof fetch;
305
- }
306
- /**
307
- * Returns `resolve(organizationId)`: the adapter for the business's saved provider and number, or null when it has no
308
- * settings, has paused texting, or chose a provider this server has no account for. Pass it to createPerBusinessSmsAdapter,
309
- * which keeps each answer for `adapterTtlMs` (5 minutes by default): a pause or a changed number reaches every worker within
310
- * that time, or at once for the worker where `forget(organizationId)` is called. Use a short `adapterTtlMs` where a pause must be quick.
311
- */
312
- declare function createTextSettingsResolver(options: TextSettingsResolverOptions): (organizationId: string) => Promise<NotificationAdapter | null>;
313
-
314
- /**
315
- * Converts a Prisma Decimal (or anything Number() can coerce) to integer cents, rounded to the nearest cent.
316
- * Throws SchedulingValidationError (SCHED_406) instead of returning NaN: a null or non-numeric value almost
317
- * always means a missing `select` upstream, and NaN would reach an Int column as an opaque type error.
318
- */
319
- declare function decimalToCents(value: unknown, field?: string): number;
320
-
321
- /** Mirrors the database enum; a test in the web app fails when the two drift apart. */
322
- type RefundStatus = 'PENDING_REVIEW' | 'NO_PAYMENT' | 'REFUNDED' | 'PARTIAL_REFUND' | 'REFUND_FAILED' | 'CREDIT_ISSUED' | 'REFUND_IN_PROGRESS';
323
- declare const ALL_REFUND_STATUSES: RefundStatus[];
324
- declare const RETRYABLE_REFUND_STATUSES: RefundStatus[];
325
- declare const TERMINAL_SUCCESS_STATUSES: RefundStatus[];
326
-
327
- /**
328
- * Attempts one refund leg and says whether the money moved. `succeeded: true` covers a fresh refund and a
329
- * payment that was already refunded in an earlier attempt (`amountCents: null`, since this call has no
330
- * amount to report). `succeeded: false` covers every failure, including a request still running elsewhere.
331
- *
332
- * The key refund:{appointmentId}:{leg} makes a duplicate submission of the same attempt collapse to one
333
- * refund. No amount is passed, so a repeat refunds only what is left, and a leg that already refunded
334
- * answers "already refunded". Two cases need more than the key:
335
- *
336
- * 1. A saved failure. The provider answers a retry under the same key with the failure it saved, for about
337
- * a day, which would make a staff retry do nothing. That answer is tried once more under a fresh random
338
- * key; a second saved failure is a real failure.
339
- * - The provider is assumed to serialize refunds on one payment, so two re-attempts racing under
340
- * different keys cannot refund twice. Not observed, only assumed.
341
- * - The stripe SDK can itself retry a request under the same key, so a saved failure is not always an
342
- * earlier staff attempt. The fresh-key try is safe there for the same reasons.
343
- * 2. A request already running under the key. Its outcome is unknown, so the leg is recorded as a retryable
344
- * failure; a later retry sees its result, or "already refunded" once the key expires.
345
- */
346
- declare function attemptLegRefund(payments: PaymentAdapter, paymentIntentId: string, idempotencyKeySuffix: 'primary' | 'balance', appointmentId: string, errorCode: 'SCHED_608' | 'SCHED_609', logLabel: string): Promise<{
347
- succeeded: boolean;
348
- amountCents: number | null;
349
- }>;
350
-
351
- /**
352
- * The result actually persisted. It can differ from the caller's computed outcome when the race reconciliation
353
- * below advances or amount-merges it, so callers must report `finalStatus`, never their own pre-write value.
354
- * `finalAmount` carries the same guarantee; nothing reads it yet.
355
- */
356
- interface PersistedRefundOutcome {
357
- finalStatus: RefundStatus;
358
- finalAmount: number | null;
359
- }
360
- /**
361
- * Thrown when the final outcome write cannot be trusted to have landed after the provider calls already resolved:
362
- * the write rejected, or the compare-and-swap matched 0 rows. Carries the diagnostic fields so a caller can read
363
- * them instead of parsing prose; today the handler's catch-all returns a generic 500, so they reach server logs.
364
- *
365
- * `legSucceeded` is true when at least one leg reported success, so money definitely moved. False does not prove
366
- * nothing moved: a leg whose call threw an ambiguous error is recorded as not succeeded yet may have been
367
- * processed, which is why the message always points at the idempotency keys and the Stripe dashboard.
368
- *
369
- * Both modes reuse SCHED_610; the `phase` in the context tells them apart.
370
- */
371
- type PersistFailurePhase = 'persist-write-failed' | 'persist-cas-lost-race';
372
- declare class RefundOutcomePersistenceError extends Error {
373
- readonly code: string;
374
- readonly ref: string;
375
- readonly diagnosis: readonly string[];
376
- readonly phase: PersistFailurePhase;
377
- readonly legSucceeded: boolean;
378
- constructor(message: string, phase: PersistFailurePhase, diagnostic: {
379
- code: string;
380
- ref: string;
381
- diagnosis: readonly string[];
382
- }, legSucceeded: boolean);
383
- }
384
- interface LegFlags {
385
- primaryAttempted: boolean;
386
- primarySucceeded: boolean;
387
- balanceAttempted: boolean;
388
- balanceSucceeded: boolean;
389
- }
390
- /**
391
- * Persists the final outcome via a guarded compare-and-swap, throwing a diagnosable error (never silently) when
392
- * the write fails or loses a race it cannot reconcile. By now money has moved for every leg that succeeded.
393
- *
394
- * Returns the status and amount actually persisted. On a reconciled race `finalStatus` can differ from what the
395
- * caller passed in, and callers must use it for anything reported to a person or written to an audit log.
396
- */
397
- declare function persistRefundOutcome(db: SchedulingDb, id: string, refundOutcome: RefundStatus, refundAmount: number | null, legs: LegFlags): Promise<PersistedRefundOutcome>;
398
-
399
- type RecordOutcome = 'cancelled' | 'cancel-failed' | 'paid' | 'duplicate' | 'recorded-live';
400
- type RecordResult = {
401
- ok: true;
402
- } | {
403
- ok: false;
404
- outcome: RecordOutcome;
405
- response: Response;
406
- };
407
- declare function recordBalanceIntent(db: Pick<SchedulingDb, 'appointment'>, payments: BalancePaymentControl, target: {
408
- appointmentId: string;
409
- organizationId: string;
410
- intentId: string;
411
- }): Promise<RecordResult>;
412
-
413
- /** Thrown when every key generation was unusable; the handler maps it to a 409 with its ref. */
414
- declare class BalanceIntentGenerationsExhaustedError extends Error {
415
- readonly ref: string;
416
- constructor(message: string, ref: string);
417
- }
418
- /** Thrown when another request for this appointment's balance is still in flight; the handler maps it to a 409 with its ref. */
419
- declare class BalanceRequestInProgressError extends Error {
420
- readonly ref: string;
421
- constructor(ref: string);
422
- }
423
- interface BalanceChargeInput {
424
- amountCents: number;
425
- currency: string;
426
- clientEmail: string;
427
- description: string;
428
- metadata: Record<string, string>;
429
- }
430
- declare function createBalanceIntent(payments: PaymentAdapter, input: BalanceChargeInput, appointmentId: string): Promise<{
431
- paymentId: string;
432
- clientSecret: string | null;
433
- }>;
434
-
435
- declare const BALANCE_BLOCKED_APPOINTMENT_STATUS: AppointmentStatus;
436
- declare const BALANCE_REQUIRED_PAYMENT_STATUS = "DEPOSIT_PAID";
437
- declare const BALANCE_REQUIRED_REFUND_STATUS: null;
438
- declare const BALANCE_APPOINTMENT_SELECT: {
439
- id: true;
440
- calendar: {
441
- select: {
442
- organizationId: true;
443
- };
444
- };
445
- clientName: true;
446
- clientEmail: true;
447
- status: true;
448
- refundStatus: true;
449
- paymentStatus: true;
450
- balancePaymentId: true;
451
- depositAmount: true;
452
- type: {
453
- select: {
454
- price: true;
455
- currency: true;
456
- name: true;
457
- };
458
- };
459
- };
460
-
461
- interface OutlookSyncConfig {
462
- /**
463
- * The database of the one organization whose calendars are synced. Appointments and calendars are found by id and
464
- * no organization check is made, so a host with a database per organization builds one sync per organization.
465
- */
466
- db: SchedulingDb;
467
- /** The Azure app's id and secret. Surrounding whitespace is removed: a pasted dashboard value often carries a newline. */
468
- clientId: string;
469
- clientSecret: string;
470
- /** Defaults to the global fetch. */
471
- fetch?: typeof fetch;
472
- now?: () => Date;
473
- /** Receives anything that failed but was handled, so the host can log it. Nothing is logged by default. */
474
- onProblem?: (message: string, context: Record<string, unknown>) => void;
475
- }
476
-
477
- interface OutlookPullHooks {
478
- /**
479
- * Called when an appointment's Outlook event was deleted. Return true once the appointment is cancelled. If it
480
- * throws or returns false, the pull stops without saving its place and the next run tries again.
481
- */
482
- cancelAppointment(appointmentId: string): Promise<boolean>;
483
- /**
484
- * Called when an appointment's time was changed in Outlook, before the new time is saved. If it throws, the pull
485
- * stops without saving its place and the next run calls it again, so it can be called more than once for one change.
486
- */
487
- onAppointmentMoved?(change: {
488
- appointmentId: string;
489
- organizationId: string | null;
490
- startTime: Date;
491
- endTime: Date;
492
- }): Promise<void>;
493
- }
494
-
495
- interface OutlookCalendarSync {
496
- /** Plug into SchedulingHost.calendarSync. */
497
- adapter: CalendarSyncAdapter;
498
- /** Run on a schedule for each connected calendar. */
499
- pull(calendarId: string): Promise<{
500
- synced: number;
501
- }>;
502
- }
503
- declare function createOutlookCalendarSync(config: OutlookSyncConfig, hooks: OutlookPullHooks): OutlookCalendarSync;
504
-
505
- type NonBlockingResult = {
506
- queued: boolean;
507
- ref?: string;
508
- };
509
- /** Pushes the new times of a saved appointment to the outside calendar. */
510
- declare function runCalendarSyncWithoutBlocking(sync: CalendarSyncAdapter, event: CalendarEvent, recordFailure?: (ref: string) => Promise<void>): Promise<NonBlockingResult>;
511
- /** Removes the outside calendar event of a cancelled appointment. */
512
- declare function runCalendarRemoveWithoutBlocking(sync: CalendarSyncAdapter, ref: CalendarEventRef, recordFailure?: (ref: string) => Promise<void>): Promise<NonBlockingResult>;
513
-
514
- declare const TOKEN_TTL_DAYS = 90;
515
- declare function isTokenExpired(startTime: Date): boolean;
516
-
517
- interface SignedInPerson {
518
- userId: string;
519
- organizationId: string;
520
- role: string;
521
- }
522
- interface StaffContextInput extends SignedInPerson {
523
- db: SchedulingDb;
524
- /** Roles that manage scheduling for the whole organization, compared without regard to case. Default: owner, admin, manager. */
525
- adminRoles?: readonly string[];
526
- /** Default: true. */
527
- schedulingEnabled?: boolean;
528
- }
529
- declare function createStaffContext(input: StaffContextInput): StaffContext;
530
- interface BearerStaffResolverInput {
531
- /** The database of the organization the person belongs to. */
532
- db(person: SignedInPerson): Promise<SchedulingDb> | SchedulingDb;
533
- /** Turns a bearer token into a person, or null when the token is not valid. A rejection reaches the route, which answers 500. */
534
- authenticate(token: string, request: Request): Promise<SignedInPerson | null>;
535
- adminRoles?: readonly string[];
536
- schedulingEnabled?(person: SignedInPerson): Promise<boolean> | boolean;
537
- }
538
- /** Signs in a request from its `Authorization: Bearer <token>` header; the host decides what a token means. */
539
- declare function createBearerStaffResolver(input: BearerStaffResolverInput): StaffResolver;
540
-
541
- type StaffScope = {
542
- mode: 'unrestricted';
543
- } | {
544
- mode: 'restricted';
545
- visibleUserIds: string[];
546
- };
547
- /**
548
- * A calendar with no staff member linked to it is visible to everyone, in either mode: until someone links a
549
- * calendar to a person it is not part of any team's data.
550
- */
551
- declare function isCalendarVisibleInScope(calendarUserId: string | null, scope: StaffScope): boolean;
552
- /** A filter that narrows a calendar or appointment query to what the scope allows, or undefined when nothing is hidden. */
553
- declare function calendarVisibilityFilter(scope: StaffScope): {
554
- OR: [{
555
- userId: {
556
- in: string[];
557
- };
558
- }, {
559
- userId: null;
560
- }];
561
- } | undefined;
562
- /**
563
- * The ids of the calendars linked to a visible staff member, or undefined when nothing is hidden. Unlinked calendars
564
- * are not in the list; a caller that wants them adds `userId: null` itself, as calendarVisibilityFilter does.
565
- */
566
- declare function visibleCalendarIdsInScope(db: Pick<SchedulingDb, 'schedulingCalendar'>, scope: StaffScope): Promise<string[] | undefined>;
567
- /**
568
- * Whether the scope lets this person see the calendar. A calendar that does not exist is not visible, so a hidden one
569
- * and a missing one look the same. Pass the scope as a promise to look the calendar up while the scope is worked out.
570
- */
571
- declare function canSeeCalendarInScope(db: Pick<SchedulingDb, 'schedulingCalendar'>, calendarId: string, scope: StaffScope | Promise<StaffScope>): Promise<boolean>;
572
- /** Whether the scope lets this person see the appointment, by the calendar it is on. False when it does not exist. */
573
- declare function canSeeAppointmentInScope(db: Pick<SchedulingDb, 'appointment'>, appointmentId: string, scope: StaffScope | Promise<StaffScope>): Promise<boolean>;
574
- /** The visibility half of a StaffContext, for a host that works out the scope itself. `getScope` runs on every question. */
575
- declare function createScopedVisibility(db: SchedulingDb, getScope: () => Promise<StaffScope>): Pick<StaffContext, 'visibleCalendars' | 'visibleCalendarIds' | 'canSeeCalendar' | 'canSeeAppointment'>;
576
-
577
- interface NodeListenerOptions {
578
- /** The address this server is reached at from outside, such as https://api.example.com. */
579
- publicUrl: string;
580
- /** Largest request body, in bytes. Default: 1,000,000. A bigger body is answered with 413. */
581
- maxBodyBytes?: number;
582
- /**
583
- * How many proxies sit between the internet and this server (a load balancer counts as one). With 0, the
584
- * caller's address is the connection's. With n, it is the nth entry from the right of x-forwarded-for, which
585
- * is the address the outermost trusted proxy saw; entries to its left were written by the caller and are
586
- * dropped. A proxy may overwrite or append: both work. Default: 0.
587
- */
588
- trustedProxies?: number;
589
- }
590
- declare function createNodeListener(api: {
591
- handle(request: Request): Promise<Response>;
592
- }, options: NodeListenerOptions): (incoming: IncomingMessage, outgoing: ServerResponse) => void;
593
-
594
- /** The key text in an `Authorization: Bearer ...` header, or null when the request carries no such header. */
595
- declare function bearerKeyOf(request: Request): string | null;
596
-
597
- export { ALL_REFUND_STATUSES, AvailabilityCache, BALANCE_APPOINTMENT_SELECT, BALANCE_BLOCKED_APPOINTMENT_STATUS, BALANCE_REQUIRED_PAYMENT_STATUS, BALANCE_REQUIRED_REFUND_STATUS, BalanceIntentGenerationsExhaustedError, BalancePaymentControl, BalanceRequestInProgressError, type BearerStaffResolverInput, DnsResolver, HttpMethod, type NodeListenerOptions, type OutlookCalendarSync, type OutlookPullHooks, type OutlookSyncConfig, type Pagination, type PerBusinessSmsAdapter, type PerBusinessSmsOptions, PublicBookingResolver, PublicOrganizationResolver, RETRYABLE_REFUND_STATUSES, RateLimitTier, RefundOutcomePersistenceError, Route, type SchedulingApi, type SchedulingApiConfig, SchedulingCache, SchedulingHost, type SchedulingServiceError, SendingDomainCheck, SendingDomainRecord, SendingDomainRecords, type SendingDomainVerifier, type SendingDomainVerifierConfig, type SignedInPerson, type SmsInboundEvent, SmsSendError, type SmsWebhookResult, StaffContext, type StaffContextInput, StaffResolver, type StaffScope, type StripeLike, TERMINAL_SUCCESS_STATUSES, TOKEN_TTL_DAYS, type TelnyxInboundEvent, SmsSendError as TelnyxSendError, type TelnyxSmsConfig, type TelnyxWebhookOptions, type TelnyxWebhookResult, type TextSettingsResolverOptions, type TwilioSmsConfig, type TwilioWebhookOptions, UnverifiedPaymentError, type WebhookHeaders, assertStripeTestKey, attemptLegRefund, bearerKeyOf, calendarVisibilityFilter, canSeeAppointmentInScope, canSeeCalendarInScope, classifyReply, createBalanceIntent, createBearerStaffResolver, createMemoryAvailabilityCache, createMemoryCache, createMemoryRateLimiter, createNoBalancePaymentControl, createNoPaymentAdapter, createNodeListener, createOutlookCalendarSync, createPerBusinessSmsAdapter, createSchedulingApi, createScopedVisibility, createSendingDomainVerifier, createSingleOrganizationDirectory, createSingleOrganizationResolver, createStaffContext, createStripePaymentAdapter, createTelnyxSmsAdapter, createTextSettingsResolver, createTwilioSmsAdapter, decimalToCents, defaultCorsHeaders, getErrorCode, getErrorMessage, getErrorRef, handleTelnyxWebhook, handleTwilioWebhook, isCalendarVisibleInScope, isSchedulingServiceError, isSupportedCurrency, isTokenExpired, normalizePhoneNumber, parsePagination, persistRefundOutcome, recordBalanceIntent, runCalendarRemoveWithoutBlocking, runCalendarSyncWithoutBlocking, verifyTelnyxSignature, verifyTwilioSignature, visibleCalendarIdsInScope };