tempest-express-sdk 0.4.0 → 0.6.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.cts CHANGED
@@ -2312,23 +2312,30 @@ declare const inboundMessageSchema: z.ZodObject<{
2312
2312
  type InboundMessage = z.infer<typeof inboundMessageSchema>;
2313
2313
  /** Handler invoked for each inbound message. */
2314
2314
  type InboundHandler = (message: InboundMessage) => Promise<void> | void;
2315
- /** A channel-agnostic messaging provider. */
2315
+ /**
2316
+ * A channel-agnostic messaging provider. `sendText`/`sendMedia`/`status` are
2317
+ * universal; `checkNumber` and `onMessage` are optional because not every
2318
+ * channel supports them (e.g. SMS has no persistent subscription — its inbound
2319
+ * arrives via a webhook receiver instead).
2320
+ */
2316
2321
  interface MessagingProvider {
2317
2322
  /** Send a text message. */
2318
2323
  sendText(to: string, text: string, options?: SendOptions): Promise<OutboundResult>;
2319
2324
  /** Send a media message. */
2320
2325
  sendMedia(to: string, media: OutboundMedia, options?: SendOptions): Promise<OutboundResult>;
2321
- /** Whether a number exists on the channel. */
2322
- checkNumber(number: string): Promise<boolean>;
2323
2326
  /** The current session/connection status. */
2324
2327
  status(): Promise<string>;
2328
+ /** Whether a number/handle exists on the channel (when supported). */
2329
+ checkNumber?(number: string): Promise<boolean>;
2325
2330
  /**
2326
2331
  * Subscribe to inbound messages; resolves to an unsubscribe function.
2332
+ * Present only on channels with a live subscription (WhatsApp `/ws`,
2333
+ * Telegram long-polling).
2327
2334
  *
2328
2335
  * @param handler - Invoked for each inbound message.
2329
2336
  * @param room - Conversation to scope to; `"*"` for all. Default `"*"`.
2330
2337
  */
2331
- onMessage(handler: InboundHandler, room?: string): Promise<() => Promise<void>>;
2338
+ onMessage?(handler: InboundHandler, room?: string): Promise<() => Promise<void>>;
2332
2339
  }
2333
2340
 
2334
2341
  /**
@@ -2398,6 +2405,228 @@ interface WhatsAppWebhookOptions {
2398
2405
  */
2399
2406
  declare function makeWhatsAppWebhookRouter(options: WhatsAppWebhookOptions): Router;
2400
2407
 
2408
+ /**
2409
+ * Telegram provider — a client for the Telegram Bot API.
2410
+ *
2411
+ * Implements {@link MessagingProvider} over the built-in {@link HTTPClient}
2412
+ * (no external SDK). Outbound via `sendMessage`/`sendPhoto`/…; inbound via
2413
+ * `getUpdates` long-polling exposed through {@link TelegramProvider.onMessage}.
2414
+ */
2415
+
2416
+ /** Options for {@link TelegramProvider}. */
2417
+ interface TelegramProviderOptions {
2418
+ /** Bot token from @BotFather. */
2419
+ token: string;
2420
+ /** API base. Default `https://api.telegram.org`. */
2421
+ apiBase?: string;
2422
+ /** Long-poll timeout in seconds for `getUpdates`. Default 30. */
2423
+ pollTimeoutSeconds?: number;
2424
+ }
2425
+ /** A typed Telegram Bot API client. */
2426
+ declare class TelegramProvider implements MessagingProvider {
2427
+ private readonly http;
2428
+ private readonly pollTimeout;
2429
+ /**
2430
+ * @param options - Bot token and API options.
2431
+ */
2432
+ constructor(options: TelegramProviderOptions);
2433
+ /** Call a Bot API method, returning the `result`, throwing on `ok: false`. */
2434
+ private call;
2435
+ sendText(to: string, text: string): Promise<OutboundResult>;
2436
+ sendMedia(to: string, media: OutboundMedia): Promise<OutboundResult>;
2437
+ status(): Promise<string>;
2438
+ /**
2439
+ * Subscribe to inbound messages via `getUpdates` long-polling.
2440
+ *
2441
+ * @param handler - Invoked for each inbound text message.
2442
+ * @returns A stop function that ends the polling loop.
2443
+ */
2444
+ onMessage(handler: InboundHandler): Promise<() => Promise<void>>;
2445
+ }
2446
+
2447
+ /**
2448
+ * SMS provider — a Twilio client + inbound-webhook receiver.
2449
+ *
2450
+ * Implements {@link MessagingProvider} over the built-in {@link HTTPClient}
2451
+ * (no `twilio` SDK). SMS has no persistent subscription, so `onMessage` is
2452
+ * absent — inbound arrives via {@link makeTwilioWebhookRouter}, which validates
2453
+ * the `X-Twilio-Signature` HMAC.
2454
+ */
2455
+
2456
+ /** Options for {@link TwilioSmsProvider}. */
2457
+ interface TwilioSmsProviderOptions {
2458
+ /** Twilio Account SID. */
2459
+ accountSid: string;
2460
+ /** Twilio Auth Token. */
2461
+ authToken: string;
2462
+ /** Default `From` number (E.164), e.g. `+15551234567`. */
2463
+ from: string;
2464
+ /** API base. Default `https://api.twilio.com`. */
2465
+ apiBase?: string;
2466
+ }
2467
+ /** A Twilio SMS client. */
2468
+ declare class TwilioSmsProvider implements MessagingProvider {
2469
+ private readonly http;
2470
+ private readonly from;
2471
+ private readonly messagesPath;
2472
+ private readonly accountPath;
2473
+ /**
2474
+ * @param options - Account SID, auth token and default sender.
2475
+ */
2476
+ constructor(options: TwilioSmsProviderOptions);
2477
+ /** POST a form body to Twilio and parse the JSON, throwing on non-2xx. */
2478
+ private postForm;
2479
+ sendText(to: string, text: string): Promise<OutboundResult>;
2480
+ sendMedia(to: string, media: OutboundMedia): Promise<OutboundResult>;
2481
+ status(): Promise<string>;
2482
+ }
2483
+ /**
2484
+ * Validate a Twilio request signature (`X-Twilio-Signature`).
2485
+ *
2486
+ * @param authToken - The Twilio auth token.
2487
+ * @param url - The full public URL Twilio posted to (scheme + host + path).
2488
+ * @param params - The POST form parameters.
2489
+ * @param signature - The `X-Twilio-Signature` header value.
2490
+ * @returns `true` when the signature matches.
2491
+ */
2492
+ declare function validateTwilioSignature(authToken: string, url: string, params: Record<string, string>, signature: string): boolean;
2493
+ /** Options for {@link makeTwilioWebhookRouter}. */
2494
+ interface TwilioWebhookOptions {
2495
+ /** Handler invoked for each inbound SMS. */
2496
+ onMessage: InboundHandler;
2497
+ /** Route path. Default `/sms/inbound`. */
2498
+ path?: string;
2499
+ /** Auth token; when set, `X-Twilio-Signature` is validated. */
2500
+ authToken?: string;
2501
+ /** Public URL Twilio posts to (needed for signature validation behind a proxy). */
2502
+ publicUrl?: string;
2503
+ }
2504
+ /**
2505
+ * Build the Twilio inbound-SMS webhook router.
2506
+ *
2507
+ * Twilio posts `application/x-www-form-urlencoded` (`From`, `Body`,
2508
+ * `MessageSid`, …). Mount after `express.urlencoded()` (included by `createApp`).
2509
+ *
2510
+ * @param options - Handler, path and signature-validation settings.
2511
+ * @returns An Express router with the webhook endpoint mounted.
2512
+ */
2513
+ declare function makeTwilioWebhookRouter(options: TwilioWebhookOptions): Router;
2514
+
2515
+ /**
2516
+ * Admin site + resource registry, mirroring `admin.site` / `admin.config`.
2517
+ *
2518
+ * The FastAPI SDK ships a server-rendered (jinja) admin UI. Here the admin is a
2519
+ * typed **JSON API**: register one {@link AdminResource} per managed entity and
2520
+ * {@link makeAdminRouter} exposes auto-derived CRUD + introspection endpoints a
2521
+ * frontend (React, etc.) renders. Resources are callback-based, so they wire to
2522
+ * a `BaseService` — or any store — in a few lines and stay ORM-agnostic.
2523
+ */
2524
+
2525
+ /** A field descriptor a frontend uses to render list columns / form inputs. */
2526
+ interface AdminField {
2527
+ /** Field name (property key). */
2528
+ name: string;
2529
+ /** Loose type hint for rendering (`string`, `number`, `boolean`, `date`, …). */
2530
+ type?: string;
2531
+ /** Whether the field is required on create. */
2532
+ required?: boolean;
2533
+ /** Whether the field is read-only (shown, never submitted). */
2534
+ readOnly?: boolean;
2535
+ }
2536
+ /** A paginated list result returned by {@link AdminResource.list}. */
2537
+ interface AdminListResult<T = unknown> {
2538
+ items: T[];
2539
+ total: number;
2540
+ page: number;
2541
+ pageSize: number;
2542
+ pages: number;
2543
+ }
2544
+ /** Query parameters passed to {@link AdminResource.list}. */
2545
+ interface AdminListQuery {
2546
+ page: number;
2547
+ pageSize: number;
2548
+ /** Remaining query-string entries (domain filters). */
2549
+ filters: Record<string, string>;
2550
+ }
2551
+ /**
2552
+ * A managed resource. Only `name`, `fields` and `list`/`get` are required;
2553
+ * omit a write callback to make that operation unavailable (405).
2554
+ */
2555
+ interface AdminResource<T = unknown> {
2556
+ /** URL-safe resource slug (e.g. `users`). */
2557
+ name: string;
2558
+ /** Field descriptors for list/detail/form rendering. */
2559
+ fields: AdminField[];
2560
+ /** Return a page of records. */
2561
+ list(query: AdminListQuery): Promise<AdminListResult<T>>;
2562
+ /** Return one record by id, or `null` when absent. */
2563
+ get(id: string): Promise<T | null>;
2564
+ /** Create a record from validated input. */
2565
+ create?(data: unknown): Promise<T>;
2566
+ /** Update a record by id from validated input. */
2567
+ update?(id: string, data: unknown): Promise<T>;
2568
+ /** Delete a record by id. */
2569
+ remove?(id: string): Promise<void>;
2570
+ /** Zod schema validating the create body. */
2571
+ createSchema?: z.ZodTypeAny;
2572
+ /** Zod schema validating the update body. */
2573
+ updateSchema?: z.ZodTypeAny;
2574
+ }
2575
+ /** A registry of admin resources. */
2576
+ declare class AdminSite {
2577
+ readonly brand: string;
2578
+ private readonly resources;
2579
+ /**
2580
+ * @param brand - Display name surfaced under `GET {prefix}/`.
2581
+ */
2582
+ constructor(brand?: string);
2583
+ /**
2584
+ * Register a resource.
2585
+ *
2586
+ * @param resource - The resource config.
2587
+ * @returns The same resource (for chaining).
2588
+ */
2589
+ register<T>(resource: AdminResource<T>): AdminResource<T>;
2590
+ /** Look up a resource by slug, or `null`. */
2591
+ get(name: string): AdminResource | null;
2592
+ /** Every registered resource. */
2593
+ list(): AdminResource[];
2594
+ }
2595
+
2596
+ /**
2597
+ * Admin JSON router, mirroring `admin.router.make_admin_router`.
2598
+ *
2599
+ * Exposes auto-derived CRUD + introspection over an {@link AdminSite}:
2600
+ *
2601
+ * ```text
2602
+ * GET {prefix}/ site brand + resource list
2603
+ * GET {prefix}/:resource/_meta resource field descriptors
2604
+ * GET {prefix}/:resource paginated list
2605
+ * GET {prefix}/:resource/:id detail (404 when absent)
2606
+ * POST {prefix}/:resource create (405 if unsupported)
2607
+ * PATCH {prefix}/:resource/:id update (405 if unsupported)
2608
+ * DELETE {prefix}/:resource/:id delete (405 if unsupported)
2609
+ * ```
2610
+ *
2611
+ * Pass a `guard` middleware (e.g. JWT + `requireRoles("admin")`) to protect it.
2612
+ */
2613
+
2614
+ /** Options for {@link makeAdminRouter}. */
2615
+ interface AdminRouterOptions {
2616
+ /** Route prefix. Default `/admin`. */
2617
+ prefix?: string;
2618
+ /** Guard middleware applied to every admin route (auth). */
2619
+ guard?: RequestHandler;
2620
+ }
2621
+ /**
2622
+ * Build the admin router.
2623
+ *
2624
+ * @param site - The registered {@link AdminSite}.
2625
+ * @param options - Prefix and guard middleware.
2626
+ * @returns An Express router with the admin endpoints mounted.
2627
+ */
2628
+ declare function makeAdminRouter(site: AdminSite, options?: AdminRouterOptions): Router;
2629
+
2401
2630
  /**
2402
2631
  * Auth DTOs (Zod), mirroring `auth.schemas`.
2403
2632
  *
@@ -2990,6 +3219,6 @@ interface RunServerOptions {
2990
3219
  declare function runServer(app: Express, options?: RunServerOptions): Promise<Server>;
2991
3220
 
2992
3221
  /** The installed SDK version. Single source of truth for the barrel + CLI. */
2993
- declare const VERSION = "0.4.0";
3222
+ declare const VERSION = "0.6.0";
2994
3223
 
2995
- export { AppException, type AppExceptionHandlerOptions, type AppExceptionOptions, type AttachWebSocketOptions, AttemptThrottle, type AttemptThrottleOptions, type AuthResponse, type AuthRouterOptions, type AuthUser, type BaseAppSettings, BaseController, BaseModel, type BaseResponse, BaseService, type BrokerManager, CEP_PATTERN, CNPJ_PATTERN, CPF_PATTERN, type CPUMetrics, type CacheManager, type CachedOptions, type CatalogData, CircuitOpenError, type ClientIpOptions, CompositeFeatureFlagBackend, ConflictException, type CreateAppOpenApi, type CreateAppOptions, type CursorPaginationFilter, DEFAULT_LOCALE, type EmailMessage, type EmailOptions, EmailUtils, type Enum, type EnumHelpers, type EnumSpec, EnvFeatureFlagBackend, EventStream, type EventStreamOptions, type ExceptionDetails, ExpiredTokenException, type FeatureFlagBackend, FeatureFlags, type FlagContext, ForbiddenException, type GenerateOpenApiOptions, HTTPClient, type HTTPClientOptions, HTTP_500_MARKER, type HandshakeInfo, type HealthCheck, type HealthRouterOptions, type InboundHandler, type InboundMessage, InvalidTokenException, type IssuedSession, JSONLogger, JWTUtils, type JWTUtilsOptions, type JwtAuthOptions, type JwtClaims, LocalUploadStorage, type LocalUploadStorageOptions, type LogExtra, type LogLevel, type LoginInput, type MediaKind, MemoryBroker, MemoryCacheManager, MemoryFeatureFlagBackend, type MemoryMetrics, MemorySessionStore, MemoryThrottleBackend, MessageCatalog, type MessageHandler, type MessagingProvider, MetricsUtils, NotFoundException, type OpenApiDocument, type OpenApiInfo, type OutboundMedia, type OutboundResult, PHONE_BR_PATTERN, type PaginationFilter, PasswordUtils, REQUEST_ID_HEADER, RabbitBroker, type RabbitBrokerOptions, RedisCacheManager, type RedisLike, type RedocOptions, type RefreshInput, Region, type RegionValue, type RegisterExceptionHandlersOptions, type RequestContext, type ResponseMapper, RetryPolicy, type RunServerOptions, SSEBroker, type SaveOptions, type SendOptions, ServerSentEvent, type ServerSentEventInit, type Session, type SessionMiddlewareOptions, SessionService, type SessionServiceOptions, type SessionStore, type SignupInput, type StateBR, type SwaggerOptions, type SystemMetrics, TOTPHelper, type TOTPOptions, type TaskHandler, TaskManager, type TaskManagerOptions, type ThrottleBackend, type ThrottleStatus, type ToDictOptions, type TokenPair, TooManyRequestsException, type TooManyRequestsOptions, UF, type UFValue, UnauthorizedException, type UnhandledExceptionHandlerOptions, type UploadResult, type UploadStorage, UserAuthService, type UserAuthServiceOptions, type UserPublic, type UserStore, VERSION, ValidationException, type WSEnvelope, WebPushDispatcher, type WebPushDispatcherOptions, WebPushError, WebPushGoneError, type WebPushKeys, type WebPushPayload, type WebPushSubscription, type WebSocketConnection, WebSocketHub, type WebSocketHubOptions, type WebSocketLike, WhatsAppProvider, type WhatsAppProviderOptions, type WhatsAppWebhookOptions, attachWebSocketHub, authResponseSchema, baseAppSettingsSchema, baseAppSettingsShape, baseResponseSchema, bearerToken, buildContentDisposition, cached, cepField, citiesByUf, cnpjField, coerceFlag, configureLogging, corsSettingsShape, cpfField, cpfOrCnpjField, createApp, createOpenApiRegistry, createdByColumn, cursorPaginationFilterSchema, cursorPaginationSchema, databaseSettingsShape, decodeCursor, defaultMessageCatalog, defineEnum, deletedAtColumn, encodeCursor, generateOpaqueToken, generateOpenApiDocument, getAuth, getClientIp, getConditions, getPaginationConditions, getRequestId, getState, hashOpaqueToken, inboundMessageSchema, isValidCep, isValidCity, isValidCnpj, isValidCpf, isValidCpfCnpj, isValidPhoneBr, isValidUf, listStates, loadSettings, loginSchema, makeAppExceptionHandler, makeAuthRouter, makeFlagGuard, makeHealthRouter, makeJwtAuthMiddleware, makeSessionMiddleware, makeUnhandledExceptionHandler, makeWhatsAppWebhookRouter, modifyDict, mountOpenApiJson, mountRedoc, mountSwaggerUi, normalizeCep, normalizeCnpj, normalizeCpf, normalizeCpfCnpj, normalizePhoneBr, normalizeUf, notFoundHandler, onlyDigits, paginationFilterSchema, paginationSchema, parseAcceptLanguage, parseCookies, phoneBrField, refreshSchema, registerExceptionHandlers, requestIdMiddleware, requireRoles, runServer, runWithRequestContext, serverSettingsShape, sessionCookie, setRequestId, signupSchema, sseResponse, statesByRegion, tableNameFor, toDict, toUtc, tokenFromUrl, tokenPairSchema, ufField, updatedByColumn, userPublicSchema, utcnow, verifyOpaqueToken, webPushKeysSchema, webPushPayloadSchema, webPushSubscriptionSchema, wsEnvelopeSchema };
3224
+ export { type AdminField, type AdminListQuery, type AdminListResult, type AdminResource, type AdminRouterOptions, AdminSite, AppException, type AppExceptionHandlerOptions, type AppExceptionOptions, type AttachWebSocketOptions, AttemptThrottle, type AttemptThrottleOptions, type AuthResponse, type AuthRouterOptions, type AuthUser, type BaseAppSettings, BaseController, BaseModel, type BaseResponse, BaseService, type BrokerManager, CEP_PATTERN, CNPJ_PATTERN, CPF_PATTERN, type CPUMetrics, type CacheManager, type CachedOptions, type CatalogData, CircuitOpenError, type ClientIpOptions, CompositeFeatureFlagBackend, ConflictException, type CreateAppOpenApi, type CreateAppOptions, type CursorPaginationFilter, DEFAULT_LOCALE, type EmailMessage, type EmailOptions, EmailUtils, type Enum, type EnumHelpers, type EnumSpec, EnvFeatureFlagBackend, EventStream, type EventStreamOptions, type ExceptionDetails, ExpiredTokenException, type FeatureFlagBackend, FeatureFlags, type FlagContext, ForbiddenException, type GenerateOpenApiOptions, HTTPClient, type HTTPClientOptions, HTTP_500_MARKER, type HandshakeInfo, type HealthCheck, type HealthRouterOptions, type InboundHandler, type InboundMessage, InvalidTokenException, type IssuedSession, JSONLogger, JWTUtils, type JWTUtilsOptions, type JwtAuthOptions, type JwtClaims, LocalUploadStorage, type LocalUploadStorageOptions, type LogExtra, type LogLevel, type LoginInput, type MediaKind, MemoryBroker, MemoryCacheManager, MemoryFeatureFlagBackend, type MemoryMetrics, MemorySessionStore, MemoryThrottleBackend, MessageCatalog, type MessageHandler, type MessagingProvider, MetricsUtils, NotFoundException, type OpenApiDocument, type OpenApiInfo, type OutboundMedia, type OutboundResult, PHONE_BR_PATTERN, type PaginationFilter, PasswordUtils, REQUEST_ID_HEADER, RabbitBroker, type RabbitBrokerOptions, RedisCacheManager, type RedisLike, type RedocOptions, type RefreshInput, Region, type RegionValue, type RegisterExceptionHandlersOptions, type RequestContext, type ResponseMapper, RetryPolicy, type RunServerOptions, SSEBroker, type SaveOptions, type SendOptions, ServerSentEvent, type ServerSentEventInit, type Session, type SessionMiddlewareOptions, SessionService, type SessionServiceOptions, type SessionStore, type SignupInput, type StateBR, type SwaggerOptions, type SystemMetrics, TOTPHelper, type TOTPOptions, type TaskHandler, TaskManager, type TaskManagerOptions, TelegramProvider, type TelegramProviderOptions, type ThrottleBackend, type ThrottleStatus, type ToDictOptions, type TokenPair, TooManyRequestsException, type TooManyRequestsOptions, TwilioSmsProvider, type TwilioSmsProviderOptions, type TwilioWebhookOptions, UF, type UFValue, UnauthorizedException, type UnhandledExceptionHandlerOptions, type UploadResult, type UploadStorage, UserAuthService, type UserAuthServiceOptions, type UserPublic, type UserStore, VERSION, ValidationException, type WSEnvelope, WebPushDispatcher, type WebPushDispatcherOptions, WebPushError, WebPushGoneError, type WebPushKeys, type WebPushPayload, type WebPushSubscription, type WebSocketConnection, WebSocketHub, type WebSocketHubOptions, type WebSocketLike, WhatsAppProvider, type WhatsAppProviderOptions, type WhatsAppWebhookOptions, attachWebSocketHub, authResponseSchema, baseAppSettingsSchema, baseAppSettingsShape, baseResponseSchema, bearerToken, buildContentDisposition, cached, cepField, citiesByUf, cnpjField, coerceFlag, configureLogging, corsSettingsShape, cpfField, cpfOrCnpjField, createApp, createOpenApiRegistry, createdByColumn, cursorPaginationFilterSchema, cursorPaginationSchema, databaseSettingsShape, decodeCursor, defaultMessageCatalog, defineEnum, deletedAtColumn, encodeCursor, generateOpaqueToken, generateOpenApiDocument, getAuth, getClientIp, getConditions, getPaginationConditions, getRequestId, getState, hashOpaqueToken, inboundMessageSchema, isValidCep, isValidCity, isValidCnpj, isValidCpf, isValidCpfCnpj, isValidPhoneBr, isValidUf, listStates, loadSettings, loginSchema, makeAdminRouter, makeAppExceptionHandler, makeAuthRouter, makeFlagGuard, makeHealthRouter, makeJwtAuthMiddleware, makeSessionMiddleware, makeTwilioWebhookRouter, makeUnhandledExceptionHandler, makeWhatsAppWebhookRouter, modifyDict, mountOpenApiJson, mountRedoc, mountSwaggerUi, normalizeCep, normalizeCnpj, normalizeCpf, normalizeCpfCnpj, normalizePhoneBr, normalizeUf, notFoundHandler, onlyDigits, paginationFilterSchema, paginationSchema, parseAcceptLanguage, parseCookies, phoneBrField, refreshSchema, registerExceptionHandlers, requestIdMiddleware, requireRoles, runServer, runWithRequestContext, serverSettingsShape, sessionCookie, setRequestId, signupSchema, sseResponse, statesByRegion, tableNameFor, toDict, toUtc, tokenFromUrl, tokenPairSchema, ufField, updatedByColumn, userPublicSchema, utcnow, validateTwilioSignature, verifyOpaqueToken, webPushKeysSchema, webPushPayloadSchema, webPushSubscriptionSchema, wsEnvelopeSchema };
package/dist/index.d.ts CHANGED
@@ -2312,23 +2312,30 @@ declare const inboundMessageSchema: z.ZodObject<{
2312
2312
  type InboundMessage = z.infer<typeof inboundMessageSchema>;
2313
2313
  /** Handler invoked for each inbound message. */
2314
2314
  type InboundHandler = (message: InboundMessage) => Promise<void> | void;
2315
- /** A channel-agnostic messaging provider. */
2315
+ /**
2316
+ * A channel-agnostic messaging provider. `sendText`/`sendMedia`/`status` are
2317
+ * universal; `checkNumber` and `onMessage` are optional because not every
2318
+ * channel supports them (e.g. SMS has no persistent subscription — its inbound
2319
+ * arrives via a webhook receiver instead).
2320
+ */
2316
2321
  interface MessagingProvider {
2317
2322
  /** Send a text message. */
2318
2323
  sendText(to: string, text: string, options?: SendOptions): Promise<OutboundResult>;
2319
2324
  /** Send a media message. */
2320
2325
  sendMedia(to: string, media: OutboundMedia, options?: SendOptions): Promise<OutboundResult>;
2321
- /** Whether a number exists on the channel. */
2322
- checkNumber(number: string): Promise<boolean>;
2323
2326
  /** The current session/connection status. */
2324
2327
  status(): Promise<string>;
2328
+ /** Whether a number/handle exists on the channel (when supported). */
2329
+ checkNumber?(number: string): Promise<boolean>;
2325
2330
  /**
2326
2331
  * Subscribe to inbound messages; resolves to an unsubscribe function.
2332
+ * Present only on channels with a live subscription (WhatsApp `/ws`,
2333
+ * Telegram long-polling).
2327
2334
  *
2328
2335
  * @param handler - Invoked for each inbound message.
2329
2336
  * @param room - Conversation to scope to; `"*"` for all. Default `"*"`.
2330
2337
  */
2331
- onMessage(handler: InboundHandler, room?: string): Promise<() => Promise<void>>;
2338
+ onMessage?(handler: InboundHandler, room?: string): Promise<() => Promise<void>>;
2332
2339
  }
2333
2340
 
2334
2341
  /**
@@ -2398,6 +2405,228 @@ interface WhatsAppWebhookOptions {
2398
2405
  */
2399
2406
  declare function makeWhatsAppWebhookRouter(options: WhatsAppWebhookOptions): Router;
2400
2407
 
2408
+ /**
2409
+ * Telegram provider — a client for the Telegram Bot API.
2410
+ *
2411
+ * Implements {@link MessagingProvider} over the built-in {@link HTTPClient}
2412
+ * (no external SDK). Outbound via `sendMessage`/`sendPhoto`/…; inbound via
2413
+ * `getUpdates` long-polling exposed through {@link TelegramProvider.onMessage}.
2414
+ */
2415
+
2416
+ /** Options for {@link TelegramProvider}. */
2417
+ interface TelegramProviderOptions {
2418
+ /** Bot token from @BotFather. */
2419
+ token: string;
2420
+ /** API base. Default `https://api.telegram.org`. */
2421
+ apiBase?: string;
2422
+ /** Long-poll timeout in seconds for `getUpdates`. Default 30. */
2423
+ pollTimeoutSeconds?: number;
2424
+ }
2425
+ /** A typed Telegram Bot API client. */
2426
+ declare class TelegramProvider implements MessagingProvider {
2427
+ private readonly http;
2428
+ private readonly pollTimeout;
2429
+ /**
2430
+ * @param options - Bot token and API options.
2431
+ */
2432
+ constructor(options: TelegramProviderOptions);
2433
+ /** Call a Bot API method, returning the `result`, throwing on `ok: false`. */
2434
+ private call;
2435
+ sendText(to: string, text: string): Promise<OutboundResult>;
2436
+ sendMedia(to: string, media: OutboundMedia): Promise<OutboundResult>;
2437
+ status(): Promise<string>;
2438
+ /**
2439
+ * Subscribe to inbound messages via `getUpdates` long-polling.
2440
+ *
2441
+ * @param handler - Invoked for each inbound text message.
2442
+ * @returns A stop function that ends the polling loop.
2443
+ */
2444
+ onMessage(handler: InboundHandler): Promise<() => Promise<void>>;
2445
+ }
2446
+
2447
+ /**
2448
+ * SMS provider — a Twilio client + inbound-webhook receiver.
2449
+ *
2450
+ * Implements {@link MessagingProvider} over the built-in {@link HTTPClient}
2451
+ * (no `twilio` SDK). SMS has no persistent subscription, so `onMessage` is
2452
+ * absent — inbound arrives via {@link makeTwilioWebhookRouter}, which validates
2453
+ * the `X-Twilio-Signature` HMAC.
2454
+ */
2455
+
2456
+ /** Options for {@link TwilioSmsProvider}. */
2457
+ interface TwilioSmsProviderOptions {
2458
+ /** Twilio Account SID. */
2459
+ accountSid: string;
2460
+ /** Twilio Auth Token. */
2461
+ authToken: string;
2462
+ /** Default `From` number (E.164), e.g. `+15551234567`. */
2463
+ from: string;
2464
+ /** API base. Default `https://api.twilio.com`. */
2465
+ apiBase?: string;
2466
+ }
2467
+ /** A Twilio SMS client. */
2468
+ declare class TwilioSmsProvider implements MessagingProvider {
2469
+ private readonly http;
2470
+ private readonly from;
2471
+ private readonly messagesPath;
2472
+ private readonly accountPath;
2473
+ /**
2474
+ * @param options - Account SID, auth token and default sender.
2475
+ */
2476
+ constructor(options: TwilioSmsProviderOptions);
2477
+ /** POST a form body to Twilio and parse the JSON, throwing on non-2xx. */
2478
+ private postForm;
2479
+ sendText(to: string, text: string): Promise<OutboundResult>;
2480
+ sendMedia(to: string, media: OutboundMedia): Promise<OutboundResult>;
2481
+ status(): Promise<string>;
2482
+ }
2483
+ /**
2484
+ * Validate a Twilio request signature (`X-Twilio-Signature`).
2485
+ *
2486
+ * @param authToken - The Twilio auth token.
2487
+ * @param url - The full public URL Twilio posted to (scheme + host + path).
2488
+ * @param params - The POST form parameters.
2489
+ * @param signature - The `X-Twilio-Signature` header value.
2490
+ * @returns `true` when the signature matches.
2491
+ */
2492
+ declare function validateTwilioSignature(authToken: string, url: string, params: Record<string, string>, signature: string): boolean;
2493
+ /** Options for {@link makeTwilioWebhookRouter}. */
2494
+ interface TwilioWebhookOptions {
2495
+ /** Handler invoked for each inbound SMS. */
2496
+ onMessage: InboundHandler;
2497
+ /** Route path. Default `/sms/inbound`. */
2498
+ path?: string;
2499
+ /** Auth token; when set, `X-Twilio-Signature` is validated. */
2500
+ authToken?: string;
2501
+ /** Public URL Twilio posts to (needed for signature validation behind a proxy). */
2502
+ publicUrl?: string;
2503
+ }
2504
+ /**
2505
+ * Build the Twilio inbound-SMS webhook router.
2506
+ *
2507
+ * Twilio posts `application/x-www-form-urlencoded` (`From`, `Body`,
2508
+ * `MessageSid`, …). Mount after `express.urlencoded()` (included by `createApp`).
2509
+ *
2510
+ * @param options - Handler, path and signature-validation settings.
2511
+ * @returns An Express router with the webhook endpoint mounted.
2512
+ */
2513
+ declare function makeTwilioWebhookRouter(options: TwilioWebhookOptions): Router;
2514
+
2515
+ /**
2516
+ * Admin site + resource registry, mirroring `admin.site` / `admin.config`.
2517
+ *
2518
+ * The FastAPI SDK ships a server-rendered (jinja) admin UI. Here the admin is a
2519
+ * typed **JSON API**: register one {@link AdminResource} per managed entity and
2520
+ * {@link makeAdminRouter} exposes auto-derived CRUD + introspection endpoints a
2521
+ * frontend (React, etc.) renders. Resources are callback-based, so they wire to
2522
+ * a `BaseService` — or any store — in a few lines and stay ORM-agnostic.
2523
+ */
2524
+
2525
+ /** A field descriptor a frontend uses to render list columns / form inputs. */
2526
+ interface AdminField {
2527
+ /** Field name (property key). */
2528
+ name: string;
2529
+ /** Loose type hint for rendering (`string`, `number`, `boolean`, `date`, …). */
2530
+ type?: string;
2531
+ /** Whether the field is required on create. */
2532
+ required?: boolean;
2533
+ /** Whether the field is read-only (shown, never submitted). */
2534
+ readOnly?: boolean;
2535
+ }
2536
+ /** A paginated list result returned by {@link AdminResource.list}. */
2537
+ interface AdminListResult<T = unknown> {
2538
+ items: T[];
2539
+ total: number;
2540
+ page: number;
2541
+ pageSize: number;
2542
+ pages: number;
2543
+ }
2544
+ /** Query parameters passed to {@link AdminResource.list}. */
2545
+ interface AdminListQuery {
2546
+ page: number;
2547
+ pageSize: number;
2548
+ /** Remaining query-string entries (domain filters). */
2549
+ filters: Record<string, string>;
2550
+ }
2551
+ /**
2552
+ * A managed resource. Only `name`, `fields` and `list`/`get` are required;
2553
+ * omit a write callback to make that operation unavailable (405).
2554
+ */
2555
+ interface AdminResource<T = unknown> {
2556
+ /** URL-safe resource slug (e.g. `users`). */
2557
+ name: string;
2558
+ /** Field descriptors for list/detail/form rendering. */
2559
+ fields: AdminField[];
2560
+ /** Return a page of records. */
2561
+ list(query: AdminListQuery): Promise<AdminListResult<T>>;
2562
+ /** Return one record by id, or `null` when absent. */
2563
+ get(id: string): Promise<T | null>;
2564
+ /** Create a record from validated input. */
2565
+ create?(data: unknown): Promise<T>;
2566
+ /** Update a record by id from validated input. */
2567
+ update?(id: string, data: unknown): Promise<T>;
2568
+ /** Delete a record by id. */
2569
+ remove?(id: string): Promise<void>;
2570
+ /** Zod schema validating the create body. */
2571
+ createSchema?: z.ZodTypeAny;
2572
+ /** Zod schema validating the update body. */
2573
+ updateSchema?: z.ZodTypeAny;
2574
+ }
2575
+ /** A registry of admin resources. */
2576
+ declare class AdminSite {
2577
+ readonly brand: string;
2578
+ private readonly resources;
2579
+ /**
2580
+ * @param brand - Display name surfaced under `GET {prefix}/`.
2581
+ */
2582
+ constructor(brand?: string);
2583
+ /**
2584
+ * Register a resource.
2585
+ *
2586
+ * @param resource - The resource config.
2587
+ * @returns The same resource (for chaining).
2588
+ */
2589
+ register<T>(resource: AdminResource<T>): AdminResource<T>;
2590
+ /** Look up a resource by slug, or `null`. */
2591
+ get(name: string): AdminResource | null;
2592
+ /** Every registered resource. */
2593
+ list(): AdminResource[];
2594
+ }
2595
+
2596
+ /**
2597
+ * Admin JSON router, mirroring `admin.router.make_admin_router`.
2598
+ *
2599
+ * Exposes auto-derived CRUD + introspection over an {@link AdminSite}:
2600
+ *
2601
+ * ```text
2602
+ * GET {prefix}/ site brand + resource list
2603
+ * GET {prefix}/:resource/_meta resource field descriptors
2604
+ * GET {prefix}/:resource paginated list
2605
+ * GET {prefix}/:resource/:id detail (404 when absent)
2606
+ * POST {prefix}/:resource create (405 if unsupported)
2607
+ * PATCH {prefix}/:resource/:id update (405 if unsupported)
2608
+ * DELETE {prefix}/:resource/:id delete (405 if unsupported)
2609
+ * ```
2610
+ *
2611
+ * Pass a `guard` middleware (e.g. JWT + `requireRoles("admin")`) to protect it.
2612
+ */
2613
+
2614
+ /** Options for {@link makeAdminRouter}. */
2615
+ interface AdminRouterOptions {
2616
+ /** Route prefix. Default `/admin`. */
2617
+ prefix?: string;
2618
+ /** Guard middleware applied to every admin route (auth). */
2619
+ guard?: RequestHandler;
2620
+ }
2621
+ /**
2622
+ * Build the admin router.
2623
+ *
2624
+ * @param site - The registered {@link AdminSite}.
2625
+ * @param options - Prefix and guard middleware.
2626
+ * @returns An Express router with the admin endpoints mounted.
2627
+ */
2628
+ declare function makeAdminRouter(site: AdminSite, options?: AdminRouterOptions): Router;
2629
+
2401
2630
  /**
2402
2631
  * Auth DTOs (Zod), mirroring `auth.schemas`.
2403
2632
  *
@@ -2990,6 +3219,6 @@ interface RunServerOptions {
2990
3219
  declare function runServer(app: Express, options?: RunServerOptions): Promise<Server>;
2991
3220
 
2992
3221
  /** The installed SDK version. Single source of truth for the barrel + CLI. */
2993
- declare const VERSION = "0.4.0";
3222
+ declare const VERSION = "0.6.0";
2994
3223
 
2995
- export { AppException, type AppExceptionHandlerOptions, type AppExceptionOptions, type AttachWebSocketOptions, AttemptThrottle, type AttemptThrottleOptions, type AuthResponse, type AuthRouterOptions, type AuthUser, type BaseAppSettings, BaseController, BaseModel, type BaseResponse, BaseService, type BrokerManager, CEP_PATTERN, CNPJ_PATTERN, CPF_PATTERN, type CPUMetrics, type CacheManager, type CachedOptions, type CatalogData, CircuitOpenError, type ClientIpOptions, CompositeFeatureFlagBackend, ConflictException, type CreateAppOpenApi, type CreateAppOptions, type CursorPaginationFilter, DEFAULT_LOCALE, type EmailMessage, type EmailOptions, EmailUtils, type Enum, type EnumHelpers, type EnumSpec, EnvFeatureFlagBackend, EventStream, type EventStreamOptions, type ExceptionDetails, ExpiredTokenException, type FeatureFlagBackend, FeatureFlags, type FlagContext, ForbiddenException, type GenerateOpenApiOptions, HTTPClient, type HTTPClientOptions, HTTP_500_MARKER, type HandshakeInfo, type HealthCheck, type HealthRouterOptions, type InboundHandler, type InboundMessage, InvalidTokenException, type IssuedSession, JSONLogger, JWTUtils, type JWTUtilsOptions, type JwtAuthOptions, type JwtClaims, LocalUploadStorage, type LocalUploadStorageOptions, type LogExtra, type LogLevel, type LoginInput, type MediaKind, MemoryBroker, MemoryCacheManager, MemoryFeatureFlagBackend, type MemoryMetrics, MemorySessionStore, MemoryThrottleBackend, MessageCatalog, type MessageHandler, type MessagingProvider, MetricsUtils, NotFoundException, type OpenApiDocument, type OpenApiInfo, type OutboundMedia, type OutboundResult, PHONE_BR_PATTERN, type PaginationFilter, PasswordUtils, REQUEST_ID_HEADER, RabbitBroker, type RabbitBrokerOptions, RedisCacheManager, type RedisLike, type RedocOptions, type RefreshInput, Region, type RegionValue, type RegisterExceptionHandlersOptions, type RequestContext, type ResponseMapper, RetryPolicy, type RunServerOptions, SSEBroker, type SaveOptions, type SendOptions, ServerSentEvent, type ServerSentEventInit, type Session, type SessionMiddlewareOptions, SessionService, type SessionServiceOptions, type SessionStore, type SignupInput, type StateBR, type SwaggerOptions, type SystemMetrics, TOTPHelper, type TOTPOptions, type TaskHandler, TaskManager, type TaskManagerOptions, type ThrottleBackend, type ThrottleStatus, type ToDictOptions, type TokenPair, TooManyRequestsException, type TooManyRequestsOptions, UF, type UFValue, UnauthorizedException, type UnhandledExceptionHandlerOptions, type UploadResult, type UploadStorage, UserAuthService, type UserAuthServiceOptions, type UserPublic, type UserStore, VERSION, ValidationException, type WSEnvelope, WebPushDispatcher, type WebPushDispatcherOptions, WebPushError, WebPushGoneError, type WebPushKeys, type WebPushPayload, type WebPushSubscription, type WebSocketConnection, WebSocketHub, type WebSocketHubOptions, type WebSocketLike, WhatsAppProvider, type WhatsAppProviderOptions, type WhatsAppWebhookOptions, attachWebSocketHub, authResponseSchema, baseAppSettingsSchema, baseAppSettingsShape, baseResponseSchema, bearerToken, buildContentDisposition, cached, cepField, citiesByUf, cnpjField, coerceFlag, configureLogging, corsSettingsShape, cpfField, cpfOrCnpjField, createApp, createOpenApiRegistry, createdByColumn, cursorPaginationFilterSchema, cursorPaginationSchema, databaseSettingsShape, decodeCursor, defaultMessageCatalog, defineEnum, deletedAtColumn, encodeCursor, generateOpaqueToken, generateOpenApiDocument, getAuth, getClientIp, getConditions, getPaginationConditions, getRequestId, getState, hashOpaqueToken, inboundMessageSchema, isValidCep, isValidCity, isValidCnpj, isValidCpf, isValidCpfCnpj, isValidPhoneBr, isValidUf, listStates, loadSettings, loginSchema, makeAppExceptionHandler, makeAuthRouter, makeFlagGuard, makeHealthRouter, makeJwtAuthMiddleware, makeSessionMiddleware, makeUnhandledExceptionHandler, makeWhatsAppWebhookRouter, modifyDict, mountOpenApiJson, mountRedoc, mountSwaggerUi, normalizeCep, normalizeCnpj, normalizeCpf, normalizeCpfCnpj, normalizePhoneBr, normalizeUf, notFoundHandler, onlyDigits, paginationFilterSchema, paginationSchema, parseAcceptLanguage, parseCookies, phoneBrField, refreshSchema, registerExceptionHandlers, requestIdMiddleware, requireRoles, runServer, runWithRequestContext, serverSettingsShape, sessionCookie, setRequestId, signupSchema, sseResponse, statesByRegion, tableNameFor, toDict, toUtc, tokenFromUrl, tokenPairSchema, ufField, updatedByColumn, userPublicSchema, utcnow, verifyOpaqueToken, webPushKeysSchema, webPushPayloadSchema, webPushSubscriptionSchema, wsEnvelopeSchema };
3224
+ export { type AdminField, type AdminListQuery, type AdminListResult, type AdminResource, type AdminRouterOptions, AdminSite, AppException, type AppExceptionHandlerOptions, type AppExceptionOptions, type AttachWebSocketOptions, AttemptThrottle, type AttemptThrottleOptions, type AuthResponse, type AuthRouterOptions, type AuthUser, type BaseAppSettings, BaseController, BaseModel, type BaseResponse, BaseService, type BrokerManager, CEP_PATTERN, CNPJ_PATTERN, CPF_PATTERN, type CPUMetrics, type CacheManager, type CachedOptions, type CatalogData, CircuitOpenError, type ClientIpOptions, CompositeFeatureFlagBackend, ConflictException, type CreateAppOpenApi, type CreateAppOptions, type CursorPaginationFilter, DEFAULT_LOCALE, type EmailMessage, type EmailOptions, EmailUtils, type Enum, type EnumHelpers, type EnumSpec, EnvFeatureFlagBackend, EventStream, type EventStreamOptions, type ExceptionDetails, ExpiredTokenException, type FeatureFlagBackend, FeatureFlags, type FlagContext, ForbiddenException, type GenerateOpenApiOptions, HTTPClient, type HTTPClientOptions, HTTP_500_MARKER, type HandshakeInfo, type HealthCheck, type HealthRouterOptions, type InboundHandler, type InboundMessage, InvalidTokenException, type IssuedSession, JSONLogger, JWTUtils, type JWTUtilsOptions, type JwtAuthOptions, type JwtClaims, LocalUploadStorage, type LocalUploadStorageOptions, type LogExtra, type LogLevel, type LoginInput, type MediaKind, MemoryBroker, MemoryCacheManager, MemoryFeatureFlagBackend, type MemoryMetrics, MemorySessionStore, MemoryThrottleBackend, MessageCatalog, type MessageHandler, type MessagingProvider, MetricsUtils, NotFoundException, type OpenApiDocument, type OpenApiInfo, type OutboundMedia, type OutboundResult, PHONE_BR_PATTERN, type PaginationFilter, PasswordUtils, REQUEST_ID_HEADER, RabbitBroker, type RabbitBrokerOptions, RedisCacheManager, type RedisLike, type RedocOptions, type RefreshInput, Region, type RegionValue, type RegisterExceptionHandlersOptions, type RequestContext, type ResponseMapper, RetryPolicy, type RunServerOptions, SSEBroker, type SaveOptions, type SendOptions, ServerSentEvent, type ServerSentEventInit, type Session, type SessionMiddlewareOptions, SessionService, type SessionServiceOptions, type SessionStore, type SignupInput, type StateBR, type SwaggerOptions, type SystemMetrics, TOTPHelper, type TOTPOptions, type TaskHandler, TaskManager, type TaskManagerOptions, TelegramProvider, type TelegramProviderOptions, type ThrottleBackend, type ThrottleStatus, type ToDictOptions, type TokenPair, TooManyRequestsException, type TooManyRequestsOptions, TwilioSmsProvider, type TwilioSmsProviderOptions, type TwilioWebhookOptions, UF, type UFValue, UnauthorizedException, type UnhandledExceptionHandlerOptions, type UploadResult, type UploadStorage, UserAuthService, type UserAuthServiceOptions, type UserPublic, type UserStore, VERSION, ValidationException, type WSEnvelope, WebPushDispatcher, type WebPushDispatcherOptions, WebPushError, WebPushGoneError, type WebPushKeys, type WebPushPayload, type WebPushSubscription, type WebSocketConnection, WebSocketHub, type WebSocketHubOptions, type WebSocketLike, WhatsAppProvider, type WhatsAppProviderOptions, type WhatsAppWebhookOptions, attachWebSocketHub, authResponseSchema, baseAppSettingsSchema, baseAppSettingsShape, baseResponseSchema, bearerToken, buildContentDisposition, cached, cepField, citiesByUf, cnpjField, coerceFlag, configureLogging, corsSettingsShape, cpfField, cpfOrCnpjField, createApp, createOpenApiRegistry, createdByColumn, cursorPaginationFilterSchema, cursorPaginationSchema, databaseSettingsShape, decodeCursor, defaultMessageCatalog, defineEnum, deletedAtColumn, encodeCursor, generateOpaqueToken, generateOpenApiDocument, getAuth, getClientIp, getConditions, getPaginationConditions, getRequestId, getState, hashOpaqueToken, inboundMessageSchema, isValidCep, isValidCity, isValidCnpj, isValidCpf, isValidCpfCnpj, isValidPhoneBr, isValidUf, listStates, loadSettings, loginSchema, makeAdminRouter, makeAppExceptionHandler, makeAuthRouter, makeFlagGuard, makeHealthRouter, makeJwtAuthMiddleware, makeSessionMiddleware, makeTwilioWebhookRouter, makeUnhandledExceptionHandler, makeWhatsAppWebhookRouter, modifyDict, mountOpenApiJson, mountRedoc, mountSwaggerUi, normalizeCep, normalizeCnpj, normalizeCpf, normalizeCpfCnpj, normalizePhoneBr, normalizeUf, notFoundHandler, onlyDigits, paginationFilterSchema, paginationSchema, parseAcceptLanguage, parseCookies, phoneBrField, refreshSchema, registerExceptionHandlers, requestIdMiddleware, requireRoles, runServer, runWithRequestContext, serverSettingsShape, sessionCookie, setRequestId, signupSchema, sseResponse, statesByRegion, tableNameFor, toDict, toUtc, tokenFromUrl, tokenPairSchema, ufField, updatedByColumn, userPublicSchema, utcnow, validateTwilioSignature, verifyOpaqueToken, webPushKeysSchema, webPushPayloadSchema, webPushSubscriptionSchema, wsEnvelopeSchema };