export { components as OpenApiComponents, operations as OpenApiOperations, paths as OpenApiPaths } from './openapi.generated.js'; /** Successful API response wrapper */ interface ApiResponse { data: T; } /** Paginated API response */ interface PaginatedResponse { data: T[]; pagination: { has_more: boolean; next_cursor: string | null; }; } /** API error thrown by the client */ declare class MedalApiError extends Error { readonly status: number; readonly code: string; readonly details?: unknown; constructor(status: number, code: string, message: string, details?: unknown); } /** Pagination options for list endpoints */ interface PaginationOptions { limit?: number; cursor?: string; } /** Lifecycle status of a hosted connect link. */ type ConnectLinkStatus = "pending" | "consumed" | "expired" | "revoked"; /** Lifecycle state of a channel connection. */ type ChannelConnectionState = "connecting" | "active" | "disconnected" | "disabled"; /** Input for minting a hosted connect link. */ interface CreateConnectLinkInput { /** Channel type to connect (e.g. `telegram_inbox`). */ channel_type: string; /** Display label shown on the hosted connect page (max 100 characters). */ label?: string; /** URL the hosted page redirects to after a successful connect — must be https. */ redirect_url?: string; } /** Result of minting a connect link (HTTP 201). */ interface ConnectLinkCreateResult { id: string; /** * The single-use hosted connect URL containing the one-time link token. * **Present ONLY in the live create response** — an idempotent replay * (retrying with the same `Idempotency-Key`) returns the link WITHOUT `url`. * If you lose it, revoke the link and mint a new one; the token can never * be retrieved again. */ url?: string; channel_type: string; label: string | null; status: ConnectLinkStatus; /** Unix timestamp in milliseconds when the link expires. */ expires_at: number; } /** A hosted connect link (list view — tokens are never returned). */ interface ConnectLink { id: string; channel_type: string; label: string | null; status: ConnectLinkStatus; /** Stable ref of the connection created by consuming this link, or `null`. */ consumed_connection_ref: string | null; /** Unix timestamp in milliseconds. */ expires_at: number; /** Unix timestamp in milliseconds. */ created_at: number; } /** Filters and cursor pagination for listing connect links. */ interface ListConnectLinksOptions extends PaginationOptions { channel_type?: string; status?: ConnectLinkStatus; } /** Result of revoking a connect link. */ interface ConnectLinkRevokeResult { id: string; status: "revoked"; } /** A channel connection attached to the workspace (generic, channel-agnostic shape). */ interface ChannelConnection { id: string; channel_type: string; label: string | null; state: ChannelConnectionState; /** Privacy-preserving identity handle (e.g. a masked phone number). */ masked_identity: string; /** Unix timestamp in milliseconds, or `null` if never active. */ last_activity_at: number | null; /** Linked helpdesk channel connection ID, or `null`. */ helpdesk_connection_id: string | null; } /** Result of disconnecting a channel connection. */ interface ChannelConnectionDisconnectResult { id: string; state: "disconnected"; } /** Lifecycle status of a helpdesk conversation. */ type ConversationStatus = "open" | "snoozed" | "closed"; /** Who authored a helpdesk message. */ type MessageAuthorType = "visitor" | "operator" | "ai" | "system"; /** Kind of helpdesk message. `note` is operator-internal and never delivered to the customer. */ type HelpdeskMessageType = "chat" | "email" | "note"; /** A helpdesk conversation across any connected channel (widget, email, social DMs, …). */ interface Conversation { id: string; /** Channel type, e.g. 'widget', 'instagram', 'messenger', 'whatsapp', 'email'. */ channel: string; channel_connection_id: string | null; status: ConversationStatus; subject: string | null; assignee_user_id: string | null; contact_id: string | null; visitor_name: string | null; visitor_email: string | null; external_conversation_id: string | null; channel_account_id: string | null; message_count: number; unread_for_operator: number; /** Unix timestamp in milliseconds. */ last_message_at: number; last_message_preview: string | null; last_message_author_type: MessageAuthorType | null; /** Unix timestamp in milliseconds. */ created_at: number; /** Unix timestamp in milliseconds. */ updated_at: number; } /** * Outbound delivery state of a helpdesk message. * * - `pending` — queued for the channel, not handed off yet. * - `sent` — handed to the channel provider, no confirmation yet. * - `delivered` — the channel confirmed delivery to the customer. * - `failed` — delivery failed; see `delivery_error` on the message. */ type MessageDeliveryStatus = "pending" | "sent" | "delivered" | "failed"; /** A single message inside a helpdesk conversation. */ interface ConversationMessage { id: string; conversation_id: string; author_type: MessageAuthorType; message_type: HelpdeskMessageType; author_user_id: string | null; author_name: string | null; body: string; /** * Outbound delivery state, or `null` for inbound messages and internal * notes — neither is ever sent to a channel, so neither has delivery state. * * **A `201` from `helpdesk.replies.create` means the reply was ACCEPTED, not * delivered.** The channel hand-off happens asynchronously afterwards: poll * this field (or subscribe to the `helpdesk.message_delivery_updated` * webhook event, which carries the same values) to learn whether the message * actually reached the customer. */ delivery_status: MessageDeliveryStatus | null; /** * Last send error for a `failed` outbound message, or `null` when there is * no error to report (including on inbound messages and internal notes). */ delivery_error: string | null; /** Unix timestamp in milliseconds. */ created_at: number; } /** Filters for listing/searching helpdesk conversations. */ interface ListConversationsOptions extends PaginationOptions { status?: ConversationStatus; /** Only conversations assigned to this user. */ assignee_user_id?: string; /** Match against visitor name/email. */ requester?: string; /** Free-text search query. */ query?: string; /** Only conversations on these channels (serialized as CSV). */ channels?: string[]; } /** Input for updating a conversation's status and/or assignee. At least one field is required. */ interface UpdateConversationInput { status?: ConversationStatus; /** User ID to assign, or `null` to unassign. */ assignee_user_id?: string | null; } /** Result of a conversation update. */ interface ConversationUpdateResult { id: string; status: ConversationStatus; assignee_user_id: string | null; } /** Input for sending an operator reply (or internal note) into a conversation. */ interface CreateReplyInput { conversation_id: string; /** Message body (max 20,000 characters). */ body: string; /** `note` = operator-internal note (not delivered to the customer). Default `chat`. */ message_type?: "chat" | "note"; /** Agent display name for bridged replies (shown in widget + inbox). */ author_name?: string; } /** Result returned after creating a reply (HTTP 201). */ interface ReplyCreateResult { id: string; conversation_id: string; status: string; } /** A webhook endpoint registered in the workspace. */ interface WebhookEndpoint { id: string; name: string; /** Destination URL (must be https). */ url: string; enabled: boolean; /** Subscribed event types. Empty array = all events. */ event_types: string[]; /** Channel-type filter (e.g. ['widget', 'whatsapp']), or `null` for all channels. */ channels: string[] | null; /** Channel-connection filter, or `null` for all connections. */ channel_connection_ids: string[] | null; /** Last 4 characters of the signing secret, for identification. */ secret_last4: string; consecutive_failures: number; /** Unix timestamps in milliseconds, or `null` if never. */ last_delivery_at: number | null; last_success_at: number | null; last_error_at: number | null; last_error: string | null; created_at: number; updated_at: number; /** * Full signing secret (`whsec_…`) — present ONLY in the `create` response. * It is returned exactly once and can never be retrieved again. Store it * securely immediately; you need it to verify delivery signatures. */ secret?: string; } /** Input for creating a webhook endpoint. */ interface CreateWebhookInput { /** Display name (max 100 characters). */ name: string; /** Destination URL — must be https. */ url: string; /** Event types to subscribe to (e.g. 'helpdesk.message_received'). Empty = all. */ event_types: string[]; /** Restrict to these channel types (e.g. ['widget', 'whatsapp']). */ channels?: string[]; /** Restrict to these channel connection IDs. */ channel_connection_ids?: string[]; } /** * Input for updating a webhook endpoint. Only provided fields change. * Pass `null` for `channels` or `channel_connection_ids` to CLEAR an existing * filter (deliver for all channels / all accounts again); omitting the field * leaves the current filter unchanged. */ interface UpdateWebhookInput { name?: string; url?: string; event_types?: string[]; channels?: string[] | null; channel_connection_ids?: string[] | null; enabled?: boolean; } /** Result of deleting a webhook endpoint. */ interface WebhookDeleteResult { id: string; status: string; } /** * A delivery attempt record for a webhook endpoint. * * `id` is the same value sent as the `X-Medal-Delivery-Id` and * `Idempotency-Key` headers on the outbound request, so you can join your own * receiving log to this listing exactly. * * **Deliveries never carry payload bodies.** The event payload can contain * customer PII, so it is not returned here — use the correlation fields below * to look the subject up through the regular API instead. * * All correlation fields (`resource_id`, `conversation_id`, `message_id`, * `connection_ref`, `channel`, `channel_connection_id`) are derived from the * stored event and **fail closed to `null`** whenever no canonical event * exists for the delivery — e.g. `test.ping` deliveries, or events that have * aged out of retention. Always null-check before using them. */ interface WebhookDelivery { id: string; event_type: string; /** * Primary subject id of the announced event (a message id for message * events, a connection id for channel lifecycle events, …), or `null`. */ resource_id: string | null; /** Helpdesk conversation the event belongs to, or `null`. */ conversation_id: string | null; /** Helpdesk message the event belongs to, or `null`. */ message_id: string | null; /** Opaque connection reference carried by the event, or `null`. */ connection_ref: string | null; /** Channel type (e.g. `telegram_inbox`, `widget`), or `null`. */ channel: string | null; /** Channel connection the event belongs to, or `null`. */ channel_connection_id: string | null; status: "pending" | "delivered" | "dead_letter"; attempt_count: number; /** Unix timestamp in milliseconds of the next retry, or `null`. */ next_attempt_at: number | null; response_status: number | null; duration_ms: number | null; last_error: string | null; /** Unix timestamp in milliseconds, or `null` if not delivered. */ delivered_at: number | null; created_at: number; } /** * Options for listing recent deliveries. * * This endpoint is **not** cursor-paginated — it returns the most recent * deliveries only, capped by `limit`. There is no `cursor` parameter; to keep * a durable record, ingest deliveries as they arrive (or poll and de-duplicate * on the delivery `id`). */ interface ListDeliveriesOptions { limit?: number; } /** Result returned after queuing a test delivery (HTTP 202). */ interface WebhookTestResult { delivery_id: string; status: string; } /** * Capability confirmation types. * * Medal's confirmable write routes require BOTH an `Idempotency-Key` and an * `X-Capability-Confirmation` token whenever the calling credential holds the * capability scope *directly* — which is the case for every correctly-scoped * partner key and OAuth grant. (API keys carrying only legacy scopes are * exempt.) The token is minted by `POST /api/v1/capability-confirmations` and * is bound to the workspace, the auth subject, the HTTP method + path, the * capability's required scopes, and the idempotency key. */ /** * Confirmable capability ids backing the write routes this SDK exposes. * * Mirrors the server-side capability registry. Each id maps to exactly one * method + path template — see {@link CAPABILITY_ROUTES}. */ declare const CAPABILITY_IDS: readonly ["channel.connect_link.create.execute", "channel.connect_link.revoke.execute", "channel.connection.disconnect.execute", "helpdesk.conversation.reply.execute", "helpdesk.conversation.update.execute", "helpdesk.webhook.create.execute", "helpdesk.webhook.update.execute", "helpdesk.webhook.delete.execute"]; /** A confirmable capability id backing an SDK write route. */ type CapabilityId = (typeof CAPABILITY_IDS)[number]; /** The API route a capability confirms, as registered server-side. */ interface CapabilityRoute { method: "POST" | "PATCH" | "DELETE"; /** Path template; `{id}` is filled from `path_params.id`. */ path_template: string; } /** * Method + path template for each confirmable capability. * * The server resolves the same mapping from its capability registry — this * copy exists so the SDK can build human-readable previews and supply * `path_params` without a round trip. */ declare const CAPABILITY_ROUTES: Record; /** Primitive accepted as a capability path parameter value. */ type CapabilityPathParamValue = string | number | boolean; /** Input for `POST /api/v1/capability-confirmations`. */ interface IssueCapabilityConfirmationInput { /** * Capability to confirm. Unknown ids are rejected with * `CAPABILITY_NOT_FOUND`; read-only or non-confirmable capabilities with * `CAPABILITY_NOT_CONFIRMABLE`. */ capability_id: CapabilityId | (string & {}); /** * Concrete `/api/v1/...` path the token should be bound to. Optional when * the capability has exactly one API target (all capabilities in * {@link CAPABILITY_ROUTES} do); required when it has several. Must match a * path built from the capability's own templates. */ api_path?: string; /** Values for the capability path template's parameters, e.g. `{ id: 'wh_1' }`. */ path_params?: Record; /** * The exact `Idempotency-Key` you will send on the confirmed write. The * token is bound to it — a mismatch is rejected. Required for every * capability in {@link CAPABILITY_ROUTES}. */ idempotency_key?: string; /** * Human-readable description of the action being approved (1–4000 chars). * This is the text your user saw and approved, and it is retained for audit. */ preview_summary: string; /** * Must be `true`. * * **This asserts that a human on your side approved this specific action.** * Do not send it to rubber-stamp unattended writes — it is the audit record * that a person, not a script, authorised the change. */ user_approved: true; } /** A minted capability confirmation token. */ interface CapabilityConfirmation { /** Send this as the `X-Capability-Confirmation` header on the write. */ confirmation_token: string; token_type: "medal_capability_confirmation"; capability_id: string; /** HTTP method the token is bound to. */ method: string; /** Concrete API path the token is bound to. */ path: string; /** Capability scopes the token was minted against. */ required_scopes: string[]; /** Idempotency key the token is bound to, or `null` if it was minted unbound. */ idempotency_key: string | null; /** Lifetime in seconds (60–900). */ expires_in: number; /** ISO-8601 expiry timestamp. */ expires_at: string; /** Echo of the submitted `preview_summary`. */ preview_summary: string; } /** * Request body type for each confirmable capability. * * `undefined` for routes that take no request body (the `DELETE` routes). */ interface CapabilityWriteBodies { "channel.connect_link.create.execute": CreateConnectLinkInput; "channel.connect_link.revoke.execute": undefined; "channel.connection.disconnect.execute": undefined; "helpdesk.conversation.reply.execute": CreateReplyInput; "helpdesk.conversation.update.execute": UpdateConversationInput; "helpdesk.webhook.create.execute": CreateWebhookInput; "helpdesk.webhook.update.execute": UpdateWebhookInput; "helpdesk.webhook.delete.execute": undefined; } /** * A capability paired with the request body for that exact route. * * Modelled as a discriminated union rather than two independent parameters so * the pair cannot be decoupled: passing a `helpdesk.conversation.reply.execute` * id alongside a webhook payload is a compile error, even when the id's static * type is the full {@link CapabilityId} union. */ type CapabilityWriteRequest = { [K in CapabilityId]: { /** Capability about to be confirmed. */ capabilityId: K; /** The request body of the pending write, or `undefined` for `DELETE` routes. */ body: CapabilityWriteBodies[K]; }; }[CapabilityId]; /** Fields common to every {@link AutoConfirmContext} variant. */ interface AutoConfirmContextBase { /** HTTP method of the write. */ method: string; /** Resolved API path of the write (path params substituted + encoded). */ path: string; /** Path parameters used to resolve `path`, if any. */ pathParams?: Record; /** Idempotency key that will be bound to the token and sent on the write. */ idempotencyKey: string; } /** * Context handed to an {@link AutoConfirmOptions.previewSummary} callback. * * A discriminated union on `capabilityId` — narrow on it to get the exact * `body` type for that route: * * ```ts * previewSummary: (ctx) => { * if (ctx.capabilityId === 'helpdesk.conversation.reply.execute') { * // ctx.body is CreateReplyInput here * return `Reply to ${ctx.body.conversation_id}: ${ctx.body.body}`; * } * return `${ctx.method} ${ctx.path}`; * } * ``` * * `body` is the **exact object you passed to the SDK method**, by reference * and unmodified — it is your own payload, so there is nothing to redact and * nothing crosses a tenant boundary. Treat it as read-only: mutating it from * the callback would change what is actually sent. */ type AutoConfirmContext = AutoConfirmContextBase & CapabilityWriteRequest; /** * Opt-in auto-confirmation. * * When configured, the SDK mints an idempotency key and a confirmation token * for you before each confirmable write, then attaches both headers. * * **This is not a bypass.** Every minted token carries * `user_approved: true`, which asserts that *your own user* approved that * specific action — the `preview_summary` you return is the audit record of * what they approved. Only enable this on a code path where a human really did * approve the write. Never wire it into unattended automation. */ interface AutoConfirmOptions { /** * Build the `preview_summary` for the pending write. Must return a * non-empty string describing what the user approved; returning blank text * throws instead of asserting an approval that has no description. * * The context includes the pending request `body`, so the summary can name * the specific action rather than the route — narrow on * `context.capabilityId` to get the exact payload type. Prefer a * payload-aware summary: `"Reply to conv_1: 'Refund issued'"` is an audit * record, `"POST /api/v1/helpdesk/replies"` is not. * * The server caps `preview_summary` at 4000 characters, so summarise the * payload rather than serialising it wholesale. */ previewSummary: (context: AutoConfirmContext) => string; } /** Configuration for the low-level HTTP client. */ interface ClientConfig { baseUrl: string; token: string; workspaceId?: string; timeout: number; userAgent: string; } /** Per-request options for write operations. */ interface RequestOptions { /** * Idempotency key sent as the `Idempotency-Key` header. Retries with the * same key return the original result instead of repeating the operation. * Required by some endpoints for capability-scoped tokens (e.g. helpdesk * replies, webhook creation). */ idempotencyKey?: string; /** * Capability confirmation token sent as the `X-Capability-Confirmation` * header. Required alongside `idempotencyKey` when a token granted a * capability-style scope directly (e.g. `helpdesk.webhook.manage`) executes * a confirmable write route. Obtain one from * `POST /api/v1/capability-confirmations`. API keys with legacy scopes do * not need it. */ capabilityConfirmation?: string; /** * Opt in to (or out of) automatic capability confirmation for this call. * * Supply `{ previewSummary }` to have the SDK mint the idempotency key and * the `X-Capability-Confirmation` token itself; pass `false` to suppress a * client-level `autoConfirmCapabilities` default. Defaults to the client * setting, which itself defaults to OFF. * * Auto-confirmation sends `user_approved: true` on your behalf, asserting * that a human on your side approved this exact action — only use it where * that is true. * * Ignored on routes that do not require a capability confirmation. */ autoConfirm?: AutoConfirmOptions | false; } /** * Low-level HTTP client used by all resource classes. * Handles authentication, retries, timeout, and error parsing. */ declare class BaseClient { /** Resolved client configuration. */ readonly config: ClientConfig; constructor(config: ClientConfig); /** Execute an authenticated GET request and return the parsed JSON body. */ get(path: string, params?: Record): Promise; /** Execute an authenticated POST request with a JSON body. */ post(path: string, body?: unknown, options?: RequestOptions): Promise; /** Execute an authenticated PATCH request with a JSON body. */ patch(path: string, body: unknown, options?: RequestOptions): Promise; /** Execute an authenticated DELETE request. */ delete(path: string, options?: RequestOptions): Promise; private writeHeaders; private buildUrl; private request; } /** * Mint short-lived capability confirmation tokens. * * Medal's confirmable write routes (connect links, channel connections, * helpdesk replies/updates, webhook endpoint writes) require BOTH an * `Idempotency-Key` and an `X-Capability-Confirmation` header when the calling * credential holds the capability scope *directly* — which is the case for * every correctly-scoped partner key. This resource issues that header value. * * @example Explicit flow * ```ts * const idempotencyKey = crypto.randomUUID(); * const { data: confirmation } = await medal.capabilityConfirmations.create({ * capability_id: 'channel.connect_link.create.execute', * idempotency_key: idempotencyKey, * preview_summary: 'Mint a Telegram connect link for Acme Support', * user_approved: true, // a human on your side approved this exact action * }); * * await medal.channels.connectLinks.create( * { channel_type: 'telegram_inbox', label: 'Acme Support' }, * { idempotencyKey, capabilityConfirmation: confirmation.confirmation_token }, * ); * ``` */ declare class CapabilityConfirmations { private client; constructor(client: BaseClient); /** * Issue a confirmation token for one pending write. * * The token is bound to the workspace, the auth subject, the capability's * method + path, its required scopes, and `idempotency_key` — so it is * usable exactly once, for exactly the write it describes, and expires * within 15 minutes. * * Setting `user_approved: true` asserts that a human on your side approved * this specific action. `preview_summary` is what they approved, and is * retained for audit — write it for a human reader, not a log parser. */ create(input: IssueCapabilityConfirmationInput): Promise>; } /** * Resolves the `Idempotency-Key` + `X-Capability-Confirmation` pair required * by confirmable write routes. * * Auto-confirmation is OFF unless the integrator opts in — either globally via * the `Medal` constructor's `autoConfirmCapabilities`, or per call via * `{ autoConfirm: { previewSummary } }`. When it is off this is a pass-through: * whatever headers the caller supplied are what gets sent. */ declare class CapabilityConfirmer { private confirmations; private defaults?; constructor(confirmations: CapabilityConfirmations, defaults?: AutoConfirmOptions | undefined); /** * Return the request options to use for a confirmable write, minting the * idempotency key and confirmation token first when auto-confirm is active. * * `body` is the pending request payload (`undefined` for `DELETE` routes). * It is handed to the `previewSummary` callback by reference so the summary * can describe the specific action, not just the route — it is the caller's * own payload, so it is passed through unmodified and unredacted. */ prepare(request: CapabilityWriteRequest, pathParams?: Record, options?: RequestOptions): Promise; } /** Mint, list, and revoke hosted connect links. */ declare class ChannelConnectLinks { private client; private confirmer; constructor(client: BaseClient, confirmer: CapabilityConfirmer); /** * Mint a single-use hosted connect link. Returns HTTP 201. * * **The response's `data.url` contains the one-time link token EXACTLY * ONCE.** Send it to the person who should connect their account — an * idempotent replay (same `Idempotency-Key`) returns the link WITHOUT * `url`, so store it immediately (or revoke and mint a new link if lost). * * Requires the `channel.connect.manage` scope; OAuth callers additionally * need the workspace `admin` role. */ create(input: CreateConnectLinkInput, options?: RequestOptions): Promise>; /** * List the workspace's connect links (tokens are never returned), newest * first, with cursor-based pagination. * * `limit` defaults to 50 server-side and is capped at 100. Follow * `pagination.next_cursor` while `pagination.has_more` is true. * * The `channel_type` / `status` filters are applied **within** each page, * so a page may hold fewer than `limit` items while `has_more` is still * true — drive the loop off `has_more`, never off the item count. */ list(options?: ListConnectLinksOptions): Promise>; /** Revoke a pending connect link so it can no longer be consumed. */ revoke(id: string, options?: RequestOptions): Promise>; } /** List and disconnect the workspace's channel connections. */ declare class ChannelConnections { private client; private confirmer; constructor(client: BaseClient, confirmer: CapabilityConfirmer); /** * List the workspace's channel connections (generic, channel-agnostic * shape), newest first, with cursor-based pagination. * * `limit` defaults to 50 server-side and is capped at 100. Follow * `pagination.next_cursor` while `pagination.has_more` is true. Rows that * are not projectable as connections are dropped within the page, so a page * may hold fewer than `limit` items while `has_more` is still true — drive * the loop off `has_more`, never off the item count. */ list(options?: PaginationOptions): Promise>; /** * Disconnect a connected channel account (best-effort platform logout, then * local revoke). Emits a `helpdesk.channel_disconnected` webhook event with * `reason: "api_disconnect"` if the account was previously connected. */ disconnect(id: string, options?: RequestOptions): Promise>; } /** * Partner channel connect — mint hosted connect links that let an external * person (no Medal account required) attach a channel account (e.g. * `telegram_inbox`) to the workspace's helpdesk, and manage the resulting * connections. */ declare class Channels { readonly connectLinks: ChannelConnectLinks; readonly connections: ChannelConnections; constructor(client: BaseClient, confirmer?: CapabilityConfirmer); } /** A contact in the workspace CRM. */ interface Contact { id: string; email: string; first_name: string | null; last_name: string | null; phone: string | null; company: string | null; job_title: string | null; address: Record | null; status: ContactStatus; email_status: EmailStatus; label_ids: string[]; source: string | null; custom_fields: Record | null; created_at: string | null; updated_at: string | null; } /** Result returned after creating a contact. */ interface ContactCreateResult { id: string; } /** Result returned after updating a contact. */ interface ContactUpdateResult { success: true; } /** Result returned after deleting a contact. */ interface ContactRemoveResult { success: true; } /** Result returned after adding a note to a contact. */ interface ContactNoteResult { id: string; } /** Lifecycle stage of a contact in the CRM. */ type ContactStatus = "lead" | "prospect" | "customer" | "churned" | "archived"; /** Email deliverability status for a contact. */ type EmailStatus = "subscribed" | "unsubscribed" | "bounced" | "complained"; /** Input for creating a new contact. */ interface CreateContactInput { email: string; first_name?: string; last_name?: string; phone?: string; company?: string; job_title?: string; address?: Record; status?: ContactStatus; email_status?: EmailStatus; label_ids?: string[]; /** Label names — auto-created if they don't exist in the workspace. */ labels?: string[]; custom_fields?: Record; notes?: string | { content: string; attachments?: { url: string; name: string; type?: string; size?: number; }[]; }; } /** Input for updating one or more fields on a contact. */ interface UpdateContactInput { email?: string; first_name?: string; last_name?: string; phone?: string; company?: string; job_title?: string; status?: ContactStatus; email_status?: EmailStatus; label_ids?: string[]; /** Label names — auto-created if they don't exist in the workspace. */ labels?: string[]; custom_fields?: Record; } /** Options for listing contacts with pagination and filters. */ interface ListContactsOptions extends PaginationOptions { status?: ContactStatus; email_status?: EmailStatus; label_ids?: string[]; search?: string; } /** A single contact record for bulk import. */ interface ImportContactInput { email: string; first_name?: string; last_name?: string; phone?: string; company?: string; job_title?: string; label_ids?: string[]; status?: string; } /** Summary returned after a bulk contact import. */ interface ImportContactsResult { added: number; skipped: number; total: number; } /** A contact activity event on the timeline. */ interface Activity { id: string; type: string; title: string | null; content: string | null; actor_name: string | null; actor_type: string | null; metadata: unknown; created_at: string | null; } /** Input for adding a text note to a contact's timeline. */ interface AddNoteInput { content: string; } /** Manage contacts in the workspace CRM. */ declare class Contacts { private client; constructor(client: BaseClient); /** List contacts with cursor-based pagination and optional filters. */ list(options?: ListContactsOptions): Promise>; /** Create a new contact. Email must be unique in the workspace. */ create(input: CreateContactInput): Promise>; /** Get a contact by ID. */ get(id: string): Promise>; /** Update one or more fields on a contact. */ update(id: string, input: UpdateContactInput): Promise>; /** Permanently delete a contact. */ remove(id: string): Promise>; /** Get the activity timeline for a contact. */ activities(id: string, options?: PaginationOptions): Promise>; /** Add a note to a contact's timeline. */ addNote(id: string, input: AddNoteInput): Promise>; /** Bulk import contacts (max 500). Duplicates are skipped. */ import(contacts: ImportContactInput[]): Promise>; } /** A sponsorship or brand deal in the workspace. */ interface Deal { id: string; title: string; description: string | null; value: number | null; currency: string | null; status: DealStatus; brand_name: string | null; brand_website: string | null; contact_id: string | null; contact_name: string | null; contact_email: string | null; start_date: string | null; end_date: string | null; notes: string | null; created_at: string | null; updated_at: string | null; } /** Result returned after creating a deal. */ interface DealCreateResult { id: string; } /** Result returned after updating a deal. */ interface DealUpdateResult { success: true; } /** Result returned after deleting a deal. */ interface DealRemoveResult { success: true; } /** Lifecycle stage of a sponsorship deal. */ type DealStatus = "draft" | "open" | "won" | "lost" | "negotiating" | "proposal_sent" | "on_hold" | "churned"; /** Input for creating a new deal. */ interface CreateDealInput { title: string; description?: string; value?: number; currency?: string; brand_name?: string; brand_website?: string; contact_id?: string; contact_name?: string; contact_email?: string; start_date?: string; end_date?: string; notes?: string; } /** Input for updating one or more fields on a deal. */ interface UpdateDealInput { title?: string; description?: string; value?: number; currency?: string; status?: DealStatus; brand_name?: string; brand_website?: string; contact_id?: string | null; contact_name?: string; contact_email?: string; start_date?: string; end_date?: string; notes?: string; } /** Options for listing deals with pagination and filters. */ interface ListDealsOptions extends PaginationOptions { status?: DealStatus; search?: string; } /** Manage sponsorship deals in the workspace. */ declare class Deals { private client; constructor(client: BaseClient); /** List deals with cursor-based pagination and optional filters. */ list(options?: ListDealsOptions): Promise>; /** Create a new deal. */ create(input: CreateDealInput): Promise>; /** Get a deal by ID. */ get(id: string): Promise>; /** Update one or more fields on a deal. Set contact_id to null to unlink. */ update(id: string, input: UpdateDealInput): Promise>; /** Permanently delete a deal. */ remove(id: string): Promise>; } /** Input for sending a transactional email via a template. */ interface SendEmailInput { template_slug: string; to: string; name?: string; locale?: string; fallback_locale?: string; variables?: Record; contact_id?: string; /** Body-level idempotency key (alternative to the `Idempotency-Key` header). */ idempotency_key?: string; /** Also send a `[Copy]` of the email to this address. */ copy_to?: string; /** Reply-To for the copy (defaults to the primary recipient). */ copy_reply_to?: string; } /** Result returned after queuing a transactional email send (HTTP 202). */ interface EmailSendResult { /** Email send id — poll `emails.get(id)` with it to track delivery. */ id: string | null; /** Send id of the `copy_to` copy, or `null` when no copy was requested. */ copy_id: string | null; /** CRM contact linked to the send, or `null`. */ contact_id: string | null; status: string; } /** Full record for a sent email, including delivery timestamps. */ interface EmailSend { id: string; status: string; recipient_email: string; recipient_name: string | null; subject: string | null; template_id: string | null; contact_id: string | null; queued_at: string | null; sent_at: string | null; delivered_at: string | null; opened_at: string | null; clicked_at: string | null; error_message: string | null; } /** Input for sending the same template to multiple recipients (max 100). */ interface BatchSendInput { template_slug: string; default_locale?: string; recipients: { email: string; name?: string; locale?: string; variables?: Record; }[]; } /** Per-recipient outcome of a batch send, in request order. */ interface BatchSendRecipientResult { email: string; /** Email send id — poll `emails.get(id)` with it. `null` when not queued. */ id: string | null; status: "queued" | "failed"; /** Failure reason for recipients that were not queued. */ error: string | null; } /** Summary returned after queuing a batch email send. */ interface BatchSendSummary { batch_id: string; total: number; queued: number; failed: number; /** Per-recipient outcome, in request order. */ results: BatchSendRecipientResult[]; } /** @deprecated Use `BatchSendSummary` for `emails.batch()` responses. */ type BatchSendResult = BatchSendSummary; /** An email template stored in the workspace. */ interface EmailTemplate { id: string; name: string; slug: string; type: string | null; subject: string | null; default_locale: string; available_locales: string[]; description: string | null; category: string | null; label_ids: string[]; is_active: boolean; is_archived: boolean; version: number; created_at: string | null; updated_at: string | null; } /** Full template detail including per-locale content. */ interface EmailTemplateDetail extends EmailTemplate { html_content: string | null; text_content: string | null; preview_text: string | null; from_name: string | null; from_email: string | null; reply_to: string | null; requested_locale: string | null; resolved_locale: string; content_source: string; localizations: { locale: string | null; subject: string | null; html_content: string | null; text_content: string | null; preview_text: string | null; }[]; } /** Options for fetching a template with locale resolution. */ interface GetTemplateOptions { locale?: string; fallback_locale?: string; } /** Manage email templates stored in the workspace. */ declare class EmailTemplates { private client; constructor(client: BaseClient); /** List all active email templates in the workspace. */ list(): Promise>; /** Get a specific email template by slug, optionally with locale resolution. */ get(slug: string, options?: GetTemplateOptions): Promise>; } /** Send transactional emails and manage templates. */ declare class Emails { private client; readonly templates: EmailTemplates; constructor(client: BaseClient); /** * Send a transactional email using a template (HTTP 202). The returned `id` * is an email send id — poll `emails.get(id)` with it to track delivery. */ send(input: SendEmailInput): Promise>; /** Get the delivery status of a sent email. */ get(id: string): Promise>; /** * Send the same template to multiple recipients (max 100, HTTP 202). Each * queued recipient gets its own send id in `results` for `emails.get(id)`. */ batch(input: BatchSendInput): Promise>; } /** A workspace data export request and its current status. */ interface GdprExport { id: string; request_type: string; status: "pending" | "in_progress" | "completed" | "failed" | string; submitted_at: string | null; completed_at: string | null; due_date?: string | null; download_url?: string | null; expires_at?: string | null; } /** GDPR consent category. */ type ConsentType = "marketing_email" | "analytics_tracking" | "third_party_sharing"; /** Input for recording a GDPR consent decision for a contact. */ interface RecordConsentInput { email: string; consent_type: ConsentType; granted: boolean; source?: string; ip_address?: string; consent_text?: string; version?: string; } /** A stored consent record for a contact. */ interface ConsentRecord { id: string; email: string; consent_type: ConsentType; granted: boolean; granted_at: string | null; revoked_at: string | null; source?: string; version?: string; } /** Result returned after recording a consent decision. */ interface ConsentResult { id: string; } /** @deprecated Use `ConsentRecord[]` for `gdpr.getConsent()` responses. */ type ContactConsents = ConsentRecord[]; /** Input for recording cookie consent from an external site. */ interface CookieConsentInput { domain: string; consentStatus: "granted" | "denied" | "partial" | string; consentTimestamp: string; ipAddress?: string; userAgent?: string; cookiePreferences: { necessary?: CookieCategoryConsent; analytics?: CookieCategoryConsent; marketing?: CookieCategoryConsent; functional?: CookieCategoryConsent; [key: string]: CookieCategoryConsent | undefined; }; } /** Consent decision and optional cookie records for a single cookie category. */ interface CookieCategoryConsent { allowed: boolean; cookieRecords?: { cookie: string; duration: string; description: string; }[]; } /** Manage GDPR compliance — data exports, consent records, and cookie consent. */ declare class Gdpr { private client; constructor(client: BaseClient); /** Request a workspace data export. Runs asynchronously. */ requestExport(): Promise>; /** List all workspace export requests. */ listExports(): Promise>; /** Get the status of a specific export. */ getExport(id: string): Promise>; /** Record a GDPR consent decision for a contact by email. */ recordConsent(input: RecordConsentInput): Promise>; /** Get all consent records for a contact by email. */ getConsent(email: string): Promise>; /** Record cookie consent from an external site (legacy endpoint). */ cookieConsent(input: CookieConsentInput): Promise<{ success: boolean; logId?: string; }>; } /** Browse and manage helpdesk conversations. */ declare class HelpdeskConversations { private client; private confirmer; constructor(client: BaseClient, confirmer: CapabilityConfirmer); /** List/search conversations with cursor-based pagination and optional filters. */ list(options?: ListConversationsOptions): Promise>; /** Get a conversation by ID. */ get(id: string): Promise>; /** Update a conversation's status and/or assignee (pass `assignee_user_id: null` to unassign). */ update(id: string, input: UpdateConversationInput, options?: RequestOptions): Promise>; /** Read a conversation's messages with cursor-based pagination. */ messages(id: string, options?: PaginationOptions): Promise>; } /** Send operator replies (or internal notes) into conversations. */ declare class HelpdeskReplies { private client; private confirmer; constructor(client: BaseClient, confirmer: CapabilityConfirmer); /** * Send an operator reply or internal note. Returns HTTP 201. * * Pass an `idempotencyKey` so retried requests do not create duplicate * messages — it is REQUIRED for capability-scoped tokens. */ create(input: CreateReplyInput, options?: RequestOptions): Promise>; } /** Helpdesk bridge — read conversations, reply, and manage assignment/status. */ declare class Helpdesk { readonly conversations: HelpdeskConversations; readonly replies: HelpdeskReplies; constructor(client: BaseClient, confirmer?: CapabilityConfirmer); } /** A post in the workspace (list view). */ interface Post { id: string; type: PostType; title: string | null; content: string; status: string; channel_ids: string[]; variant_count: number; published_count: number; failed_count: number; scheduled_at: string | null; published_at: string | null; created_at: string | null; updated_at: string | null; } /** Content format / distribution channel type for a post. */ type PostType = "social" | "newsletter" | "blog"; /** Per-channel variant of a post with publishing state. */ interface PostVariant { id: string; channel_id: string; content: string; status: string; platform: string | null; channel_display_name: string | null; scheduled_at: string | null; published_at: string | null; platform_post_id: string | null; permalink: string | null; error: string | null; } /** Full post detail including per-channel variants. */ interface PostDetail extends Post { variants: PostVariant[]; } /** A connected publishing channel in the workspace. */ interface Channel { id: string; platform: string | null; display_name: string | null; platform_username: string | null; state: string; connected_at: string | null; } /** Input for creating a new post. */ interface CreatePostInput { type?: PostType; title?: string; content: string; channel_ids: string[]; } /** Input for updating a draft post's title or content. */ interface UpdatePostInput { title?: string; content?: string; } /** Input for scheduling a post for future publication. */ interface SchedulePostInput { /** Unix timestamp (ms) or ISO datetime string. */ scheduled_at: number | string; } /** Options for listing posts with pagination and filters. */ interface ListPostsOptions extends PaginationOptions { status?: string; type?: PostType; } /** Result returned after scheduling a post. */ interface ScheduleResult { success: boolean; workflow_id: string; } /** Result returned after publishing a post immediately. */ interface PublishResult { success: boolean; workflow_id: string; } /** Create and publish posts across connected channels. */ declare class Posts { private client; constructor(client: BaseClient); /** List posts with cursor-based pagination and optional filters. */ list(options?: ListPostsOptions): Promise>; /** Create a new post with content and target channels. */ create(input: CreatePostInput): Promise>; /** Get a post by ID, including its per-channel variants. */ get(id: string): Promise>; /** Update a draft post's title or content. */ update(id: string, input: UpdatePostInput): Promise>; /** Delete a post. */ remove(id: string): Promise>; /** Schedule a post for future publication. */ schedule(id: string, input: SchedulePostInput): Promise>; /** Publish a post immediately to all target channels. */ publish(id: string): Promise>; /** List connected publishing channels for this workspace. */ channels(): Promise>; } /** Input for creating a scan — provide exactly ONE of `url`, `orgnr`, or `name`. */ interface ScanCreateInput { /** Website URL to scan directly (https is assumed when the scheme is missing). */ url?: string; /** 9-digit Norwegian organisation number — resolved via the public registry. */ orgnr?: string; /** Company name — resolved to the best registry match before scanning. */ name?: string; } /** Reference returned when a scan job is queued (HTTP 202). */ interface ScanCreateResult { id: string; status: "pending" | string; message?: string; } /** Lifecycle of an asynchronous scan job. */ type ScanStatus = "pending" | "running" | "done" | "failed"; /** A company-registry search hit from `scan.companies()`. */ interface ScanCompany { orgnr: string; name: string; org_form: string | null; industry: string | null; city: string | null; website: string | null; } /** Nettskår sub-scores (0–100); null = the axis could not be measured. */ interface ScanSubScores { fart: number | null; google: number | null; ai: number | null; trygghet: number | null; omdomme: number | null; } /** * The versioned scan findings payload. Shapes within are additive per * `version`; string unions stay open (`| string`) so new detections never * break consumers. */ interface ScanResultPayload { version: number; /** Weighted composite score (0–100); null when nothing could be measured. */ nettskaar: number | null; subScores: ScanSubScores; registry?: { orgnr: string; navn: string; organisasjonsform?: string; naeringBeskrivelse?: string; antallAnsatte?: number; poststed?: string; }; signals: { version: number; tech: string[]; pixels: string[]; consent: string[]; commerce: string[]; marketing?: string[]; social: Record; emailProvider?: string; unreachable?: boolean; inconclusive?: boolean; dnsPending?: boolean; }; pagespeed?: { mobileScore?: number; lcpMs?: number; cls?: number; inpMs?: number; error?: string; }; seo: { titleLength: number; metaDescriptionLength: number; h1Count: number; hasOg: boolean; hasCanonical: boolean; hreflangCount: number; hasViewport: boolean; }; ai: { /** null = llms.txt could not be checked (unknown), false = confirmed absent. */ llmsTxtFound: boolean | null; /** null = robots.txt could not be read (unknown, not "none blocked"). */ blockedBots: string[] | null; jsonLdTypes: string[]; faqFound: boolean; }; gdpr: { /** * true = tracking pixels load with no consent platform; false = clean or * a consent platform is present; null = unknown (unreachable / JS-only). */ trackingBeforeConsent: boolean | null; cmp: string | null; privacyPageFound: boolean; }; mailAuth: { spf: "ok" | "missing" | "unknown" | string; dmarc: "ok" | "missing" | "unknown" | string; dmarcPolicy?: string; }; httpsOk: boolean; } /** A scan job as returned by `scan.get()`. */ interface ScanJob { id: string; status: ScanStatus | string; input: ScanCreateInput; resolved: { orgnr?: string; companyName?: string; websiteUrl?: string; } | null; result: ScanResultPayload | null; /** Public-safe failure code (`company_not_found`, `no_website`, …). */ error: string | null; created_at: string | null; finished_at: string | null; } /** Options for `scan.waitForResult()`. */ interface WaitForScanOptions { /** Poll interval in milliseconds. Default 2500. */ intervalMs?: number; /** Give up after this long. Default 120000 (scans normally finish in ~30 s). */ timeoutMs?: number; } /** * Company & website scans (Nettsjekk) — score a Norwegian company's web * presence (performance, SEO, GDPR consent, AI visibility, mail auth) from a * URL, an organisation number, or a company name. */ declare class Scan { private client; constructor(client: BaseClient); /** * Queue a scan. Provide exactly one of `url`, `orgnr`, or `name`. * Runs asynchronously — poll with `get()` or use `waitForResult()`. * * @throws Error before any request when zero or several selectors are set — * the server would reject the body anyway; failing locally is clearer. */ create(input: ScanCreateInput): Promise>; /** Get a scan job's status and, once done, its findings payload. */ get(id: string): Promise>; /** Search the Norwegian company registry by name (typeahead, top 5 hits). */ companies(q: string): Promise>; /** * Poll a scan until it settles. Resolves with the job for both `done` and * `failed` (check `job.error`); throws only when the deadline passes while * the scan is still pending/running. */ waitForResult(id: string, options?: WaitForScanOptions): Promise; } /** Manage webhook endpoints and inspect their deliveries. */ declare class Webhooks { private client; private confirmer; constructor(client: BaseClient, confirmer?: CapabilityConfirmer); /** List all webhook endpoints in the workspace. */ list(): Promise>; /** * Create a webhook endpoint. Returns HTTP 201. * * **The response's `data.secret` contains the signing secret EXACTLY ONCE.** * It can never be retrieved again — store it securely immediately. You need * it to verify the `X-Medal-Signature` header on incoming deliveries (see * `verifyWebhookSignature`). * * `secret` is typed optional because an idempotent replay (retrying with the * same `Idempotency-Key`, `X-Idempotent-Replayed: true`) returns the existing * endpoint WITHOUT the secret — handle that case (rotate if you lost it). */ create(input: CreateWebhookInput, options?: RequestOptions): Promise>; /** Get a webhook endpoint by ID. */ get(id: string): Promise>; /** Update a webhook endpoint (name, url, event types, filters, enabled). */ update(id: string, input: UpdateWebhookInput, options?: RequestOptions): Promise>; /** * Permanently delete a webhook endpoint (stops all outbound deliveries). * Capability-scoped tokens must pass `idempotencyKey` — the API requires * `Idempotency-Key` + `X-Capability-Confirmation` for direct capability * grants on this route. API keys with legacy scopes may omit it. */ delete(id: string, options?: RequestOptions): Promise>; /** List recent deliveries for an endpoint (most recent first). */ deliveries(id: string, options?: ListDeliveriesOptions): Promise>; /** Queue a signed `test.ping` delivery to the endpoint. Returns HTTP 202. */ test(id: string): Promise>; } /** A Medal Social workspace accessible to the authenticated credential. */ interface Workspace { id: string; name: string; slug: string; [key: string]: unknown; } /** Access workspaces for the authenticated credential. */ declare class Workspaces { private client; constructor(client: BaseClient); /** List workspaces accessible to the current API key or OAuth token. */ list(): Promise>; } /** * Webhook event types and signature verification for the Medal Social * outbound webhook bridge. * * Every delivery is an HTTP POST with headers: * - `X-Medal-Timestamp` — Unix milliseconds when the request was signed * - `X-Medal-Signature` — `sha256=` * - `X-Medal-Event` — the event type * - `X-Medal-Delivery-Id` / `Idempotency-Key` — unique delivery ID (deduplicate on this) * * Use {@link verifyWebhookSignature} to authenticate a delivery and get the * parsed, typed event back. Uses Web Crypto (`crypto.subtle`) so it works in * Node.js 18+, Deno, Bun, Cloudflare Workers, and browsers. */ /** Snapshot of a conversation included in every helpdesk webhook event. */ interface WebhookConversationSnapshot { id: string; channel: string; channelConnectionId: string | null; status: string; subject: string | null; assigneeUserId: string | null; contactId: string | null; visitorName: string | null; visitorEmail: string | null; externalConversationId: string | null; channelAccountId: string | null; messageCount: number; /** Unix timestamp in milliseconds. */ lastMessageAt: number; /** Unix timestamp in milliseconds. */ createdAt: number; } /** Snapshot of a message included in helpdesk message events. */ interface WebhookMessageSnapshot { id: string; authorType: "visitor" | "operator" | "ai" | "system"; messageType: "chat" | "email" | "note"; body: string; authorUserId: string | null; authorName: string | null; externalMessageId: string | null; deliveryStatus: string | null; deliveryError: string | null; /** Unix timestamp in milliseconds. */ createdAt: number; } /** Fields present in the `data` of every helpdesk event. */ interface HelpdeskEventData { /** Channel type at the top level, for quick filtering. */ channel: string; channelConnectionId: string | null; conversation: WebhookConversationSnapshot; } /** Envelope fields shared by all webhook events. */ interface WebhookEventBase { /** Unique delivery/event ID — use for deduplication. */ id: string; /** Unix timestamp in milliseconds when the event was created. */ created_at: number; workspace_id: string; } /** A new conversation was created. */ interface ConversationCreatedEvent extends WebhookEventBase { type: "helpdesk.conversation_created"; data: HelpdeskEventData; } /** A conversation was assigned or unassigned. */ interface ConversationAssignedEvent extends WebhookEventBase { type: "helpdesk.conversation_assigned"; data: HelpdeskEventData & { assigneeUserId: string | null; previousAssigneeUserId: string | null; }; } /** A conversation's status changed (open / snoozed / closed). */ interface ConversationStatusChangedEvent extends WebhookEventBase { type: "helpdesk.conversation_status_changed"; data: HelpdeskEventData & { status: string; previousStatus: string; }; } /** A message arrived from the visitor/customer. */ interface MessageReceivedEvent extends WebhookEventBase { type: "helpdesk.message_received"; data: HelpdeskEventData & { message: WebhookMessageSnapshot; }; } /** A message was sent by an operator, AI, or the system. */ interface MessageSentEvent extends WebhookEventBase { type: "helpdesk.message_sent"; data: HelpdeskEventData & { message: WebhookMessageSnapshot; }; } /** The delivery status of an outbound message changed (sent / delivered / failed …). */ interface MessageDeliveryUpdatedEvent extends WebhookEventBase { type: "helpdesk.message_delivery_updated"; data: HelpdeskEventData & { message: WebhookMessageSnapshot; }; } /** * Fields present in the `data` of channel lifecycle events. Unlike message * events there is no conversation snapshot — the payload is channel-generic. * `channel` / `channelConnectionId` sit at the top level so endpoint channel * filters match exactly like message events. */ interface WebhookChannelLifecycleData { /** Helpdesk channel type (e.g. `telegram`), or `null` for non-helpdesk channels. */ channel: string | null; channelConnectionId: string | null; /** Connector channel type (e.g. `telegram_inbox`). */ channel_type: string; /** Adapter-defined stable connection ref (matches `consumed_connection_ref` on the connect link). */ connection_ref: string; label: string | null; masked_identity: string | null; } /** A channel account was connected to the workspace (e.g. via a partner connect link). */ interface ChannelConnectedEvent extends WebhookEventBase { type: "helpdesk.channel_connected"; data: WebhookChannelLifecycleData; } /** Why a channel account was disconnected. */ type ChannelDisconnectReason = "api_disconnect" | "user_revoked" | "member_disconnect"; /** A previously connected channel account was removed from the workspace. */ interface ChannelDisconnectedEvent extends WebhookEventBase { type: "helpdesk.channel_disconnected"; data: WebhookChannelLifecycleData & { /** Why the account went away. */ reason?: ChannelDisconnectReason; }; } /** A `test.ping` delivery queued via `medal.webhooks.test(id)`. Carries sample data. */ interface TestPingEvent extends WebhookEventBase { type: "test.ping"; data: Record; } /** * Discriminated union of all webhook events, keyed on `type`. * * @example * ```ts * switch (event.type) { * case 'helpdesk.message_received': * console.log(event.data.message.body); * break; * case 'helpdesk.conversation_status_changed': * console.log(event.data.previousStatus, '→', event.data.status); * break; * } * ``` */ type WebhookEvent = ConversationCreatedEvent | ConversationAssignedEvent | ConversationStatusChangedEvent | MessageReceivedEvent | MessageSentEvent | MessageDeliveryUpdatedEvent | ChannelConnectedEvent | ChannelDisconnectedEvent | TestPingEvent; /** Machine-readable reason a webhook verification failed. */ type WebhookVerificationErrorCode = "malformed_header" | "timestamp_out_of_tolerance" | "invalid_signature" | "invalid_payload"; /** Thrown by {@link verifyWebhookSignature} when a delivery cannot be authenticated. */ declare class WebhookVerificationError extends Error { readonly code: WebhookVerificationErrorCode; constructor(code: WebhookVerificationErrorCode, message: string); } /** Input for {@link verifyWebhookSignature}. */ interface VerifyWebhookSignatureInput { /** The RAW request body string, exactly as received (do not re-serialize parsed JSON). */ payload: string; /** Value of the `X-Medal-Timestamp` header (Unix milliseconds). */ timestamp: string; /** Value of the `X-Medal-Signature` header (`sha256=`). */ signature: string; /** The endpoint signing secret (`whsec_…`) returned once at creation time. */ secret: string; /** Max allowed clock skew between now and the signed timestamp. Default 5 minutes. */ toleranceMs?: number; } /** Default allowed clock skew for webhook verification (5 minutes). */ declare const DEFAULT_WEBHOOK_TOLERANCE_MS: number; /** * Verify a webhook delivery's signature and timestamp, then return the parsed * typed event. * * Recomputes `HMAC-SHA256("{timestamp}.{payload}", secret)` with Web Crypto * and compares it against the signature in constant time. Deliveries whose * timestamp deviates from the current time by more than `toleranceMs` * (default 5 minutes) are rejected to prevent replay attacks. * * @throws {WebhookVerificationError} if the headers are malformed, the * timestamp is outside the tolerance window, the signature does not match, * or the payload is not valid JSON. * * @example * ```ts * const event = await verifyWebhookSignature({ * payload: rawBody, * timestamp: req.headers['x-medal-timestamp'], * signature: req.headers['x-medal-signature'], * secret: process.env.MEDAL_WEBHOOK_SECRET, * }); * ``` */ declare function verifyWebhookSignature(input: VerifyWebhookSignatureInput): Promise; /** Options for configuring the {@link Medal} client. */ interface MedalOptions { /** Override the base URL (defaults to https://io.medalsocial.com). */ baseUrl?: string; /** Request timeout in ms (default 30000). */ timeout?: number; /** * Workspace ID — required for OAuth access tokens, ignored for API keys. * API keys are scoped to a single workspace, so the workspace is inferred. * OAuth tokens can access multiple workspaces, so you must specify which one. */ workspaceId?: string; /** * Opt in to automatic capability confirmation for confirmable writes. * **Defaults to OFF.** * * Medal's confirmable write routes (connect links, channel connections, * helpdesk replies/updates, webhook endpoint writes) require BOTH an * `Idempotency-Key` and an `X-Capability-Confirmation` token whenever the * credential holds the capability scope directly — which is the case for * every correctly-scoped partner key. With this option set, the SDK mints * both for you before each such write instead of making you hand-roll * `POST /api/v1/capability-confirmations`. * * **Read before enabling:** each minted token carries `user_approved: true`, * which asserts to Medal that *a human on your side approved that specific * action*, and the `previewSummary` you return is retained as the audit * record of what they approved. Enable it only on code paths where that is * genuinely true — never to rubber-stamp unattended writes. Pass * `{ autoConfirm: false }` on an individual call to opt out again, or use * `medal.capabilityConfirmations.create(...)` for full manual control. * * @example * ```ts * const medal = new Medal('medal_xxx', { * autoConfirmCapabilities: { * previewSummary: (ctx) => * `${operator.email} approved ${ctx.method} ${ctx.path}`, * }, * }); * ``` */ autoConfirmCapabilities?: AutoConfirmOptions; } /** * Medal Social SDK client. * * Supports both API key and OAuth access token authentication: * * @example API Key (recommended for server-side) * ```ts * import { Medal } from '@medalsocial/sdk'; * * // API keys start with medal_ and are scoped to one workspace * const medal = new Medal('medal_xxx'); * ``` * * @example OAuth Access Token * ```ts * // OAuth tokens require a workspaceId * const medal = new Medal('oauth_access_token', { * workspaceId: 'workspace_id_here', * }); * ``` * * @example Full usage * ```ts * const medal = new Medal('medal_xxx'); * * // Posts — create, schedule, publish * const { data: post } = await medal.posts.create({ * content: 'Hello world!', * channel_ids: ['ch_1'], * }); * await medal.posts.schedule(post.id, { scheduled_at: '2026-03-15T10:00:00Z' }); * * // Emails — send transactional emails * await medal.emails.send({ * template_slug: 'welcome', * to: 'user@example.com', * variables: { name: 'John' }, * }); * * // Contacts, Deals, GDPR, Workspaces * const contacts = await medal.contacts.list({ status: 'lead' }); * const { data: deal } = await medal.deals.create({ title: 'Acme', value: 50000 }); * await medal.gdpr.recordConsent({ email: 'u@x.com', consent_type: 'marketing_email', granted: true }); * const { data: workspaces } = await medal.workspaces.list(); * ``` */ declare class Medal { readonly capabilityConfirmations: CapabilityConfirmations; readonly channels: Channels; readonly emails: Emails; readonly contacts: Contacts; readonly deals: Deals; readonly gdpr: Gdpr; readonly helpdesk: Helpdesk; readonly posts: Posts; readonly scan: Scan; readonly webhooks: Webhooks; readonly workspaces: Workspaces; constructor(token: string, options?: MedalOptions); } /** Convenience factory — equivalent to `new Medal(apiKey, options)`. */ declare function createMedalClient(apiKey: string, options?: MedalOptions): Medal; export { type Activity, type AddNoteInput, type ApiResponse, type AutoConfirmContext, type AutoConfirmOptions, BaseClient, type BatchSendInput, type BatchSendResult, type BatchSendSummary, CAPABILITY_IDS, CAPABILITY_ROUTES, type CapabilityConfirmation, CapabilityConfirmations, CapabilityConfirmer, type CapabilityId, type CapabilityPathParamValue, type CapabilityRoute, type CapabilityWriteBodies, type CapabilityWriteRequest, type Channel, type ChannelConnectedEvent, type ChannelConnection, type ChannelConnectionDisconnectResult, type ChannelConnectionState, type ChannelDisconnectReason, type ChannelDisconnectedEvent, Channels, type ConnectLink, type ConnectLinkCreateResult, type ConnectLinkRevokeResult, type ConnectLinkStatus, type ConsentRecord, type ConsentResult, type ConsentType, type Contact, type ContactConsents, type ContactCreateResult, type ContactNoteResult, type ContactRemoveResult, type ContactStatus, type ContactUpdateResult, Contacts, type Conversation, type ConversationAssignedEvent, type ConversationCreatedEvent, type ConversationMessage, type ConversationStatus, type ConversationStatusChangedEvent, type ConversationUpdateResult, type CookieCategoryConsent, type CookieConsentInput, type CreateConnectLinkInput, type CreateContactInput, type CreateDealInput, type CreatePostInput, type CreateReplyInput, type CreateWebhookInput, DEFAULT_WEBHOOK_TOLERANCE_MS, type Deal, type DealCreateResult, type DealRemoveResult, type DealStatus, type DealUpdateResult, Deals, type EmailSend, type EmailSendResult, type EmailStatus, type EmailTemplate, type EmailTemplateDetail, Emails, Gdpr, type GdprExport, type GetTemplateOptions, Helpdesk, type HelpdeskMessageType, type ImportContactInput, type ImportContactsResult, type IssueCapabilityConfirmationInput, type ListConnectLinksOptions, type ListContactsOptions, type ListConversationsOptions, type ListDealsOptions, type ListDeliveriesOptions, type ListPostsOptions, Medal, MedalApiError, type MedalOptions, type MessageAuthorType, type MessageDeliveryStatus, type MessageDeliveryUpdatedEvent, type MessageReceivedEvent, type MessageSentEvent, type PaginatedResponse, type PaginationOptions, type Post, type PostDetail, type PostType, type PostVariant, Posts, type PublishResult, type RecordConsentInput, type ReplyCreateResult, type RequestOptions, Scan, type ScanCompany, type ScanCreateInput, type ScanCreateResult, type ScanJob, type ScanResultPayload, type ScanStatus, type ScanSubScores, type SchedulePostInput, type ScheduleResult, type SendEmailInput, type TestPingEvent, type UpdateContactInput, type UpdateConversationInput, type UpdateDealInput, type UpdatePostInput, type UpdateWebhookInput, type VerifyWebhookSignatureInput, type WaitForScanOptions, type WebhookChannelLifecycleData, type WebhookConversationSnapshot, type WebhookDeleteResult, type WebhookDelivery, type WebhookEndpoint, type WebhookEvent, type WebhookMessageSnapshot, type WebhookTestResult, WebhookVerificationError, type WebhookVerificationErrorCode, Webhooks, type Workspace, Workspaces, createMedalClient, Medal as default, verifyWebhookSignature };