meta-cloud-api 1.1.7 → 1.1.9
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/chunk-CTAAG5j7.js +1 -0
- package/dist/index.d.ts +3929 -437
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -2633
- package/dist/index.js.map +1 -1
- package/dist/types/enums-C_tIIGBV.d.ts +668 -0
- package/dist/types/enums-C_tIIGBV.d.ts.map +1 -0
- package/dist/{types.js → types/enums.d.ts} +2 -3
- package/dist/types/enums.js +2 -0
- package/dist/types/enums.js.map +1 -0
- package/dist/{index-C37I1sT7.d.ts → types/index.d.ts} +1268 -2117
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/index.js +2 -0
- package/dist/types/index.js.map +1 -0
- package/package.json +13 -3
- package/dist/chunk-PECeCxCb.js +0 -15
- package/dist/index-C37I1sT7.d.ts.map +0 -1
- package/dist/types-Ov9U2ABw.js +0 -801
- package/dist/types-Ov9U2ABw.js.map +0 -1
- package/dist/types.d.ts +0 -2
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["LIB_NAME","LOG_LOCAL","LOGGER","wabaConfig: WabaConfigType","LIB_NAME","LOG_LOCAL","LOGGER","LIB_NAME","LOGGER","headers: HeadersInit","fileContent: Blob","body: m.MessageRequestBody<T>","textPayload: m.TextObject","MessageApi","queryParts: string[]","body: registration.RegistrationRequest","header: TemplateHeader","body: TemplateBody","buttons: TemplateButton[]","urlButton: any","flowButton: any","components: ComponentTypes[]","carouselComponents: ComponentTypes[]","carouselCards: MediaCarouselCard[]","cardComponents: (TemplateHeader | TemplateBody | TemplateButtons)[]","carouselCards: ProductCarouselCard[]","LIB_NAME","LOGGER","MessagesApi","MediaApi","PhoneNumberApi","TwoStepVerificationApi","FlowApi","BusinessProfileApi","EncryptionApi","QrCodeApi","RegistrationApi","WabaApi","SDKEnums","LOGGER","errors: string[]","processedStatus: WebhookMessage","processedMessage: WebhookMessage","decryptedAesKey: Buffer","flipped_iv: number[]","chunks: Buffer[]","webhookHandler","crypto"],"sources":["../src/utils/logger.ts","../src/config/importConfig.ts","../src/utils/configTable.ts","../src/utils/isMetaError.ts","../src/utils/http/httpsClient.ts","../src/utils/http/request.ts","../src/utils/version.ts","../src/types/base.ts","../src/api/encryption/EncryptionApi.ts","../src/api/encryption/index.ts","../src/api/flow/FlowApi.ts","../src/api/flow/index.ts","../src/api/media/MediaApi.ts","../src/api/media/index.ts","../src/api/messages/MessageApi.ts","../src/api/messages/index.ts","../src/utils/objectToQueryString.ts","../src/api/phone/PhoneNumberApi.ts","../src/api/phone/index.ts","../src/utils/buildFieldsQueryString.ts","../src/api/profile/BusinessProfileApi.ts","../src/api/profile/index.ts","../src/api/qrCode/QrCodeApi.ts","../src/api/qrCode/index.ts","../src/api/registration/RegistrationApi.ts","../src/api/registration/index.ts","../src/api/template/TemplateApi.ts","../src/api/template/factories/index.ts","../src/api/twoStepVerification/TwoStepVerificationApi.ts","../src/api/twoStepVerification/index.ts","../src/api/waba/WabaApi.ts","../src/api/waba/index.ts","../src/utils/logoConsole.ts","../src/core/whatsapp/WhatsApp.ts","../src/utils/flowTypeGuards.ts","../src/core/webhook/utils/webhookUtils.ts","../src/core/webhook/WebhookProcessor.ts","../src/core/webhook/frameworks/handler.ts","../src/core/webhook/frameworks/express.ts","../src/core/webhook/frameworks/nextjs.ts","../src/core/webhook/utils/generateXHub256Sig.ts"],"sourcesContent":["// @ts-nocheck\nimport type { LoggerInterface } from '../types/logger';\n\nexport default class Logger implements LoggerInterface {\n private name: string;\n private debug: boolean;\n\n constructor(name: string, debug: boolean = false) {\n this.name = name;\n this.debug = debug;\n }\n\n log(...data: any[]) {\n if (this.debug) {\n let prefix = `[ ${Date.now()} ]`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.log.apply(console, [prefix, ': ', ...data]);\n }\n }\n\n error(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - ERROR`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.error.apply(console, [prefix, ': ', ...data]);\n }\n\n warn(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - WARN`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.warn.apply(console, [prefix, ': ', ...data]);\n }\n\n info(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - INFO`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.info.apply(console, [prefix, ': ', ...data]);\n }\n}\n","import type { WabaConfigType, WhatsAppConfig } from '../types/config';\nimport { WabaConfigEnum } from '../types/enums';\nimport Logger from '../utils/logger';\n\nconst LIB_NAME = 'UTILS';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\nconst DEFAULT_LISTENER_PORT = 3000;\nconst DEFAULT_MAX_RETRIES_AFTER_WAIT = 30;\nconst DEFAULT_REQUEST_TIMEOUT = 20000;\n\nconst emptyConfigChecker = (config: WhatsAppConfig | undefined) => {\n if (!process.env[WabaConfigEnum.AccessToken] && !config?.accessToken) {\n LOGGER.log(`Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined.`);\n throw new Error('Missing WhatsApp access token.');\n }\n};\n\nexport const importConfig = (inputConfig?: WhatsAppConfig) => {\n emptyConfigChecker(inputConfig);\n\n const wabaConfig: WabaConfigType = {\n [WabaConfigEnum.AppId]: inputConfig?.appId || process.env.M4D_APP_ID || '',\n [WabaConfigEnum.AppSecret]: inputConfig?.appSecret || process.env.M4D_APP_SECRET || '',\n [WabaConfigEnum.PhoneNumberId]: inputConfig?.phoneNumberId || Number(process.env.WA_PHONE_NUMBER_ID),\n [WabaConfigEnum.BusinessAcctId]: inputConfig?.businessAcctId || process.env.WA_BUSINESS_ACCOUNT_ID || '',\n [WabaConfigEnum.APIVersion]: inputConfig?.apiVersion || process.env.CLOUD_API_VERSION || '',\n [WabaConfigEnum.AccessToken]: inputConfig?.accessToken || process.env.CLOUD_API_ACCESS_TOKEN || '',\n [WabaConfigEnum.WebhookEndpoint]: inputConfig?.webhookEndpoint || process.env.WEBHOOK_ENDPOINT || '',\n [WabaConfigEnum.WebhookVerificationToken]:\n inputConfig?.webhookVerificationToken || process.env.WEBHOOK_VERIFICATION_TOKEN || '',\n [WabaConfigEnum.ListenerPort]:\n inputConfig?.listenerPort || parseInt(process.env.LISTENER_PORT || '') || DEFAULT_LISTENER_PORT,\n [WabaConfigEnum.MaxRetriesAfterWait]:\n inputConfig?.maxRetriesAfterWait ||\n parseInt(process.env.MAX_RETRIES_AFTER_WAIT || '') ||\n DEFAULT_MAX_RETRIES_AFTER_WAIT,\n [WabaConfigEnum.RequestTimeout]:\n inputConfig?.requestTimeout || parseInt(process.env.REQUEST_TIMEOUT || '') || DEFAULT_REQUEST_TIMEOUT,\n [WabaConfigEnum.Debug]: inputConfig?.debug || process.env.DEBUG === 'true',\n [WabaConfigEnum.PrivatePem]: inputConfig?.privatePem || process.env.FLOW_API_PRIVATE_PEM || '',\n [WabaConfigEnum.Passphrase]: inputConfig?.passphrase || process.env.FLOW_API_PASSPHRASE || '',\n };\n\n return wabaConfig;\n};\n","import type { WabaConfigType } from '../types/config';\nimport { WabaConfigEnum } from '../types/enums';\n\n/**\n * Formats configuration as a terminal table\n * @param config - The WABA configuration object\n * @param apiName - The name of the API being initialized\n * @returns Formatted table string\n */\nexport function formatConfigTable(config: WabaConfigType): string {\n const configData = [\n ['App ID', config[WabaConfigEnum.AppId] || 'Not Set'],\n ['Phone Number ID', config[WabaConfigEnum.PhoneNumberId]?.toString() || 'Not Set'],\n ['Business Account ID', config[WabaConfigEnum.BusinessAcctId] || 'Not Set'],\n ['API Version', config[WabaConfigEnum.APIVersion] || 'Not Set'],\n [\n 'Access Token',\n config[WabaConfigEnum.AccessToken]\n ? `${config[WabaConfigEnum.AccessToken].substring(0, 20)}...`\n : 'Not Set',\n ],\n ['Webhook Endpoint', config[WabaConfigEnum.WebhookEndpoint] || 'Not Set'],\n [\n 'Webhook Verification Token',\n config[WabaConfigEnum.WebhookVerificationToken]\n ? `${config[WabaConfigEnum.WebhookVerificationToken].substring(0, 10)}...`\n : 'Not Set',\n ],\n ['Listener Port', config[WabaConfigEnum.ListenerPort]?.toString() || 'Not Set'],\n ['Debug Mode', config[WabaConfigEnum.Debug] ? 'Enabled' : 'Disabled'],\n ['Max Retries', config[WabaConfigEnum.MaxRetriesAfterWait]?.toString() || 'Not Set'],\n [\n 'Request Timeout',\n config[WabaConfigEnum.RequestTimeout] ? `${config[WabaConfigEnum.RequestTimeout]}ms` : 'Not Set',\n ],\n ['Private PEM', config[WabaConfigEnum.PrivatePem] ? 'Configured' : 'Not Set'],\n ['Passphrase', config[WabaConfigEnum.Passphrase] ? 'Configured' : 'Not Set'],\n ];\n\n // Calculate column widths\n const maxKeyLength = Math.max(...configData.map(([key]) => key?.length || 0));\n const maxValueLength = Math.max(...configData.map(([, value]) => value?.length || 0));\n\n const keyWidth = Math.max(maxKeyLength, 20);\n const valueWidth = Math.max(maxValueLength, 30);\n\n // Create table\n const horizontalLine = `┌${'─'.repeat(keyWidth + 2)}┬${'─'.repeat(valueWidth + 2)}┐`;\n const separator = `├${'─'.repeat(keyWidth + 2)}┼${'─'.repeat(valueWidth + 2)}┤`;\n const bottomLine = `└${'─'.repeat(keyWidth + 2)}┴${'─'.repeat(valueWidth + 2)}┘`;\n\n const header = `│ ${'Configuration'.padEnd(keyWidth)} │ ${'Value'.padEnd(valueWidth)} │`;\n\n const rows = configData.map(([key, value]) => `│ ${key?.padEnd(keyWidth)} │ ${value?.padEnd(valueWidth)} │`);\n\n return [horizontalLine, header, separator, ...rows, bottomLine].join('\\n');\n}\n","export interface MetaError extends Error {\n error: {\n message: string;\n type: string;\n code: number;\n error_data?: {\n messaging_product: 'whatsapp';\n details: string;\n };\n error_subcode?: number;\n fbtrace_id: string;\n };\n}\n\n/**\n * Determines if the error is a Meta API error response\n * @param error Any error object to check\n * @returns Type guard indicating if error is a Meta API error\n */\nexport function isMetaError(error: any): error is MetaError {\n return (\n error != null &&\n typeof error === 'object' &&\n 'error' in error &&\n typeof error.error === 'object' &&\n error.error != null &&\n 'message' in error.error &&\n typeof error.error.message === 'string' &&\n 'type' in error.error &&\n typeof error.error.type === 'string' &&\n 'code' in error.error &&\n typeof error.error.code === 'number' &&\n 'fbtrace_id' in error.error &&\n typeof error.error.fbtrace_id === 'string' &&\n (!('error_data' in error.error) ||\n (typeof error.error.error_data === 'object' &&\n error.error.error_data != null &&\n 'messaging_product' in error.error.error_data &&\n error.error.error_data.messaging_product === 'whatsapp' &&\n 'details' in error.error.error_data &&\n typeof error.error.error_data.details === 'string')) &&\n (!('error_subcode' in error.error) || typeof error.error.error_subcode === 'number')\n );\n}\n","import { Agent } from 'https';\n\nimport { HttpMethodsEnum } from '../../types/enums';\nimport { HttpsClientClass, HttpsClientResponseClass, ResponseHeaders, ResponseJSONBody } from '../../types/httpsClient';\nimport Logger from '../logger';\n\nconst LIB_NAME = 'HttpsClient';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class HttpsClient implements HttpsClientClass {\n agent: Agent;\n\n constructor() {\n this.agent = new Agent({ keepAlive: true });\n }\n\n clearSockets(): boolean {\n this.agent.destroy();\n return true;\n }\n\n async sendRequest(\n hostname: string,\n path: string,\n method: HttpMethodsEnum,\n headers: HeadersInit,\n timeout: number,\n body?: BodyInit | null,\n ): Promise<HttpsClientResponseClass> {\n const url = `https://${hostname}/${path}`;\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n try {\n const response = await fetch(url, {\n method,\n headers,\n body,\n signal: controller.signal,\n });\n LOGGER.log(`${method} : ${url} - ${JSON.stringify(response)}`);\n\n clearTimeout(timeoutId);\n return new HttpsClientResponse(response);\n } catch (error) {\n LOGGER.error(`${method} : ${url} - ${JSON.stringify(error)}`);\n throw error;\n }\n }\n}\n\nexport class HttpsClientResponse implements HttpsClientResponseClass {\n res: Response;\n respStatusCode: number;\n respHeaders: ResponseHeaders;\n\n constructor(resp: Response) {\n this.res = resp;\n this.respStatusCode = resp.status;\n this.respHeaders = Object.fromEntries(resp.headers.entries());\n }\n\n statusCode(): number {\n return this.respStatusCode;\n }\n\n headers(): ResponseHeaders {\n return this.respHeaders;\n }\n\n rawResponse(): Response {\n return this.res;\n }\n\n async json(): Promise<ResponseJSONBody> {\n try {\n return (await this.res.json()) as ResponseJSONBody;\n } catch (err) {\n // TODO Error Handling\n throw new Error('Failed to parse response body to JSON: ' + (err as Error).message);\n }\n }\n}\n","import type { HttpMethodsEnum } from '../../types/enums';\nimport type { RequesterClass } from '../../types/request';\nimport { isMetaError, MetaError } from '../isMetaError';\nimport Logger from '../logger';\nimport HttpsClient from './httpsClient';\n\nconst LIB_NAME = 'REQUESTER';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class Requester implements RequesterClass {\n client: Readonly<HttpsClient>;\n accessToken: Readonly<string>;\n phoneNumberId: Readonly<number>;\n businessAcctId: Readonly<string>;\n apiVersion: Readonly<string>;\n userAgent: Readonly<string>;\n host: Readonly<string>;\n protocol: Readonly<string> = 'https:';\n\n constructor(\n apiVersion: string,\n phoneNumberId: number,\n accessToken: string,\n businessAcctId: string,\n userAgent: string,\n ) {\n this.client = new HttpsClient();\n this.host = 'graph.facebook.com';\n this.apiVersion = apiVersion || '22';\n this.phoneNumberId = phoneNumberId;\n this.accessToken = accessToken;\n this.businessAcctId = businessAcctId;\n this.userAgent = userAgent;\n }\n\n buildHeader(contentType: string, additionalHeaders?: Record<string, string>): HeadersInit {\n const headers: HeadersInit = {\n Authorization: `Bearer ${this.accessToken}`,\n 'User-Agent': this.userAgent,\n };\n\n if (contentType !== 'multipart/form-data') {\n headers['Content-Type'] = contentType;\n }\n\n if (additionalHeaders) {\n Object.assign(headers, additionalHeaders);\n }\n\n return headers;\n }\n\n buildCAPIPath(endpoint: string): string {\n return `v${this.apiVersion}.0/${endpoint}`;\n }\n\n async sendRequest(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n body?: any,\n contentType: string = 'application/json',\n additionalHeaders?: Record<string, string>,\n ) {\n let effectiveContentType = contentType;\n\n if (body instanceof FormData) {\n effectiveContentType = 'multipart/form-data';\n } else if (typeof body === 'string' && body.startsWith('<?xml')) {\n effectiveContentType = 'application/xml';\n }\n\n const path = `${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(endpoint)}`;\n\n LOGGER.log(`${method} : ${path} (${effectiveContentType})`);\n\n try {\n const response = await this.client.sendRequest(\n this.host,\n this.buildCAPIPath(endpoint),\n method,\n this.buildHeader(effectiveContentType, additionalHeaders),\n timeout,\n method === 'POST' || method === 'PUT' ? body : undefined,\n );\n\n if (!response.rawResponse().ok) {\n const errorData = await response.json();\n if (isMetaError(errorData)) {\n throw errorData;\n }\n // If the error doesn't match Meta's format, create a generic MetaError\n throw {\n name: 'MetaError',\n message: 'Unknown error occurred',\n error: {\n message: errorData.message || 'Unknown error occurred',\n type: 'UnknownError',\n code: response.statusCode(),\n fbtrace_id: '',\n },\n } as MetaError;\n }\n\n return response;\n } catch (error) {\n if (isMetaError(error)) {\n throw error;\n }\n // Handle network errors or other unexpected errors\n throw {\n name: 'MetaError',\n message: error instanceof Error ? error.message : 'Network error occurred',\n error: {\n message: error instanceof Error ? error.message : 'Network error occurred',\n type: 'NetworkError',\n code: 500,\n fbtrace_id: '',\n },\n } as MetaError;\n }\n }\n\n async getJson<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n body?: any,\n additionalHeaders?: Record<string, string>,\n ): Promise<T> {\n const res = await this.sendRequest(method, endpoint, timeout, body, 'application/json', additionalHeaders);\n return (await res.json()) as T;\n }\n\n async sendFormData<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n formData: FormData,\n additionalHeaders?: Record<string, string>,\n ): Promise<T> {\n const res = await this.sendRequest(\n method,\n endpoint,\n timeout,\n formData,\n 'multipart/form-data',\n additionalHeaders,\n );\n return (await res.json()) as T;\n }\n\n async sendUrlEncodedForm<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n formData: Record<string, string>,\n additionalHeaders?: Record<string, string>,\n ): Promise<T> {\n const urlEncodedBody = new URLSearchParams(formData).toString();\n const res = await this.sendRequest(\n method,\n endpoint,\n timeout,\n urlEncodedBody,\n 'application/x-www-form-urlencoded',\n additionalHeaders,\n );\n return (await res.json()) as T;\n }\n}\n","import { readFileSync } from 'fs';\nimport { join } from 'path';\n\n/**\n * Get SDK version from package.json\n */\nexport function getVersion(): string {\n try {\n const packagePath = join(__dirname, '../../package.json');\n const packageJson = JSON.parse(readFileSync(packagePath, 'utf-8'));\n return packageJson.version;\n } catch (error) {\n return 'unknown';\n }\n}\n\n/**\n * Generate User-Agent string following official SDK pattern\n */\nexport function getUserAgent(): string {\n const version = getVersion();\n const nodeVersion = process.version;\n return `WhatsApp-Nodejs-SDK/${version} (Node.js ${nodeVersion})`;\n}\n","import type { WabaConfigType } from './config';\n\nexport declare class BaseClass {\n constructor(config: WabaConfigType);\n}\n\nimport { HttpMethodsEnum } from './enums';\nimport type { RequesterClass } from './request';\n\nexport class BaseAPI implements BaseClass {\n protected config: WabaConfigType;\n protected client: RequesterClass;\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n this.config = config;\n this.client = client;\n }\n\n protected sendJson<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any): Promise<T> {\n return this.client.getJson<T>(method, endpoint, timeout, body);\n }\n\n protected sendFormData<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any): Promise<T> {\n return this.client.sendFormData<T>(method, endpoint, timeout, body);\n }\n\n protected sendUrlEncodedForm<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n body?: any,\n ): Promise<T> {\n return this.client.sendUrlEncodedForm<T>(method, endpoint, timeout, body);\n }\n}\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../types/request';\nimport type { EncryptionClass, EncryptionPublicKeyResponse } from './types';\n\nexport default class EncryptionApi extends BaseAPI implements EncryptionClass {\n private readonly endpoint = 'whatsapp_business_encryption';\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n async getEncryptionPublicKey(): Promise<EncryptionPublicKeyResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async setEncryptionPublicKey(businessPublicKey: string): Promise<ResponseSuccess> {\n const formData = new FormData();\n formData.append('business_public_key', businessPublicKey);\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n formData,\n );\n }\n}\n","import EncryptionApi from './EncryptionApi';\nexport default EncryptionApi;\nexport { EncryptionApi };\nexport type { EncryptionClass, EncryptionPublicKeyResponse } from './types';\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../types/request';\n\nimport type * as flow from './types';\n\n/**\n * API for managing WhatsApp Flows.\n *\n * This API allows you to:\n * - List flows\n * - Create flows\n * - Get flow details and previews\n * - Update flow metadata and JSON\n * - Delete flows\n * - Publish and deprecate flows\n * - Migrate flows between WABAs\n * - Validate flow JSON\n */\nexport default class FlowApi extends BaseAPI implements flow.FlowClass {\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * List Flows\n *\n * @param wabaId - The WABA ID\n * @returns Promise with the list of flows\n */\n async listFlows(wabaId: string): Promise<flow.FlowsListResponse> {\n return this.sendJson(HttpMethodsEnum.Get, `/${wabaId}/flows`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n /**\n * Create Flow\n *\n * @param wabaId - The WABA ID\n * @param data - The flow data including name, categories, endpoint_uri, and optional clone_flow_id\n * @returns Promise with the created flow ID and validation errors if any\n */\n async createFlow(\n wabaId: string,\n data: {\n name: string;\n categories?: flow.FlowCategoryEnum[];\n endpoint_uri?: string;\n clone_flow_id?: string;\n flow_json?: string; // Flow JSON as a string\n publish?: boolean;\n },\n ): Promise<flow.CreateFlowResponse> {\n // The API expects application/json for this endpoint based on documentation examples\n // Let's ensure we send JSON, not FormData, unless specifically required by an endpoint variation.\n const payload = {\n name: data.name,\n categories: data.categories,\n ...(data.endpoint_uri && { endpoint_uri: data.endpoint_uri }),\n ...(data.clone_flow_id && { clone_flow_id: data.clone_flow_id }),\n ...(data.flow_json && { flow_json: data.flow_json }),\n ...(data.publish !== undefined && { publish: data.publish }),\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${wabaId}/flows`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(payload), // Send as JSON\n );\n }\n\n /**\n * Get Flow details\n *\n * @param flowId - The flow ID\n * @param fields - Optional fields to return (e.g., 'name,status,preview.invalidate(false)')\n * @param dateFormat - Optional date format\n * @returns Promise with the flow details or preview response\n */\n async getFlow(flowId: string, fields?: string, dateFormat?: string): Promise<flow.Flow | flow.FlowPreviewResponse> {\n const params = new URLSearchParams();\n if (fields) params.append('fields', fields);\n if (dateFormat) params.append('date_format', dateFormat);\n\n const queryString = params.toString() ? `?${params.toString()}` : '';\n return this.sendJson(\n HttpMethodsEnum.Get,\n `/${flowId}${queryString}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Get Flow Preview URL\n *\n * @param flowId - The flow ID\n * @param invalidate - Optional. If true, invalidates existing preview and generates a new one. Defaults to false.\n * @returns Promise with the flow preview details\n */\n async getFlowPreview(flowId: string, invalidate: boolean = false): Promise<flow.FlowPreviewResponse> {\n const fields = `preview.invalidate(${invalidate})`;\n // Type assertion needed as getFlow can return Flow or FlowPreviewResponse\n return this.getFlow(flowId, fields) as Promise<flow.FlowPreviewResponse>;\n }\n\n /**\n * Update Flow Metadata\n *\n * @param flowId - The flow ID\n * @param data - The flow metadata to update (name, categories, endpoint_uri, application_id)\n * @returns Promise with the success status\n */\n async updateFlowMetadata(\n flowId: string,\n data: {\n name?: string;\n categories?: flow.FlowCategoryEnum[];\n endpoint_uri?: string;\n application_id?: string;\n },\n ): Promise<ResponseSuccess> {\n // The API expects application/json for this endpoint based on documentation examples\n const payload = {\n ...(data.name && { name: data.name }),\n ...(data.categories && { categories: data.categories }),\n ...(data.endpoint_uri && { endpoint_uri: data.endpoint_uri }),\n ...(data.application_id && { application_id: data.application_id }),\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(payload), // Send as JSON\n );\n }\n\n /**\n * Delete Flow (only works if the Flow is in DRAFT status)\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async deleteFlow(flowId: string): Promise<ResponseSuccess> {\n return this.sendJson(HttpMethodsEnum.Delete, `/${flowId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n /**\n * List Assets (e.g., get Flow JSON download URL)\n *\n * @param flowId - The flow ID\n * @returns Promise with the list of assets\n */\n async listAssets(flowId: string): Promise<flow.FlowAssetsResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `/${flowId}/assets`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Update Flow JSON by uploading a file, buffer, JSON object, or Blob.\n *\n * @param flowId - The flow ID\n * @param data - Object containing the file data and optional name.\n * @param data.file - The Flow JSON content as a Buffer, JSON object, or Blob.\n * @param data.name - Optional name for the asset, defaults to 'flow.json'.\n * @returns Promise with the success status and validation errors, if any.\n */\n async updateFlowJson(\n flowId: string,\n data: {\n file: Blob | Buffer | object; // JSON object, Buffer, or Blob\n name?: string; // Default to \"flow.json\"\n },\n ): Promise<flow.UpdateFlowResponse> {\n const formData = new FormData();\n let fileContent: Blob;\n\n // Handle different input types for the file\n if (data.file instanceof Buffer) {\n // Buffer\n // Create a Blob from the Buffer and cast it to the global Blob type\n fileContent = new globalThis.Blob([data.file]);\n formData.append('file', fileContent as unknown as Blob);\n } else if (typeof data.file === 'object' && !(data.file instanceof Blob)) {\n // JSON object - stringify and create Blob\n try {\n // Create a Blob from the JSON string and cast it to the global Blob type\n fileContent = new globalThis.Blob([JSON.stringify(data.file, null, 2)], { type: 'application/json' });\n formData.append('file', fileContent as unknown as Blob);\n } catch (e) {\n throw new Error('Failed to stringify JSON object for Flow JSON update.');\n }\n } else if (data.file instanceof Blob) {\n // Blob (already in correct format)\n fileContent = data.file;\n formData.append('file', fileContent as unknown as Blob);\n } else {\n throw new Error('Invalid file type provided for Flow JSON update. Must be a Buffer, JSON object, or Blob.');\n }\n\n formData.append('asset_type', 'FLOW_JSON'); // Required by API\n formData.append('name', data.name || 'flow.json'); // Required by API\n\n return this.sendFormData(\n HttpMethodsEnum.Post,\n `/${flowId}/assets`,\n this.config[WabaConfigEnum.RequestTimeout],\n formData,\n );\n }\n\n /**\n * Validate Flow JSON by attempting an update without publishing.\n * This is a convenience method; the API doesn't have a dedicated validation endpoint.\n *\n * @param flowId - The ID of the Flow (must exist, can be in DRAFT status).\n * @param flowJsonData - The Flow JSON content as a file path (string), Buffer, JSON object, or Blob.\n * @returns Promise indicating if the JSON is valid and includes validation errors if any.\n */\n async validateFlowJson(\n flowId: string,\n flowJsonData: Blob | Buffer | object,\n ): Promise<flow.ValidateFlowJsonResponse> {\n try {\n const result = await this.updateFlowJson(flowId, {\n file: flowJsonData,\n });\n\n const isValid = !result.validation_errors || result.validation_errors.length === 0;\n\n const enhancedResponse = {\n ...result,\n valid: isValid,\n };\n\n return enhancedResponse;\n } catch (error) {\n throw error;\n }\n }\n\n /**\n * Publish Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async publishFlow(flowId: string): Promise<ResponseSuccess> {\n // This endpoint expects an empty JSON body or no body\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}/publish`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify({}), // Send empty JSON object\n );\n }\n\n /**\n * Deprecate Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async deprecateFlow(flowId: string): Promise<ResponseSuccess> {\n // This endpoint expects an empty JSON body or no body\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}/deprecate`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify({}), // Send empty JSON object\n );\n }\n\n /**\n * Migrate Flows between WABAs\n *\n * @param destinationWabaId - The destination WABA ID\n * @param data - The migration data including source_waba_id and optional source_flow_names\n * @returns Promise with migration results (successes and failures)\n */\n async migrateFlows(\n destinationWabaId: string,\n data: {\n source_waba_id: string;\n source_flow_names?: string[];\n },\n ): Promise<flow.FlowMigrationResponse> {\n // API documentation suggests this endpoint might expect application/json\n // Let's double-check or assume JSON based on typical Graph API patterns unless FormData is confirmed.\n // Assuming JSON for now:\n const payload = {\n source_waba_id: data.source_waba_id,\n ...(data.source_flow_names && { source_flow_names: data.source_flow_names }),\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${destinationWabaId}/migrate_flows`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(payload),\n );\n }\n}\n","import FlowApi from './FlowApi';\n\nexport default FlowApi;\nexport { FlowApi };\n\nexport { FlowTypeEnum } from './types';\n\nexport type {\n CreateFlowResponse,\n Flow,\n FlowActionEnum,\n FlowAssetsResponse,\n FlowCategoryEnum,\n FlowClass,\n FlowEndpointRequest,\n FlowEndpointResponse,\n FlowMigrationResponse,\n FlowPreviewResponse,\n FlowsListResponse,\n FlowStatusEnum,\n FlowType,\n FlowValidationError,\n UpdateFlowResponse,\n ValidateFlowJsonResponse,\n} from './types';\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../types/request';\n\nimport type * as media from './types';\n\n/**\n * API for managing WhatsApp Media.\n *\n * This API allows you to:\n * - Get media information by ID\n * - Upload media files\n * - Delete media files\n * - Download media files from URLs\n */\nexport default class MediaApi extends BaseAPI implements media.MediaClass {\n private readonly endpoint = 'media';\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * Retrieve media information by media ID.\n *\n * @param mediaId The media ID to retrieve information for\n * @param phone_number_id Optional phone number ID (defaults to configured one)\n * @returns Media information including URL, mime type, file size, etc.\n *\n * @example\n * const mediaInfo = await whatsappClient.media.getMediaById('media_id_123');\n */\n async getMediaById(mediaId: string, phone_number_id?: string): Promise<media.MediaResponse> {\n return this.sendJson(HttpMethodsEnum.Get, `${mediaId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n /**\n * Upload a media file to WhatsApp.\n *\n * @param file The file to upload\n * @param messagingProduct The messaging product (default: 'whatsapp')\n * @returns Upload response containing the media ID\n *\n * @example\n * const file = new File([buffer], 'image.jpg', { type: 'image/jpeg' });\n * const result = await whatsappClient.media.uploadMedia(file);\n */\n async uploadMedia(file: File, messagingProduct: string = 'whatsapp'): Promise<media.UploadMediaResponse> {\n const formData = new FormData();\n formData.append('file', file);\n formData.append('messaging_product', messagingProduct);\n formData.append('type', file.type);\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n formData,\n );\n }\n\n /**\n * Delete a media file.\n *\n * @param mediaId The media ID to delete\n * @param phone_number_id Optional phone number ID (defaults to configured one)\n * @returns Response indicating success or failure\n *\n * @example\n * await whatsappClient.media.deleteMedia('media_id_123');\n */\n async deleteMedia(mediaId: string, phone_number_id?: string): Promise<ResponseSuccess> {\n return this.sendJson(HttpMethodsEnum.Delete, `${mediaId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n /**\n * Download media from a URL.\n *\n * @param mediaUrl The URL to download media from\n * @returns Blob containing the media data\n *\n * @example\n * const blob = await whatsappClient.media.downloadMedia('https://...');\n */\n async downloadMedia(mediaUrl: string): Promise<Blob> {\n return this.sendJson(HttpMethodsEnum.Get, mediaUrl, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n}\n","import MediaApi from './MediaApi';\n\nexport default MediaApi;\n\nexport { MediaApi };\n\nexport type { MediaClass, MediaResponse, MediasResponse, UploadMediaResponse } from './types';\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport {\n type ComponentTypesEnum,\n HttpMethodsEnum,\n type InteractiveTypesEnum,\n MessageTypesEnum,\n WabaConfigEnum,\n} from '../../types/enums';\nimport type { RequesterClass } from '../../types/request';\n\nimport type * as m from './types';\n\n/**\n * Maps each message type to its appropriate payload type\n */\nexport type MessagePayloadType<T extends MessageTypesEnum> = T extends MessageTypesEnum.Audio\n ? m.AudioMediaObject\n : T extends MessageTypesEnum.Contacts\n ? [m.ContactObject]\n : T extends MessageTypesEnum.Document\n ? m.DocumentMediaObject\n : T extends MessageTypesEnum.Image\n ? m.ImageMediaObject\n : T extends MessageTypesEnum.Interactive\n ? m.InteractiveObject\n : T extends MessageTypesEnum.Location\n ? m.LocationObject\n : T extends MessageTypesEnum.Template\n ? m.MessageTemplateObject<ComponentTypesEnum>\n : T extends MessageTypesEnum.Sticker\n ? m.StickerMediaObject\n : T extends MessageTypesEnum.Text\n ? m.TextObject\n : T extends MessageTypesEnum.Video\n ? m.VideoMediaObject\n : T extends MessageTypesEnum.Reaction\n ? { message_id: string; emoji: string }\n : never;\n\nexport default class MessagesApi extends BaseAPI implements m.MessagesClass {\n private readonly commonMethod = HttpMethodsEnum.Post;\n private readonly commonEndpoint = 'messages';\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * Builds the request body for WhatsApp API messages\n * @param type The type of message to send\n * @param payload The message payload object\n * @param to The recipient's phone number\n * @param replyMessageId Optional message ID to reply to\n * @returns The formatted request body\n */\n bodyBuilder<T extends MessageTypesEnum>(\n type: T,\n payload: MessagePayloadType<T>,\n to: string,\n replyMessageId?: string,\n ) {\n const body: m.MessageRequestBody<T> = {\n messaging_product: 'whatsapp',\n recipient_type: 'individual',\n to,\n type,\n [type]: payload,\n };\n\n if (replyMessageId) body['context'] = { message_id: replyMessageId };\n\n return body;\n }\n\n /**\n * Sends a request to the WhatsApp API\n * @param body The request body to send\n * @returns Promise with the API response\n */\n private send(body: BodyInit | null): Promise<m.MessagesResponse> {\n return this.sendJson(\n this.commonMethod,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.commonEndpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n body,\n );\n }\n\n /**\n * Sends an audio message via WhatsApp\n * @param params The audio message parameter object\n * @returns Promise with the message response\n */\n async audio(params: m.MessageRequestParams<m.AudioMediaObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Audio, body, to, replyMessageId)));\n }\n\n /**\n * Sends a contact card via WhatsApp\n * @param params The contact message parameter object\n * @returns Promise with the message response\n */\n async contacts(params: m.MessageRequestParams<[m.ContactObject]>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Contacts, body, to, replyMessageId)));\n }\n\n /**\n * Sends a document via WhatsApp\n * @param params The document message parameter object\n * @returns Promise with the message response\n */\n async document(params: m.MessageRequestParams<m.DocumentMediaObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Document, body, to, replyMessageId)));\n }\n\n /**\n * Sends an image via WhatsApp\n * @param params The image message parameter object\n * @returns Promise with the message response\n */\n async image(params: m.MessageRequestParams<m.ImageMediaObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Image, body, to, replyMessageId)));\n }\n\n /**\n * Sends an interactive message via WhatsApp\n * @param params The interactive message parameter object\n * @returns Promise with the message response\n */\n async interactive(params: m.MessageRequestParams<m.InteractiveObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Interactive, body, to, replyMessageId)));\n }\n\n /**\n * Sends a location via WhatsApp\n * @param params The location message parameter object\n * @returns Promise with the message response\n */\n async location(params: m.MessageRequestParams<m.LocationObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Location, body, to, replyMessageId)));\n }\n\n /**\n * Sends a sticker via WhatsApp\n * @param params The sticker message parameter object\n * @returns Promise with the message response\n */\n async sticker(params: m.MessageRequestParams<m.StickerMediaObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Sticker, body, to, replyMessageId)));\n }\n\n /**\n * Sends a template message via WhatsApp\n * @param params The template message parameter object\n * @returns Promise with the message response\n */\n async template(\n params: m.MessageRequestParams<m.MessageTemplateObject<ComponentTypesEnum>>,\n ): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Template, body, to, replyMessageId)));\n }\n\n /**\n * Sends a text message via WhatsApp\n * @param params The text message parameter object\n * @returns Promise with the message response\n */\n async text(params: m.TextMessageParams): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId, previewUrl } = params;\n\n // Handle both string and TextObject types\n const textPayload: m.TextObject =\n typeof body === 'string'\n ? { body, preview_url: previewUrl ?? true }\n : { ...body, preview_url: previewUrl ?? body.preview_url ?? true };\n\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Text, textPayload, to, replyMessageId)));\n }\n\n /**\n * Sends a video message via WhatsApp\n * @param params The video message parameter object\n * @returns Promise with the message response\n */\n async video(params: m.MessageRequestParams<m.VideoMediaObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Video, body, to, replyMessageId)));\n }\n\n /**\n * Updates message status (mark as read, etc.)\n * @param params The status update parameters\n * @returns Promise with the API response\n */\n async status(params: m.StatusParams): Promise<m.MessagesResponse> {\n const body = {\n messaging_product: 'whatsapp',\n status: params.status,\n message_id: params.messageId,\n ...(params.typingIndicator && { typing_indicator: params.typingIndicator }),\n };\n\n return this.send(JSON.stringify(body));\n }\n\n /**\n * Marks a message as read\n * @param params Object containing messageId\n * @returns Promise with the API response\n */\n async markAsRead(params: { messageId: string }): Promise<m.MessagesResponse> {\n return this.status({\n status: 'read',\n messageId: params.messageId,\n });\n }\n\n /**\n * Shows typing indicator\n * @param params Object containing messageId\n * @returns Promise with the API response\n */\n async showTypingIndicator(params: { messageId: string }): Promise<m.MessagesResponse> {\n return this.status({\n status: 'read',\n messageId: params.messageId,\n typingIndicator: { type: 'text' },\n });\n }\n\n /**\n * Sends a list interactive message\n * @param params The list interactive message parameters\n * @returns Promise with the message response\n */\n async interactiveList(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.List }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive(params);\n }\n\n /**\n * Sends a CTA URL interactive message\n * @param params The CTA URL interactive message parameters\n * @returns Promise with the message response\n */\n async interactiveCtaUrl(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.CtaUrl }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive(params);\n }\n\n /**\n * Sends a location request interactive message\n * @param params The location request interactive message parameters\n * @returns Promise with the message response\n */\n async interactiveLocationRequest(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.LocationRequest }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive(params);\n }\n\n /**\n * Sends an address message interactive message\n * @param params The address message interactive message parameters\n * @returns Promise with the message response\n */\n async interactiveAddressMessage(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.AddressMessage }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive(params);\n }\n\n /**\n * Sends a reply buttons interactive message\n * @param params The reply buttons interactive message parameters\n * @returns Promise with the message response\n */\n async interactiveReplyButtons(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.Button }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive(params);\n }\n\n /**\n * Sends a flow interactive message\n * @param params The flow interactive message parameters\n * @returns Promise with the message response\n */\n async interactiveFlow(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.Flow }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive(params);\n }\n\n /**\n * Sends a reaction to a message\n * @param params The reaction parameters\n * @returns Promise with the message response\n */\n async reaction(params: m.ReactionParams): Promise<m.MessagesResponse> {\n const reactionPayload = {\n message_id: params.messageId,\n emoji: params.emoji,\n };\n\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Reaction, reactionPayload, params.to)));\n }\n}\n","import MessageApi from './MessageApi';\n\nexport default MessageApi;\n\nexport { MessageApi };\n\nexport type {\n AudioMediaObject,\n ContactObject,\n DocumentMediaObject,\n ImageMediaObject,\n InteractiveObject,\n LocationObject,\n MessageRequestParams,\n MessageTemplateObject,\n MessagesResponse,\n ReactionParams,\n StatusParams,\n StickerMediaObject,\n TextMessageParams,\n TextObject,\n VideoMediaObject,\n} from './types';\n","export const objectToQueryString = (params: Record<string, any>): string => {\n if (!params || Object.keys(params).length === 0) {\n return '';\n }\n\n const queryParts: string[] = [];\n\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined) {\n const encodedKey = encodeURIComponent(key);\n const encodedValue = encodeURIComponent(String(value));\n queryParts.push(`${encodedKey}=${encodedValue}`);\n }\n }\n\n return queryParts.length > 0 ? `?${queryParts.join('&')}` : '';\n};\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../types/request';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\n\nimport type * as phoneNumber from './types';\n\n/**\n * API for managing WhatsApp Phone Numb ers.\n *\n * This API allows you to:\n * - Get phone number information by ID\n * - Get all phone numbers for a business account\n * - Request verification codes for phone numbers\n * - Verify phone numbers with codes\n */\nexport default class PhoneNumberApi extends BaseAPI implements phoneNumber.PhoneNumberClass {\n private readonly endpoint = 'phone_numbers';\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * Get phone number information by ID.\n *\n * @param fields Optional comma-separated list of fields to include in the response\n * @returns Phone number information including verification status, quality rating, etc.\n *\n * @example\n * const phoneNumber = await whatsappClient.phoneNumber.getPhoneNumberById();\n * const phoneNumberWithFields = await whatsappClient.phoneNumber.getPhoneNumberById('display_phone_number,verified_name');\n */\n async getPhoneNumberById(fields?: string): Promise<phoneNumber.PhoneNumberResponse> {\n const queryParams = fields ? objectToQueryString({ fields }) : '';\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}${queryParams}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Get all phone numbers for the business account.\n *\n * @returns List of phone numbers associated with the business account\n *\n * @example\n * const phoneNumbers = await whatsappClient.phoneNumber.getPhoneNumbers();\n */\n async getPhoneNumbers(): Promise<phoneNumber.PhoneNumbersResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.BusinessAcctId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Request a verification code for the phone number.\n *\n * @param request Verification code request containing method and language\n * @returns Response indicating success or failure\n *\n * @example\n * await whatsappClient.phoneNumber.requestVerificationCode({\n * code_method: 'SMS',\n * language: 'en_US'\n * });\n */\n async requestVerificationCode(request: phoneNumber.RequestVerificationCodeRequest): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/request_code`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n /**\n * Verify the phone number with the received code.\n *\n * @param request Verification request containing the code\n * @returns Response indicating success or failure\n *\n * @example\n * await whatsappClient.phoneNumber.verifyCode({\n * code: '123456'\n * });\n */\n async verifyCode(request: phoneNumber.VerifyCodeRequest): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/verify_code`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n}\n","import PhoneNumberApi from './PhoneNumberApi';\n\nexport default PhoneNumberApi;\n\nexport { PhoneNumberApi };\n\nexport type {\n AccountMode,\n CodeVerificationStatus,\n Cursors,\n HealthStatus,\n HealthStatusEntity,\n MessagingLimitTier,\n PhoneNumberClass,\n PhoneNumberResponse,\n PhoneNumbersResponse,\n PlatformType,\n QualityRating,\n QualityScore,\n RequestVerificationCodeRequest,\n Throughput,\n ThroughputLevel,\n TwoStepVerificationParams,\n VerifyCodeRequest,\n} from './types';\n","export function buildFieldsQueryString(fields?: string[] | string): string {\n if (!fields) return '';\n\n let fieldParams = '';\n\n if (Array.isArray(fields)) {\n fieldParams = fields.join(',');\n } else if (typeof fields === 'string') {\n fieldParams = fields;\n } else {\n fieldParams = Object.entries(fields)\n .filter(([_, value]) => value)\n .map(([key]) => key)\n .join(',');\n }\n\n return fieldParams ? `?fields=${fieldParams}` : '';\n}\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../types/request';\nimport { buildFieldsQueryString } from '../../utils/buildFieldsQueryString';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\n\nimport type * as bp from './types';\n\n/**\n * API for managing WhatsApp Business Profiles and profile pictures.\n *\n * This API allows you to:\n * - Get business profile information\n * - Update business profile details\n * - Upload profile pictures using a three-step process:\n * 1. Create an upload session\n * 2. Upload the image binary data\n * 3. Get the upload handle to use when updating the profile\n */\nexport default class BusinessProfileApi extends BaseAPI implements bp.BusinessProfileClass {\n private readonly endpoint = 'whatsapp_business_profile';\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * Get your business profile information.\n *\n * Use this method to retrieve details about your WhatsApp business profile, including\n * about text, address, description, email, profile picture URL, websites, and vertical.\n *\n * @param fields Fields to be returned in the response. If not specified, all fields will be returned.\n * Possible values: about, address, description, email, profile_picture_url, websites, vertical\n * @returns The business profile information.\n *\n * @example\n * // Get all business profile fields\n * const profile = await whatsappClient.businessProfile.getBusinessProfile();\n *\n * // Get specific business profile fields\n * const profile = await whatsappClient.businessProfile.getBusinessProfile('about,address,email');\n *\n * // Using the BusinessProfileFieldsParam type\n * const profile = await whatsappClient.businessProfile.getBusinessProfile(['about', 'address', 'email']);\n */\n async getBusinessProfile(fields?: bp.BusinessProfileFieldsParam): Promise<bp.BusinessProfileResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}${buildFieldsQueryString(fields)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Update your business profile.\n *\n * Use this method to update one or more fields of your WhatsApp business profile.\n *\n * @param updateRequest The request object containing the fields to update.\n * - messaging_product: Required. Always set to \"whatsapp\".\n * - about: Optional. Business's About text (1-139 characters).\n * - address: Optional. Business address (max 256 characters).\n * - description: Optional. Business description (max 512 characters).\n * - vertical: Optional. Business category (use BusinessVerticalEnum for type safety).\n * - email: Optional. Contact email (valid format, max 128 characters).\n * - websites: Optional. Up to 2 URLs (max 256 characters each).\n * - profile_picture_handle: Optional. Handle from upload process.\n * @returns Response indicating success or failure.\n *\n * @example\n * // Update business profile with multiple fields including vertical using enum\n * await whatsappClient.businessProfile.updateBusinessProfile({\n * messaging_product: 'whatsapp',\n * about: 'We provide excellent service',\n * email: 'contact@example.com',\n * websites: ['https://example.com'],\n * vertical: BusinessVerticalEnum.RETAIL\n * });\n */\n async updateBusinessProfile(updateRequest: bp.UpdateBusinessProfileRequest): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(updateRequest),\n );\n }\n\n /**\n * Create an upload session for a profile picture.\n *\n * This is the first step in the profile picture upload process.\n *\n * @param fileLength Length of the file to be uploaded in bytes.\n * @param fileType MIME type of the file (e.g., 'image/jpeg').\n * @param fileName Name of the file with extension.\n * @returns Response containing the upload session ID needed for the next step.\n *\n * @example\n * // Create upload session for profile picture\n * const session = await whatsappClient.businessProfile.createUploadSession(\n * fileBuffer.length,\n * 'image/jpeg',\n * 'profile.jpg'\n * );\n * const uploadSessionId = session.upload_session_id;\n */\n async createUploadSession(\n fileLength: number,\n fileType: string,\n fileName: string,\n ): Promise<bp.UploadSessionResponse> {\n const queryParams = objectToQueryString({\n file_length: fileLength,\n file_type: fileType,\n file_name: fileName,\n });\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `app/uploads/${queryParams}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Upload media file to the upload session.\n *\n * This is the second step in the profile picture upload process.\n * Upload the binary content of the file to the previously created upload session.\n *\n * @param uploadId The upload session ID from createUploadSession response.\n * @param file The binary data of the file (Buffer).\n * @returns Response indicating success or failure.\n *\n * @example\n * // Upload the actual file content\n * await whatsappClient.businessProfile.uploadMedia(\n * uploadSessionId,\n * fileBuffer\n * );\n */\n async uploadMedia(uploadId: string, file: Buffer): Promise<bp.UploadBusinessProfileResponse> {\n return this.sendJson(HttpMethodsEnum.Post, `${uploadId}`, this.config[WabaConfigEnum.RequestTimeout], file);\n }\n\n /**\n * Get the upload handle information.\n *\n * This is the third step in the profile picture upload process.\n * After uploading the file, get the handle to use when updating the profile.\n *\n * @param uploadId The upload session ID from createUploadSession response.\n * @returns Response containing the upload handle information.\n *\n * @example\n * // Complete profile picture update process\n * // 1. Create upload session\n * const session = await whatsappClient.businessProfile.createUploadSession(\n * fileBuffer.length, 'image/jpeg', 'profile.jpg'\n * );\n *\n * // 2. Upload the image data\n * await whatsappClient.businessProfile.uploadMedia(\n * session.upload_session_id, fileBuffer\n * );\n *\n * // 3. Get the handle for the uploaded file\n * const handleInfo = await whatsappClient.businessProfile.getUploadHandle(\n * session.upload_session_id\n * );\n *\n * // 4. Update profile with new picture and business information\n * await whatsappClient.businessProfile.updateBusinessProfile({\n * messaging_product: 'whatsapp',\n * profile_picture_handle: handleInfo.handle,\n * vertical: BusinessVerticalEnum.RESTAURANT,\n * about: 'Delicious food served daily'\n * });\n */\n async getUploadHandle(uploadId: string): Promise<bp.UploadHandle> {\n return this.sendJson(HttpMethodsEnum.Get, `${uploadId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n}\n","import BusinessProfileApi from './BusinessProfileApi';\n\nexport default BusinessProfileApi;\n\nexport { BusinessProfileApi };\n\nexport type {\n BusinessProfileClass,\n BusinessProfileData,\n BusinessProfileField,\n BusinessProfileFieldsParam,\n BusinessProfileResponse,\n CreateUploadSessionParams,\n GetUploadHandleParams,\n UpdateBusinessProfileRequest,\n UploadBusinessProfileResponse,\n UploadHandle,\n UploadMediaParams,\n UploadSession,\n UploadSessionResponse,\n} from './types';\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../types/request';\n\nimport type * as qrCode from './types';\n\n/**\n * API for managing WhatsApp QR Codes.\n *\n * This API allows you to:\n * - Create QR codes with prefilled messages\n * - Get all QR codes\n * - Get specific QR code details\n * - Update QR code messages\n * - Delete QR codes\n */\nexport default class QrCodeApi extends BaseAPI implements qrCode.QrCodeClass {\n private readonly endpoint = 'message_qrdls';\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * Create a new QR code with a prefilled message.\n *\n * @param request The QR code creation request\n * @returns QR code information including code, deep link URL, and optional image URL\n *\n * @example\n * const qrCode = await whatsappClient.qrCode.createQrCode({\n * prefilled_message: 'Hello from WhatsApp!',\n * generate_qr_image: 'PNG'\n * });\n */\n async createQrCode(request: qrCode.CreateQrCodeRequest): Promise<qrCode.QrCodeResponse> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n /**\n * Get all QR codes for the current phone number.\n *\n * @returns List of all QR codes\n *\n * @example\n * const qrCodes = await whatsappClient.qrCode.getQrCodes();\n */\n async getQrCodes(): Promise<qrCode.QrCodesResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Get a specific QR code by ID.\n *\n * @param qrCodeId The QR code ID to retrieve\n * @returns QR code information\n *\n * @example\n * const qrCode = await whatsappClient.qrCode.getQrCode('qr_code_123');\n */\n async getQrCode(qrCodeId: string): Promise<qrCode.QrCodeResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}/${qrCodeId}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Update an existing QR code's prefilled message.\n *\n * @param request The QR code update request containing code and new message\n * @returns Updated QR code information\n *\n * @example\n * const updatedQrCode = await whatsappClient.qrCode.updateQrCode({\n * code: 'existing_qr_code',\n * prefilled_message: 'Updated message!'\n * });\n */\n async updateQrCode(request: qrCode.UpdateQrCodeRequest): Promise<qrCode.QrCodeResponse> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n /**\n * Delete a QR code.\n *\n * @param qrCodeId The QR code ID to delete\n * @returns Response indicating success or failure\n *\n * @example\n * await whatsappClient.qrCode.deleteQrCode('qr_code_123');\n */\n async deleteQrCode(qrCodeId: string): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Delete,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}/${qrCodeId}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n}\n","import QrCodeApi from './QrCodeApi';\n\nexport default QrCodeApi;\n\nexport { QrCodeApi };\n\nexport type { CreateQrCodeRequest, QrCodeClass, QrCodeResponse, QrCodesResponse, UpdateQrCodeRequest } from './types';\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { DataLocalizationRegionEnum, HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../types/request';\n\nimport type * as registration from './types';\n\n/**\n * API for managing WhatsApp Business Account registration.\n *\n * This API allows you to:\n * - Register a WhatsApp Business Account with a PIN\n * - Deregister a WhatsApp Business Account\n */\nexport default class RegistrationApi extends BaseAPI implements registration.RegistrationClass {\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * Register a WhatsApp Business Account using a PIN.\n *\n * @param pin The registration PIN received via SMS or voice call\n * @param dataLocalizationRegion Optional data localization region\n * @returns Response indicating success or failure\n *\n * @example\n * await whatsappClient.registration.register('123456', DataLocalizationRegionEnum.Asia);\n */\n async register(pin: string, dataLocalizationRegion?: DataLocalizationRegionEnum): Promise<ResponseSuccess> {\n const body: registration.RegistrationRequest = {\n messaging_product: 'whatsapp',\n pin,\n ...(dataLocalizationRegion && { data_localization_region: dataLocalizationRegion }),\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/register`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Deregister a WhatsApp Business Account.\n *\n * @returns Response indicating success or failure\n *\n * @example\n * await whatsappClient.registration.deregister();\n */\n async deregister(): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/deregister`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n}\n","import RegistrationApi from './RegistrationApi';\n\nexport default RegistrationApi;\n\nexport { RegistrationApi };\n\nexport type { RegistrationClass, RegistrationRequest } from './types';\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponsePagination, ResponseSuccess } from '../../types/request';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\nimport type {\n TemplateClass,\n TemplateDeleteParams,\n TemplateGetParams,\n TemplateRequestBody,\n TemplateResponse,\n} from './types';\n\nexport default class TemplateApi extends BaseAPI implements TemplateClass {\n private readonly endpoint = 'message_templates';\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n async getTemplate(templateId: string): Promise<TemplateResponse> {\n return this.sendJson(HttpMethodsEnum.Get, `${templateId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n async updateTemplate(templateId: string, template: Partial<TemplateRequestBody>): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${templateId}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(template),\n );\n }\n\n async getTemplates(params?: TemplateGetParams): Promise<ResponsePagination<TemplateResponse>> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.BusinessAcctId]}/${this.endpoint}${objectToQueryString(params ?? {})}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async createTemplate(template: TemplateRequestBody): Promise<TemplateResponse> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.BusinessAcctId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(template),\n );\n }\n\n async deleteTemplate(params: TemplateDeleteParams): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Delete,\n `${this.config[WabaConfigEnum.BusinessAcctId]}/${this.endpoint}${objectToQueryString(params)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n}\n","import { CategoryEnum } from '../../../types/enums';\nimport type {\n ComponentTypes,\n MediaCarouselCard,\n ProductCarouselCard,\n TemplateBody,\n TemplateButton,\n TemplateButtons,\n TemplateFooter,\n TemplateHeader,\n TemplateRequestBody,\n} from '../types';\nimport type {\n AuthenticationTemplateOptions,\n BodyOptions,\n ButtonOptions,\n CatalogTemplateOptions,\n CouponTemplateOptions,\n FooterOptions,\n HeaderOptions,\n LimitedTimeOfferTemplateOptions,\n MediaCardCarouselTemplateOptions,\n MPMTemplateOptions,\n OTPTemplateOptions,\n ProductCardCarouselTemplateOptions,\n SPMTemplateOptions,\n TemplateOptions,\n TemplateParameter,\n} from '../types';\n\n// Helper function to create header component\nfunction createHeader(options: HeaderOptions): TemplateHeader {\n const header: TemplateHeader = {\n type: 'HEADER',\n format: options.format,\n };\n\n if (options.text) {\n header.text = options.text;\n }\n\n if (options.example) {\n header.example = options.example;\n }\n\n return header;\n}\n\n// Helper function to create body component\nfunction createBody(options: BodyOptions): TemplateBody {\n const body: TemplateBody = {\n type: 'BODY',\n text: options.text,\n };\n\n if (options.example) {\n body.example = options.example;\n }\n\n return body;\n}\n\n// Helper function to create footer component\nfunction createFooter(options: FooterOptions): TemplateFooter {\n return {\n type: 'FOOTER',\n text: options.text,\n };\n}\n\n// Helper function to create buttons\nfunction createButtons(options: ButtonOptions): ComponentTypes[] {\n const buttons: TemplateButton[] = [];\n\n if (options.phone_number) {\n buttons.push({\n type: 'PHONE_NUMBER',\n text: options.phone_number.text,\n phone_number: options.phone_number.phone_number,\n });\n }\n\n if (options.url) {\n const urlButton: any = {\n type: 'URL',\n text: options.url.text,\n url: options.url.url,\n };\n if (options.url.example) {\n urlButton.example = [options.url.example];\n }\n buttons.push(urlButton);\n }\n\n if (options.quick_reply) {\n options.quick_reply.forEach((qr) => {\n buttons.push({\n type: 'QUICK_REPLY',\n text: qr.text,\n });\n });\n }\n\n if (options.copy_code) {\n buttons.push({\n type: 'COPY_CODE',\n example: options.copy_code.example,\n });\n }\n\n if (options.flow) {\n const flowButton: any = {\n type: 'FLOW',\n text: options.flow.text,\n };\n if (options.flow.flow_id) flowButton.flow_id = options.flow.flow_id;\n if (options.flow.flow_name) flowButton.flow_name = options.flow.flow_name;\n if (options.flow.flow_json) flowButton.flow_json = options.flow.flow_json;\n if (options.flow.flow_action) flowButton.flow_action = options.flow.flow_action;\n if (options.flow.navigate_screen) flowButton.navigate_screen = options.flow.navigate_screen;\n buttons.push(flowButton);\n }\n\n if (options.mpm) {\n buttons.push({ type: 'MPM' });\n }\n\n if (options.otp) {\n buttons.push({ type: 'OTP' });\n }\n\n if (options.spm) {\n buttons.push({ type: 'SPM' });\n }\n\n return buttons.length > 0\n ? [\n {\n type: 'BUTTONS',\n buttons: buttons,\n },\n ]\n : [];\n}\n\n// Helper function to format parameter examples\nfunction formatParameterExamples(parameters: TemplateParameter[]): string[] {\n return parameters.map((param) => {\n switch (param.type) {\n case 'text':\n return param.value;\n case 'currency':\n return param.fallback_value;\n case 'date_time':\n return param.fallback_value;\n case 'image':\n case 'video':\n case 'document':\n return param.handle || param.link || '';\n case 'location':\n return param.name || '';\n case 'product':\n return param.product_retailer_id;\n default:\n return '';\n }\n });\n}\n\n// Generic template factory\nexport function createTemplate(options: TemplateOptions): TemplateRequestBody {\n const components: ComponentTypes[] = [];\n\n if (options.header) {\n components.push(createHeader(options.header));\n }\n\n if (options.body) {\n components.push(createBody(options.body));\n }\n\n if (options.footer) {\n components.push(createFooter(options.footer));\n }\n\n if (options.buttons) {\n components.push(...createButtons(options.buttons));\n }\n\n if (options.carousel) {\n // Handle carousel components\n const carouselComponents: ComponentTypes[] = [];\n options.carousel.cards.forEach((card, index) => {\n if (card.image || card.video || card.product) {\n const format = card.image ? 'IMAGE' : card.video ? 'VIDEO' : 'DOCUMENT';\n const handle = card.image || card.video || card.product || '';\n carouselComponents.push({\n type: 'HEADER',\n format: format,\n example: {\n header_handle: [handle],\n },\n });\n }\n if (card.body) {\n carouselComponents.push({\n type: 'BODY',\n text: card.body,\n example: card.bodyParameters\n ? {\n body_text: [formatParameterExamples(card.bodyParameters)],\n }\n : undefined,\n });\n }\n if (card.buttons) {\n carouselComponents.push(...createButtons(card.buttons));\n }\n });\n components.push(...carouselComponents);\n }\n\n if (options.limitedTimeOffer) {\n components.push({\n type: 'LIMITED_TIME_OFFER',\n limited_time_offer: {\n expiration_time_ms: options.limitedTimeOffer.expiration_time_ms,\n },\n });\n }\n\n return {\n name: options.name,\n language: options.language,\n category: options.category,\n components: components.length > 0 ? components : undefined,\n };\n}\n\n// OTP Template Factory\nexport function createOTPTemplate(options: OTPTemplateOptions): TemplateRequestBody {\n const components: ComponentTypes[] = [];\n\n // Add security recommendation if requested\n let bodyText = '*{{1}}* is your verification code.';\n if (options.add_security_recommendation) {\n bodyText += ' For your security, do not share this code.';\n }\n if (options.code_expiration_minutes) {\n bodyText += ` This code expires in ${options.code_expiration_minutes} minutes.`;\n }\n\n components.push({\n type: 'BODY',\n text: bodyText,\n example: {\n body_text: [['123456']], // Example OTP code\n },\n });\n\n // Add OTP button\n components.push({\n type: 'BUTTONS',\n buttons: [{ type: 'OTP' }],\n });\n\n return {\n name: options.name,\n language: options.language,\n category: CategoryEnum.Authentication,\n components,\n };\n}\n\n// Authentication Template Factory\nexport function createAuthenticationTemplate(options: AuthenticationTemplateOptions): TemplateRequestBody {\n const components: ComponentTypes[] = [];\n\n // Add security message\n let bodyText = 'Your security code is *{{1}}*.';\n if (options.add_security_recommendation) {\n bodyText += ' Do not share this code with anyone.';\n }\n if (options.code_expiration_minutes) {\n bodyText += ` This code expires in ${options.code_expiration_minutes} minutes.`;\n }\n\n components.push({\n type: 'BODY',\n text: bodyText,\n example: {\n body_text: [['ABCD1234']], // Example auth code\n },\n });\n\n // Add copy code button if requested\n if (options.copy_code_button) {\n components.push({\n type: 'BUTTONS',\n buttons: [\n {\n type: 'COPY_CODE',\n example: 'ABCD1234',\n },\n ],\n });\n }\n\n return {\n name: options.name,\n language: options.language,\n category: CategoryEnum.Authentication,\n components,\n };\n}\n\n// Catalog Template Factory\nexport function createCatalogTemplate(options: CatalogTemplateOptions): TemplateRequestBody {\n const components: ComponentTypes[] = [];\n\n if (options.header) {\n components.push(createHeader({ ...options.header, format: 'TEXT' }));\n }\n\n components.push(createBody(options.body));\n\n if (options.footer) {\n components.push(createFooter(options.footer));\n }\n\n // Add catalog button\n components.push({\n type: 'BUTTONS',\n buttons: [\n {\n type: 'CATALOG',\n action: {\n thumbnail_product_retailer_id: options.thumbnail_product_retailer_id,\n },\n },\n ],\n });\n\n return {\n name: options.name,\n language: options.language,\n category: CategoryEnum.Marketing,\n components,\n };\n}\n\n// Coupon Template Factory\nexport function createCouponTemplate(options: CouponTemplateOptions): TemplateRequestBody {\n const components: ComponentTypes[] = [];\n\n if (options.header) {\n components.push(createHeader({ ...options.header, format: 'TEXT' }));\n }\n\n components.push(createBody(options.body));\n\n if (options.footer) {\n components.push(createFooter(options.footer));\n }\n\n // Add copy code button\n components.push({\n type: 'BUTTONS',\n buttons: [\n {\n type: 'COPY_CODE',\n example: options.coupon_code,\n },\n ],\n });\n\n return {\n name: options.name,\n language: options.language,\n category: CategoryEnum.Marketing,\n components,\n };\n}\n\n// Limited Time Offer Template Factory\nexport function createLimitedTimeOfferTemplate(options: LimitedTimeOfferTemplateOptions): TemplateRequestBody {\n const components: ComponentTypes[] = [];\n\n // Add limited time offer component first\n components.push({\n type: 'LIMITED_TIME_OFFER',\n limited_time_offer: {\n expiration_time_ms: options.expiration_time_ms,\n },\n });\n\n if (options.header) {\n components.push(createHeader({ ...options.header, format: 'TEXT' }));\n }\n\n components.push(createBody(options.body));\n\n if (options.footer) {\n components.push(createFooter(options.footer));\n }\n\n return {\n name: options.name,\n language: options.language,\n category: CategoryEnum.Marketing,\n components,\n };\n}\n\n// Media Card Carousel Template Factory\nexport function createMediaCardCarouselTemplate(options: MediaCardCarouselTemplateOptions): TemplateRequestBody {\n const components: ComponentTypes[] = [];\n\n // Add carousel component\n const carouselCards: MediaCarouselCard[] = [];\n options.cards.forEach((card, index) => {\n const cardComponents: (TemplateHeader | TemplateBody | TemplateButtons)[] = [];\n\n // Add header (media)\n cardComponents.push({\n type: 'HEADER' as const,\n format: card.header.format,\n example: card.header.example,\n });\n\n // Add body\n cardComponents.push(createBody(card.body));\n\n // Add buttons if any\n if (card.buttons) {\n cardComponents.push(...(createButtons(card.buttons) as TemplateButtons[]));\n }\n\n carouselCards.push({\n card_index: index,\n components: cardComponents,\n });\n });\n\n components.push({\n type: 'CAROUSEL',\n cards: carouselCards,\n });\n\n return {\n name: options.name,\n language: options.language,\n category: CategoryEnum.Marketing,\n components,\n };\n}\n\n// MPM (Multi-Product Message) Template Factory\nexport function createMPMTemplate(options: MPMTemplateOptions): TemplateRequestBody {\n const components: ComponentTypes[] = [];\n\n if (options.header) {\n components.push(createHeader({ ...options.header, format: 'TEXT' }));\n }\n\n components.push(createBody(options.body));\n\n if (options.footer) {\n components.push(createFooter(options.footer));\n }\n\n // Add MPM button\n components.push({\n type: 'BUTTONS',\n buttons: [\n {\n type: 'MPM',\n action: {\n thumbnail_product_retailer_id: options.thumbnail_product_retailer_id,\n sections: options.sections,\n },\n },\n ],\n });\n\n return {\n name: options.name,\n language: options.language,\n category: CategoryEnum.Marketing,\n components,\n };\n}\n\n// Product Card Carousel Template Factory\nexport function createProductCardCarouselTemplate(options: ProductCardCarouselTemplateOptions): TemplateRequestBody {\n const components: ComponentTypes[] = [];\n\n if (options.header) {\n components.push(createHeader({ ...options.header, format: 'TEXT' }));\n }\n\n components.push(createBody(options.body));\n\n if (options.footer) {\n components.push(createFooter(options.footer));\n }\n\n // Add carousel with product cards\n const carouselCards: ProductCarouselCard[] = options.cards.map((card, index) => ({\n card_index: index,\n components: [\n {\n type: 'HEADER' as const,\n format: 'PRODUCT' as const,\n example: {\n header_handle: [card.product_retailer_id],\n },\n },\n ],\n }));\n\n components.push({\n type: 'CAROUSEL',\n cards: carouselCards,\n });\n\n return {\n name: options.name,\n language: options.language,\n category: CategoryEnum.Marketing,\n components,\n };\n}\n\n// SPM (Single-Product Message) Template Factory\nexport function createSPMTemplate(options: SPMTemplateOptions): TemplateRequestBody {\n const components: ComponentTypes[] = [];\n\n if (options.header) {\n components.push(createHeader({ ...options.header, format: 'TEXT' }));\n }\n\n components.push(createBody(options.body));\n\n if (options.footer) {\n components.push(createFooter(options.footer));\n }\n\n // Add SPM button\n components.push({\n type: 'BUTTONS',\n buttons: [\n {\n type: 'SPM',\n action: {\n product_retailer_id: options.product_retailer_id,\n },\n },\n ],\n });\n\n return {\n name: options.name,\n language: options.language,\n category: CategoryEnum.Marketing,\n components,\n };\n}\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../types/request';\n\nimport type * as twoStepVerification from './types';\n\n/**\n * API for managing WhatsApp Two-Step Verification.\n *\n * This API allows you to:\n * - Set a two-step verification PIN code\n * - Manage two-step verification settings\n */\nexport default class TwoStepVerificationApi extends BaseAPI implements twoStepVerification.TwoStepVerificationClass {\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * Set a two-step verification PIN code.\n *\n * @param pin The PIN code to set for two-step verification (6-digit numeric string)\n * @returns Response indicating success or failure\n *\n * @example\n * await whatsappClient.twoStepVerification.setTwoStepVerificationCode('123456');\n */\n async setTwoStepVerificationCode(pin: string): Promise<ResponseSuccess> {\n const body = {\n pin,\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n}\n","import TwoStepVerificationApi from './TwoStepVerificationApi';\n\nexport default TwoStepVerificationApi;\n\nexport { TwoStepVerificationApi };\n\nexport type { TwoStepVerificationClass, TwoStepVerificationRequest } from './types';\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../types/request';\nimport { buildFieldsQueryString } from '../../utils/buildFieldsQueryString';\n\nimport type * as waba from './types';\n\n/**\n * API for managing WhatsApp Business Account (WABA).\n *\n * This API allows you to:\n * - Get WABA account information\n * - Manage WABA subscriptions\n * - Subscribe/unsubscribe from WABA webhooks\n * - Update subscription settings\n */\nexport default class WabaApi extends BaseAPI implements waba.WABAClass {\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * Retrieve WhatsApp Business Account information.\n *\n * @param fields Optional array of specific fields to retrieve\n * @returns WABA account information including status, health, verification status, etc.\n *\n * @example\n * const account = await whatsappClient.waba.getWabaAccount(['id', 'name', 'status']);\n */\n async getWabaAccount(fields?: waba.WabaAccountFieldsParam): Promise<waba.WabaAccount> {\n const queryString = buildFieldsQueryString(fields)?.replace(/,/g, '%2C');\n\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.BusinessAcctId]}${queryString}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Get all WABA subscriptions for the business account.\n *\n * @returns List of all subscribed apps and their configurations\n *\n * @example\n * const subscriptions = await whatsappClient.waba.getAllWabaSubscriptions();\n */\n async getAllWabaSubscriptions(): Promise<waba.WabaSubscriptions> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.BusinessAcctId]}/subscribed_apps`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Update WABA subscription configuration.\n *\n * @param params Configuration parameters including callback URI and verify token\n * @returns Response indicating success or failure\n *\n * @example\n * await whatsappClient.waba.updateWabaSubscription({\n * override_callback_uri: 'https://example.com/webhook',\n * verify_token: 'your_verify_token'\n * });\n */\n async updateWabaSubscription({\n override_callback_uri,\n verify_token,\n }: waba.UpdateWabaSubscription): Promise<ResponseSuccess> {\n const body = {\n override_callback_uri,\n verify_token,\n };\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.BusinessAcctId]}/subscribed_apps`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Unsubscribe from WABA webhooks.\n *\n * @returns Response indicating success or failure\n *\n * @example\n * await whatsappClient.waba.unsubscribeFromWaba();\n */\n async unsubscribeFromWaba(): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Delete,\n `${this.config[WabaConfigEnum.BusinessAcctId]}/subscribed_apps`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n}\n","import WabaApi from './WabaApi';\n\nexport default WabaApi;\n\nexport { WabaApi };\n\nexport type { UpdateWabaSubscription, WABAClass, WabaAccount, WabaSubscriptions } from './types';\n","export function printLogo() {\n // 테스트 환경에서는 로고를 출력하지 않음\n if (\n process.env.NODE_ENV === 'test' ||\n process.env.VITEST === 'true' ||\n (typeof global !== 'undefined' && (global as any).__VITEST__)\n ) {\n return;\n }\n\n console.log(\n '\\x1b[36m%s\\x1b[0m',\n `\n██████╗ ██╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ██████╗ ██╗\n██╔════╝ ██║ ██╔═══██╗ ██║ ██║ ██╔══██╗ ██╔══██╗ ██╔══██╗ ██║\n██║ ██║ ██║ ██║ ██║ ██║ ██║ ██║ ███████║ ██████╔╝ ██║\n██║ ██║ ██║ ██║ ██║ ██║ ██║ ██║ ██╔══██║ ██╔═══╝ ██║\n╚██████╗ ███████╗ ╚██████╔╝ ╚██████╔╝ ██████╔╝ ██║ ██║ ██║ ██║\n ╚═════╝ ╚══════╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝\n`,\n );\n}\n","import { importConfig } from '../../config/importConfig';\nimport { WabaConfigType, WhatsAppConfig } from '../../types/config';\nimport * as SDKEnums from '../../types/enums';\nimport { formatConfigTable } from '../../utils/configTable';\nimport Requester from '../../utils/http/request';\nimport Logger from '../../utils/logger';\nimport { getUserAgent, getVersion } from '../../utils/version';\n\nimport {\n BusinessProfileApi,\n EncryptionApi,\n FlowApi,\n MediaApi,\n MessagesApi,\n PhoneNumberApi,\n QrCodeApi,\n RegistrationApi,\n TemplateApi,\n TwoStepVerificationApi,\n WabaApi,\n} from '../../api';\nimport { printLogo } from '../../utils/logoConsole';\n\nconst LIB_NAME = 'WHATSAPP';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\n/**\n * WhatsApp SDK Main Class following official patterns\n * Provides unified access to WhatsApp Cloud API and Flows API\n */\nexport default class WhatsApp {\n config: WabaConfigType;\n requester: Readonly<Requester>;\n messages: MessagesApi;\n media: MediaApi;\n phoneNumbers: PhoneNumberApi;\n twoStepVerification: TwoStepVerificationApi;\n flows: FlowApi;\n businessProfile: BusinessProfileApi;\n templates: TemplateApi;\n encryption: EncryptionApi;\n qrCode: QrCodeApi;\n registration: RegistrationApi;\n waba: WabaApi;\n\n constructor(config?: WhatsAppConfig) {\n printLogo();\n this.config = importConfig(config);\n\n this.requester = new Requester(\n this.config[SDKEnums.WabaConfigEnum.APIVersion],\n this.config[SDKEnums.WabaConfigEnum.PhoneNumberId],\n this.config[SDKEnums.WabaConfigEnum.AccessToken],\n this.config[SDKEnums.WabaConfigEnum.BusinessAcctId],\n this.getUserAgent(),\n );\n\n this.messages = new MessagesApi(this.config, this.requester);\n this.media = new MediaApi(this.config, this.requester);\n this.phoneNumbers = new PhoneNumberApi(this.config, this.requester);\n this.twoStepVerification = new TwoStepVerificationApi(this.config, this.requester);\n this.flows = new FlowApi(this.config, this.requester);\n this.businessProfile = new BusinessProfileApi(this.config, this.requester);\n this.templates = new TemplateApi(this.config, this.requester);\n this.encryption = new EncryptionApi(this.config, this.requester);\n this.qrCode = new QrCodeApi(this.config, this.requester);\n this.registration = new RegistrationApi(this.config, this.requester);\n this.waba = new WabaApi(this.config, this.requester);\n\n LOGGER.log('\\n' + formatConfigTable(this.config));\n }\n\n /**\n * Runtime configuration updates following official patterns\n */\n updateTimeout(timeout: number): void {\n this.config[SDKEnums.WabaConfigEnum.RequestTimeout] = timeout;\n if ('updateTimeout' in this.requester) {\n (this.requester as any).updateTimeout(timeout);\n }\n LOGGER.log(`Timeout updated to ${timeout}ms`);\n }\n\n updateSenderNumberId(phoneNumberId: number): void {\n this.config[SDKEnums.WabaConfigEnum.PhoneNumberId] = phoneNumberId;\n LOGGER.log(`Sender number ID updated to ${phoneNumberId}`);\n }\n\n updateAccessToken(accessToken: string): void {\n this.config[SDKEnums.WabaConfigEnum.AccessToken] = accessToken;\n if ('updateAccessToken' in this.requester) {\n (this.requester as any).updateAccessToken(accessToken);\n }\n LOGGER.log('Access token updated');\n }\n\n /**\n * Get SDK version\n */\n version(): string {\n return getVersion();\n }\n\n /**\n * Static enums access\n */\n static get Enums() {\n return SDKEnums;\n }\n\n /**\n * Get User-Agent string\n */\n getUserAgent(): string {\n return getUserAgent();\n }\n}\n","import {\n FlowActionEnum,\n FlowDataExchangeRequest,\n FlowEndpointRequest,\n FlowErrorNotificationRequest,\n FlowHealthCheckRequest,\n} from '../api/flow/types';\n\n/**\n * Helper function to check if a value is an object\n * @param value The value to check\n * @returns True if the value is a non-null object\n */\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/**\n * Helper function to check if a value is a string\n * @param value The value to check\n * @returns True if the value is a string\n */\nfunction isString(value: unknown): value is string {\n return typeof value === 'string';\n}\n\n// Array of allowed action types for data exchange requests\nconst DATA_EXCHANGE_ACTIONS = [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT, FlowActionEnum.BACK] as const;\n\n// Array of allowed action types for error notification requests\nconst ERROR_ACTIONS = [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT] as const;\n\n/**\n * Type guard to check if a request is a Data Exchange request\n * Validates the request structure according to the Flow API specifications\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a valid Data Exchange request, false otherwise\n */\nexport function isFlowDataExchangeRequest(request: FlowEndpointRequest): request is FlowDataExchangeRequest & {\n action: (typeof DATA_EXCHANGE_ACTIONS)[number];\n screen?: string;\n flow_token: string;\n data?: Record<string, any>;\n} {\n // Check for basic required fields\n if (!('flow_token' in request && isString(request.flow_token) && 'action' in request)) {\n return false;\n }\n\n const { action, version, screen, data } = request;\n\n // Validate API version\n const hasValidVersion = version === '3.0';\n\n // Check if the action is one of the allowed actions for data exchange\n const hasValidAction = DATA_EXCHANGE_ACTIONS.includes(action as any);\n\n // Screen is optional, but when present must be a string and not 'SUCCESS'\n const hasValidScreen = typeof screen === 'undefined' || (isString(screen) && screen !== 'SUCCESS');\n\n // Data is required except for DATA_EXCHANGE action\n const hasValidData = action === FlowActionEnum.DATA_EXCHANGE || isObject(data);\n\n // All conditions must be met for a valid data exchange request\n return hasValidVersion && hasValidAction && hasValidScreen && hasValidData;\n}\n\n/**\n * Type guard to check if a request is an Error Notification request\n * Validates the request structure according to the Flow API error specifications\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a valid Error Notification request, false otherwise\n */\nexport function isFlowErrorRequest(request: FlowEndpointRequest): request is FlowErrorNotificationRequest & {\n action: (typeof ERROR_ACTIONS)[number];\n screen: string;\n flow_token: string;\n data: {\n error: string;\n error_message: string;\n };\n} {\n // Check for basic required fields\n if (!('flow_token' in request && isString(request.flow_token) && 'action' in request)) {\n return false;\n }\n\n const { action, screen, data } = request;\n\n // Check if the action is one of the allowed actions for error notifications\n const hasValidAction = ERROR_ACTIONS.includes(action as any);\n\n // Screen is required for error notifications\n const hasValidScreen = isString(screen);\n\n // Validate error data structure\n const hasValidData =\n isObject(data) &&\n 'error_key' in data &&\n isString(data.error) &&\n 'error_message' in data &&\n isString(data.error_message);\n\n // All conditions must be met for a valid error notification request\n return hasValidAction && hasValidScreen && hasValidData;\n}\n\n/**\n * Type guard to check if a request is a Ping (health check) request\n * Simple validation for health check endpoints in the Flow API\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a Ping request, false otherwise\n */\nexport function isFlowPingRequest(request: FlowEndpointRequest): request is FlowHealthCheckRequest {\n // A ping request only requires the 'action' field with value 'ping'\n return 'action' in request && request.action === 'ping';\n}\n","import crypto from 'crypto';\nimport { FlowEndpointRequest } from '../../../api/flow';\nimport { FlowTypeEnum } from '../../../api/flow/types';\nimport { WabaConfigType } from '../../../types/config';\nimport { MessageTypesEnum } from '../../../types/enums';\nimport { isFlowDataExchangeRequest, isFlowErrorRequest, isFlowPingRequest } from '../../../utils/flowTypeGuards';\nimport Logger from '../../../utils/logger';\nimport { WhatsApp } from '../../whatsapp';\nimport { WebhookMessage, WebhookMessageValue } from '../types';\n\nconst LIB_NAME = 'WEBHOOK_UTILS';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\nexport type MessageHandler = (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>;\nexport type FlowHandler = (whatsapp: WhatsApp, request: FlowEndpointRequest) => any | Promise<any>;\n\n/**\n * Process webhook messages\n */\nexport async function processWebhookMessages(\n request: Request,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<Response> {\n try {\n LOGGER.info('Processing webhook messages request');\n const body = await request.json();\n LOGGER.info('Webhook request body:', body);\n\n // Check this is a WhatsApp Business Account webhook\n if (body.object !== 'whatsapp_business_account') {\n const errorMsg = 'Received webhook for non-WhatsApp event';\n LOGGER.warn(errorMsg, { body });\n return new Response(JSON.stringify({ error: errorMsg }), { status: 404 });\n }\n\n const errors: string[] = [];\n\n // Process each entry\n for (const entry of body.entry) {\n try {\n LOGGER.info('Processing webhook entry:', { entryId: entry.id });\n const changes = entry.changes;\n for (const change of changes) {\n if (change.field === 'messages') {\n LOGGER.info('Processing messages change:', { change });\n await processMessages(entry.id, change.value, whatsapp, handlers);\n }\n }\n } catch (error) {\n const errorMsg = `Error processing webhook: ${error}`;\n LOGGER.error(errorMsg, { entry, error });\n errors.push(errorMsg);\n }\n }\n\n LOGGER.info('Webhook processing complete', { errorCount: errors.length });\n return new Response(errors.length > 0 ? JSON.stringify({ errors }) : null, { status: 200 });\n } catch (error) {\n LOGGER.error('Error processing webhook:', error);\n return new Response(JSON.stringify({ error: 'Internal Server Error' }), { status: 500 });\n }\n}\n\n/**\n * Handle flow requests\n */\nexport async function processFlowRequest(\n request: Request,\n config: WabaConfigType,\n whatsapp: WhatsApp,\n flowHandlers: Map<FlowTypeEnum, FlowHandler>,\n): Promise<Response> {\n try {\n LOGGER.info('Processing flow request');\n const body = await request.text();\n const signature = request.headers.get('x-hub-signature-256');\n LOGGER.info('Flow request signature:', { signature });\n\n // Validate request signature\n if (!verifySignature(body, signature, config.WEBHOOK_VERIFICATION_TOKEN || '')) {\n LOGGER.warn('Invalid request signature', { signature });\n return new Response(JSON.stringify({ error: 'Unauthorized' }), { status: 401 });\n }\n\n const data = JSON.parse(body);\n LOGGER.info('Flow request data:', data);\n\n // Decrypt the request\n const { decryptedBody } = decryptFlowRequest(data, config);\n LOGGER.info('Decrypted flow request:', decryptedBody);\n\n // Get the flow handler\n const handler = flowHandlers.get(FlowTypeEnum.All);\n if (!handler) {\n LOGGER.warn('No handler registered for flow action:', { action: decryptedBody.action });\n return new Response(JSON.stringify({ error: 'Handler not found' }), { status: 404 });\n }\n\n // Handle different flow types\n if (isFlowPingRequest(decryptedBody)) {\n LOGGER.info('Handling flow ping request');\n return new Response(\n JSON.stringify({\n version: '3.0',\n data: { status: 'active' },\n }),\n { status: 200 },\n );\n }\n\n if (isFlowErrorRequest(decryptedBody)) {\n LOGGER.warn('Flow error request received:', decryptedBody);\n return new Response(null, { status: 200 });\n }\n\n if (isFlowDataExchangeRequest(decryptedBody)) {\n LOGGER.info('Processing flow data exchange request');\n const result = await handler(whatsapp, decryptedBody);\n LOGGER.info('Flow handler result:', result);\n\n const encryptedResponse = encryptFlowResponse(\n result,\n Buffer.from(data.aes_key, 'base64'),\n Buffer.from(data.initial_vector, 'base64'),\n );\n LOGGER.info('Encrypted flow response generated');\n\n return new Response(JSON.stringify(encryptedResponse), { status: 200 });\n }\n\n LOGGER.warn('Unknown flow request type:', decryptedBody);\n return new Response(JSON.stringify({ error: 'Unknown request type' }), { status: 400 });\n } catch (error) {\n LOGGER.error('Error handling flow request:', error);\n return new Response(JSON.stringify({ error: 'Internal server error' }), { status: 500 });\n }\n}\n\n/**\n * Verify webhook signature\n */\nfunction verifySignature(body: string, signature: string | null, verificationToken: string): boolean {\n if (!signature) {\n LOGGER.warn('Missing signature in request');\n return false;\n }\n\n LOGGER.info('Signature verification details:', {\n bodyLength: body.length,\n verificationTokenLength: verificationToken.length,\n rawSignature: signature,\n cleanedSignature: signature.replace('sha256=', ''),\n });\n\n const expectedSignature = crypto.createHmac('sha256', verificationToken).update(body).digest('hex');\n LOGGER.info('Signature verification:', {\n received: signature.replace('sha256=', ''),\n expected: expectedSignature,\n });\n\n return crypto.timingSafeEqual(Buffer.from(signature.replace('sha256=', '')), Buffer.from(expectedSignature));\n}\n\n/**\n * Constructs a full URL from framework-specific request headers and URL\n * @param headers - Request headers containing host and protocol information\n * @param url - Relative URL path\n * @returns Full URL string\n */\nexport function constructFullUrl(headers: Record<string, string | string[] | undefined>, url?: string): string {\n const protocol = headers['x-forwarded-proto'] || 'http';\n const host = headers.host || 'localhost';\n const path = url || '/';\n return `${protocol}://${host}${path}`;\n}\n\n/**\n * Private helper functions\n */\nasync function processMessages(\n waba_id: string,\n value: WebhookMessageValue,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<void> {\n LOGGER.info('Processing messages:', { waba_id, value });\n\n const metadata = value.metadata;\n const contacts = value.contacts;\n const wabaId = waba_id;\n const displayPhoneNumber = metadata?.display_phone_number || '';\n const phoneNumberId = metadata?.phone_number_id || '';\n const profileName = contacts?.[0]?.profile?.name || '';\n\n if (value.statuses && value.statuses.length > 0) {\n LOGGER.info('Processing statuses:', { statusCount: value.statuses.length });\n const statuses = value.statuses;\n for (const status of statuses) {\n const processedStatus: WebhookMessage = {\n wabaId,\n id: status.id,\n from: status.recipient_id,\n timestamp: status.timestamp,\n type: MessageTypesEnum.Statuses,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n statuses: value.statuses[0],\n originalData: status,\n };\n\n LOGGER.info('Processing status:', processedStatus);\n await executeHandler(\n handlers.messageHandlers.get(MessageTypesEnum.Statuses),\n whatsapp,\n processedStatus,\n MessageTypesEnum.Statuses,\n );\n }\n return;\n }\n\n if (value.messages && value.messages.length > 0) {\n LOGGER.info('Processing messages:', { messageCount: value.messages.length });\n const messages = value.messages;\n\n for (const message of messages) {\n const messageType = message.type;\n LOGGER.info('Processing message:', { messageType, messageId: message.id });\n\n const processedMessage: WebhookMessage = {\n wabaId,\n id: message.id,\n from: message.from,\n timestamp: message.timestamp,\n type: message.type,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n originalData: message,\n };\n\n switch (messageType) {\n case MessageTypesEnum.Text:\n processedMessage.text = message.text;\n break;\n case MessageTypesEnum.Image:\n processedMessage.image = message.image;\n break;\n case MessageTypesEnum.Video:\n processedMessage.video = message.video;\n break;\n case MessageTypesEnum.Audio:\n processedMessage.audio = message.audio;\n break;\n case MessageTypesEnum.Document:\n processedMessage.document = message.document;\n break;\n case MessageTypesEnum.Sticker:\n processedMessage.sticker = message.sticker;\n break;\n case MessageTypesEnum.Location:\n processedMessage.location = message.location;\n break;\n case MessageTypesEnum.Contacts:\n processedMessage.contacts = message.contacts;\n break;\n case MessageTypesEnum.Interactive:\n processedMessage.interactive = message.interactive;\n break;\n case MessageTypesEnum.Button:\n processedMessage.button = message.button;\n break;\n case MessageTypesEnum.Order:\n processedMessage.order = message.order;\n break;\n case MessageTypesEnum.System:\n processedMessage.system = message.system;\n break;\n case MessageTypesEnum.Reaction:\n processedMessage.reaction = message.reaction;\n break;\n default:\n LOGGER.warn('Unknown message type:', { messageType });\n break;\n }\n\n // Execute handlers in sequence\n LOGGER.info('Executing message handlers');\n await executeHandler(handlers.preProcessHandler, whatsapp, processedMessage, 'pre-process');\n await executeHandler(handlers.messageHandlers.get(messageType), whatsapp, processedMessage, messageType);\n await executeHandler(handlers.postProcessHandler, whatsapp, processedMessage, 'post-process');\n }\n }\n}\n\nasync function executeHandler(\n handler: MessageHandler | undefined,\n whatsapp: WhatsApp,\n message: WebhookMessage,\n handlerType: string,\n): Promise<void> {\n if (handler) {\n try {\n LOGGER.info('Executing handler:', { handlerType, messageId: message.id });\n await handler(whatsapp, message);\n LOGGER.info('Handler execution complete:', { handlerType, messageId: message.id });\n } catch (error) {\n LOGGER.error(`Error in ${handlerType} handler:`, { error, messageId: message.id });\n }\n } else {\n LOGGER.info('No handler registered:', { handlerType });\n }\n}\n\nfunction decryptFlowRequest(\n body: any,\n config: WabaConfigType,\n): {\n decryptedBody: FlowEndpointRequest;\n aesKeyBuffer: Buffer;\n initialVectorBuffer: Buffer;\n} {\n LOGGER.info('Decrypting flow request');\n const { encrypted_aes_key, encrypted_flow_data, initial_vector } = body;\n\n if (!encrypted_aes_key || !encrypted_flow_data || !initial_vector) {\n LOGGER.error('Missing required encryption properties');\n throw new Error('Missing required encryption properties');\n }\n\n const privatePem = config.FLOW_API_PRIVATE_PEM.replace(/\\\\n/g, '\\n');\n const passphrase = config.FLOW_API_PASSPHRASE;\n\n const privateKey = crypto.createPrivateKey({ key: privatePem, passphrase });\n let decryptedAesKey: Buffer;\n\n try {\n LOGGER.info('Decrypting AES key');\n decryptedAesKey = crypto.privateDecrypt(\n {\n key: privateKey,\n padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,\n oaepHash: 'sha256',\n },\n Buffer.from(encrypted_aes_key, 'base64'),\n );\n } catch (error) {\n LOGGER.error('Failed to decrypt AES key:', error);\n throw new Error('Failed to decrypt the request. Please verify your private key.');\n }\n\n const flowDataBuffer = Buffer.from(encrypted_flow_data, 'base64');\n const initialVectorBuffer = Buffer.from(initial_vector, 'base64');\n\n const TAG_LENGTH = 16;\n const encrypted_flow_data_body = flowDataBuffer.subarray(0, -TAG_LENGTH);\n const encrypted_flow_data_tag = flowDataBuffer.subarray(-TAG_LENGTH);\n\n LOGGER.info('Decrypting flow data');\n const decipher = crypto.createDecipheriv('aes-128-gcm', decryptedAesKey, initialVectorBuffer);\n decipher.setAuthTag(encrypted_flow_data_tag);\n\n const decryptedJSONString = Buffer.concat([decipher.update(encrypted_flow_data_body), decipher.final()]).toString(\n 'utf-8',\n );\n\n LOGGER.info('Flow request decryption complete');\n return {\n decryptedBody: JSON.parse(decryptedJSONString),\n aesKeyBuffer: decryptedAesKey,\n initialVectorBuffer,\n };\n}\n\nfunction encryptFlowResponse(response: any, aesKeyBuffer: Buffer, initialVectorBuffer: Buffer): string {\n LOGGER.info('Encrypting flow response');\n const flipped_iv: number[] = [];\n for (const pair of Array.from(initialVectorBuffer.entries())) {\n flipped_iv.push(~pair[1]);\n }\n\n try {\n const cipher = crypto.createCipheriv('aes-128-gcm', aesKeyBuffer, Buffer.from(flipped_iv));\n const encryptedResponse = Buffer.concat([\n cipher.update(JSON.stringify(response || {}), 'utf-8'),\n cipher.final(),\n cipher.getAuthTag(),\n ]).toString('base64');\n\n LOGGER.info('Flow response encryption complete');\n return encryptedResponse;\n } catch (error) {\n LOGGER.error('Response encryption error:', error);\n throw new Error('Failed to encrypt response. Internal server error.');\n }\n}\n","import { FlowTypeEnum } from '../../api/flow/types';\nimport { importConfig } from '../../config/importConfig';\nimport { WabaConfigType, WhatsAppConfig } from '../../types/config';\nimport { MessageTypesEnum } from '../../types/enums';\nimport Logger from '../../utils/logger';\nimport { WhatsApp } from '../whatsapp';\nimport { FlowHandler, MessageHandler, processFlowRequest, processWebhookMessages } from './utils/webhookUtils';\n\nconst LOGGER = new Logger('WEBHOOK_PROCESSOR', process.env.DEBUG === 'true');\n\nexport interface WebhookResponse {\n status: number;\n body: string;\n headers: Record<string, string>;\n}\n\nexport class WebhookProcessor {\n private config: WabaConfigType;\n private client: WhatsApp;\n private messageHandlers: Map<MessageTypesEnum, MessageHandler> = new Map();\n private preProcessHandler: MessageHandler | undefined = undefined;\n private postProcessHandler: MessageHandler | undefined = undefined;\n private flowHandlers: Map<FlowTypeEnum, FlowHandler> = new Map();\n\n constructor(config: WhatsAppConfig) {\n this.config = importConfig(config);\n this.client = new WhatsApp(config);\n LOGGER.log('WebhookProcessor instantiated');\n }\n\n async processVerification(\n mode: string | null,\n token: string | null,\n challenge: string | null,\n ): Promise<WebhookResponse> {\n if (mode === 'subscribe' && token === this.config.WEBHOOK_VERIFICATION_TOKEN) {\n return {\n status: 200,\n body: challenge || '',\n headers: { 'Content-Type': 'text/plain' },\n };\n }\n\n return {\n status: 403,\n body: JSON.stringify({ error: 'Forbidden' }),\n headers: { 'Content-Type': 'application/json' },\n };\n }\n\n async processWebhook(request: Request): Promise<WebhookResponse> {\n try {\n const webResponse = await processWebhookMessages(request, this.client, {\n messageHandlers: this.messageHandlers,\n preProcessHandler: this.preProcessHandler,\n postProcessHandler: this.postProcessHandler,\n });\n\n const body = await webResponse.text();\n const contentType = webResponse.headers.get('content-type') || 'application/json';\n\n return {\n status: webResponse.status,\n body,\n headers: { 'Content-Type': contentType },\n };\n } catch (error) {\n LOGGER.log(`Error processing webhook: ${error}`);\n return {\n status: 500,\n body: JSON.stringify({ error: 'Internal Server Error' }),\n headers: { 'Content-Type': 'application/json' },\n };\n }\n }\n\n async processFlow(request: Request): Promise<WebhookResponse> {\n try {\n const webResponse = await processFlowRequest(request, this.config, this.client, this.flowHandlers);\n const body = await webResponse.text();\n const contentType = webResponse.headers.get('content-type') || 'application/json';\n\n return {\n status: webResponse.status,\n body,\n headers: { 'Content-Type': contentType },\n };\n } catch (error) {\n LOGGER.log(`Error processing flow: ${error}`);\n return {\n status: 500,\n body: JSON.stringify({ error: 'Internal Server Error' }),\n headers: { 'Content-Type': 'application/json' },\n };\n }\n }\n\n onMessage(type: MessageTypesEnum, handler: MessageHandler): void {\n this.messageHandlers.set(type, handler);\n LOGGER.log(`Registered message handler for ${type}`);\n }\n\n onMessagePreProcess(handler: MessageHandler): void {\n this.preProcessHandler = handler;\n LOGGER.log('Registered pre-process handler');\n }\n\n onMessagePostProcess(handler: MessageHandler): void {\n this.postProcessHandler = handler;\n LOGGER.log('Registered post-process handler');\n }\n\n onFlow(type: FlowTypeEnum, handler: FlowHandler): void {\n this.flowHandlers.set(type, handler);\n LOGGER.log(`Registered flow handler for ${type}`);\n }\n\n getClient(): WhatsApp {\n return this.client;\n }\n\n getConfig(): WabaConfigType {\n return this.config;\n }\n}\n","import { WhatsAppConfig } from '../../../types/config';\nimport { WebhookProcessor } from '../WebhookProcessor';\nimport { constructFullUrl } from '../utils/webhookUtils';\n\n// Generic request/response interfaces for framework abstraction\nexport interface BaseRequest {\n method?: string;\n url?: string;\n headers: Record<string, string | string[] | undefined>;\n body?: any;\n query?: Record<string, any> | URLSearchParams;\n rawBody?: any;\n}\n\nexport interface BaseResponse<T = any> {\n status(code: number): T;\n json?(data: any): T | void;\n send?(data?: any): T | void;\n setHeader?(name: string, value: string): void;\n}\n\n// Base configuration interface\nexport interface BaseWebhookConfig extends WhatsAppConfig {\n // Framework-specific configs can extend this\n}\n\n// Response result interface for consistent return types\nexport interface WebhookResult {\n status: number;\n headers: Record<string, string>;\n body: any;\n}\n\n/**\n * Abstract base class for framework-agnostic webhook handlers\n * Provides common architecture and functionality across all frameworks\n */\nexport abstract class BaseWebhookHandler<TRequest extends BaseRequest, TResponse extends BaseResponse> {\n protected processor: WebhookProcessor;\n\n constructor(config: BaseWebhookConfig) {\n this.processor = new WebhookProcessor(config);\n }\n\n /**\n * Abstract method for handling GET requests (webhook verification)\n * Each framework implements this based on their request/response patterns\n */\n protected abstract handleGet(req: TRequest, res: TResponse, ...args: any[]): Promise<any>;\n\n /**\n * Abstract method for handling POST requests (webhook processing)\n * Each framework implements this based on their request/response patterns\n */\n protected abstract handlePost(req: TRequest, res: TResponse, ...args: any[]): Promise<any>;\n\n /**\n * Abstract method for handling flow requests\n * Each framework implements this based on their request/response patterns\n */\n protected abstract handleFlow(req: TRequest, res: TResponse, ...args: any[]): Promise<any>;\n\n /**\n * Common webhook verification logic\n */\n protected async processVerification(\n mode: string | null,\n token: string | null,\n challenge: string | null,\n ): Promise<WebhookResult> {\n return await this.processor.processVerification(mode, token, challenge);\n }\n\n /**\n * Common webhook processing logic\n */\n protected async processWebhook(request: Request): Promise<WebhookResult> {\n return await this.processor.processWebhook(request);\n }\n\n /**\n * Common flow processing logic\n */\n protected async processFlow(request: Request): Promise<WebhookResult> {\n return await this.processor.processFlow(request);\n }\n\n /**\n * Helper to construct full URL from headers and path\n */\n protected constructFullUrl(headers: Record<string, string | string[] | undefined>, url: string = ''): string {\n return constructFullUrl(headers, url);\n }\n\n /**\n * Helper to apply result headers to response\n */\n protected applyHeaders(result: WebhookResult, res: TResponse): void {\n if (res.setHeader) {\n Object.entries(result.headers).forEach(([key, value]) => {\n res.setHeader!(key, value);\n });\n }\n }\n\n /**\n * Auto-routing method handler that dispatches based on request method\n */\n protected async autoRoute(req: TRequest, res: TResponse, ...args: any[]): Promise<any> {\n const method = req.method?.toUpperCase();\n\n switch (method) {\n case 'GET':\n return await this.handleGet(req, res, ...args);\n case 'POST':\n return await this.handlePost(req, res, ...args);\n default:\n if (res.status && res.json) {\n return res.status(405).json({ error: 'Method Not Allowed' });\n }\n throw new Error('Method Not Allowed');\n }\n }\n\n /**\n * Get the processor instance for handler registration\n */\n get webhookProcessor(): WebhookProcessor {\n return this.processor;\n }\n\n /**\n * Abstract method to return the clean handler object\n * Each framework implements this to return their specific handler structure\n */\n abstract getHandlers(): {\n GET: (...args: any[]) => Promise<any>;\n POST: (...args: any[]) => Promise<any>;\n webhook: (...args: any[]) => Promise<any>;\n flow: (...args: any[]) => Promise<any>;\n processor: WebhookProcessor;\n };\n}\n","import { BaseRequest, BaseResponse, BaseWebhookConfig, BaseWebhookHandler } from './handler';\n\n// Express-like interfaces to avoid direct Express dependency\nexport interface ExpressRequest extends BaseRequest {\n method: string;\n url: string;\n headers: Record<string, string | string[] | undefined>;\n body?: any;\n query: Record<string, any>;\n rawBody?: any;\n}\n\nexport interface ExpressResponse extends BaseResponse<ExpressResponse> {\n status(code: number): ExpressResponse;\n json(data: any): ExpressResponse;\n send(data?: any): ExpressResponse;\n setHeader(name: string, value: string): void;\n}\n\nexport interface NextFunction {\n (error?: any): void;\n}\n\nexport interface ExpressWebhookConfig extends BaseWebhookConfig {\n path?: string;\n}\n\n/**\n * Express-specific webhook handler extending the base handler\n */\nclass ExpressWebhookHandler extends BaseWebhookHandler<ExpressRequest, ExpressResponse> {\n constructor(config: ExpressWebhookConfig) {\n super(config);\n }\n\n protected async handleGet(req: ExpressRequest, res: ExpressResponse, next: NextFunction): Promise<ExpressResponse> {\n try {\n const { 'hub.mode': mode, 'hub.verify_token': token, 'hub.challenge': challenge } = req.query;\n\n const result = await this.processVerification(\n (mode as string) || null,\n (token as string) || null,\n (challenge as string) || null,\n );\n\n this.applyHeaders(result, res);\n return res.status(result.status).send(result.body);\n } catch (error) {\n next(error);\n return res;\n }\n }\n\n protected async handlePost(\n req: ExpressRequest,\n res: ExpressResponse,\n next: NextFunction,\n ): Promise<ExpressResponse> {\n try {\n const fullUrl = this.constructFullUrl(req.headers, req.url);\n const webRequest = new globalThis.Request(fullUrl, {\n method: req.method,\n headers: req.headers as HeadersInit,\n body: JSON.stringify(req.body),\n });\n\n const result = await this.processWebhook(webRequest);\n this.applyHeaders(result, res);\n return res.status(result.status).send(result.body);\n } catch (error) {\n next(error);\n return res;\n }\n }\n\n protected async handleFlow(\n req: ExpressRequest,\n res: ExpressResponse,\n next: NextFunction,\n ): Promise<ExpressResponse> {\n try {\n const fullUrl = this.constructFullUrl(req.headers, req.url);\n const webRequest = new globalThis.Request(fullUrl, {\n method: req.method,\n headers: req.headers as HeadersInit,\n body: req.method === 'POST' ? JSON.stringify(req.body) : undefined,\n });\n\n const result = await this.processFlow(webRequest);\n this.applyHeaders(result, res);\n return res.status(result.status).send(result.body);\n } catch (error) {\n next(error);\n return res;\n }\n }\n\n getHandlers() {\n return {\n // Method handlers for clean destructuring\n GET: (req: ExpressRequest, res: ExpressResponse, next: NextFunction) => this.handleGet(req, res, next),\n POST: (req: ExpressRequest, res: ExpressResponse, next: NextFunction) => this.handlePost(req, res, next),\n\n // Auto-routing webhook handler\n webhook: (req: ExpressRequest, res: ExpressResponse, next: NextFunction) => this.autoRoute(req, res, next),\n\n // Flow handler\n flow: (req: ExpressRequest, res: ExpressResponse, next: NextFunction) => this.handleFlow(req, res, next),\n\n // Expose processor for handler registration\n processor: this.webhookProcessor,\n };\n }\n}\n\nexport function webhookHandler(config: ExpressWebhookConfig) {\n const handler = new ExpressWebhookHandler(config);\n return handler.getHandlers();\n}\n","import { BaseRequest, BaseResponse, BaseWebhookConfig, BaseWebhookHandler } from './handler';\n\n// Next.js specific interfaces\nexport interface BaseApiRequest extends BaseRequest {\n method?: string;\n url?: string;\n headers: Record<string, string | string[] | undefined>;\n body?: any;\n query: Partial<Record<string, string | string[]>>;\n rawBody?: any;\n}\n\nexport interface BaseApiResponse extends BaseResponse {\n status(code: number): any;\n json(data: any): void | any;\n send(data?: any): void | any;\n setHeader(name: string, value: string): void;\n}\n\nexport interface NextJsWebhookConfig extends BaseWebhookConfig {\n // Next.js specific config can be added here\n}\n\n/**\n * Next.js Page Router webhook handler extending the base handler\n */\nclass NextJsWebhookHandler<\n TRequest extends BaseApiRequest,\n TResponse extends BaseApiResponse,\n> extends BaseWebhookHandler<TRequest, TResponse> {\n constructor(config: NextJsWebhookConfig) {\n super(config);\n }\n\n // Helper function to parse request body for POST requests\n private async parseRequestBody(req: TRequest): Promise<void> {\n if (req.method === 'POST' && !req.body) {\n const chunks: Buffer[] = [];\n\n // Check if req is a stream (has Symbol.asyncIterator)\n if (typeof (req as any)[Symbol.asyncIterator] === 'function') {\n for await (const chunk of req as any) {\n chunks.push(chunk);\n }\n\n const body = Buffer.concat(chunks).toString();\n\n // Only attempt to parse if there's actual content\n if (body.trim()) {\n try {\n req.body = JSON.parse(body);\n } catch (error) {\n throw new Error('Invalid JSON in request body');\n }\n } else {\n req.body = {};\n }\n }\n }\n }\n\n protected async handleGet(req: TRequest, res: TResponse): Promise<any> {\n try {\n const { 'hub.mode': mode, 'hub.verify_token': token, 'hub.challenge': challenge } = req.query;\n\n const result = await this.processVerification(\n (mode as string) || null,\n (token as string) || null,\n (challenge as string) || null,\n );\n\n this.applyHeaders(result, res);\n return res.status(result.status).send(result.body);\n } catch (error) {\n console.error('Webhook verification error:', error);\n return res.status(500).json({ error: 'Internal Server Error' });\n }\n }\n\n protected async handlePost(req: TRequest, res: TResponse): Promise<any> {\n try {\n // Auto-parse body if needed\n await this.parseRequestBody(req);\n } catch (error) {\n console.error('Webhook processing error:', error);\n\n // Handle JSON parsing errors specifically\n if (error instanceof Error && error.message === 'Invalid JSON in request body') {\n return res.status(400).json({ error: 'Invalid JSON' });\n }\n\n return res.status(500).json({ error: 'Internal Server Error' });\n }\n\n try {\n const fullUrl = this.constructFullUrl(req.headers, req.url);\n\n const webRequest = new Request(fullUrl, {\n method: 'POST',\n headers: req.headers as HeadersInit,\n body: JSON.stringify(req.body),\n });\n\n const result = await this.processWebhook(webRequest);\n this.applyHeaders(result, res);\n return res.status(result.status).send(result.body);\n } catch (error) {\n console.error('Webhook processing error:', error);\n return res.status(500).json({ error: 'Internal Server Error' });\n }\n }\n\n protected async handleFlow(req: TRequest, res: TResponse): Promise<any> {\n try {\n const fullUrl = this.constructFullUrl(req.headers, req.url);\n\n const webRequest = new Request(fullUrl, {\n method: req.method,\n headers: req.headers as HeadersInit,\n body: req.method === 'POST' ? JSON.stringify(req.body) : undefined,\n });\n\n const result = await this.processFlow(webRequest);\n this.applyHeaders(result, res);\n return res.status(result.status).send(result.body);\n } catch (error) {\n console.error('Flow error:', error);\n return res.status(500).json({ error: 'Internal Server Error' });\n }\n }\n\n getHandlers() {\n return {\n // Method handlers for clean destructuring\n GET: (req: TRequest, res: TResponse) => this.handleGet(req, res),\n POST: (req: TRequest, res: TResponse) => this.handlePost(req, res),\n\n // Auto-routing webhook handler\n webhook: (req: TRequest, res: TResponse) => this.autoRoute(req, res),\n\n // Flow handler\n flow: (req: TRequest, res: TResponse) => this.handleFlow(req, res),\n\n // Expose processor for handler registration\n processor: this.webhookProcessor,\n };\n }\n}\n\n// Generic webhook handler that accepts any compatible request/response types\nexport function webhookHandler<TRequest extends BaseApiRequest, TResponse extends BaseApiResponse>(\n config: NextJsWebhookConfig,\n) {\n const handler = new NextJsWebhookHandler<TRequest, TResponse>(config);\n return handler.getHandlers();\n}\n","import * as crypto from 'crypto';\n\nexport const generateXHub256Sig = (body: string, appSecret: string) => {\n return crypto.createHmac('sha256', appSecret).update(body, 'utf-8').digest('hex');\n};\n"],"mappings":";;;;;;;;AAGA,IAA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CAAC,KAAK,OAAO,KAAK;WAC7C,OAAO;AACZ,WAAQ,MAAM,6BAA6B,MAAM;AACjD,UAAO,IAAI,OAAO,IAAI,CAAC,KAAK,EAAE,OAAO,yBAAyB,CAAC;;;CAIvE,MAAgB,WAAW,KAAe,KAA8B;AACpE,MAAI;GACA,MAAM,UAAU,KAAK,iBAAiB,IAAI,SAAS,IAAI,IAAI;GAE3D,MAAM,aAAa,IAAI,QAAQ,SAAS;IACpC,QAAQ,IAAI;IACZ,SAAS,IAAI;IACb,MAAM,IAAI,WAAW,SAAS,KAAK,UAAU,IAAI,KAAK,GAAG;IAC5D,CAAC;GAEF,MAAM,SAAS,MAAM,KAAK,YAAY,WAAW;AACjD,QAAK,aAAa,QAAQ,IAAI;AAC9B,UAAO,IAAI,OAAO,OAAO,OAAO,CAAC,KAAK,OAAO,KAAK;WAC7C,OAAO;AACZ,WAAQ,MAAM,eAAe,MAAM;AACnC,UAAO,IAAI,OAAO,IAAI,CAAC,KAAK,EAAE,OAAO,yBAAyB,CAAC;;;CAIvE,cAAc;AACV,SAAO;GAEH,MAAM,KAAe,QAAmB,KAAK,UAAU,KAAK,IAAI;GAChE,OAAO,KAAe,QAAmB,KAAK,WAAW,KAAK,IAAI;GAGlE,UAAU,KAAe,QAAmB,KAAK,UAAU,KAAK,IAAI;GAGpE,OAAO,KAAe,QAAmB,KAAK,WAAW,KAAK,IAAI;GAGlE,WAAW,KAAK;GACnB;;;AAKT,SAAgBC,iBACZ,QACF;CACE,MAAM,UAAU,IAAI,qBAA0C,OAAO;AACrE,QAAO,QAAQ,aAAa;;;;;ACxJhC,MAAa,sBAAsB,MAAc,cAAsB;AACnE,QAAOC,SAAO,WAAW,UAAU,UAAU,CAAC,OAAO,MAAM,QAAQ,CAAC,OAAO,MAAM"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["LOGGER","LOGGER","LOGGER","headers: HeadersInit","fileContent: Blob","body: m.MessageRequestBody<T>","textPayload: m.TextObject","name: NameObject","phoneObj: PhoneObject","emailObj: EmailObject","address: AddressesObject","org: OrgObject","urlObj: URLObject","queryParts: string[]","body: registration.RegistrationRequest","header: TemplateHeader","body: TemplateBody","buttons: TemplateButton[]","urlButton: any","flowButton: any","components: ComponentTypes[]","carouselComponents: ComponentTypes[]","carouselCards: MediaCarouselCard[]","cardComponents: (TemplateHeader | TemplateBody | TemplateButtons)[]","carouselCards: ProductCarouselCard[]","LOGGER","MessageApi","SDKEnums","LOGGER","errors: string[]","processedStatus: WebhookMessage","processedMessage: WebhookMessage","decryptedAesKey: Buffer","flipped_iv: number[]","chunks: Buffer[]","crypto"],"sources":["../src/types/enums.ts","../src/utils/logger.ts","../src/config/importConfig.ts","../src/utils/configTable.ts","../src/utils/isMetaError.ts","../src/utils/http/httpsClient.ts","../src/utils/http/request.ts","../src/utils/version.ts","../src/types/base.ts","../src/api/encryption/EncryptionApi.ts","../src/api/flow/FlowApi.ts","../src/api/flow/types/common.ts","../src/api/media/MediaApi.ts","../src/api/messages/MessageApi.ts","../src/api/messages/builders/ContactMessageBuilder.ts","../src/api/messages/builders/InteractiveMessageBuilder.ts","../src/api/messages/builders/LocationMessageBuilder.ts","../src/api/messages/builders/MediaMessageBuilder.ts","../src/api/messages/builders/ReactionMessageBuilder.ts","../src/api/messages/builders/TemplateMessageBuilder.ts","../src/api/messages/builders/TextMessageBuilder.ts","../src/utils/objectToQueryString.ts","../src/api/phone/PhoneNumberApi.ts","../src/utils/buildFieldsQueryString.ts","../src/api/profile/BusinessProfileApi.ts","../src/api/qrCode/QrCodeApi.ts","../src/api/registration/RegistrationApi.ts","../src/api/template/TemplateApi.ts","../src/api/template/factories/index.ts","../src/api/twoStepVerification/TwoStepVerificationApi.ts","../src/api/waba/WabaApi.ts","../src/utils/logoConsole.ts","../src/core/whatsapp/WhatsApp.ts","../src/utils/flowTypeGuards.ts","../src/core/webhook/utils/webhookUtils.ts","../src/core/webhook/WebhookProcessor.ts","../src/core/webhook/frameworks/handler.ts","../src/core/webhook/frameworks/express/express.ts","../src/core/webhook/frameworks/nextjs/nextjs.ts","../src/core/webhook/frameworks/nextjs-app/nextjs-app.ts","../src/core/webhook/utils/generateXHub256Sig.ts"],"sourcesContent":["export enum CategoryEnum {\n Authentication = 'AUTHENTICATION',\n Marketing = 'MARKETING',\n Utility = 'UTILITY',\n}\n\nexport enum TemplateStatusEnum {\n Approved = 'APPROVED',\n Pending = 'PENDING',\n Rejected = 'REJECTED',\n}\n\nexport enum HttpMethodsEnum {\n Get = 'GET',\n Post = 'POST',\n Put = 'PUT',\n Delete = 'DELETE',\n}\n\nexport enum MessageTypesEnum {\n Audio = 'audio',\n Contacts = 'contacts',\n Document = 'document',\n Image = 'image',\n Interactive = 'interactive',\n Location = 'location',\n Reaction = 'reaction',\n Sticker = 'sticker',\n Template = 'template',\n Text = 'text',\n Video = 'video',\n Button = 'button',\n Order = 'order',\n System = 'system',\n Unknown = 'unknown',\n Statuses = 'statuses',\n '*' = '*',\n}\n\nexport enum ParametersTypesEnum {\n Action = 'ACTION',\n CouponCode = 'COUPON_CODE',\n Currency = 'CURRENCY',\n DateTime = 'DATE_TIME',\n Document = 'DOCUMENT',\n ExpirationTimeMs = 'EXPIRATION_TIME_MS',\n Image = 'IMAGE',\n LimitedTimeOffer = 'LIMITED_TIME_OFFER',\n Location = 'LOCATION',\n OrderStatus = 'ORDER_STATUS',\n Payload = 'PAYLOAD',\n Product = 'PRODUCT',\n Text = 'TEXT',\n TtlMinutes = 'TTL_MINUTES',\n Video = 'VIDEO',\n WebviewInteraction = 'WEBVIEW_INTERACTION',\n WebviewPresentation = 'WEBVIEW_PRESENTATION',\n}\n\nexport enum InteractiveTypesEnum {\n Button = 'button',\n List = 'list',\n Product = 'product',\n ProductList = 'product_list',\n CtaUrl = 'cta_url',\n LocationRequest = 'location_request_message',\n AddressMessage = 'address_message',\n Flow = 'flow',\n}\n\nexport enum ButtonPositionEnum {\n First = 1,\n Second = 2,\n Third = 3,\n Fourth = 4,\n Fifth = 5,\n}\n\nexport enum SubTypeEnum {\n Catalog = 'CATALOG',\n CopyCode = 'COPY_CODE',\n Flow = 'FLOW',\n Mpm = 'MPM',\n OrderDetails = 'ORDER_DETAILS',\n QuickReply = 'QUICK_REPLY',\n Reminder = 'REMINDER',\n Url = 'URL',\n VoiceCall = 'VOICE_CALL',\n}\n\nexport enum ComponentTypesEnum {\n Header = 'HEADER',\n Body = 'BODY',\n Button = 'BUTTON',\n Footer = 'FOOTER',\n}\n\nexport enum WabaConfigEnum {\n AppId = 'M4D_APP_ID',\n Port = 'WA_PORT',\n AppSecret = 'M4D_APP_SECRET',\n PhoneNumberId = 'WA_PHONE_NUMBER_ID',\n BusinessAcctId = 'WA_BUSINESS_ACCOUNT_ID',\n APIVersion = 'CLOUD_API_VERSION',\n AccessToken = 'CLOUD_API_ACCESS_TOKEN',\n WebhookEndpoint = 'WEBHOOK_ENDPOINT',\n WebhookVerificationToken = 'WEBHOOK_VERIFICATION_TOKEN',\n ListenerPort = 'LISTENER_PORT',\n MaxRetriesAfterWait = 'MAX_RETRIES_AFTER_WAIT',\n RequestTimeout = 'REQUEST_TIMEOUT',\n Debug = 'DEBUG',\n PrivatePem = 'FLOW_API_PRIVATE_PEM',\n Passphrase = 'FLOW_API_PASSPHRASE',\n}\n\nexport enum ConversationTypesEnum {\n BusinessInitiated = 'business_initiated',\n CustomerInitiated = 'customer_initiated',\n ReferralConversion = 'referral_conversion',\n}\n\nexport enum StatusEnum {\n Delivered = 'delivered',\n Read = 'read',\n Sent = 'sent',\n}\n\nexport enum VideoMediaTypesEnum {\n Mp4 = 'video/mp4',\n Threegp = 'video/3gp',\n}\n\nexport enum StickerMediaTypesEnum {\n Webp = 'image/webp',\n}\n\nexport enum ImageMediaTypesEnum {\n Jpeg = 'image/jpeg',\n Png = 'image/png',\n}\n\nexport enum DocumentMediaTypesEnum {\n Text = 'text/plain',\n Pdf = 'application/pdf',\n Ppt = 'application/vnd.ms-powerpoint',\n Word = 'application/msword',\n Excel = 'application/vnd.ms-excel',\n OpenDoc = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n OpenPres = 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n OpenSheet = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n}\n\nexport enum AudioMediaTypesEnum {\n Aac = 'audio/aac',\n Mp4 = 'audio/mp4',\n Mpeg = 'audio/mpeg',\n Amr = 'audio/amr',\n Ogg = 'audio/ogg',\n}\n\nexport enum WebhookTypesEnum {\n Audio = 'audio',\n Button = 'button',\n Document = 'document',\n Text = 'text',\n Image = 'image',\n Interactive = 'interactive',\n Order = 'order',\n Sticker = 'sticker',\n System = 'system',\n Unknown = 'unknown',\n Video = 'video',\n}\n\nexport enum SystemChangeTypesEnum {\n CustomerChangedNumber = 'customer_changed_number',\n CustomerIdentityChanged = 'customer_identity_changed',\n}\n\nexport enum ReferralSourceTypesEnum {\n Ad = 'ad',\n Post = 'post',\n}\n\nexport enum RequestCodeMethodsEnum {\n Sms = 'SMS',\n Voice = 'VOICE',\n}\n\nexport enum LanguagesEnum {\n Afrikaans = 'af',\n Albanian = 'sq',\n Arabic = 'ar',\n Azerbaijani = 'az',\n Bengali = 'bn',\n Bulgarian = 'bg',\n Catalan = 'ca',\n Chinese_CHN = 'zh_CN',\n Chinese_HKG = 'zh_HK',\n Chinese_TAI = 'zh_TW',\n Croatian = 'hr',\n Czech = 'cs',\n Danish = 'da',\n Dutch = 'nl',\n English = 'en',\n English_UK = 'en_GB',\n English_US = 'en_US',\n Estonian = 'et',\n Filipino = 'fil',\n Finnish = 'fi',\n French = 'fr',\n Georgian = 'ka',\n German = 'de',\n Greek = 'el',\n Gujarati = 'gu',\n Hausa = 'ha',\n Hebrew = 'he',\n Hindi = 'hi',\n Hungarian = 'hu',\n Indonesian = 'id',\n Irish = 'ga',\n Italian = 'it',\n Japanese = 'ja',\n Kannada = 'kn',\n Kazakh = 'kk',\n Kinyarwanda = 'rw_RW',\n Korean = 'ko',\n Kyrgyz_Kyrgyzstan = 'ky_KG',\n Lao = 'lo',\n Latvian = 'lv',\n Lithuanian = 'lt',\n Macedonian = 'mk',\n Malay = 'ms',\n Malayalam = 'ml',\n Marathi = 'mr',\n Norwegian = 'nb',\n Persian = 'fa',\n Polish = 'pl',\n Portuguese_BR = 'pt_BR',\n Portuguese_POR = 'pt_PT',\n Punjabi = 'pa',\n Romanian = 'ro',\n Russian = 'ru',\n Serbian = 'sr',\n Slovak = 'sk',\n Slovenian = 'sl',\n Spanish = 'es',\n Spanish_ARG = 'es_AR',\n Spanish_SPA = 'es_ES',\n Spanish_MEX = 'es_MX',\n Swahili = 'sw',\n Swedish = 'sv',\n Tamil = 'ta',\n Telugu = 'te',\n Thai = 'th',\n Turkish = 'tr',\n Ukrainian = 'uk',\n Urdu = 'ur',\n Uzbek = 'uz',\n Vietnamese = 'vi',\n Zulu = 'zu',\n}\n\nexport enum CurrencyCodesEnum {\n AFN = 'AFN',\n EUR = 'EUR',\n ALL = 'ALL',\n DZD = 'DZD',\n USD = 'USD',\n AOA = 'AOA',\n XCD = 'XCD',\n ARS = 'ARS',\n AMD = 'AMD',\n AWG = 'AWG',\n AUD = 'AUD',\n AZN = 'AZN',\n BSD = 'BSD',\n BHD = 'BHD',\n BDT = 'BDT',\n BBD = 'BBD',\n BYN = 'BYN',\n BZD = 'BZD',\n XOF = 'XOF',\n BMD = 'BMD',\n INR = 'INR',\n BTN = 'BTN',\n BOB = 'BOB',\n BOV = 'BOV',\n BAM = 'BAM',\n BWP = 'BWP',\n NOK = 'NOK',\n BRL = 'BRL',\n BND = 'BND',\n BGN = 'BGN',\n BIF = 'BIF',\n CVE = 'CVE',\n KHR = 'KHR',\n XAF = 'XAF',\n CAD = 'CAD',\n KYD = 'KYD',\n CLP = 'CLP',\n CLF = 'CLF',\n CNY = 'CNY',\n COP = 'COP',\n COU = 'COU',\n KMF = 'KMF',\n CDF = 'CDF',\n NZD = 'NZD',\n CRC = 'CRC',\n HRK = 'HRK',\n CUP = 'CUP',\n CUC = 'CUC',\n ANG = 'ANG',\n CZK = 'CZK',\n DKK = 'DKK',\n DJF = 'DJF',\n DOP = 'DOP',\n EGP = 'EGP',\n SVC = 'SVC',\n ERN = 'ERN',\n SZL = 'SZL',\n ETB = 'ETB',\n FKP = 'FKP',\n FJD = 'FJD',\n XPF = 'XPF',\n GMD = 'GMD',\n GEL = 'GEL',\n GHS = 'GHS',\n GIP = 'GIP',\n GTQ = 'GTQ',\n GBP = 'GBP',\n GNF = 'GNF',\n GYD = 'GYD',\n HTG = 'HTG',\n HNL = 'HNL',\n HKD = 'HKD',\n HUF = 'HUF',\n ISK = 'ISK',\n IDR = 'IDR',\n XDR = 'XDR',\n IRR = 'IRR',\n IQD = 'IQD',\n ILS = 'ILS',\n JMD = 'JMD',\n JPY = 'JPY',\n JOD = 'JOD',\n KZT = 'KZT',\n KES = 'KES',\n KPW = 'KPW',\n KRW = 'KRW',\n KWD = 'KWD',\n KGS = 'KGS',\n LAK = 'LAK',\n LBP = 'LBP',\n LSL = 'LSL',\n ZAR = 'ZAR',\n LRD = 'LRD',\n LYD = 'LYD',\n CHF = 'CHF',\n MOP = 'MOP',\n MKD = 'MKD',\n MGA = 'MGA',\n MWK = 'MWK',\n MYR = 'MYR',\n MVR = 'MVR',\n MRU = 'MRU',\n MUR = 'MUR',\n XUA = 'XUA',\n MXN = 'MXN',\n MXV = 'MXV',\n MDL = 'MDL',\n MNT = 'MNT',\n MAD = 'MAD',\n MZN = 'MZN',\n MMK = 'MMK',\n NAD = 'NAD',\n NPR = 'NPR',\n NIO = 'NIO',\n NGN = 'NGN',\n OMR = 'OMR',\n PKR = 'PKR',\n PAB = 'PAB',\n PGK = 'PGK',\n PYG = 'PYG',\n PEN = 'PEN',\n PHP = 'PHP',\n PLN = 'PLN',\n QAR = 'QAR',\n RON = 'RON',\n RUB = 'RUB',\n RWF = 'RWF',\n SHP = 'SHP',\n WST = 'WST',\n STN = 'STN',\n SAR = 'SAR',\n RSD = 'RSD',\n SCR = 'SCR',\n SLL = 'SLL',\n SGD = 'SGD',\n XSU = 'XSU',\n SBD = 'SBD',\n SOS = 'SOS',\n SSP = 'SSP',\n LKR = 'LKR',\n SDG = 'SDG',\n SRD = 'SRD',\n SEK = 'SEK',\n CHE = 'CHE',\n CHW = 'CHW',\n SYP = 'SYP',\n TWD = 'TWD',\n TJS = 'TJS',\n TZS = 'TZS',\n THB = 'THB',\n TOP = 'TOP',\n TTD = 'TTD',\n TND = 'TND',\n TRY = 'TRY',\n TMT = 'TMT',\n UGX = 'UGX',\n UAH = 'UAH',\n AED = 'AED',\n USN = 'USN',\n UYU = 'UYU',\n UYI = 'UYI',\n UYW = 'UYW',\n UZS = 'UZS',\n VUV = 'VUV',\n VES = 'VES',\n VND = 'VND',\n YER = 'YER',\n ZMW = 'ZMW',\n ZWL = 'ZWL',\n XBA = 'XBA',\n XBB = 'XBB',\n XBC = 'XBC',\n XBD = 'XBD',\n XTS = 'XTS',\n XXX = 'XXX',\n XAU = 'XAU',\n XPD = 'XPD',\n XPT = 'XPT',\n XAG = 'XAG',\n AFA = 'AFA',\n FIM = 'FIM',\n ALK = 'ALK',\n ADP = 'ADP',\n ESP = 'ESP',\n FRF = 'FRF',\n AOK = 'AOK',\n AON = 'AON',\n AOR = 'AOR',\n ARA = 'ARA',\n ARP = 'ARP',\n ARY = 'ARY',\n RUR = 'RUR',\n ATS = 'ATS',\n AYM = 'AYM',\n AZM = 'AZM',\n BYB = 'BYB',\n BYR = 'BYR',\n BEC = 'BEC',\n BEF = 'BEF',\n BEL = 'BEL',\n BOP = 'BOP',\n BAD = 'BAD',\n BRB = 'BRB',\n BRC = 'BRC',\n BRE = 'BRE',\n BRN = 'BRN',\n BRR = 'BRR',\n BGJ = 'BGJ',\n BGK = 'BGK',\n BGL = 'BGL',\n BUK = 'BUK',\n HRD = 'HRD',\n CYP = 'CYP',\n CSJ = 'CSJ',\n CSK = 'CSK',\n ECS = 'ECS',\n ECV = 'ECV',\n GQE = 'GQE',\n EEK = 'EEK',\n XEU = 'XEU',\n GEK = 'GEK',\n DDM = 'DDM',\n DEM = 'DEM',\n GHC = 'GHC',\n GHP = 'GHP',\n GRD = 'GRD',\n GNE = 'GNE',\n GNS = 'GNS',\n GWE = 'GWE',\n GWP = 'GWP',\n ITL = 'ITL',\n ISJ = 'ISJ',\n IEP = 'IEP',\n ILP = 'ILP',\n ILR = 'ILR',\n LAJ = 'LAJ',\n LVL = 'LVL',\n LVR = 'LVR',\n LSM = 'LSM',\n ZAL = 'ZAL',\n LTL = 'LTL',\n LTT = 'LTT',\n LUC = 'LUC',\n LUF = 'LUF',\n LUL = 'LUL',\n MGF = 'MGF',\n MVQ = 'MVQ',\n MLF = 'MLF',\n MTL = 'MTL',\n MTP = 'MTP',\n MRO = 'MRO',\n MXP = 'MXP',\n MZE = 'MZE',\n MZM = 'MZM',\n NLG = 'NLG',\n NIC = 'NIC',\n PEH = 'PEH',\n PEI = 'PEI',\n PES = 'PES',\n PLZ = 'PLZ',\n PTE = 'PTE',\n ROK = 'ROK',\n ROL = 'ROL',\n STD = 'STD',\n CSD = 'CSD',\n SKK = 'SKK',\n SIT = 'SIT',\n RHD = 'RHD',\n ESA = 'ESA',\n ESB = 'ESB',\n SDD = 'SDD',\n SDP = 'SDP',\n SRG = 'SRG',\n CHC = 'CHC',\n TJR = 'TJR',\n TPE = 'TPE',\n TRL = 'TRL',\n TMM = 'TMM',\n UGS = 'UGS',\n UGW = 'UGW',\n UAK = 'UAK',\n SUR = 'SUR',\n USS = 'USS',\n UYN = 'UYN',\n UYP = 'UYP',\n VEB = 'VEB',\n VEF = 'VEF',\n VNC = 'VNC',\n YDD = 'YDD',\n YUD = 'YUD',\n YUM = 'YUM',\n YUN = 'YUN',\n ZRN = 'ZRN',\n ZRZ = 'ZRZ',\n ZMK = 'ZMK',\n ZWC = 'ZWC',\n ZWD = 'ZWD',\n ZWN = 'ZWN',\n ZWR = 'ZWR',\n XFO = 'XFO',\n XRE = 'XRE',\n XFU = 'XFU',\n}\n\nexport enum DataLocalizationRegionEnum {\n // APAC\n AU = 'AU', // Australia\n ID = 'ID', // Indonesia\n IN = 'IN', // India\n JP = 'JP', // Japan\n SG = 'SG', // Singapore\n KR = 'KR', // South Korea\n\n // Europe\n DE = 'DE', // EU (Germany)\n CH = 'CH', // Switzerland\n GB = 'GB', // United Kingdom\n\n // LATAM\n BR = 'BR', // Brazil\n\n // MEA\n BH = 'BH', // Bahrain\n ZA = 'ZA', // South Africa\n AE = 'AE', // United Arab Emirates\n\n // NORAM\n CA = 'CA', // Canada\n}\n\n/**\n * Business category values for WhatsApp Business Profile.\n * These values map to specific strings displayed in the WhatsApp client.\n */\nexport enum BusinessVerticalEnum {\n /**\n * Alcoholic Beverages\n */\n ALCOHOL = 'ALCOHOL',\n /**\n * Clothing and Apparel\n */\n APPAREL = 'APPAREL',\n /**\n * Automotive\n */\n AUTO = 'AUTO',\n /**\n * Beauty, Spa and Salon\n */\n BEAUTY = 'BEAUTY',\n /**\n * Education\n */\n EDU = 'EDU',\n /**\n * Entertainment\n */\n ENTERTAIN = 'ENTERTAIN',\n /**\n * Event Planning and Service\n */\n EVENT_PLAN = 'EVENT_PLAN',\n /**\n * Finance and Banking\n */\n FINANCE = 'FINANCE',\n /**\n * Public Service\n */\n GOVT = 'GOVT',\n /**\n * Food and Grocery\n */\n GROCERY = 'GROCERY',\n /**\n * Medical and Health\n */\n HEALTH = 'HEALTH',\n /**\n * Hotel and Lodging\n */\n HOTEL = 'HOTEL',\n /**\n * Non-profit\n */\n NONPROFIT = 'NONPROFIT',\n /**\n * Online Gambling & Gaming\n */\n ONLINE_GAMBLING = 'ONLINE_GAMBLING',\n /**\n * Over-the-Counter Drugs\n */\n OTC_DRUGS = 'OTC_DRUGS',\n /**\n * Other\n */\n OTHER = 'OTHER',\n /**\n * Non-Online Gambling & Gaming (E.g. Brick and mortar)\n */\n PHYSICAL_GAMBLING = 'PHYSICAL_GAMBLING',\n /**\n * Professional Services\n */\n PROF_SERVICES = 'PROF_SERVICES',\n /**\n * Restaurant\n */\n RESTAURANT = 'RESTAURANT',\n /**\n * Shopping and Retail\n */\n RETAIL = 'RETAIL',\n /**\n * Travel and Transportation\n */\n TRAVEL = 'TRAVEL',\n}\n","// @ts-nocheck\nimport type { LoggerInterface } from '../types/logger';\n\nexport default class Logger implements LoggerInterface {\n private name: string;\n private debug: boolean;\n\n constructor(name: string, debug: boolean = false) {\n this.name = name;\n this.debug = debug;\n }\n\n log(...data: any[]) {\n if (this.debug) {\n let prefix = `[ ${Date.now()} ]`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.log.apply(console, [prefix, ': ', ...data]);\n }\n }\n\n error(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - ERROR`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.error.apply(console, [prefix, ': ', ...data]);\n }\n\n warn(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - WARN`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.warn.apply(console, [prefix, ': ', ...data]);\n }\n\n info(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - INFO`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.info.apply(console, [prefix, ': ', ...data]);\n }\n}\n","import type { WabaConfigType, WhatsAppConfig } from '../types/config';\nimport { WabaConfigEnum } from '../types/enums';\nimport Logger from '../utils/logger';\n\nconst LIB_NAME = 'UTILS';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\nconst DEFAULT_LISTENER_PORT = 3000;\nconst DEFAULT_MAX_RETRIES_AFTER_WAIT = 30;\nconst DEFAULT_REQUEST_TIMEOUT = 20000;\n\nconst emptyConfigChecker = (config: WhatsAppConfig | undefined) => {\n if (!process.env[WabaConfigEnum.AccessToken] && !config?.accessToken) {\n LOGGER.log(`Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined.`);\n throw new Error('Missing WhatsApp access token.');\n }\n};\n\nexport const importConfig = (inputConfig?: WhatsAppConfig) => {\n emptyConfigChecker(inputConfig);\n\n const wabaConfig: WabaConfigType = {\n [WabaConfigEnum.AppId]: inputConfig?.appId || process.env.M4D_APP_ID || '',\n [WabaConfigEnum.AppSecret]: inputConfig?.appSecret || process.env.M4D_APP_SECRET || '',\n [WabaConfigEnum.PhoneNumberId]: inputConfig?.phoneNumberId || Number(process.env.WA_PHONE_NUMBER_ID),\n [WabaConfigEnum.BusinessAcctId]: inputConfig?.businessAcctId || process.env.WA_BUSINESS_ACCOUNT_ID || '',\n [WabaConfigEnum.APIVersion]: inputConfig?.apiVersion || process.env.CLOUD_API_VERSION || '',\n [WabaConfigEnum.AccessToken]: inputConfig?.accessToken || process.env.CLOUD_API_ACCESS_TOKEN || '',\n [WabaConfigEnum.WebhookEndpoint]: inputConfig?.webhookEndpoint || process.env.WEBHOOK_ENDPOINT || '',\n [WabaConfigEnum.WebhookVerificationToken]:\n inputConfig?.webhookVerificationToken || process.env.WEBHOOK_VERIFICATION_TOKEN || '',\n [WabaConfigEnum.ListenerPort]:\n inputConfig?.listenerPort || parseInt(process.env.LISTENER_PORT || '') || DEFAULT_LISTENER_PORT,\n [WabaConfigEnum.MaxRetriesAfterWait]:\n inputConfig?.maxRetriesAfterWait ||\n parseInt(process.env.MAX_RETRIES_AFTER_WAIT || '') ||\n DEFAULT_MAX_RETRIES_AFTER_WAIT,\n [WabaConfigEnum.RequestTimeout]:\n inputConfig?.requestTimeout || parseInt(process.env.REQUEST_TIMEOUT || '') || DEFAULT_REQUEST_TIMEOUT,\n [WabaConfigEnum.Debug]: inputConfig?.debug || process.env.DEBUG === 'true',\n [WabaConfigEnum.PrivatePem]: inputConfig?.privatePem || process.env.FLOW_API_PRIVATE_PEM || '',\n [WabaConfigEnum.Passphrase]: inputConfig?.passphrase || process.env.FLOW_API_PASSPHRASE || '',\n };\n\n return wabaConfig;\n};\n","import type { WabaConfigType } from '../types/config';\nimport { WabaConfigEnum } from '../types/enums';\n\n/**\n * Formats configuration as a terminal table\n * @param config - The WABA configuration object\n * @param apiName - The name of the API being initialized\n * @returns Formatted table string\n */\nexport function formatConfigTable(config: WabaConfigType): string {\n const configData = [\n ['App ID', config[WabaConfigEnum.AppId] || 'Not Set'],\n ['Phone Number ID', config[WabaConfigEnum.PhoneNumberId]?.toString() || 'Not Set'],\n ['Business Account ID', config[WabaConfigEnum.BusinessAcctId] || 'Not Set'],\n ['API Version', config[WabaConfigEnum.APIVersion] || 'Not Set'],\n [\n 'Access Token',\n config[WabaConfigEnum.AccessToken]\n ? `${config[WabaConfigEnum.AccessToken].substring(0, 20)}...`\n : 'Not Set',\n ],\n ['Webhook Endpoint', config[WabaConfigEnum.WebhookEndpoint] || 'Not Set'],\n [\n 'Webhook Verification Token',\n config[WabaConfigEnum.WebhookVerificationToken]\n ? `${config[WabaConfigEnum.WebhookVerificationToken].substring(0, 10)}...`\n : 'Not Set',\n ],\n ['Listener Port', config[WabaConfigEnum.ListenerPort]?.toString() || 'Not Set'],\n ['Debug Mode', config[WabaConfigEnum.Debug] ? 'Enabled' : 'Disabled'],\n ['Max Retries', config[WabaConfigEnum.MaxRetriesAfterWait]?.toString() || 'Not Set'],\n [\n 'Request Timeout',\n config[WabaConfigEnum.RequestTimeout] ? `${config[WabaConfigEnum.RequestTimeout]}ms` : 'Not Set',\n ],\n ['Private PEM', config[WabaConfigEnum.PrivatePem] ? 'Configured' : 'Not Set'],\n ['Passphrase', config[WabaConfigEnum.Passphrase] ? 'Configured' : 'Not Set'],\n ];\n\n // Calculate column widths\n const maxKeyLength = Math.max(...configData.map(([key]) => key?.length || 0));\n const maxValueLength = Math.max(...configData.map(([, value]) => value?.length || 0));\n\n const keyWidth = Math.max(maxKeyLength, 20);\n const valueWidth = Math.max(maxValueLength, 30);\n\n // Create table\n const horizontalLine = `┌${'─'.repeat(keyWidth + 2)}┬${'─'.repeat(valueWidth + 2)}┐`;\n const separator = `├${'─'.repeat(keyWidth + 2)}┼${'─'.repeat(valueWidth + 2)}┤`;\n const bottomLine = `└${'─'.repeat(keyWidth + 2)}┴${'─'.repeat(valueWidth + 2)}┘`;\n\n const header = `│ ${'Configuration'.padEnd(keyWidth)} │ ${'Value'.padEnd(valueWidth)} │`;\n\n const rows = configData.map(([key, value]) => `│ ${key?.padEnd(keyWidth)} │ ${value?.padEnd(valueWidth)} │`);\n\n return [horizontalLine, header, separator, ...rows, bottomLine].join('\\n');\n}\n","export interface MetaError extends Error {\n error: {\n message: string;\n type: string;\n code: number;\n error_data?: {\n messaging_product: 'whatsapp';\n details: string;\n };\n error_subcode?: number;\n fbtrace_id: string;\n };\n}\n\n/**\n * Determines if the error is a Meta API error response\n * @param error Any error object to check\n * @returns Type guard indicating if error is a Meta API error\n */\nexport function isMetaError(error: any): error is MetaError {\n return (\n error != null &&\n typeof error === 'object' &&\n 'error' in error &&\n typeof error.error === 'object' &&\n error.error != null &&\n 'message' in error.error &&\n typeof error.error.message === 'string' &&\n 'type' in error.error &&\n typeof error.error.type === 'string' &&\n 'code' in error.error &&\n typeof error.error.code === 'number' &&\n 'fbtrace_id' in error.error &&\n typeof error.error.fbtrace_id === 'string' &&\n (!('error_data' in error.error) ||\n (typeof error.error.error_data === 'object' &&\n error.error.error_data != null &&\n 'messaging_product' in error.error.error_data &&\n error.error.error_data.messaging_product === 'whatsapp' &&\n 'details' in error.error.error_data &&\n typeof error.error.error_data.details === 'string')) &&\n (!('error_subcode' in error.error) || typeof error.error.error_subcode === 'number')\n );\n}\n","import { Agent } from 'https';\n\nimport { HttpMethodsEnum } from '../../types/enums';\nimport { HttpsClientClass, HttpsClientResponseClass, ResponseHeaders, ResponseJSONBody } from '../../types/httpsClient';\nimport Logger from '../logger';\n\nconst LIB_NAME = 'HttpsClient';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class HttpsClient implements HttpsClientClass {\n agent: Agent;\n\n constructor() {\n this.agent = new Agent({ keepAlive: true });\n }\n\n clearSockets(): boolean {\n this.agent.destroy();\n return true;\n }\n\n async sendRequest(\n hostname: string,\n path: string,\n method: HttpMethodsEnum,\n headers: HeadersInit,\n timeout: number,\n body?: BodyInit | null,\n ): Promise<HttpsClientResponseClass> {\n const url = `https://${hostname}/${path}`;\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n try {\n const response = await fetch(url, {\n method,\n headers,\n body,\n signal: controller.signal,\n });\n LOGGER.log(`${method} : ${url} - ${JSON.stringify(response)}`);\n\n clearTimeout(timeoutId);\n return new HttpsClientResponse(response);\n } catch (error) {\n LOGGER.error(`${method} : ${url} - ${JSON.stringify(error)}`);\n throw error;\n }\n }\n}\n\nexport class HttpsClientResponse implements HttpsClientResponseClass {\n res: Response;\n respStatusCode: number;\n respHeaders: ResponseHeaders;\n\n constructor(resp: Response) {\n this.res = resp;\n this.respStatusCode = resp.status;\n this.respHeaders = Object.fromEntries(resp.headers.entries());\n }\n\n statusCode(): number {\n return this.respStatusCode;\n }\n\n headers(): ResponseHeaders {\n return this.respHeaders;\n }\n\n rawResponse(): Response {\n return this.res;\n }\n\n async json(): Promise<ResponseJSONBody> {\n try {\n return (await this.res.json()) as ResponseJSONBody;\n } catch (err) {\n // TODO Error Handling\n throw new Error('Failed to parse response body to JSON: ' + (err as Error).message);\n }\n }\n}\n","import type { HttpMethodsEnum } from '../../types/enums';\nimport type { RequesterClass } from '../../types/request';\nimport { isMetaError, MetaError } from '../isMetaError';\nimport Logger from '../logger';\nimport HttpsClient from './httpsClient';\n\nconst LIB_NAME = 'REQUESTER';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class Requester implements RequesterClass {\n client: Readonly<HttpsClient>;\n accessToken: Readonly<string>;\n phoneNumberId: Readonly<number>;\n businessAcctId: Readonly<string>;\n apiVersion: Readonly<string>;\n userAgent: Readonly<string>;\n host: Readonly<string>;\n protocol: Readonly<string> = 'https:';\n\n constructor(\n apiVersion: string,\n phoneNumberId: number,\n accessToken: string,\n businessAcctId: string,\n userAgent: string,\n ) {\n this.client = new HttpsClient();\n this.host = 'graph.facebook.com';\n this.apiVersion = apiVersion || '22';\n this.phoneNumberId = phoneNumberId;\n this.accessToken = accessToken;\n this.businessAcctId = businessAcctId;\n this.userAgent = userAgent;\n }\n\n buildHeader(contentType: string, additionalHeaders?: Record<string, string>): HeadersInit {\n const headers: HeadersInit = {\n Authorization: `Bearer ${this.accessToken}`,\n 'User-Agent': this.userAgent,\n };\n\n if (contentType !== 'multipart/form-data') {\n headers['Content-Type'] = contentType;\n }\n\n if (additionalHeaders) {\n Object.assign(headers, additionalHeaders);\n }\n\n return headers;\n }\n\n buildCAPIPath(endpoint: string): string {\n return `v${this.apiVersion}.0/${endpoint}`;\n }\n\n async sendRequest(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n body?: any,\n contentType: string = 'application/json',\n additionalHeaders?: Record<string, string>,\n ) {\n let effectiveContentType = contentType;\n\n if (body instanceof FormData) {\n effectiveContentType = 'multipart/form-data';\n } else if (typeof body === 'string' && body.startsWith('<?xml')) {\n effectiveContentType = 'application/xml';\n }\n\n const path = `${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(endpoint)}`;\n\n LOGGER.log(`${method} : ${path} (${effectiveContentType})`);\n\n try {\n const response = await this.client.sendRequest(\n this.host,\n this.buildCAPIPath(endpoint),\n method,\n this.buildHeader(effectiveContentType, additionalHeaders),\n timeout,\n method === 'POST' || method === 'PUT' ? body : undefined,\n );\n\n if (!response.rawResponse().ok) {\n const errorData = await response.json();\n if (isMetaError(errorData)) {\n throw errorData;\n }\n // If the error doesn't match Meta's format, create a generic MetaError\n throw {\n name: 'MetaError',\n message: 'Unknown error occurred',\n error: {\n message: errorData.message || 'Unknown error occurred',\n type: 'UnknownError',\n code: response.statusCode(),\n fbtrace_id: '',\n },\n } as MetaError;\n }\n\n return response;\n } catch (error) {\n if (isMetaError(error)) {\n throw error;\n }\n // Handle network errors or other unexpected errors\n throw {\n name: 'MetaError',\n message: error instanceof Error ? error.message : 'Network error occurred',\n error: {\n message: error instanceof Error ? error.message : 'Network error occurred',\n type: 'NetworkError',\n code: 500,\n fbtrace_id: '',\n },\n } as MetaError;\n }\n }\n\n async getJson<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n body?: any,\n additionalHeaders?: Record<string, string>,\n ): Promise<T> {\n const res = await this.sendRequest(method, endpoint, timeout, body, 'application/json', additionalHeaders);\n return (await res.json()) as T;\n }\n\n async sendFormData<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n formData: FormData,\n additionalHeaders?: Record<string, string>,\n ): Promise<T> {\n const res = await this.sendRequest(\n method,\n endpoint,\n timeout,\n formData,\n 'multipart/form-data',\n additionalHeaders,\n );\n return (await res.json()) as T;\n }\n\n async sendUrlEncodedForm<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n formData: Record<string, string>,\n additionalHeaders?: Record<string, string>,\n ): Promise<T> {\n const urlEncodedBody = new URLSearchParams(formData).toString();\n const res = await this.sendRequest(\n method,\n endpoint,\n timeout,\n urlEncodedBody,\n 'application/x-www-form-urlencoded',\n additionalHeaders,\n );\n return (await res.json()) as T;\n }\n}\n","import { readFileSync } from 'fs';\nimport { join } from 'path';\n\n/**\n * Get SDK version from package.json\n */\nexport function getVersion(): string {\n try {\n const packagePath = join(__dirname, '../../package.json');\n const packageJson = JSON.parse(readFileSync(packagePath, 'utf-8'));\n return packageJson.version;\n } catch (error) {\n return 'unknown';\n }\n}\n\n/**\n * Generate User-Agent string following official SDK pattern\n */\nexport function getUserAgent(): string {\n const version = getVersion();\n const nodeVersion = process.version;\n return `WhatsApp-Nodejs-SDK/${version} (Node.js ${nodeVersion})`;\n}\n","import type { WabaConfigType } from './config';\n\nexport declare class BaseClass {\n constructor(config: WabaConfigType);\n}\n\nimport { HttpMethodsEnum } from './enums';\nimport type { RequesterClass } from './request';\n\nexport class BaseAPI implements BaseClass {\n protected config: WabaConfigType;\n protected client: RequesterClass;\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n this.config = config;\n this.client = client;\n }\n\n protected sendJson<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any): Promise<T> {\n return this.client.getJson<T>(method, endpoint, timeout, body);\n }\n\n protected sendFormData<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any): Promise<T> {\n return this.client.sendFormData<T>(method, endpoint, timeout, body);\n }\n\n protected sendUrlEncodedForm<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n body?: any,\n ): Promise<T> {\n return this.client.sendUrlEncodedForm<T>(method, endpoint, timeout, body);\n }\n}\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../types/request';\nimport type { EncryptionClass, EncryptionPublicKeyResponse } from './types';\n\nexport default class EncryptionApi extends BaseAPI implements EncryptionClass {\n private readonly endpoint = 'whatsapp_business_encryption';\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n async getEncryptionPublicKey(): Promise<EncryptionPublicKeyResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async setEncryptionPublicKey(businessPublicKey: string): Promise<ResponseSuccess> {\n const formData = new FormData();\n formData.append('business_public_key', businessPublicKey);\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n formData,\n );\n }\n}\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../types/request';\n\nimport type * as flow from './types';\n\n/**\n * API for managing WhatsApp Flows.\n *\n * This API allows you to:\n * - List flows\n * - Create flows\n * - Get flow details and previews\n * - Update flow metadata and JSON\n * - Delete flows\n * - Publish and deprecate flows\n * - Migrate flows between WABAs\n * - Validate flow JSON\n */\nexport default class FlowApi extends BaseAPI implements flow.FlowClass {\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * List Flows\n *\n * @param wabaId - The WABA ID\n * @returns Promise with the list of flows\n */\n async listFlows(wabaId: string): Promise<flow.FlowsListResponse> {\n return this.sendJson(HttpMethodsEnum.Get, `/${wabaId}/flows`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n /**\n * Create Flow\n *\n * @param wabaId - The WABA ID\n * @param data - The flow data including name, categories, endpoint_uri, and optional clone_flow_id\n * @returns Promise with the created flow ID and validation errors if any\n */\n async createFlow(\n wabaId: string,\n data: {\n name: string;\n categories?: flow.FlowCategoryEnum[];\n endpoint_uri?: string;\n clone_flow_id?: string;\n flow_json?: string; // Flow JSON as a string\n publish?: boolean;\n },\n ): Promise<flow.CreateFlowResponse> {\n // The API expects application/json for this endpoint based on documentation examples\n // Let's ensure we send JSON, not FormData, unless specifically required by an endpoint variation.\n const payload = {\n name: data.name,\n categories: data.categories,\n ...(data.endpoint_uri && { endpoint_uri: data.endpoint_uri }),\n ...(data.clone_flow_id && { clone_flow_id: data.clone_flow_id }),\n ...(data.flow_json && { flow_json: data.flow_json }),\n ...(data.publish !== undefined && { publish: data.publish }),\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${wabaId}/flows`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(payload), // Send as JSON\n );\n }\n\n /**\n * Get Flow details\n *\n * @param flowId - The flow ID\n * @param fields - Optional fields to return (e.g., 'name,status,preview.invalidate(false)')\n * @param dateFormat - Optional date format\n * @returns Promise with the flow details or preview response\n */\n async getFlow(flowId: string, fields?: string, dateFormat?: string): Promise<flow.Flow | flow.FlowPreviewResponse> {\n const params = new URLSearchParams();\n if (fields) params.append('fields', fields);\n if (dateFormat) params.append('date_format', dateFormat);\n\n const queryString = params.toString() ? `?${params.toString()}` : '';\n return this.sendJson(\n HttpMethodsEnum.Get,\n `/${flowId}${queryString}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Get Flow Preview URL\n *\n * @param flowId - The flow ID\n * @param invalidate - Optional. If true, invalidates existing preview and generates a new one. Defaults to false.\n * @returns Promise with the flow preview details\n */\n async getFlowPreview(flowId: string, invalidate: boolean = false): Promise<flow.FlowPreviewResponse> {\n const fields = `preview.invalidate(${invalidate})`;\n // Type assertion needed as getFlow can return Flow or FlowPreviewResponse\n return this.getFlow(flowId, fields) as Promise<flow.FlowPreviewResponse>;\n }\n\n /**\n * Update Flow Metadata\n *\n * @param flowId - The flow ID\n * @param data - The flow metadata to update (name, categories, endpoint_uri, application_id)\n * @returns Promise with the success status\n */\n async updateFlowMetadata(\n flowId: string,\n data: {\n name?: string;\n categories?: flow.FlowCategoryEnum[];\n endpoint_uri?: string;\n application_id?: string;\n },\n ): Promise<ResponseSuccess> {\n // The API expects application/json for this endpoint based on documentation examples\n const payload = {\n ...(data.name && { name: data.name }),\n ...(data.categories && { categories: data.categories }),\n ...(data.endpoint_uri && { endpoint_uri: data.endpoint_uri }),\n ...(data.application_id && { application_id: data.application_id }),\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(payload), // Send as JSON\n );\n }\n\n /**\n * Delete Flow (only works if the Flow is in DRAFT status)\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async deleteFlow(flowId: string): Promise<ResponseSuccess> {\n return this.sendJson(HttpMethodsEnum.Delete, `/${flowId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n /**\n * List Assets (e.g., get Flow JSON download URL)\n *\n * @param flowId - The flow ID\n * @returns Promise with the list of assets\n */\n async listAssets(flowId: string): Promise<flow.FlowAssetsResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `/${flowId}/assets`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Update Flow JSON by uploading a file, buffer, JSON object, or Blob.\n *\n * @param flowId - The flow ID\n * @param data - Object containing the file data and optional name.\n * @param data.file - The Flow JSON content as a Buffer, JSON object, or Blob.\n * @param data.name - Optional name for the asset, defaults to 'flow.json'.\n * @returns Promise with the success status and validation errors, if any.\n */\n async updateFlowJson(\n flowId: string,\n data: {\n file: Blob | Buffer | object; // JSON object, Buffer, or Blob\n name?: string; // Default to \"flow.json\"\n },\n ): Promise<flow.UpdateFlowResponse> {\n const formData = new FormData();\n let fileContent: Blob;\n\n // Handle different input types for the file\n if (data.file instanceof Buffer) {\n // Buffer\n // Create a Blob from the Buffer and cast it to the global Blob type\n fileContent = new globalThis.Blob([data.file]);\n formData.append('file', fileContent as unknown as Blob);\n } else if (typeof data.file === 'object' && !(data.file instanceof Blob)) {\n // JSON object - stringify and create Blob\n try {\n // Create a Blob from the JSON string and cast it to the global Blob type\n fileContent = new globalThis.Blob([JSON.stringify(data.file, null, 2)], { type: 'application/json' });\n formData.append('file', fileContent as unknown as Blob);\n } catch (e) {\n throw new Error('Failed to stringify JSON object for Flow JSON update.');\n }\n } else if (data.file instanceof Blob) {\n // Blob (already in correct format)\n fileContent = data.file;\n formData.append('file', fileContent as unknown as Blob);\n } else {\n throw new Error('Invalid file type provided for Flow JSON update. Must be a Buffer, JSON object, or Blob.');\n }\n\n formData.append('asset_type', 'FLOW_JSON'); // Required by API\n formData.append('name', data.name || 'flow.json'); // Required by API\n\n return this.sendFormData(\n HttpMethodsEnum.Post,\n `/${flowId}/assets`,\n this.config[WabaConfigEnum.RequestTimeout],\n formData,\n );\n }\n\n /**\n * Validate Flow JSON by attempting an update without publishing.\n * This is a convenience method; the API doesn't have a dedicated validation endpoint.\n *\n * @param flowId - The ID of the Flow (must exist, can be in DRAFT status).\n * @param flowJsonData - The Flow JSON content as a file path (string), Buffer, JSON object, or Blob.\n * @returns Promise indicating if the JSON is valid and includes validation errors if any.\n */\n async validateFlowJson(\n flowId: string,\n flowJsonData: Blob | Buffer | object,\n ): Promise<flow.ValidateFlowJsonResponse> {\n try {\n const result = await this.updateFlowJson(flowId, {\n file: flowJsonData,\n });\n\n const isValid = !result.validation_errors || result.validation_errors.length === 0;\n\n const enhancedResponse = {\n ...result,\n valid: isValid,\n };\n\n return enhancedResponse;\n } catch (error) {\n throw error;\n }\n }\n\n /**\n * Publish Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async publishFlow(flowId: string): Promise<ResponseSuccess> {\n // This endpoint expects an empty JSON body or no body\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}/publish`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify({}), // Send empty JSON object\n );\n }\n\n /**\n * Deprecate Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async deprecateFlow(flowId: string): Promise<ResponseSuccess> {\n // This endpoint expects an empty JSON body or no body\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}/deprecate`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify({}), // Send empty JSON object\n );\n }\n\n /**\n * Migrate Flows between WABAs\n *\n * @param destinationWabaId - The destination WABA ID\n * @param data - The migration data including source_waba_id and optional source_flow_names\n * @returns Promise with migration results (successes and failures)\n */\n async migrateFlows(\n destinationWabaId: string,\n data: {\n source_waba_id: string;\n source_flow_names?: string[];\n },\n ): Promise<flow.FlowMigrationResponse> {\n // API documentation suggests this endpoint might expect application/json\n // Let's double-check or assume JSON based on typical Graph API patterns unless FormData is confirmed.\n // Assuming JSON for now:\n const payload = {\n source_waba_id: data.source_waba_id,\n ...(data.source_flow_names && { source_flow_names: data.source_flow_names }),\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${destinationWabaId}/migrate_flows`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(payload),\n );\n }\n}\n","import { ResponseSuccess } from '../../../types';\nimport { IncomingHttpHeaders, IncomingMessage } from 'http';\n\n/**\n * Enum for Flow Status\n */\nexport enum FlowStatusEnum {\n Draft = 'DRAFT',\n Published = 'PUBLISHED',\n Throttled = 'THROTTLED',\n Blocked = 'BLOCKED',\n Deprecated = 'DEPRECATED',\n}\n\n/**\n * Enum for Flow Categories\n */\nexport enum FlowCategoryEnum {\n SignUp = 'SIGN_UP',\n SignIn = 'SIGN_IN',\n AppointmentBooking = 'APPOINTMENT_BOOKING',\n LeadGeneration = 'LEAD_GENERATION',\n ContactUs = 'CONTACT_US',\n CustomerSupport = 'CUSTOMER_SUPPORT',\n Survey = 'SURVEY',\n Other = 'OTHER',\n}\n\nexport enum FlowActionEnum {\n INIT = 'INIT',\n BACK = 'BACK',\n DATA_EXCHANGE = 'data_exchange',\n}\n\n/**\n * Enum for Flow Types in webhook handlers\n * Used to register handlers for specific flow events\n */\nexport enum FlowTypeEnum {\n /** Health check/ping requests */\n Ping = 'ping',\n /** Data exchange requests */\n Change = 'data_exchange',\n /** Error notification requests */\n Error = 'error',\n /** Match all flow action types */\n All = '*',\n}\n\nexport type FlowType = (typeof FlowTypeEnum)[keyof typeof FlowTypeEnum];\n\n/**\n * Flow Validation Error Pointer\n */\nexport interface FlowValidationErrorPointer {\n line_start: number;\n line_end: number;\n column_start: number;\n column_end: number;\n path: string;\n}\n\n/**\n * Flow Validation Error\n */\nexport interface FlowValidationError {\n error: string;\n error_type: string;\n message: string;\n line_start: number;\n line_end: number;\n column_start: number;\n column_end: number;\n pointers: FlowValidationErrorPointer[];\n}\n\n/**\n * Flow Item\n */\nexport interface Flow {\n id: string;\n name: string;\n status: FlowStatusEnum;\n categories: FlowCategoryEnum[];\n validation_errors: FlowValidationError[];\n}\n\n/**\n * Pagination Cursors\n */\nexport interface PaginationCursors {\n before: string;\n after: string;\n}\n\n/**\n * Pagination Object\n */\nexport interface Pagination {\n cursors: PaginationCursors;\n}\n\n/**\n * Flows List Response\n */\nexport interface FlowsListResponse {\n data: Flow[];\n paging: Pagination;\n}\n\n/**\n * Flow Asset\n */\nexport interface FlowAsset {\n name: string;\n asset_type: string;\n download_url: string;\n}\n\n/**\n * Flow Assets Response\n */\nexport interface FlowAssetsResponse {\n data: FlowAsset[];\n paging: Pagination;\n}\n\n/**\n * Flow Preview\n */\nexport interface FlowPreview {\n preview_url: string;\n expires_at: string;\n}\n\n/**\n * Flow Preview Response\n */\nexport interface FlowPreviewResponse {\n preview: FlowPreview;\n id: string;\n}\n\n/**\n * Flow Migration Result\n */\nexport interface FlowMigrationResult {\n source_name: string;\n source_id: string;\n migrated_id: string;\n}\n\n/**\n * Flow Migration Failure\n */\nexport interface FlowMigrationFailure {\n source_name: string;\n error_code: string;\n error_message: string;\n}\n\n/**\n * Create Flow Response\n */\nexport interface CreateFlowResponse {\n id: string;\n success: boolean;\n validation_errors?: FlowValidationError[];\n}\n\n/**\n * Update Flow Response\n */\nexport interface UpdateFlowResponse {\n success: boolean;\n validation_errors?: FlowValidationError[];\n}\n\n/**\n * Flow Migration Response\n */\nexport interface FlowMigrationResponse {\n migrated_flows: FlowMigrationResult[];\n failed_flows: FlowMigrationFailure[];\n}\n\n/**\n * Validate Flow JSON Response\n */\nexport interface ValidateFlowJsonResponse {\n valid: boolean;\n success: boolean;\n validation_errors?: FlowValidationError[];\n}\n\n/**\n * WhatsApp Flow Endpoint - Encrypted Request Payload\n * Represents the raw encrypted data received from WhatsApp\n */\nexport interface FlowEncryptedRequestPayload {\n encrypted_aes_key: string;\n encrypted_flow_data: string;\n initial_vector: string;\n}\n\n/**\n * WhatsApp Flow Endpoint - Decrypted Request Response\n * Represents the successfully decrypted data and encryption keys\n */\nexport interface FlowDecryptedRequestResponse {\n decryptedBody: any;\n aesKeyBuffer: Buffer;\n initialVectorBuffer: Buffer;\n}\n\n/**\n * WhatsApp Flow Endpoint - HTTP Request with Body\n * Represents an HTTP request with the encrypted payload\n */\nexport interface FlowHttpRequest extends IncomingMessage {\n body: FlowEncryptedRequestPayload;\n headers: IncomingHttpHeaders;\n}\n\n/**\n * WhatsApp Flow Endpoint - Health Check Request\n * Represents the structure of a health check request\n */\nexport interface FlowHealthCheckRequest {\n action: 'ping';\n version: '3.0';\n}\n\n/**\n * WhatsApp Flow Endpoint - Health Check Response\n * The expected response structure for health check requests\n */\nexport interface FlowHealthCheckResponse {\n data: {\n status: 'active';\n };\n}\n\n/**\n * WhatsApp Flow Endpoint - Data Exchange Request\n * Represents the structure of a data exchange request\n */\nexport interface FlowDataExchangeRequest {\n version: '3.0';\n action: FlowActionEnum;\n screen: string;\n flow_token: string;\n data?: Record<string, any> & { error_message?: string };\n}\n\n/**\n * WhatsApp Flow Endpoint - Data Exchange Response\n * The expected response structure for data exchange requests\n */\nexport interface FlowDataExchangeResponse {\n screen?: string;\n data?: Record<string, any | { error_message?: string }>;\n}\n\n/**\n * WhatsApp Flow Endpoint - Success Screen Response\n * The expected response structure for success screen requests\n */\nexport interface FlowSuccessScreenResponse {\n screen: 'SUCCESS';\n data: {\n extension_message_response?: {\n params?: {\n flow_token: string;\n [key: string]: string;\n };\n };\n };\n}\n\n/**\n * WhatsApp Flow Endpoint - Error Notification Request\n * Represents the structure of an error notification request\n */\nexport interface FlowErrorNotificationRequest {\n version: '3.0';\n action: Exclude<FlowActionEnum, FlowActionEnum.BACK>;\n screen: string;\n flow_token: string;\n data: {\n error: string;\n error_message: string;\n };\n}\n\n/**\n * WhatsApp Flow Endpoint - Error Notification Response\n * The expected response structure for error notification requests\n */\nexport interface FlowErrorNotificationResponse {\n acknowledged: boolean;\n}\n\n/**\n * WhatsApp Flow Endpoint - Comprehensive Request Object\n * A combined type that includes all possible fields from different request types\n * with all fields being optional for flexibility\n */\nexport interface FlowEndpointRequest {\n // Common fields\n version?: '3.0';\n action?: 'ping' | FlowActionEnum;\n\n screen?: string;\n flow_token?: string;\n\n data?: Record<string, any> & {\n error_key?: string;\n error_message?: string;\n };\n}\n\n/**\n * WhatsApp Flow Endpoint - Response\n * Union type for all possible response types from a Flow endpoint\n */\nexport type FlowEndpointResponse =\n | FlowHealthCheckResponse\n | FlowDataExchangeResponse\n | FlowErrorNotificationResponse\n | FlowSuccessScreenResponse;\n\nexport interface FlowClass {\n /**\n * List Flows\n *\n * @param wabaId - The WABA ID\n * @returns Promise with the list of flows\n */\n listFlows(wabaId: string): Promise<FlowsListResponse>;\n\n /**\n * Create Flow\n *\n * @param wabaId - The WABA ID\n * @param data - The flow data including name, categories, endpoint_uri, and optional clone_flow_id\n * @returns Promise with the created flow ID\n */\n createFlow(\n wabaId: string,\n data: {\n name: string;\n categories?: FlowCategoryEnum[];\n endpoint_uri?: string;\n clone_flow_id?: string;\n flow_json?: string;\n publish?: boolean;\n },\n ): Promise<CreateFlowResponse>;\n\n /**\n * Get Flow\n *\n * @param flowId - The flow ID\n * @param fields - Optional fields to return\n * @param dateFormat - Optional date format\n * @returns Promise with the flow details\n */\n getFlow(flowId: string, fields?: string, dateFormat?: string): Promise<Flow | FlowPreviewResponse>;\n\n /**\n * Update Flow Metadata\n *\n * @param flowId - The flow ID\n * @param data - The flow metadata to update\n * @returns Promise with the success status\n */\n updateFlowMetadata(\n flowId: string,\n data: {\n name?: string;\n categories?: FlowCategoryEnum[];\n endpoint_uri?: string;\n application_id?: string;\n },\n ): Promise<ResponseSuccess>;\n\n /**\n * Delete Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n deleteFlow(flowId: string): Promise<ResponseSuccess>;\n\n /**\n * List Assets (Get Flow JSON URL)\n *\n * @param flowId - The flow ID\n * @returns Promise with the list of assets\n */\n listAssets(flowId: string): Promise<FlowAssetsResponse>;\n\n /**\n * Update Flow JSON\n *\n * @param flowId - The flow ID\n * @param data - The asset data including asset_type, file, and name\n * @returns Promise with the success status and validation errors\n */\n updateFlowJson(\n flowId: string,\n data: {\n file: Blob | Buffer | object;\n name?: string;\n },\n ): Promise<UpdateFlowResponse>;\n\n /**\n * Validate Flow JSON by attempting an update without publishing.\n * This is a convenience method; the API doesn't have a dedicated validation endpoint.\n *\n * @param flowId - The ID of the Flow (must exist, can be in DRAFT status).\n * @param flowJsonData - The Flow JSON content as a Buffer, JSON object, or Blob.\n * @returns Promise indicating if the JSON is valid and includes validation errors if any.\n */\n validateFlowJson(flowId: string, flowJsonData: Blob | Buffer | object): Promise<ValidateFlowJsonResponse>;\n\n /**\n * Publish Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n publishFlow(flowId: string): Promise<ResponseSuccess>;\n\n /**\n * Deprecate Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n deprecateFlow(flowId: string): Promise<ResponseSuccess>;\n\n /**\n * Migrate Flows\n *\n * @param wabaId - The destination WABA ID\n * @param data - The migration data including source_waba_id and optional source_flow_names\n * @returns Promise with migration results\n */\n migrateFlows(\n wabaId: string,\n data: {\n source_waba_id: string;\n source_flow_names?: string[];\n },\n ): Promise<FlowMigrationResponse>;\n}\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../types/request';\n\nimport type * as media from './types';\n\n/**\n * API for managing WhatsApp Media.\n *\n * This API allows you to:\n * - Get media information by ID\n * - Upload media files\n * - Delete media files\n * - Download media files from URLs\n */\nexport default class MediaApi extends BaseAPI implements media.MediaClass {\n private readonly endpoint = 'media';\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * Retrieve media information by media ID.\n *\n * @param mediaId The media ID to retrieve information for\n * @param phone_number_id Optional phone number ID (defaults to configured one)\n * @returns Media information including URL, mime type, file size, etc.\n *\n * @example\n * const mediaInfo = await whatsappClient.media.getMediaById('media_id_123');\n */\n async getMediaById(mediaId: string, phone_number_id?: string): Promise<media.MediaResponse> {\n return this.sendJson(HttpMethodsEnum.Get, `${mediaId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n /**\n * Upload a media file to WhatsApp.\n *\n * @param file The file to upload\n * @param messagingProduct The messaging product (default: 'whatsapp')\n * @returns Upload response containing the media ID\n *\n * @example\n * const file = new File([buffer], 'image.jpg', { type: 'image/jpeg' });\n * const result = await whatsappClient.media.uploadMedia(file);\n */\n async uploadMedia(file: File, messagingProduct: string = 'whatsapp'): Promise<media.UploadMediaResponse> {\n const formData = new FormData();\n formData.append('file', file);\n formData.append('messaging_product', messagingProduct);\n formData.append('type', file.type);\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n formData,\n );\n }\n\n /**\n * Delete a media file.\n *\n * @param mediaId The media ID to delete\n * @param phone_number_id Optional phone number ID (defaults to configured one)\n * @returns Response indicating success or failure\n *\n * @example\n * await whatsappClient.media.deleteMedia('media_id_123');\n */\n async deleteMedia(mediaId: string, phone_number_id?: string): Promise<ResponseSuccess> {\n return this.sendJson(HttpMethodsEnum.Delete, `${mediaId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n /**\n * Download media from a URL.\n *\n * @param mediaUrl The URL to download media from\n * @returns Blob containing the media data\n *\n * @example\n * const blob = await whatsappClient.media.downloadMedia('https://...');\n */\n async downloadMedia(mediaUrl: string): Promise<Blob> {\n return this.sendJson(HttpMethodsEnum.Get, mediaUrl, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n}\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport {\n type ComponentTypesEnum,\n HttpMethodsEnum,\n type InteractiveTypesEnum,\n MessageTypesEnum,\n WabaConfigEnum,\n} from '../../types/enums';\nimport type { RequesterClass } from '../../types/request';\n\nimport type * as m from './types';\n\n/**\n * Maps each message type to its appropriate payload type\n */\nexport type MessagePayloadType<T extends MessageTypesEnum> = T extends MessageTypesEnum.Audio\n ? m.AudioMediaObject\n : T extends MessageTypesEnum.Contacts\n ? [m.ContactObject]\n : T extends MessageTypesEnum.Document\n ? m.DocumentMediaObject\n : T extends MessageTypesEnum.Image\n ? m.ImageMediaObject\n : T extends MessageTypesEnum.Interactive\n ? m.InteractiveObject\n : T extends MessageTypesEnum.Location\n ? m.LocationObject\n : T extends MessageTypesEnum.Template\n ? m.MessageTemplateObject<ComponentTypesEnum>\n : T extends MessageTypesEnum.Sticker\n ? m.StickerMediaObject\n : T extends MessageTypesEnum.Text\n ? m.TextObject\n : T extends MessageTypesEnum.Video\n ? m.VideoMediaObject\n : T extends MessageTypesEnum.Reaction\n ? { message_id: string; emoji: string }\n : never;\n\nexport default class MessagesApi extends BaseAPI implements m.MessagesClass {\n private readonly commonMethod = HttpMethodsEnum.Post;\n private readonly commonEndpoint = 'messages';\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * Builds the request body for WhatsApp API messages\n * @param type The type of message to send\n * @param payload The message payload object\n * @param to The recipient's phone number\n * @param replyMessageId Optional message ID to reply to\n * @returns The formatted request body\n */\n bodyBuilder<T extends MessageTypesEnum>(\n type: T,\n payload: MessagePayloadType<T>,\n to: string,\n replyMessageId?: string,\n ) {\n const body: m.MessageRequestBody<T> = {\n messaging_product: 'whatsapp',\n recipient_type: 'individual',\n to,\n type,\n [type]: payload,\n };\n\n if (replyMessageId) body['context'] = { message_id: replyMessageId };\n\n return body;\n }\n\n /**\n * Sends a request to the WhatsApp API\n * @param body The request body to send\n * @returns Promise with the API response\n */\n private send(body: BodyInit | null): Promise<m.MessagesResponse> {\n return this.sendJson(\n this.commonMethod,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.commonEndpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n body,\n );\n }\n\n /**\n * Sends an audio message via WhatsApp\n * @param params The audio message parameter object\n * @returns Promise with the message response\n */\n async audio(params: m.MessageRequestParams<m.AudioMediaObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Audio, body, to, replyMessageId)));\n }\n\n /**\n * Sends a contact card via WhatsApp\n * @param params The contact message parameter object\n * @returns Promise with the message response\n */\n async contacts(params: m.MessageRequestParams<[m.ContactObject]>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Contacts, body, to, replyMessageId)));\n }\n\n /**\n * Sends a document via WhatsApp\n * @param params The document message parameter object\n * @returns Promise with the message response\n */\n async document(params: m.MessageRequestParams<m.DocumentMediaObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Document, body, to, replyMessageId)));\n }\n\n /**\n * Sends an image via WhatsApp\n * @param params The image message parameter object\n * @returns Promise with the message response\n */\n async image(params: m.MessageRequestParams<m.ImageMediaObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Image, body, to, replyMessageId)));\n }\n\n /**\n * Sends an interactive message via WhatsApp\n * @param params The interactive message parameter object\n * @returns Promise with the message response\n */\n async interactive(params: m.MessageRequestParams<m.InteractiveObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Interactive, body, to, replyMessageId)));\n }\n\n /**\n * Sends a location via WhatsApp\n * @param params The location message parameter object\n * @returns Promise with the message response\n */\n async location(params: m.MessageRequestParams<m.LocationObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Location, body, to, replyMessageId)));\n }\n\n /**\n * Sends a sticker via WhatsApp\n * @param params The sticker message parameter object\n * @returns Promise with the message response\n */\n async sticker(params: m.MessageRequestParams<m.StickerMediaObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Sticker, body, to, replyMessageId)));\n }\n\n /**\n * Sends a template message via WhatsApp\n * @param params The template message parameter object\n * @returns Promise with the message response\n */\n async template(\n params: m.MessageRequestParams<m.MessageTemplateObject<ComponentTypesEnum>>,\n ): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Template, body, to, replyMessageId)));\n }\n\n /**\n * Sends a text message via WhatsApp\n * @param params The text message parameter object\n * @returns Promise with the message response\n */\n async text(params: m.TextMessageParams): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId, previewUrl } = params;\n\n // Handle both string and TextObject types\n const textPayload: m.TextObject =\n typeof body === 'string'\n ? { body, preview_url: previewUrl ?? true }\n : { ...body, preview_url: previewUrl ?? body.preview_url ?? true };\n\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Text, textPayload, to, replyMessageId)));\n }\n\n /**\n * Sends a video message via WhatsApp\n * @param params The video message parameter object\n * @returns Promise with the message response\n */\n async video(params: m.MessageRequestParams<m.VideoMediaObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Video, body, to, replyMessageId)));\n }\n\n /**\n * Updates message status (mark as read, etc.)\n * @param params The status update parameters\n * @returns Promise with the API response\n */\n async status(params: m.StatusParams): Promise<m.MessagesResponse> {\n const body = {\n messaging_product: 'whatsapp',\n status: params.status,\n message_id: params.messageId,\n ...(params.typingIndicator && { typing_indicator: params.typingIndicator }),\n };\n\n return this.send(JSON.stringify(body));\n }\n\n /**\n * Marks a message as read\n * @param params Object containing messageId\n * @returns Promise with the API response\n */\n async markAsRead(params: { messageId: string }): Promise<m.MessagesResponse> {\n return this.status({\n status: 'read',\n messageId: params.messageId,\n });\n }\n\n /**\n * Shows typing indicator\n * @param params Object containing messageId\n * @returns Promise with the API response\n */\n async showTypingIndicator(params: { messageId: string }): Promise<m.MessagesResponse> {\n return this.status({\n status: 'read',\n messageId: params.messageId,\n typingIndicator: { type: 'text' },\n });\n }\n\n /**\n * Sends a list interactive message\n * @param params The list interactive message parameters\n * @returns Promise with the message response\n */\n async interactiveList(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.List }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive(params);\n }\n\n /**\n * Sends a CTA URL interactive message\n * @param params The CTA URL interactive message parameters\n * @returns Promise with the message response\n */\n async interactiveCtaUrl(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.CtaUrl }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive(params);\n }\n\n /**\n * Sends a location request interactive message\n * @param params The location request interactive message parameters\n * @returns Promise with the message response\n */\n async interactiveLocationRequest(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.LocationRequest }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive(params);\n }\n\n /**\n * Sends an address message interactive message\n * @param params The address message interactive message parameters\n * @returns Promise with the message response\n */\n async interactiveAddressMessage(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.AddressMessage }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive(params);\n }\n\n /**\n * Sends a reply buttons interactive message\n * @param params The reply buttons interactive message parameters\n * @returns Promise with the message response\n */\n async interactiveReplyButtons(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.Button }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive(params);\n }\n\n /**\n * Sends a flow interactive message\n * @param params The flow interactive message parameters\n * @returns Promise with the message response\n */\n async interactiveFlow(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.Flow }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive(params);\n }\n\n /**\n * Sends a reaction to a message\n * @param params The reaction parameters\n * @returns Promise with the message response\n */\n async reaction(params: m.ReactionParams): Promise<m.MessagesResponse> {\n const reactionPayload = {\n message_id: params.messageId,\n emoji: params.emoji,\n };\n\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Reaction, reactionPayload, params.to)));\n }\n}\n","import type {\n AddressesObject,\n ContactObject,\n EmailObject,\n NameObject,\n OrgObject,\n PhoneObject,\n URLObject,\n} from '../types/contact';\n\n/**\n * Builder class for creating contact messages with a fluent API\n */\nexport class ContactMessageBuilder {\n private contact: Partial<ContactObject> = {};\n\n /**\n * Set the contact name (required)\n */\n setName(name: NameObject): this {\n if (!name || typeof name !== 'object') {\n throw new Error('Name must be an object');\n }\n this.contact.name = name;\n return this;\n }\n\n /**\n * Set simple name with first name only\n */\n setSimpleName(firstName: string, lastName?: string): this {\n if (!firstName || typeof firstName !== 'string') {\n throw new Error('First name must be a non-empty string');\n }\n const name: NameObject = {\n formatted_name: lastName ? `${firstName} ${lastName}` : firstName,\n first_name: firstName,\n };\n if (lastName) {\n name.last_name = lastName;\n }\n return this.setName(name);\n }\n\n /**\n * Set full name details\n */\n setFullName(firstName: string, lastName?: string, middleName?: string, suffix?: string, prefix?: string): this {\n if (!firstName || typeof firstName !== 'string') {\n throw new Error('First name must be a non-empty string');\n }\n\n const nameParts = [prefix, firstName, middleName, lastName, suffix].filter(Boolean);\n const name: NameObject = {\n formatted_name: nameParts.join(' '),\n first_name: firstName,\n };\n\n if (lastName) name.last_name = lastName;\n if (middleName) name.middle_name = middleName;\n if (suffix) name.suffix = suffix;\n if (prefix) name.prefix = prefix;\n\n return this.setName(name);\n }\n\n /**\n * Add phone numbers\n */\n addPhone(phone: string, type?: string, waId?: string): this {\n if (!phone || typeof phone !== 'string') {\n throw new Error('Phone number must be a non-empty string');\n }\n\n const phoneObj: PhoneObject = { phone: 'PHONE_NUMBER' };\n if (type) phoneObj.type = type;\n if (waId) phoneObj.wa_id = waId;\n\n if (!this.contact.phones) {\n this.contact.phones = [];\n }\n this.contact.phones.push(phoneObj);\n return this;\n }\n\n /**\n * Add email addresses\n */\n addEmail(email: string, type?: string): this {\n if (!email || typeof email !== 'string') {\n throw new Error('Email must be a non-empty string');\n }\n if (!email.match(/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/)) {\n throw new Error('Invalid email format');\n }\n\n const emailObj: EmailObject = { email };\n if (type) emailObj.type = type;\n\n if (!this.contact.emails) {\n this.contact.emails = [];\n }\n this.contact.emails.push(emailObj);\n return this;\n }\n\n /**\n * Add address\n */\n addAddress(address: AddressesObject): this {\n if (!address || typeof address !== 'object') {\n throw new Error('Address must be an object');\n }\n\n if (!this.contact.addresses) {\n this.contact.addresses = [];\n }\n this.contact.addresses.push(address);\n return this;\n }\n\n /**\n * Add simple address\n */\n addSimpleAddress(street: string, city: string, country: string, type?: string): this {\n const address: AddressesObject = {\n street,\n city,\n country,\n };\n if (type) address.type = type;\n return this.addAddress(address);\n }\n\n /**\n * Set organization details\n */\n setOrganization(company: string, department?: string, title?: string): this {\n const org: OrgObject = {};\n if (company) org.company = company;\n if (department) org.department = department;\n if (title) org.title = title;\n\n this.contact.org = org;\n return this;\n }\n\n /**\n * Add URL\n */\n addUrl(url: string, type?: string): this {\n if (!url || typeof url !== 'string') {\n throw new Error('URL must be a non-empty string');\n }\n\n const urlObj: URLObject = { url };\n if (type) urlObj.type = type;\n\n if (!this.contact.urls) {\n this.contact.urls = [];\n }\n this.contact.urls.push(urlObj);\n return this;\n }\n\n /**\n * Set birthday (format: YYYY-MM-DD)\n */\n setBirthday(year: number, month: number, day: number): this {\n const monthStr = month.toString().padStart(2, '0');\n const dayStr = day.toString().padStart(2, '0');\n this.contact.birthday = `${year}-${monthStr}-${dayStr}` as ContactObject['birthday'];\n return this;\n }\n\n /**\n * Build the final contact object\n */\n build(): ContactObject {\n if (!this.contact.name) {\n throw new Error('Contact name is required');\n }\n\n return this.contact as ContactObject;\n }\n\n /**\n * Reset the builder for reuse\n */\n reset(): this {\n this.contact = {};\n return this;\n }\n}\n\n/**\n * Factory class for common contact patterns\n */\nexport class ContactMessageFactory {\n /**\n * Create a simple contact with name and phone\n */\n static createSimpleContact(firstName: string, phone: string): ContactObject {\n return new ContactMessageBuilder().setSimpleName(firstName).addPhone(phone).build();\n }\n\n /**\n * Create a business contact\n */\n static createBusinessContact(\n firstName: string,\n lastName: string,\n company: string,\n title: string,\n phone: string,\n email: string,\n ): ContactObject {\n return new ContactMessageBuilder()\n .setSimpleName(firstName, lastName)\n .setOrganization(company, undefined, title)\n .addPhone(phone, 'WORK')\n .addEmail(email, 'WORK')\n .build();\n }\n\n /**\n * Create a personal contact with full details\n */\n static createPersonalContact(\n firstName: string,\n lastName: string,\n mobilePhone: string,\n email?: string,\n birthday?: { year: number; month: number; day: number },\n ): ContactObject {\n const builder = new ContactMessageBuilder().setSimpleName(firstName, lastName).addPhone(mobilePhone, 'MOBILE');\n\n if (email) {\n builder.addEmail(email, 'HOME');\n }\n\n if (birthday) {\n builder.setBirthday(birthday.year, birthday.month, birthday.day);\n }\n\n return builder.build();\n }\n}\n","import { InteractiveTypesEnum } from '../../../types/enums';\nimport type { InteractiveObject } from '../types/interactive';\n\n/**\n * Type guards for different action object types\n */\ntype RowObject = {\n id: string;\n title: string;\n description?: string;\n};\n\ntype SectionObject = {\n title?: string;\n rows: RowObject[];\n};\n\ntype BaseActionObject = {\n buttons?: Array<{ type: 'reply'; reply: { id: string; title: string } }>;\n sections?: SectionObject[];\n button?: string;\n catalog_id?: string;\n product_retailer_id?: string;\n};\n\ntype CtaUrlActionObject = {\n name: 'cta_url';\n parameters: {\n display_text: string;\n url: string;\n };\n};\n\ntype ActionObjectUnion = BaseActionObject | CtaUrlActionObject;\n\nfunction isBaseActionObject(action: ActionObjectUnion): action is BaseActionObject {\n return !('name' in action);\n}\n\nfunction isCtaUrlActionObject(action: ActionObjectUnion): action is CtaUrlActionObject {\n return 'name' in action && action.name === 'cta_url';\n}\n\n/**\n * Builder class for creating interactive messages with a fluent API\n */\nexport class InteractiveMessageBuilder {\n private message: Partial<InteractiveObject> = {};\n\n /**\n * Set the interactive message type\n */\n setType(type: InteractiveTypesEnum): this {\n this.message.type = type;\n return this;\n }\n\n /**\n * Set the body text of the message\n */\n setBody(text: string): this {\n this.message.body = { text };\n return this;\n }\n\n /**\n * Set the footer text of the message\n */\n setFooter(text: string): this {\n this.message.footer = { text };\n return this;\n }\n\n /**\n * Set a text header\n */\n setTextHeader(text: string): this {\n this.message.header = { type: 'text', text };\n return this;\n }\n\n /**\n * Set an image header\n */\n setImageHeader(imageUrl: string): this {\n this.message.header = {\n type: 'image',\n image: { link: imageUrl },\n };\n return this;\n }\n\n /**\n * Add reply buttons (for button type messages)\n */\n addReplyButtons(buttons: Array<{ id: string; title: string }>): this {\n if (!this.message.action) {\n this.message.action = {} as ActionObjectUnion;\n }\n\n const action = this.message.action as ActionObjectUnion;\n if (isBaseActionObject(action)) {\n action.buttons = buttons.map((btn) => ({\n type: 'reply',\n reply: {\n id: btn.id,\n title: btn.title,\n },\n }));\n }\n\n return this;\n }\n\n /**\n * Add list sections (for list type messages)\n * Note: This creates a single section with multiple rows\n */\n addListSections(\n sections: Array<{\n title?: string;\n rows: Array<{ id: string; title: string; description?: string }>;\n }>,\n ): this {\n if (!this.message.action) {\n this.message.action = {} as ActionObjectUnion;\n }\n\n const action = this.message.action as ActionObjectUnion;\n if (isBaseActionObject(action)) {\n // Convert sections to the proper format expected by WhatsApp API\n action.sections = sections.map((section) => ({\n title: section.title,\n rows: section.rows,\n }));\n }\n\n return this;\n }\n\n /**\n * Set the button text for list messages\n */\n setListButtonText(buttonText: string): this {\n if (!this.message.action) {\n this.message.action = {} as ActionObjectUnion;\n }\n\n const action = this.message.action as ActionObjectUnion;\n if (isBaseActionObject(action)) {\n action.button = buttonText;\n }\n\n return this;\n }\n\n /**\n * Set CTA URL action\n */\n setCTAUrl(displayText: string, url: string): this {\n this.message.action = {\n name: 'cta_url',\n parameters: {\n display_text: displayText,\n url: url,\n },\n } as CtaUrlActionObject;\n\n return this;\n }\n\n /**\n * Build the final interactive object\n */\n build(): InteractiveObject {\n if (!this.message.type) {\n throw new Error('Interactive message type is required');\n }\n if (!this.message.body) {\n throw new Error('Interactive message body is required');\n }\n if (!this.message.action) {\n throw new Error('Interactive message action is required');\n }\n\n return this.message as InteractiveObject;\n }\n\n /**\n * Reset the builder for reuse\n */\n reset(): this {\n this.message = {};\n return this;\n }\n}\n\n/**\n * Convenience factory functions for common interactive message types\n */\nexport class InteractiveMessageFactory {\n /**\n * Create a button message with reply buttons\n */\n static createButtonMessage(\n bodyText: string,\n buttons: Array<{ id: string; title: string }>,\n options?: { headerText?: string; footerText?: string },\n ): InteractiveObject {\n const builder = new InteractiveMessageBuilder()\n .setType(InteractiveTypesEnum.Button)\n .setBody(bodyText)\n .addReplyButtons(buttons);\n\n if (options?.headerText) {\n builder.setTextHeader(options.headerText);\n }\n if (options?.footerText) {\n builder.setFooter(options.footerText);\n }\n\n return builder.build();\n }\n\n /**\n * Create a list message with sections\n */\n static createListMessage(\n bodyText: string,\n buttonText: string,\n sections: Array<{\n title?: string;\n rows: Array<{ id: string; title: string; description?: string }>;\n }>,\n options?: { headerText?: string; footerText?: string },\n ): InteractiveObject {\n const builder = new InteractiveMessageBuilder()\n .setType(InteractiveTypesEnum.List)\n .setBody(bodyText)\n .addListSections(sections);\n\n if (options?.headerText) {\n builder.setTextHeader(options.headerText);\n }\n if (options?.footerText) {\n builder.setFooter(options.footerText);\n }\n\n const message = builder.build();\n\n // Add button text for list messages\n const action = message.action as ActionObjectUnion;\n if (isBaseActionObject(action)) {\n action.button = buttonText;\n }\n\n return message;\n }\n\n /**\n * Create a CTA URL message\n */\n static createCTAUrlMessage(\n bodyText: string,\n displayText: string,\n url: string,\n options?: { headerText?: string; footerText?: string },\n ): InteractiveObject {\n const builder = new InteractiveMessageBuilder()\n .setType(InteractiveTypesEnum.CtaUrl)\n .setBody(bodyText)\n .setCTAUrl(displayText, url);\n\n if (options?.headerText) {\n builder.setTextHeader(options.headerText);\n }\n if (options?.footerText) {\n builder.setFooter(options.footerText);\n }\n\n return builder.build();\n }\n}\n","import type { LocationObject } from '../types/location';\n\n/**\n * Builder class for creating location messages with a fluent API\n */\nexport class LocationMessageBuilder {\n private location: Partial<LocationObject> = {};\n\n /**\n * Set the latitude coordinate\n */\n setLatitude(latitude: number): this {\n if (typeof latitude !== 'number' || latitude < -90 || latitude > 90) {\n throw new Error('Latitude must be a number between -90 and 90');\n }\n this.location.latitude = latitude;\n return this;\n }\n\n /**\n * Set the longitude coordinate\n */\n setLongitude(longitude: number): this {\n if (typeof longitude !== 'number' || longitude < -180 || longitude > 180) {\n throw new Error('Longitude must be a number between -180 and 180');\n }\n this.location.longitude = longitude;\n return this;\n }\n\n /**\n * Set coordinates using latitude and longitude\n */\n setCoordinates(latitude: number, longitude: number): this {\n return this.setLatitude(latitude).setLongitude(longitude);\n }\n\n /**\n * Set the location name\n */\n setName(name: string): this {\n if (name && typeof name !== 'string') {\n throw new Error('Location name must be a string');\n }\n this.location.name = name;\n return this;\n }\n\n /**\n * Set the location address\n */\n setAddress(address: string): this {\n if (address && typeof address !== 'string') {\n throw new Error('Location address must be a string');\n }\n this.location.address = address;\n return this;\n }\n\n /**\n * Build the final location object\n */\n build(): LocationObject {\n if (this.location.latitude === undefined) {\n throw new Error('Latitude is required');\n }\n if (this.location.longitude === undefined) {\n throw new Error('Longitude is required');\n }\n\n return this.location as LocationObject;\n }\n\n /**\n * Reset the builder for reuse\n */\n reset(): this {\n this.location = {};\n return this;\n }\n}\n\n/**\n * Factory class for common location patterns\n */\nexport class LocationMessageFactory {\n /**\n * Create a simple location with just coordinates\n */\n static createSimpleLocation(latitude: number, longitude: number): LocationObject {\n return new LocationMessageBuilder().setCoordinates(latitude, longitude).build();\n }\n\n /**\n * Create a location with name and address\n */\n static createNamedLocation(latitude: number, longitude: number, name: string, address: string): LocationObject {\n return new LocationMessageBuilder()\n .setCoordinates(latitude, longitude)\n .setName(name)\n .setAddress(address)\n .build();\n }\n\n /**\n * Create a business location\n */\n static createBusinessLocation(\n latitude: number,\n longitude: number,\n businessName: string,\n fullAddress: string,\n ): LocationObject {\n return new LocationMessageBuilder()\n .setCoordinates(latitude, longitude)\n .setName(businessName)\n .setAddress(fullAddress)\n .build();\n }\n}\n","import type {\n AudioMediaObject,\n DocumentMediaObject,\n ImageMediaObject,\n StickerMediaObject,\n VideoMediaObject,\n} from '../types/media';\n\n/**\n * Base builder for media messages\n */\nabstract class BaseMediaBuilder<T> {\n protected media: Partial<T> = {};\n\n /**\n * Set media ID (for uploaded media)\n */\n setId(id: string): this {\n if (!id || typeof id !== 'string') {\n throw new Error('Media ID must be a non-empty string');\n }\n (this.media as any).id = id;\n return this;\n }\n\n /**\n * Set media URL\n */\n setLink(url: string): this {\n if (!url || typeof url !== 'string') {\n throw new Error('Media URL must be a non-empty string');\n }\n if (!url.match(/^https?:\\/\\//)) {\n throw new Error('Media URL must be a valid HTTP/HTTPS URL');\n }\n (this.media as any).link = url;\n return this;\n }\n\n /**\n * Set media caption\n */\n setCaption(caption: string): this {\n if (caption && typeof caption !== 'string') {\n throw new Error('Caption must be a string');\n }\n (this.media as any).caption = caption;\n return this;\n }\n\n /**\n * Build the media object\n */\n build(): T {\n if (!(this.media as any).id && !(this.media as any).link) {\n throw new Error('Either media ID or link is required');\n }\n return this.media as T;\n }\n\n /**\n * Reset the builder\n */\n reset(): this {\n this.media = {};\n return this;\n }\n}\n\n/**\n * Builder for image messages\n */\nexport class ImageMessageBuilder extends BaseMediaBuilder<ImageMediaObject> {\n // Image inherits all methods from BaseMediaBuilder\n}\n\n/**\n * Builder for video messages\n */\nexport class VideoMessageBuilder extends BaseMediaBuilder<VideoMediaObject> {\n // Video inherits all methods from BaseMediaBuilder\n}\n\n/**\n * Builder for audio messages\n */\nexport class AudioMessageBuilder extends BaseMediaBuilder<AudioMediaObject> {\n // Audio doesn't support caption\n setCaption(caption: string): this {\n throw new Error('Audio messages do not support captions');\n }\n}\n\n/**\n * Builder for document messages\n */\nexport class DocumentMessageBuilder extends BaseMediaBuilder<DocumentMediaObject> {\n /**\n * Set document filename\n */\n setFilename(filename: string): this {\n if (!filename || typeof filename !== 'string') {\n throw new Error('Filename must be a non-empty string');\n }\n this.media.filename = filename;\n return this;\n }\n}\n\n/**\n * Builder for sticker messages\n */\nexport class StickerMessageBuilder extends BaseMediaBuilder<StickerMediaObject> {\n // Sticker doesn't support caption\n setCaption(caption: string): this {\n throw new Error('Sticker messages do not support captions');\n }\n}\n\n/**\n * Factory class for common media patterns\n */\nexport class MediaMessageFactory {\n /**\n * Create an image with caption\n */\n static createImageWithCaption(linkOrId: string, caption: string, isId: boolean = false): ImageMediaObject {\n const builder = new ImageMessageBuilder();\n if (isId) {\n builder.setId(linkOrId);\n } else {\n builder.setLink(linkOrId);\n }\n return builder.setCaption(caption).build();\n }\n\n /**\n * Create a video with caption\n */\n static createVideoWithCaption(linkOrId: string, caption: string, isId: boolean = false): VideoMediaObject {\n const builder = new VideoMessageBuilder();\n if (isId) {\n builder.setId(linkOrId);\n } else {\n builder.setLink(linkOrId);\n }\n return builder.setCaption(caption).build();\n }\n\n /**\n * Create a document with filename\n */\n static createDocument(\n linkOrId: string,\n filename: string,\n caption?: string,\n isId: boolean = false,\n ): DocumentMediaObject {\n const builder = new DocumentMessageBuilder();\n if (isId) {\n builder.setId(linkOrId);\n } else {\n builder.setLink(linkOrId);\n }\n builder.setFilename(filename);\n if (caption) {\n builder.setCaption(caption);\n }\n return builder.build();\n }\n\n /**\n * Create an audio message\n */\n static createAudio(linkOrId: string, isId: boolean = false): AudioMediaObject {\n const builder = new AudioMessageBuilder();\n if (isId) {\n builder.setId(linkOrId);\n } else {\n builder.setLink(linkOrId);\n }\n return builder.build();\n }\n\n /**\n * Create a sticker message\n */\n static createSticker(linkOrId: string, isId: boolean = false): StickerMediaObject {\n const builder = new StickerMessageBuilder();\n if (isId) {\n builder.setId(linkOrId);\n } else {\n builder.setLink(linkOrId);\n }\n return builder.build();\n }\n}\n","/**\n * Builder class for creating reaction messages with a fluent API\n */\nexport class ReactionMessageBuilder {\n private reaction: { message_id?: string; emoji?: string } = {};\n\n /**\n * Set the message ID to react to\n */\n setMessageId(messageId: string): this {\n if (!messageId || typeof messageId !== 'string') {\n throw new Error('Message ID must be a non-empty string');\n }\n this.reaction.message_id = messageId;\n return this;\n }\n\n /**\n * Set the emoji for the reaction\n */\n setEmoji(emoji: string): this {\n if (!emoji || typeof emoji !== 'string') {\n throw new Error('Emoji must be a non-empty string');\n }\n // Validate that it's a single emoji (basic check)\n if (emoji.length > 4) {\n throw new Error('Please provide a single emoji character');\n }\n this.reaction.emoji = emoji;\n return this;\n }\n\n /**\n * Remove a reaction (by sending empty emoji)\n */\n removeReaction(): this {\n this.reaction.emoji = '';\n return this;\n }\n\n /**\n * Build the final reaction object\n */\n build(): { message_id: string; emoji: string } {\n if (!this.reaction.message_id) {\n throw new Error('Message ID is required');\n }\n if (this.reaction.emoji === undefined) {\n throw new Error('Emoji is required (use empty string to remove reaction)');\n }\n\n return this.reaction as { message_id: string; emoji: string };\n }\n\n /**\n * Reset the builder for reuse\n */\n reset(): this {\n this.reaction = {};\n return this;\n }\n}\n\n/**\n * Factory class for common reaction patterns\n */\nexport class ReactionMessageFactory {\n /**\n * Create a like reaction\n */\n static createLike(messageId: string): { message_id: string; emoji: string } {\n return new ReactionMessageBuilder().setMessageId(messageId).setEmoji('👍').build();\n }\n\n /**\n * Create a heart reaction\n */\n static createHeart(messageId: string): { message_id: string; emoji: string } {\n return new ReactionMessageBuilder().setMessageId(messageId).setEmoji('❤️').build();\n }\n\n /**\n * Create a laughing reaction\n */\n static createLaugh(messageId: string): { message_id: string; emoji: string } {\n return new ReactionMessageBuilder().setMessageId(messageId).setEmoji('😂').build();\n }\n\n /**\n * Create a wow reaction\n */\n static createWow(messageId: string): { message_id: string; emoji: string } {\n return new ReactionMessageBuilder().setMessageId(messageId).setEmoji('😮').build();\n }\n\n /**\n * Create a sad reaction\n */\n static createSad(messageId: string): { message_id: string; emoji: string } {\n return new ReactionMessageBuilder().setMessageId(messageId).setEmoji('😢').build();\n }\n\n /**\n * Create an angry reaction\n */\n static createAngry(messageId: string): { message_id: string; emoji: string } {\n return new ReactionMessageBuilder().setMessageId(messageId).setEmoji('😠').build();\n }\n\n /**\n * Remove a reaction\n */\n static removeReaction(messageId: string): { message_id: string; emoji: string } {\n return new ReactionMessageBuilder().setMessageId(messageId).removeReaction().build();\n }\n}\n","import {\n ButtonPositionEnum,\n ComponentTypesEnum,\n CurrencyCodesEnum,\n LanguagesEnum,\n ParametersTypesEnum,\n SubTypeEnum,\n} from '../../../types/enums';\nimport type { MessageTemplateObject } from '../types/template';\n\n// Helper type for currency parameter\nexport type CurrencyParameterHelper = {\n type: ParametersTypesEnum.Currency;\n currency: {\n fallback_value: string;\n code: CurrencyCodesEnum;\n amount_1000: number;\n };\n};\n\n// Helper type for date time parameter\nexport type DateTimeParameterHelper = {\n type: ParametersTypesEnum.DateTime;\n date_time: {\n fallback_value: string;\n timestamp: number;\n };\n};\n\n// Union type for all parameter helpers\nexport type ParameterObject = CurrencyParameterHelper | DateTimeParameterHelper;\n\n// Type guards for validation\nfunction isValidLanguageCode(code: string): code is LanguagesEnum {\n return Object.values(LanguagesEnum).includes(code as LanguagesEnum);\n}\n\nfunction isValidButtonPosition(index: number): index is ButtonPositionEnum {\n return Object.values(ButtonPositionEnum).includes(index as ButtonPositionEnum);\n}\n\n/**\n * Builder class for creating template messages with a fluent API\n */\nexport class TemplateMessageBuilder {\n private template: Partial<MessageTemplateObject<ComponentTypesEnum>> = {\n components: [],\n };\n\n /**\n * Set the template name\n */\n setName(name: string): this {\n if (!name || name.trim().length === 0) {\n throw new Error('Template name cannot be empty');\n }\n this.template.name = name;\n return this;\n }\n\n /**\n * Set the template language\n */\n setLanguage(code: string): this {\n if (!isValidLanguageCode(code)) {\n throw new Error(`Invalid language code: ${code}. Must be a valid LanguagesEnum value.`);\n }\n this.template.language = { policy: 'deterministic', code };\n return this;\n }\n\n /**\n * Add a header component with text parameters\n */\n addTextHeader(parameters: string[]): this {\n if (!Array.isArray(parameters)) {\n throw new Error('Parameters must be an array');\n }\n\n const headerComponent = {\n type: ComponentTypesEnum.Header,\n parameters: parameters.map((param) => {\n if (typeof param !== 'string') {\n throw new Error('All parameters must be strings');\n }\n return { type: ParametersTypesEnum.Text, text: param };\n }),\n };\n\n if (!this.template.components) {\n this.template.components = [];\n }\n this.template.components.push(headerComponent as any);\n return this;\n }\n\n /**\n * Add a header component with image\n */\n addImageHeader(imageUrl: string): this {\n if (!imageUrl || typeof imageUrl !== 'string') {\n throw new Error('Image URL must be a non-empty string');\n }\n\n const headerComponent = {\n type: ComponentTypesEnum.Header,\n parameters: [\n {\n type: ParametersTypesEnum.Image,\n image: { link: imageUrl },\n },\n ],\n };\n\n if (!this.template.components) {\n this.template.components = [];\n }\n this.template.components.push(headerComponent as any);\n return this;\n }\n\n /**\n * Add a body component with text parameters\n */\n addBody(parameters: string[]): this {\n if (!Array.isArray(parameters)) {\n throw new Error('Parameters must be an array');\n }\n\n const bodyComponent = {\n type: ComponentTypesEnum.Body,\n parameters: parameters.map((param) => {\n if (typeof param !== 'string') {\n throw new Error('All parameters must be strings');\n }\n return { type: ParametersTypesEnum.Text, text: param };\n }),\n };\n\n if (!this.template.components) {\n this.template.components = [];\n }\n this.template.components.push(bodyComponent as any);\n return this;\n }\n\n /**\n * Add a footer component (usually no parameters needed)\n */\n addFooter(): this {\n const footerComponent = {\n type: ComponentTypesEnum.Footer,\n };\n\n if (!this.template.components) {\n this.template.components = [];\n }\n this.template.components.push(footerComponent as any);\n return this;\n }\n\n /**\n * Add button components (for quick replies, URLs, etc.)\n */\n addButtons(\n buttons: Array<{\n index: number;\n type: 'quick_reply' | 'url';\n parameters?: string[];\n }>,\n ): this {\n if (!Array.isArray(buttons)) {\n throw new Error('Buttons must be an array');\n }\n\n buttons.forEach((button) => {\n if (typeof button.index !== 'number' || !isValidButtonPosition(button.index)) {\n throw new Error(`Button index must be a valid ButtonPositionEnum value: ${button.index}`);\n }\n\n // Map string types to SubTypeEnum values\n const subType = button.type === 'quick_reply' ? SubTypeEnum.QuickReply : SubTypeEnum.Url;\n\n const buttonComponent = {\n type: ComponentTypesEnum.Button,\n sub_type: subType,\n index: button.index,\n } as any;\n\n if (button.parameters && button.parameters.length > 0) {\n if (!Array.isArray(button.parameters)) {\n throw new Error('Button parameters must be an array');\n }\n\n // Handle different parameter types based on button type\n if (button.type === 'quick_reply') {\n // Quick reply buttons use payload parameters\n buttonComponent.parameters = button.parameters.map((param) => {\n if (typeof param !== 'string') {\n throw new Error('All button parameters must be strings');\n }\n return { type: ParametersTypesEnum.Payload, payload: param };\n });\n } else if (button.type === 'url') {\n // URL buttons use text parameters\n buttonComponent.parameters = button.parameters.map((param) => {\n if (typeof param !== 'string') {\n throw new Error('All button parameters must be strings');\n }\n return { type: ParametersTypesEnum.Text, text: param };\n });\n }\n }\n\n if (!this.template.components) {\n this.template.components = [];\n }\n this.template.components.push(buttonComponent);\n });\n\n return this;\n }\n\n /**\n * Add a currency parameter for header/body\n */\n addCurrencyParameter(fallbackValue: string, currencyCode: string, amount: number): CurrencyParameterHelper {\n if (!fallbackValue || typeof fallbackValue !== 'string') {\n throw new Error('Fallback value must be a non-empty string');\n }\n if (!currencyCode || typeof currencyCode !== 'string') {\n throw new Error('Currency code must be a non-empty string');\n }\n if (typeof amount !== 'number' || amount < 0) {\n throw new Error('Amount must be a non-negative number');\n }\n\n return {\n type: ParametersTypesEnum.Currency,\n currency: {\n fallback_value: fallbackValue,\n code: currencyCode as CurrencyCodesEnum,\n amount_1000: amount * 1000, // WhatsApp expects amount in smallest unit\n },\n };\n }\n\n /**\n * Add a date time parameter\n */\n addDateTimeParameter(fallbackValue: string, timestamp: number): DateTimeParameterHelper {\n if (!fallbackValue || typeof fallbackValue !== 'string') {\n throw new Error('Fallback value must be a non-empty string');\n }\n if (typeof timestamp !== 'number' || timestamp <= 0) {\n throw new Error('Timestamp must be a positive number');\n }\n\n return {\n type: ParametersTypesEnum.DateTime,\n date_time: {\n fallback_value: fallbackValue,\n timestamp: timestamp,\n },\n };\n }\n\n /**\n * Build the final template object\n */\n build(): MessageTemplateObject<ComponentTypesEnum> {\n if (!this.template.name) {\n throw new Error('Template name is required');\n }\n if (!this.template.language) {\n throw new Error('Template language is required');\n }\n\n return this.template as MessageTemplateObject<ComponentTypesEnum>;\n }\n\n /**\n * Reset the builder for reuse\n */\n reset(): this {\n this.template = { components: [] };\n return this;\n }\n}\n\n/**\n * Factory class for common template patterns\n */\nexport class TemplateMessageFactory {\n /**\n * Create a simple text-only template\n */\n static createSimpleTextTemplate(\n name: string,\n language: string,\n bodyParameters: string[],\n ): MessageTemplateObject<ComponentTypesEnum> {\n if (!name || !language || !Array.isArray(bodyParameters)) {\n throw new Error('Invalid parameters for simple text template');\n }\n\n return new TemplateMessageBuilder().setName(name).setLanguage(language).addBody(bodyParameters).build();\n }\n\n /**\n * Create a template with header, body and buttons\n */\n static createCompleteTemplate(\n name: string,\n language: string,\n options: {\n headerParameters?: string[];\n headerImage?: string;\n bodyParameters: string[];\n buttons?: Array<{\n index: number;\n type: 'quick_reply' | 'url';\n parameters?: string[];\n }>;\n },\n ): MessageTemplateObject<ComponentTypesEnum> {\n if (!name || !language || !options.bodyParameters) {\n throw new Error('Invalid parameters for complete template');\n }\n\n const builder = new TemplateMessageBuilder()\n .setName(name)\n .setLanguage(language)\n .addBody(options.bodyParameters);\n\n if (options.headerParameters) {\n builder.addTextHeader(options.headerParameters);\n } else if (options.headerImage) {\n builder.addImageHeader(options.headerImage);\n }\n\n if (options.buttons) {\n builder.addButtons(options.buttons);\n }\n\n return builder.build();\n }\n\n /**\n * Create an order confirmation template\n */\n static createOrderConfirmationTemplate(\n language: string,\n customerName: string,\n orderNumber: string,\n amount: number,\n currencyCode: string,\n ): MessageTemplateObject<ComponentTypesEnum> {\n if (!language || !customerName || !orderNumber || typeof amount !== 'number' || !currencyCode) {\n throw new Error('Invalid parameters for order confirmation template');\n }\n\n return new TemplateMessageBuilder()\n .setName('order_confirmation')\n .setLanguage(language)\n .addBody([customerName, orderNumber, amount.toString(), currencyCode])\n .addButtons([\n { index: 0, type: 'quick_reply' },\n { index: 1, type: 'url', parameters: [orderNumber] },\n ])\n .build();\n }\n}\n","import type { TextObject } from '../types/text';\n\n/**\n * Builder class for creating text messages with a fluent API\n */\nexport class TextMessageBuilder {\n private textMessage: Partial<TextObject> = {};\n\n /**\n * Set the message body text\n */\n setBody(text: string): this {\n if (!text || typeof text !== 'string') {\n throw new Error('Message body must be a non-empty string');\n }\n this.textMessage.body = text;\n return this;\n }\n\n /**\n * Enable or disable URL preview\n */\n setPreviewUrl(enable: boolean = true): this {\n this.textMessage.preview_url = enable;\n return this;\n }\n\n /**\n * Build the final text object\n */\n build(): TextObject {\n if (!this.textMessage.body) {\n throw new Error('Message body is required');\n }\n\n return this.textMessage as TextObject;\n }\n\n /**\n * Reset the builder for reuse\n */\n reset(): this {\n this.textMessage = {};\n return this;\n }\n}\n\n/**\n * Factory class for common text message patterns\n */\nexport class TextMessageFactory {\n /**\n * Create a simple text message\n */\n static createSimpleText(body: string): TextObject {\n return new TextMessageBuilder().setBody(body).build();\n }\n\n /**\n * Create a text message with URL preview\n */\n static createTextWithPreview(body: string): TextObject {\n return new TextMessageBuilder().setBody(body).setPreviewUrl(true).build();\n }\n\n /**\n * Create a notification message\n */\n static createNotification(title: string, message: string): TextObject {\n return new TextMessageBuilder().setBody(`*${title}*\\n\\n${message}`).build();\n }\n}\n","export const objectToQueryString = (params: Record<string, any>): string => {\n if (!params || Object.keys(params).length === 0) {\n return '';\n }\n\n const queryParts: string[] = [];\n\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined) {\n const encodedKey = encodeURIComponent(key);\n const encodedValue = encodeURIComponent(String(value));\n queryParts.push(`${encodedKey}=${encodedValue}`);\n }\n }\n\n return queryParts.length > 0 ? `?${queryParts.join('&')}` : '';\n};\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../types/request';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\n\nimport type * as phoneNumber from './types';\n\n/**\n * API for managing WhatsApp Phone Numb ers.\n *\n * This API allows you to:\n * - Get phone number information by ID\n * - Get all phone numbers for a business account\n * - Request verification codes for phone numbers\n * - Verify phone numbers with codes\n */\nexport default class PhoneNumberApi extends BaseAPI implements phoneNumber.PhoneNumberClass {\n private readonly endpoint = 'phone_numbers';\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * Get phone number information by ID.\n *\n * @param fields Optional comma-separated list of fields to include in the response\n * @returns Phone number information including verification status, quality rating, etc.\n *\n * @example\n * const phoneNumber = await whatsappClient.phoneNumber.getPhoneNumberById();\n * const phoneNumberWithFields = await whatsappClient.phoneNumber.getPhoneNumberById('display_phone_number,verified_name');\n */\n async getPhoneNumberById(fields?: string): Promise<phoneNumber.PhoneNumberResponse> {\n const queryParams = fields ? objectToQueryString({ fields }) : '';\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}${queryParams}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Get all phone numbers for the business account.\n *\n * @returns List of phone numbers associated with the business account\n *\n * @example\n * const phoneNumbers = await whatsappClient.phoneNumber.getPhoneNumbers();\n */\n async getPhoneNumbers(): Promise<phoneNumber.PhoneNumbersResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.BusinessAcctId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Request a verification code for the phone number.\n *\n * @param request Verification code request containing method and language\n * @returns Response indicating success or failure\n *\n * @example\n * await whatsappClient.phoneNumber.requestVerificationCode({\n * code_method: 'SMS',\n * language: 'en_US'\n * });\n */\n async requestVerificationCode(request: phoneNumber.RequestVerificationCodeRequest): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/request_code`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n /**\n * Verify the phone number with the received code.\n *\n * @param request Verification request containing the code\n * @returns Response indicating success or failure\n *\n * @example\n * await whatsappClient.phoneNumber.verifyCode({\n * code: '123456'\n * });\n */\n async verifyCode(request: phoneNumber.VerifyCodeRequest): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/verify_code`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n}\n","export function buildFieldsQueryString(fields?: string[] | string): string {\n if (!fields) return '';\n\n let fieldParams = '';\n\n if (Array.isArray(fields)) {\n fieldParams = fields.join(',');\n } else if (typeof fields === 'string') {\n fieldParams = fields;\n } else {\n fieldParams = Object.entries(fields)\n .filter(([_, value]) => value)\n .map(([key]) => key)\n .join(',');\n }\n\n return fieldParams ? `?fields=${fieldParams}` : '';\n}\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../types/request';\nimport { buildFieldsQueryString } from '../../utils/buildFieldsQueryString';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\n\nimport type * as bp from './types';\n\n/**\n * API for managing WhatsApp Business Profiles and profile pictures.\n *\n * This API allows you to:\n * - Get business profile information\n * - Update business profile details\n * - Upload profile pictures using a three-step process:\n * 1. Create an upload session\n * 2. Upload the image binary data\n * 3. Get the upload handle to use when updating the profile\n */\nexport default class BusinessProfileApi extends BaseAPI implements bp.BusinessProfileClass {\n private readonly endpoint = 'whatsapp_business_profile';\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * Get your business profile information.\n *\n * Use this method to retrieve details about your WhatsApp business profile, including\n * about text, address, description, email, profile picture URL, websites, and vertical.\n *\n * @param fields Fields to be returned in the response. If not specified, all fields will be returned.\n * Possible values: about, address, description, email, profile_picture_url, websites, vertical\n * @returns The business profile information.\n *\n * @example\n * // Get all business profile fields\n * const profile = await whatsappClient.businessProfile.getBusinessProfile();\n *\n * // Get specific business profile fields\n * const profile = await whatsappClient.businessProfile.getBusinessProfile('about,address,email');\n *\n * // Using the BusinessProfileFieldsParam type\n * const profile = await whatsappClient.businessProfile.getBusinessProfile(['about', 'address', 'email']);\n */\n async getBusinessProfile(fields?: bp.BusinessProfileFieldsParam): Promise<bp.BusinessProfileResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}${buildFieldsQueryString(fields)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Update your business profile.\n *\n * Use this method to update one or more fields of your WhatsApp business profile.\n *\n * @param updateRequest The request object containing the fields to update.\n * - messaging_product: Required. Always set to \"whatsapp\".\n * - about: Optional. Business's About text (1-139 characters).\n * - address: Optional. Business address (max 256 characters).\n * - description: Optional. Business description (max 512 characters).\n * - vertical: Optional. Business category (use BusinessVerticalEnum for type safety).\n * - email: Optional. Contact email (valid format, max 128 characters).\n * - websites: Optional. Up to 2 URLs (max 256 characters each).\n * - profile_picture_handle: Optional. Handle from upload process.\n * @returns Response indicating success or failure.\n *\n * @example\n * // Update business profile with multiple fields including vertical using enum\n * await whatsappClient.businessProfile.updateBusinessProfile({\n * messaging_product: 'whatsapp',\n * about: 'We provide excellent service',\n * email: 'contact@example.com',\n * websites: ['https://example.com'],\n * vertical: BusinessVerticalEnum.RETAIL\n * });\n */\n async updateBusinessProfile(updateRequest: bp.UpdateBusinessProfileRequest): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(updateRequest),\n );\n }\n\n /**\n * Create an upload session for a profile picture.\n *\n * This is the first step in the profile picture upload process.\n *\n * @param fileLength Length of the file to be uploaded in bytes.\n * @param fileType MIME type of the file (e.g., 'image/jpeg').\n * @param fileName Name of the file with extension.\n * @returns Response containing the upload session ID needed for the next step.\n *\n * @example\n * // Create upload session for profile picture\n * const session = await whatsappClient.businessProfile.createUploadSession(\n * fileBuffer.length,\n * 'image/jpeg',\n * 'profile.jpg'\n * );\n * const uploadSessionId = session.upload_session_id;\n */\n async createUploadSession(\n fileLength: number,\n fileType: string,\n fileName: string,\n ): Promise<bp.UploadSessionResponse> {\n const queryParams = objectToQueryString({\n file_length: fileLength,\n file_type: fileType,\n file_name: fileName,\n });\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `app/uploads/${queryParams}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Upload media file to the upload session.\n *\n * This is the second step in the profile picture upload process.\n * Upload the binary content of the file to the previously created upload session.\n *\n * @param uploadId The upload session ID from createUploadSession response.\n * @param file The binary data of the file (Buffer).\n * @returns Response indicating success or failure.\n *\n * @example\n * // Upload the actual file content\n * await whatsappClient.businessProfile.uploadMedia(\n * uploadSessionId,\n * fileBuffer\n * );\n */\n async uploadMedia(uploadId: string, file: Buffer): Promise<bp.UploadBusinessProfileResponse> {\n return this.sendJson(HttpMethodsEnum.Post, `${uploadId}`, this.config[WabaConfigEnum.RequestTimeout], file);\n }\n\n /**\n * Get the upload handle information.\n *\n * This is the third step in the profile picture upload process.\n * After uploading the file, get the handle to use when updating the profile.\n *\n * @param uploadId The upload session ID from createUploadSession response.\n * @returns Response containing the upload handle information.\n *\n * @example\n * // Complete profile picture update process\n * // 1. Create upload session\n * const session = await whatsappClient.businessProfile.createUploadSession(\n * fileBuffer.length, 'image/jpeg', 'profile.jpg'\n * );\n *\n * // 2. Upload the image data\n * await whatsappClient.businessProfile.uploadMedia(\n * session.upload_session_id, fileBuffer\n * );\n *\n * // 3. Get the handle for the uploaded file\n * const handleInfo = await whatsappClient.businessProfile.getUploadHandle(\n * session.upload_session_id\n * );\n *\n * // 4. Update profile with new picture and business information\n * await whatsappClient.businessProfile.updateBusinessProfile({\n * messaging_product: 'whatsapp',\n * profile_picture_handle: handleInfo.handle,\n * vertical: BusinessVerticalEnum.RESTAURANT,\n * about: 'Delicious food served daily'\n * });\n */\n async getUploadHandle(uploadId: string): Promise<bp.UploadHandle> {\n return this.sendJson(HttpMethodsEnum.Get, `${uploadId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n}\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../types/request';\n\nimport type * as qrCode from './types';\n\n/**\n * API for managing WhatsApp QR Codes.\n *\n * This API allows you to:\n * - Create QR codes with prefilled messages\n * - Get all QR codes\n * - Get specific QR code details\n * - Update QR code messages\n * - Delete QR codes\n */\nexport default class QrCodeApi extends BaseAPI implements qrCode.QrCodeClass {\n private readonly endpoint = 'message_qrdls';\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * Create a new QR code with a prefilled message.\n *\n * @param request The QR code creation request\n * @returns QR code information including code, deep link URL, and optional image URL\n *\n * @example\n * const qrCode = await whatsappClient.qrCode.createQrCode({\n * prefilled_message: 'Hello from WhatsApp!',\n * generate_qr_image: 'PNG'\n * });\n */\n async createQrCode(request: qrCode.CreateQrCodeRequest): Promise<qrCode.QrCodeResponse> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n /**\n * Get all QR codes for the current phone number.\n *\n * @returns List of all QR codes\n *\n * @example\n * const qrCodes = await whatsappClient.qrCode.getQrCodes();\n */\n async getQrCodes(): Promise<qrCode.QrCodesResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Get a specific QR code by ID.\n *\n * @param qrCodeId The QR code ID to retrieve\n * @returns QR code information\n *\n * @example\n * const qrCode = await whatsappClient.qrCode.getQrCode('qr_code_123');\n */\n async getQrCode(qrCodeId: string): Promise<qrCode.QrCodeResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}/${qrCodeId}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Update an existing QR code's prefilled message.\n *\n * @param request The QR code update request containing code and new message\n * @returns Updated QR code information\n *\n * @example\n * const updatedQrCode = await whatsappClient.qrCode.updateQrCode({\n * code: 'existing_qr_code',\n * prefilled_message: 'Updated message!'\n * });\n */\n async updateQrCode(request: qrCode.UpdateQrCodeRequest): Promise<qrCode.QrCodeResponse> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n /**\n * Delete a QR code.\n *\n * @param qrCodeId The QR code ID to delete\n * @returns Response indicating success or failure\n *\n * @example\n * await whatsappClient.qrCode.deleteQrCode('qr_code_123');\n */\n async deleteQrCode(qrCodeId: string): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Delete,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}/${qrCodeId}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n}\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { DataLocalizationRegionEnum, HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../types/request';\n\nimport type * as registration from './types';\n\n/**\n * API for managing WhatsApp Business Account registration.\n *\n * This API allows you to:\n * - Register a WhatsApp Business Account with a PIN\n * - Deregister a WhatsApp Business Account\n */\nexport default class RegistrationApi extends BaseAPI implements registration.RegistrationClass {\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * Register a WhatsApp Business Account using a PIN.\n *\n * @param pin The registration PIN received via SMS or voice call\n * @param dataLocalizationRegion Optional data localization region\n * @returns Response indicating success or failure\n *\n * @example\n * await whatsappClient.registration.register('123456', DataLocalizationRegionEnum.Asia);\n */\n async register(pin: string, dataLocalizationRegion?: DataLocalizationRegionEnum): Promise<ResponseSuccess> {\n const body: registration.RegistrationRequest = {\n messaging_product: 'whatsapp',\n pin,\n ...(dataLocalizationRegion && { data_localization_region: dataLocalizationRegion }),\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/register`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Deregister a WhatsApp Business Account.\n *\n * @returns Response indicating success or failure\n *\n * @example\n * await whatsappClient.registration.deregister();\n */\n async deregister(): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/deregister`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n}\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponsePagination, ResponseSuccess } from '../../types/request';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\nimport type {\n TemplateClass,\n TemplateDeleteParams,\n TemplateGetParams,\n TemplateRequestBody,\n TemplateResponse,\n} from './types';\n\nexport default class TemplateApi extends BaseAPI implements TemplateClass {\n private readonly endpoint = 'message_templates';\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n async getTemplate(templateId: string): Promise<TemplateResponse> {\n return this.sendJson(HttpMethodsEnum.Get, `${templateId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n async updateTemplate(templateId: string, template: Partial<TemplateRequestBody>): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${templateId}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(template),\n );\n }\n\n async getTemplates(params?: TemplateGetParams): Promise<ResponsePagination<TemplateResponse>> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.BusinessAcctId]}/${this.endpoint}${objectToQueryString(params ?? {})}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async createTemplate(template: TemplateRequestBody): Promise<TemplateResponse> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.BusinessAcctId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(template),\n );\n }\n\n async deleteTemplate(params: TemplateDeleteParams): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Delete,\n `${this.config[WabaConfigEnum.BusinessAcctId]}/${this.endpoint}${objectToQueryString(params)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n}\n","import { CategoryEnum } from '../../../types/enums';\nimport type {\n ComponentTypes,\n MediaCarouselCard,\n ProductCarouselCard,\n TemplateBody,\n TemplateButton,\n TemplateButtons,\n TemplateFooter,\n TemplateHeader,\n TemplateRequestBody,\n} from '../types';\nimport type {\n AuthenticationTemplateOptions,\n BodyOptions,\n ButtonOptions,\n CatalogTemplateOptions,\n CouponTemplateOptions,\n FooterOptions,\n HeaderOptions,\n LimitedTimeOfferTemplateOptions,\n MediaCardCarouselTemplateOptions,\n MPMTemplateOptions,\n OTPTemplateOptions,\n ProductCardCarouselTemplateOptions,\n SPMTemplateOptions,\n TemplateOptions,\n TemplateParameter,\n} from '../types';\n\n// Helper function to create header component\nfunction createHeader(options: HeaderOptions): TemplateHeader {\n const header: TemplateHeader = {\n type: 'HEADER',\n format: options.format,\n };\n\n if (options.text) {\n header.text = options.text;\n }\n\n if (options.example) {\n header.example = options.example;\n }\n\n return header;\n}\n\n// Helper function to create body component\nfunction createBody(options: BodyOptions): TemplateBody {\n const body: TemplateBody = {\n type: 'BODY',\n text: options.text,\n };\n\n if (options.example) {\n body.example = options.example;\n }\n\n return body;\n}\n\n// Helper function to create footer component\nfunction createFooter(options: FooterOptions): TemplateFooter {\n return {\n type: 'FOOTER',\n text: options.text,\n };\n}\n\n// Helper function to create buttons\nfunction createButtons(options: ButtonOptions): ComponentTypes[] {\n const buttons: TemplateButton[] = [];\n\n if (options.phone_number) {\n buttons.push({\n type: 'PHONE_NUMBER',\n text: options.phone_number.text,\n phone_number: options.phone_number.phone_number,\n });\n }\n\n if (options.url) {\n const urlButton: any = {\n type: 'URL',\n text: options.url.text,\n url: options.url.url,\n };\n if (options.url.example) {\n urlButton.example = [options.url.example];\n }\n buttons.push(urlButton);\n }\n\n if (options.quick_reply) {\n options.quick_reply.forEach((qr) => {\n buttons.push({\n type: 'QUICK_REPLY',\n text: qr.text,\n });\n });\n }\n\n if (options.copy_code) {\n buttons.push({\n type: 'COPY_CODE',\n example: options.copy_code.example,\n });\n }\n\n if (options.flow) {\n const flowButton: any = {\n type: 'FLOW',\n text: options.flow.text,\n };\n if (options.flow.flow_id) flowButton.flow_id = options.flow.flow_id;\n if (options.flow.flow_name) flowButton.flow_name = options.flow.flow_name;\n if (options.flow.flow_json) flowButton.flow_json = options.flow.flow_json;\n if (options.flow.flow_action) flowButton.flow_action = options.flow.flow_action;\n if (options.flow.navigate_screen) flowButton.navigate_screen = options.flow.navigate_screen;\n buttons.push(flowButton);\n }\n\n if (options.mpm) {\n buttons.push({ type: 'MPM' });\n }\n\n if (options.otp) {\n buttons.push({ type: 'OTP' });\n }\n\n if (options.spm) {\n buttons.push({ type: 'SPM' });\n }\n\n return buttons.length > 0\n ? [\n {\n type: 'BUTTONS',\n buttons: buttons,\n },\n ]\n : [];\n}\n\n// Helper function to format parameter examples\nfunction formatParameterExamples(parameters: TemplateParameter[]): string[] {\n return parameters.map((param) => {\n switch (param.type) {\n case 'text':\n return param.value;\n case 'currency':\n return param.fallback_value;\n case 'date_time':\n return param.fallback_value;\n case 'image':\n case 'video':\n case 'document':\n return param.handle || param.link || '';\n case 'location':\n return param.name || '';\n case 'product':\n return param.product_retailer_id;\n default:\n return '';\n }\n });\n}\n\n// Generic template factory\nexport function createTemplate(options: TemplateOptions): TemplateRequestBody {\n const components: ComponentTypes[] = [];\n\n if (options.header) {\n components.push(createHeader(options.header));\n }\n\n if (options.body) {\n components.push(createBody(options.body));\n }\n\n if (options.footer) {\n components.push(createFooter(options.footer));\n }\n\n if (options.buttons) {\n components.push(...createButtons(options.buttons));\n }\n\n if (options.carousel) {\n // Handle carousel components\n const carouselComponents: ComponentTypes[] = [];\n options.carousel.cards.forEach((card, index) => {\n if (card.image || card.video || card.product) {\n const format = card.image ? 'IMAGE' : card.video ? 'VIDEO' : 'DOCUMENT';\n const handle = card.image || card.video || card.product || '';\n carouselComponents.push({\n type: 'HEADER',\n format: format,\n example: {\n header_handle: [handle],\n },\n });\n }\n if (card.body) {\n carouselComponents.push({\n type: 'BODY',\n text: card.body,\n example: card.bodyParameters\n ? {\n body_text: [formatParameterExamples(card.bodyParameters)],\n }\n : undefined,\n });\n }\n if (card.buttons) {\n carouselComponents.push(...createButtons(card.buttons));\n }\n });\n components.push(...carouselComponents);\n }\n\n if (options.limitedTimeOffer) {\n components.push({\n type: 'LIMITED_TIME_OFFER',\n limited_time_offer: {\n expiration_time_ms: options.limitedTimeOffer.expiration_time_ms,\n },\n });\n }\n\n return {\n name: options.name,\n language: options.language,\n category: options.category,\n components: components.length > 0 ? components : undefined,\n };\n}\n\n// OTP Template Factory\nexport function createOTPTemplate(options: OTPTemplateOptions): TemplateRequestBody {\n const components: ComponentTypes[] = [];\n\n // Add security recommendation if requested\n let bodyText = '*{{1}}* is your verification code.';\n if (options.add_security_recommendation) {\n bodyText += ' For your security, do not share this code.';\n }\n if (options.code_expiration_minutes) {\n bodyText += ` This code expires in ${options.code_expiration_minutes} minutes.`;\n }\n\n components.push({\n type: 'BODY',\n text: bodyText,\n example: {\n body_text: [['123456']], // Example OTP code\n },\n });\n\n // Add OTP button\n components.push({\n type: 'BUTTONS',\n buttons: [{ type: 'OTP' }],\n });\n\n return {\n name: options.name,\n language: options.language,\n category: CategoryEnum.Authentication,\n components,\n };\n}\n\n// Authentication Template Factory\nexport function createAuthenticationTemplate(options: AuthenticationTemplateOptions): TemplateRequestBody {\n const components: ComponentTypes[] = [];\n\n // Add security message\n let bodyText = 'Your security code is *{{1}}*.';\n if (options.add_security_recommendation) {\n bodyText += ' Do not share this code with anyone.';\n }\n if (options.code_expiration_minutes) {\n bodyText += ` This code expires in ${options.code_expiration_minutes} minutes.`;\n }\n\n components.push({\n type: 'BODY',\n text: bodyText,\n example: {\n body_text: [['ABCD1234']], // Example auth code\n },\n });\n\n // Add copy code button if requested\n if (options.copy_code_button) {\n components.push({\n type: 'BUTTONS',\n buttons: [\n {\n type: 'COPY_CODE',\n example: 'ABCD1234',\n },\n ],\n });\n }\n\n return {\n name: options.name,\n language: options.language,\n category: CategoryEnum.Authentication,\n components,\n };\n}\n\n// Catalog Template Factory\nexport function createCatalogTemplate(options: CatalogTemplateOptions): TemplateRequestBody {\n const components: ComponentTypes[] = [];\n\n if (options.header) {\n components.push(createHeader({ ...options.header, format: 'TEXT' }));\n }\n\n components.push(createBody(options.body));\n\n if (options.footer) {\n components.push(createFooter(options.footer));\n }\n\n // Add catalog button\n components.push({\n type: 'BUTTONS',\n buttons: [\n {\n type: 'CATALOG',\n action: {\n thumbnail_product_retailer_id: options.thumbnail_product_retailer_id,\n },\n },\n ],\n });\n\n return {\n name: options.name,\n language: options.language,\n category: CategoryEnum.Marketing,\n components,\n };\n}\n\n// Coupon Template Factory\nexport function createCouponTemplate(options: CouponTemplateOptions): TemplateRequestBody {\n const components: ComponentTypes[] = [];\n\n if (options.header) {\n components.push(createHeader({ ...options.header, format: 'TEXT' }));\n }\n\n components.push(createBody(options.body));\n\n if (options.footer) {\n components.push(createFooter(options.footer));\n }\n\n // Add copy code button\n components.push({\n type: 'BUTTONS',\n buttons: [\n {\n type: 'COPY_CODE',\n example: options.coupon_code,\n },\n ],\n });\n\n return {\n name: options.name,\n language: options.language,\n category: CategoryEnum.Marketing,\n components,\n };\n}\n\n// Limited Time Offer Template Factory\nexport function createLimitedTimeOfferTemplate(options: LimitedTimeOfferTemplateOptions): TemplateRequestBody {\n const components: ComponentTypes[] = [];\n\n // Add limited time offer component first\n components.push({\n type: 'LIMITED_TIME_OFFER',\n limited_time_offer: {\n expiration_time_ms: options.expiration_time_ms,\n },\n });\n\n if (options.header) {\n components.push(createHeader({ ...options.header, format: 'TEXT' }));\n }\n\n components.push(createBody(options.body));\n\n if (options.footer) {\n components.push(createFooter(options.footer));\n }\n\n return {\n name: options.name,\n language: options.language,\n category: CategoryEnum.Marketing,\n components,\n };\n}\n\n// Media Card Carousel Template Factory\nexport function createMediaCardCarouselTemplate(options: MediaCardCarouselTemplateOptions): TemplateRequestBody {\n const components: ComponentTypes[] = [];\n\n // Add carousel component\n const carouselCards: MediaCarouselCard[] = [];\n options.cards.forEach((card, index) => {\n const cardComponents: (TemplateHeader | TemplateBody | TemplateButtons)[] = [];\n\n // Add header (media)\n cardComponents.push({\n type: 'HEADER' as const,\n format: card.header.format,\n example: card.header.example,\n });\n\n // Add body\n cardComponents.push(createBody(card.body));\n\n // Add buttons if any\n if (card.buttons) {\n cardComponents.push(...(createButtons(card.buttons) as TemplateButtons[]));\n }\n\n carouselCards.push({\n card_index: index,\n components: cardComponents,\n });\n });\n\n components.push({\n type: 'CAROUSEL',\n cards: carouselCards,\n });\n\n return {\n name: options.name,\n language: options.language,\n category: CategoryEnum.Marketing,\n components,\n };\n}\n\n// MPM (Multi-Product Message) Template Factory\nexport function createMPMTemplate(options: MPMTemplateOptions): TemplateRequestBody {\n const components: ComponentTypes[] = [];\n\n if (options.header) {\n components.push(createHeader({ ...options.header, format: 'TEXT' }));\n }\n\n components.push(createBody(options.body));\n\n if (options.footer) {\n components.push(createFooter(options.footer));\n }\n\n // Add MPM button\n components.push({\n type: 'BUTTONS',\n buttons: [\n {\n type: 'MPM',\n action: {\n thumbnail_product_retailer_id: options.thumbnail_product_retailer_id,\n sections: options.sections,\n },\n },\n ],\n });\n\n return {\n name: options.name,\n language: options.language,\n category: CategoryEnum.Marketing,\n components,\n };\n}\n\n// Product Card Carousel Template Factory\nexport function createProductCardCarouselTemplate(options: ProductCardCarouselTemplateOptions): TemplateRequestBody {\n const components: ComponentTypes[] = [];\n\n if (options.header) {\n components.push(createHeader({ ...options.header, format: 'TEXT' }));\n }\n\n components.push(createBody(options.body));\n\n if (options.footer) {\n components.push(createFooter(options.footer));\n }\n\n // Add carousel with product cards\n const carouselCards: ProductCarouselCard[] = options.cards.map((card, index) => ({\n card_index: index,\n components: [\n {\n type: 'HEADER' as const,\n format: 'PRODUCT' as const,\n example: {\n header_handle: [card.product_retailer_id],\n },\n },\n ],\n }));\n\n components.push({\n type: 'CAROUSEL',\n cards: carouselCards,\n });\n\n return {\n name: options.name,\n language: options.language,\n category: CategoryEnum.Marketing,\n components,\n };\n}\n\n// SPM (Single-Product Message) Template Factory\nexport function createSPMTemplate(options: SPMTemplateOptions): TemplateRequestBody {\n const components: ComponentTypes[] = [];\n\n if (options.header) {\n components.push(createHeader({ ...options.header, format: 'TEXT' }));\n }\n\n components.push(createBody(options.body));\n\n if (options.footer) {\n components.push(createFooter(options.footer));\n }\n\n // Add SPM button\n components.push({\n type: 'BUTTONS',\n buttons: [\n {\n type: 'SPM',\n action: {\n product_retailer_id: options.product_retailer_id,\n },\n },\n ],\n });\n\n return {\n name: options.name,\n language: options.language,\n category: CategoryEnum.Marketing,\n components,\n };\n}\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../types/request';\n\nimport type * as twoStepVerification from './types';\n\n/**\n * API for managing WhatsApp Two-Step Verification.\n *\n * This API allows you to:\n * - Set a two-step verification PIN code\n * - Manage two-step verification settings\n */\nexport default class TwoStepVerificationApi extends BaseAPI implements twoStepVerification.TwoStepVerificationClass {\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * Set a two-step verification PIN code.\n *\n * @param pin The PIN code to set for two-step verification (6-digit numeric string)\n * @returns Response indicating success or failure\n *\n * @example\n * await whatsappClient.twoStepVerification.setTwoStepVerificationCode('123456');\n */\n async setTwoStepVerificationCode(pin: string): Promise<ResponseSuccess> {\n const body = {\n pin,\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n}\n","import { BaseAPI } from '../../types/base';\nimport type { WabaConfigType } from '../../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../../types/request';\nimport { buildFieldsQueryString } from '../../utils/buildFieldsQueryString';\n\nimport type * as waba from './types';\n\n/**\n * API for managing WhatsApp Business Account (WABA).\n *\n * This API allows you to:\n * - Get WABA account information\n * - Manage WABA subscriptions\n * - Subscribe/unsubscribe from WABA webhooks\n * - Update subscription settings\n */\nexport default class WabaApi extends BaseAPI implements waba.WABAClass {\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n /**\n * Retrieve WhatsApp Business Account information.\n *\n * @param fields Optional array of specific fields to retrieve\n * @returns WABA account information including status, health, verification status, etc.\n *\n * @example\n * const account = await whatsappClient.waba.getWabaAccount(['id', 'name', 'status']);\n */\n async getWabaAccount(fields?: waba.WabaAccountFieldsParam): Promise<waba.WabaAccount> {\n const queryString = buildFieldsQueryString(fields)?.replace(/,/g, '%2C');\n\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.BusinessAcctId]}${queryString}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Get all WABA subscriptions for the business account.\n *\n * @returns List of all subscribed apps and their configurations\n *\n * @example\n * const subscriptions = await whatsappClient.waba.getAllWabaSubscriptions();\n */\n async getAllWabaSubscriptions(): Promise<waba.WabaSubscriptions> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.BusinessAcctId]}/subscribed_apps`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Update WABA subscription configuration.\n *\n * @param params Configuration parameters including callback URI and verify token\n * @returns Response indicating success or failure\n *\n * @example\n * await whatsappClient.waba.updateWabaSubscription({\n * override_callback_uri: 'https://example.com/webhook',\n * verify_token: 'your_verify_token'\n * });\n */\n async updateWabaSubscription({\n override_callback_uri,\n verify_token,\n }: waba.UpdateWabaSubscription): Promise<ResponseSuccess> {\n const body = {\n override_callback_uri,\n verify_token,\n };\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.BusinessAcctId]}/subscribed_apps`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Unsubscribe from WABA webhooks.\n *\n * @returns Response indicating success or failure\n *\n * @example\n * await whatsappClient.waba.unsubscribeFromWaba();\n */\n async unsubscribeFromWaba(): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Delete,\n `${this.config[WabaConfigEnum.BusinessAcctId]}/subscribed_apps`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n}\n","export function printLogo() {\n // 테스트 환경에서는 로고를 출력하지 않음\n if (\n process.env.NODE_ENV === 'test' ||\n process.env.VITEST === 'true' ||\n (typeof global !== 'undefined' && (global as any).__VITEST__)\n ) {\n return;\n }\n\n console.log(\n '\\x1b[36m%s\\x1b[0m',\n `\n██████╗ ██╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ██████╗ ██╗\n██╔════╝ ██║ ██╔═══██╗ ██║ ██║ ██╔══██╗ ██╔══██╗ ██╔══██╗ ██║\n██║ ██║ ██║ ██║ ██║ ██║ ██║ ██║ ███████║ ██████╔╝ ██║\n██║ ██║ ██║ ██║ ██║ ██║ ██║ ██║ ██╔══██║ ██╔═══╝ ██║\n╚██████╗ ███████╗ ╚██████╔╝ ╚██████╔╝ ██████╔╝ ██║ ██║ ██║ ██║\n ╚═════╝ ╚══════╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝\n`,\n );\n}\n","import { importConfig } from '../../config/importConfig';\nimport { WabaConfigType, WhatsAppConfig } from '../../types/config';\nimport * as SDKEnums from '../../types/enums';\nimport { formatConfigTable } from '../../utils/configTable';\nimport Requester from '../../utils/http/request';\nimport Logger from '../../utils/logger';\nimport { getUserAgent, getVersion } from '../../utils/version';\n\nimport {\n BusinessProfileApi,\n EncryptionApi,\n FlowApi,\n MediaApi,\n MessageApi,\n PhoneNumberApi,\n QrCodeApi,\n RegistrationApi,\n TemplateApi,\n TwoStepVerificationApi,\n WabaApi,\n} from '../../api';\nimport { printLogo } from '../../utils/logoConsole';\n\nconst LIB_NAME = 'WHATSAPP';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\n/**\n * WhatsApp SDK Main Class following official patterns\n * Provides unified access to WhatsApp Cloud API and Flows API\n */\nexport default class WhatsApp {\n config: WabaConfigType;\n requester: Readonly<Requester>;\n messages: MessageApi;\n media: MediaApi;\n phoneNumbers: PhoneNumberApi;\n twoStepVerification: TwoStepVerificationApi;\n flows: FlowApi;\n businessProfile: BusinessProfileApi;\n templates: TemplateApi;\n encryption: EncryptionApi;\n qrCode: QrCodeApi;\n registration: RegistrationApi;\n waba: WabaApi;\n\n constructor(config?: WhatsAppConfig) {\n printLogo();\n this.config = importConfig(config);\n\n this.requester = new Requester(\n this.config[SDKEnums.WabaConfigEnum.APIVersion],\n this.config[SDKEnums.WabaConfigEnum.PhoneNumberId],\n this.config[SDKEnums.WabaConfigEnum.AccessToken],\n this.config[SDKEnums.WabaConfigEnum.BusinessAcctId],\n this.getUserAgent(),\n );\n\n this.messages = new MessageApi(this.config, this.requester);\n this.media = new MediaApi(this.config, this.requester);\n this.phoneNumbers = new PhoneNumberApi(this.config, this.requester);\n this.twoStepVerification = new TwoStepVerificationApi(this.config, this.requester);\n this.flows = new FlowApi(this.config, this.requester);\n this.businessProfile = new BusinessProfileApi(this.config, this.requester);\n this.templates = new TemplateApi(this.config, this.requester);\n this.encryption = new EncryptionApi(this.config, this.requester);\n this.qrCode = new QrCodeApi(this.config, this.requester);\n this.registration = new RegistrationApi(this.config, this.requester);\n this.waba = new WabaApi(this.config, this.requester);\n\n LOGGER.log('\\n' + formatConfigTable(this.config));\n }\n\n /**\n * Runtime configuration updates following official patterns\n */\n updateTimeout(timeout: number): void {\n this.config[SDKEnums.WabaConfigEnum.RequestTimeout] = timeout;\n if ('updateTimeout' in this.requester) {\n (this.requester as any).updateTimeout(timeout);\n }\n LOGGER.log(`Timeout updated to ${timeout}ms`);\n }\n\n updateSenderNumberId(phoneNumberId: number): void {\n this.config[SDKEnums.WabaConfigEnum.PhoneNumberId] = phoneNumberId;\n LOGGER.log(`Sender number ID updated to ${phoneNumberId}`);\n }\n\n updateAccessToken(accessToken: string): void {\n this.config[SDKEnums.WabaConfigEnum.AccessToken] = accessToken;\n if ('updateAccessToken' in this.requester) {\n (this.requester as any).updateAccessToken(accessToken);\n }\n LOGGER.log('Access token updated');\n }\n\n /**\n * Get SDK version\n */\n version(): string {\n return getVersion();\n }\n\n /**\n * Static enums access\n */\n static get Enums() {\n return SDKEnums;\n }\n\n /**\n * Get User-Agent string\n */\n getUserAgent(): string {\n return getUserAgent();\n }\n}\n","import {\n FlowActionEnum,\n FlowDataExchangeRequest,\n FlowEndpointRequest,\n FlowErrorNotificationRequest,\n FlowHealthCheckRequest,\n} from '../api/flow/types';\n\n/**\n * Helper function to check if a value is an object\n * @param value The value to check\n * @returns True if the value is a non-null object\n */\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/**\n * Helper function to check if a value is a string\n * @param value The value to check\n * @returns True if the value is a string\n */\nfunction isString(value: unknown): value is string {\n return typeof value === 'string';\n}\n\n// Array of allowed action types for data exchange requests\nconst DATA_EXCHANGE_ACTIONS = [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT, FlowActionEnum.BACK] as const;\n\n// Array of allowed action types for error notification requests\nconst ERROR_ACTIONS = [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT] as const;\n\n/**\n * Type guard to check if a request is a Data Exchange request\n * Validates the request structure according to the Flow API specifications\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a valid Data Exchange request, false otherwise\n */\nexport function isFlowDataExchangeRequest(request: FlowEndpointRequest): request is FlowDataExchangeRequest & {\n action: (typeof DATA_EXCHANGE_ACTIONS)[number];\n screen?: string;\n flow_token: string;\n data?: Record<string, any>;\n} {\n // Check for basic required fields\n if (!('flow_token' in request && isString(request.flow_token) && 'action' in request)) {\n return false;\n }\n\n const { action, version, screen, data } = request;\n\n // Validate API version\n const hasValidVersion = version === '3.0';\n\n // Check if the action is one of the allowed actions for data exchange\n const hasValidAction = DATA_EXCHANGE_ACTIONS.includes(action as any);\n\n // Screen is optional, but when present must be a string and not 'SUCCESS'\n const hasValidScreen = typeof screen === 'undefined' || (isString(screen) && screen !== 'SUCCESS');\n\n // Data is required except for DATA_EXCHANGE action\n const hasValidData = action === FlowActionEnum.DATA_EXCHANGE || isObject(data);\n\n // All conditions must be met for a valid data exchange request\n return hasValidVersion && hasValidAction && hasValidScreen && hasValidData;\n}\n\n/**\n * Type guard to check if a request is an Error Notification request\n * Validates the request structure according to the Flow API error specifications\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a valid Error Notification request, false otherwise\n */\nexport function isFlowErrorRequest(request: FlowEndpointRequest): request is FlowErrorNotificationRequest & {\n action: (typeof ERROR_ACTIONS)[number];\n screen: string;\n flow_token: string;\n data: {\n error: string;\n error_message: string;\n };\n} {\n // Check for basic required fields\n if (!('flow_token' in request && isString(request.flow_token) && 'action' in request)) {\n return false;\n }\n\n const { action, screen, data } = request;\n\n // Check if the action is one of the allowed actions for error notifications\n const hasValidAction = ERROR_ACTIONS.includes(action as any);\n\n // Screen is required for error notifications\n const hasValidScreen = isString(screen);\n\n // Validate error data structure\n const hasValidData =\n isObject(data) &&\n 'error_key' in data &&\n isString(data.error) &&\n 'error_message' in data &&\n isString(data.error_message);\n\n // All conditions must be met for a valid error notification request\n return hasValidAction && hasValidScreen && hasValidData;\n}\n\n/**\n * Type guard to check if a request is a Ping (health check) request\n * Simple validation for health check endpoints in the Flow API\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a Ping request, false otherwise\n */\nexport function isFlowPingRequest(request: FlowEndpointRequest): request is FlowHealthCheckRequest {\n // A ping request only requires the 'action' field with value 'ping'\n return 'action' in request && request.action === 'ping';\n}\n","import crypto from 'crypto';\n\nimport WhatsApp from '../../whatsapp/WhatsApp';\nimport { WebhookMessage } from '../types';\nimport { FlowEndpointRequest } from '../../../api/flow';\nimport { FlowTypeEnum } from '../../../api/flow/types';\nimport { WabaConfigType } from '../../../types/config';\nimport { MessageTypesEnum } from '../../../types/enums';\nimport { isFlowDataExchangeRequest, isFlowErrorRequest, isFlowPingRequest } from '../../../utils/flowTypeGuards';\nimport Logger from '../../../utils/logger';\nimport { WebhookMessageValue } from '../types';\n\nconst LIB_NAME = 'WEBHOOK_UTILS';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\nexport type MessageHandler = (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>;\nexport type FlowHandler = (whatsapp: WhatsApp, request: FlowEndpointRequest) => any | Promise<any>;\n\n/**\n * Process webhook messages\n */\nexport async function processWebhookMessages(\n request: Request,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<Response> {\n try {\n LOGGER.info('Processing webhook messages request');\n const body = await request.json();\n LOGGER.info('Webhook request body:', body);\n\n // Check this is a WhatsApp Business Account webhook\n if (body.object !== 'whatsapp_business_account') {\n const errorMsg = 'Received webhook for non-WhatsApp event';\n LOGGER.warn(errorMsg, { body });\n return new Response(JSON.stringify({ error: errorMsg }), { status: 404 });\n }\n\n const errors: string[] = [];\n\n // Process each entry\n for (const entry of body.entry) {\n try {\n LOGGER.info('Processing webhook entry:', { entryId: entry.id });\n const changes = entry.changes;\n for (const change of changes) {\n if (change.field === 'messages') {\n LOGGER.info('Processing messages change:', { change });\n await processMessages(entry.id, change.value, whatsapp, handlers);\n }\n }\n } catch (error) {\n const errorMsg = `Error processing webhook: ${error}`;\n LOGGER.error(errorMsg, { entry, error });\n errors.push(errorMsg);\n }\n }\n\n LOGGER.info('Webhook processing complete', { errorCount: errors.length });\n return new Response(errors.length > 0 ? JSON.stringify({ errors }) : null, { status: 200 });\n } catch (error) {\n LOGGER.error('Error processing webhook:', error);\n return new Response(JSON.stringify({ error: 'Internal Server Error' }), { status: 500 });\n }\n}\n\n/**\n * Handle flow requests\n */\nexport async function processFlowRequest(\n request: Request,\n config: WabaConfigType,\n whatsapp: WhatsApp,\n flowHandlers: Map<FlowTypeEnum, FlowHandler>,\n): Promise<Response> {\n try {\n LOGGER.info('Processing flow request');\n const body = await request.text();\n const signature = request.headers.get('x-hub-signature-256');\n LOGGER.info('Flow request signature:', { signature });\n\n // Validate request signature\n if (!verifySignature(body, signature, config.WEBHOOK_VERIFICATION_TOKEN || '')) {\n LOGGER.warn('Invalid request signature', { signature });\n return new Response(JSON.stringify({ error: 'Unauthorized' }), { status: 401 });\n }\n\n const data = JSON.parse(body);\n LOGGER.info('Flow request data:', data);\n\n // Decrypt the request\n const { decryptedBody } = decryptFlowRequest(data, config);\n LOGGER.info('Decrypted flow request:', decryptedBody);\n\n // Get the flow handler\n const handler = flowHandlers.get(FlowTypeEnum.All);\n if (!handler) {\n LOGGER.warn('No handler registered for flow action:', { action: decryptedBody.action });\n return new Response(JSON.stringify({ error: 'Handler not found' }), { status: 404 });\n }\n\n // Handle different flow types\n if (isFlowPingRequest(decryptedBody)) {\n LOGGER.info('Handling flow ping request');\n return new Response(\n JSON.stringify({\n version: '3.0',\n data: { status: 'active' },\n }),\n { status: 200 },\n );\n }\n\n if (isFlowErrorRequest(decryptedBody)) {\n LOGGER.warn('Flow error request received:', decryptedBody);\n return new Response(null, { status: 200 });\n }\n\n if (isFlowDataExchangeRequest(decryptedBody)) {\n LOGGER.info('Processing flow data exchange request');\n const result = await handler(whatsapp, decryptedBody);\n LOGGER.info('Flow handler result:', result);\n\n const encryptedResponse = encryptFlowResponse(\n result,\n Buffer.from(data.aes_key, 'base64'),\n Buffer.from(data.initial_vector, 'base64'),\n );\n LOGGER.info('Encrypted flow response generated');\n\n return new Response(JSON.stringify(encryptedResponse), { status: 200 });\n }\n\n LOGGER.warn('Unknown flow request type:', decryptedBody);\n return new Response(JSON.stringify({ error: 'Unknown request type' }), { status: 400 });\n } catch (error) {\n LOGGER.error('Error handling flow request:', error);\n return new Response(JSON.stringify({ error: 'Internal server error' }), { status: 500 });\n }\n}\n\n/**\n * Verify webhook signature\n */\nfunction verifySignature(body: string, signature: string | null, verificationToken: string): boolean {\n if (!signature) {\n LOGGER.warn('Missing signature in request');\n return false;\n }\n\n LOGGER.info('Signature verification details:', {\n bodyLength: body.length,\n verificationTokenLength: verificationToken.length,\n rawSignature: signature,\n cleanedSignature: signature.replace('sha256=', ''),\n });\n\n const expectedSignature = crypto.createHmac('sha256', verificationToken).update(body).digest('hex');\n LOGGER.info('Signature verification:', {\n received: signature.replace('sha256=', ''),\n expected: expectedSignature,\n });\n\n return crypto.timingSafeEqual(Buffer.from(signature.replace('sha256=', '')), Buffer.from(expectedSignature));\n}\n\n/**\n * Constructs a full URL from framework-specific request headers and URL\n * @param headers - Request headers containing host and protocol information\n * @param url - Relative URL path\n * @returns Full URL string\n */\nexport function constructFullUrl(headers: Record<string, string | string[] | undefined>, url?: string): string {\n const protocol = headers['x-forwarded-proto'] || 'http';\n const host = headers.host || 'localhost';\n const path = url || '/';\n return `${protocol}://${host}${path}`;\n}\n\n/**\n * Private helper functions\n */\nasync function processMessages(\n waba_id: string,\n value: WebhookMessageValue,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<void> {\n LOGGER.info('Processing messages:', { waba_id, value });\n\n const metadata = value.metadata;\n const contacts = value.contacts;\n const wabaId = waba_id;\n const displayPhoneNumber = metadata?.display_phone_number || '';\n const phoneNumberId = metadata?.phone_number_id || '';\n const profileName = contacts?.[0]?.profile?.name || '';\n\n if (value.statuses && value.statuses.length > 0) {\n LOGGER.info('Processing statuses:', { statusCount: value.statuses.length });\n const statuses = value.statuses;\n for (const status of statuses) {\n const processedStatus: WebhookMessage = {\n wabaId,\n id: status.id,\n from: status.recipient_id,\n timestamp: status.timestamp,\n type: MessageTypesEnum.Statuses,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n statuses: value.statuses[0],\n originalData: status,\n };\n\n LOGGER.info('Processing status:', processedStatus);\n await executeHandler(\n handlers.messageHandlers.get(MessageTypesEnum.Statuses),\n whatsapp,\n processedStatus,\n MessageTypesEnum.Statuses,\n );\n }\n return;\n }\n\n if (value.messages && value.messages.length > 0) {\n LOGGER.info('Processing messages:', { messageCount: value.messages.length });\n const messages = value.messages;\n\n for (const message of messages) {\n const messageType = message.type;\n LOGGER.info('Processing message:', { messageType, messageId: message.id });\n\n const processedMessage: WebhookMessage = {\n wabaId,\n id: message.id,\n from: message.from,\n timestamp: message.timestamp,\n type: message.type,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n originalData: message,\n };\n\n switch (messageType) {\n case MessageTypesEnum.Text:\n processedMessage.text = message.text;\n break;\n case MessageTypesEnum.Image:\n processedMessage.image = message.image;\n break;\n case MessageTypesEnum.Video:\n processedMessage.video = message.video;\n break;\n case MessageTypesEnum.Audio:\n processedMessage.audio = message.audio;\n break;\n case MessageTypesEnum.Document:\n processedMessage.document = message.document;\n break;\n case MessageTypesEnum.Sticker:\n processedMessage.sticker = message.sticker;\n break;\n case MessageTypesEnum.Location:\n processedMessage.location = message.location;\n break;\n case MessageTypesEnum.Contacts:\n processedMessage.contacts = message.contacts;\n break;\n case MessageTypesEnum.Interactive:\n processedMessage.interactive = message.interactive;\n break;\n case MessageTypesEnum.Button:\n processedMessage.button = message.button;\n break;\n case MessageTypesEnum.Order:\n processedMessage.order = message.order;\n break;\n case MessageTypesEnum.System:\n processedMessage.system = message.system;\n break;\n case MessageTypesEnum.Reaction:\n processedMessage.reaction = message.reaction;\n break;\n default:\n LOGGER.warn('Unknown message type:', { messageType });\n break;\n }\n\n // Execute handlers in sequence\n LOGGER.info('Executing message handlers');\n await executeHandler(handlers.preProcessHandler, whatsapp, processedMessage, 'pre-process');\n await executeHandler(handlers.messageHandlers.get(messageType), whatsapp, processedMessage, messageType);\n await executeHandler(handlers.postProcessHandler, whatsapp, processedMessage, 'post-process');\n }\n }\n}\n\nasync function executeHandler(\n handler: MessageHandler | undefined,\n whatsapp: WhatsApp,\n message: WebhookMessage,\n handlerType: string,\n): Promise<void> {\n if (handler) {\n try {\n LOGGER.info('Executing handler:', { handlerType, messageId: message.id });\n await handler(whatsapp, message);\n LOGGER.info('Handler execution complete:', { handlerType, messageId: message.id });\n } catch (error) {\n LOGGER.error(`Error in ${handlerType} handler:`, { error, messageId: message.id });\n }\n } else {\n LOGGER.info('No handler registered:', { handlerType });\n }\n}\n\nfunction decryptFlowRequest(\n body: any,\n config: WabaConfigType,\n): {\n decryptedBody: FlowEndpointRequest;\n aesKeyBuffer: Buffer;\n initialVectorBuffer: Buffer;\n} {\n LOGGER.info('Decrypting flow request');\n const { encrypted_aes_key, encrypted_flow_data, initial_vector } = body;\n\n if (!encrypted_aes_key || !encrypted_flow_data || !initial_vector) {\n LOGGER.error('Missing required encryption properties');\n throw new Error('Missing required encryption properties');\n }\n\n const privatePem = config.FLOW_API_PRIVATE_PEM.replace(/\\\\n/g, '\\n');\n const passphrase = config.FLOW_API_PASSPHRASE;\n\n const privateKey = crypto.createPrivateKey({ key: privatePem, passphrase });\n let decryptedAesKey: Buffer;\n\n try {\n LOGGER.info('Decrypting AES key');\n decryptedAesKey = crypto.privateDecrypt(\n {\n key: privateKey,\n padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,\n oaepHash: 'sha256',\n },\n Buffer.from(encrypted_aes_key, 'base64'),\n );\n } catch (error) {\n LOGGER.error('Failed to decrypt AES key:', error);\n throw new Error('Failed to decrypt the request. Please verify your private key.');\n }\n\n const flowDataBuffer = Buffer.from(encrypted_flow_data, 'base64');\n const initialVectorBuffer = Buffer.from(initial_vector, 'base64');\n\n const TAG_LENGTH = 16;\n const encrypted_flow_data_body = flowDataBuffer.subarray(0, -TAG_LENGTH);\n const encrypted_flow_data_tag = flowDataBuffer.subarray(-TAG_LENGTH);\n\n LOGGER.info('Decrypting flow data');\n const decipher = crypto.createDecipheriv('aes-128-gcm', decryptedAesKey, initialVectorBuffer);\n decipher.setAuthTag(encrypted_flow_data_tag);\n\n const decryptedJSONString = Buffer.concat([decipher.update(encrypted_flow_data_body), decipher.final()]).toString(\n 'utf-8',\n );\n\n LOGGER.info('Flow request decryption complete');\n return {\n decryptedBody: JSON.parse(decryptedJSONString),\n aesKeyBuffer: decryptedAesKey,\n initialVectorBuffer,\n };\n}\n\nfunction encryptFlowResponse(response: any, aesKeyBuffer: Buffer, initialVectorBuffer: Buffer): string {\n LOGGER.info('Encrypting flow response');\n const flipped_iv: number[] = [];\n for (const pair of Array.from(initialVectorBuffer.entries())) {\n flipped_iv.push(~pair[1]);\n }\n\n try {\n const cipher = crypto.createCipheriv('aes-128-gcm', aesKeyBuffer, Buffer.from(flipped_iv));\n const encryptedResponse = Buffer.concat([\n cipher.update(JSON.stringify(response || {}), 'utf-8'),\n cipher.final(),\n cipher.getAuthTag(),\n ]).toString('base64');\n\n LOGGER.info('Flow response encryption complete');\n return encryptedResponse;\n } catch (error) {\n LOGGER.error('Response encryption error:', error);\n throw new Error('Failed to encrypt response. Internal server error.');\n }\n}\n","import { FlowTypeEnum } from '../../api/flow/types';\nimport { importConfig } from '../../config/importConfig';\nimport { WabaConfigType, WhatsAppConfig } from '../../types/config';\nimport { MessageTypesEnum } from '../../types/enums';\nimport Logger from '../../utils/logger';\nimport { WhatsApp } from '../whatsapp';\n\nimport { FlowHandler, MessageHandler, processFlowRequest, processWebhookMessages } from './utils/webhookUtils';\n\nconst LOGGER = new Logger('WEBHOOK_PROCESSOR', process.env.DEBUG === 'true');\n\nexport interface WebhookResponse {\n status: number;\n body: string;\n headers: Record<string, string>;\n}\n\nexport class WebhookProcessor {\n private config: WabaConfigType;\n private client: WhatsApp;\n private messageHandlers: Map<MessageTypesEnum, MessageHandler> = new Map();\n private preProcessHandler: MessageHandler | undefined = undefined;\n private postProcessHandler: MessageHandler | undefined = undefined;\n private flowHandlers: Map<FlowTypeEnum, FlowHandler> = new Map();\n\n constructor(config: WhatsAppConfig) {\n this.config = importConfig(config);\n this.client = new WhatsApp(config);\n LOGGER.log('WebhookProcessor instantiated');\n }\n\n async processVerification(\n mode: string | null,\n token: string | null,\n challenge: string | null,\n ): Promise<WebhookResponse> {\n if (mode === 'subscribe' && token === this.config.WEBHOOK_VERIFICATION_TOKEN) {\n return {\n status: 200,\n body: challenge || '',\n headers: { 'Content-Type': 'text/plain' },\n };\n }\n\n return {\n status: 403,\n body: JSON.stringify({ error: 'Forbidden' }),\n headers: { 'Content-Type': 'application/json' },\n };\n }\n\n async processWebhook(request: Request): Promise<WebhookResponse> {\n try {\n const webResponse = await processWebhookMessages(request, this.client, {\n messageHandlers: this.messageHandlers,\n preProcessHandler: this.preProcessHandler,\n postProcessHandler: this.postProcessHandler,\n });\n\n const body = await webResponse.text();\n const contentType = webResponse.headers.get('content-type') || 'application/json';\n\n return {\n status: webResponse.status,\n body,\n headers: { 'Content-Type': contentType },\n };\n } catch (error) {\n LOGGER.log(`Error processing webhook: ${error}`);\n return {\n status: 500,\n body: JSON.stringify({ error: 'Internal Server Error' }),\n headers: { 'Content-Type': 'application/json' },\n };\n }\n }\n\n async processFlow(request: Request): Promise<WebhookResponse> {\n try {\n const webResponse = await processFlowRequest(request, this.config, this.client, this.flowHandlers);\n const body = await webResponse.text();\n const contentType = webResponse.headers.get('content-type') || 'application/json';\n\n return {\n status: webResponse.status,\n body,\n headers: { 'Content-Type': contentType },\n };\n } catch (error) {\n LOGGER.log(`Error processing flow: ${error}`);\n return {\n status: 500,\n body: JSON.stringify({ error: 'Internal Server Error' }),\n headers: { 'Content-Type': 'application/json' },\n };\n }\n }\n\n onMessage(type: MessageTypesEnum, handler: MessageHandler): void {\n this.messageHandlers.set(type, handler);\n LOGGER.log(`Registered message handler for ${type}`);\n }\n\n onMessagePreProcess(handler: MessageHandler): void {\n this.preProcessHandler = handler;\n LOGGER.log('Registered pre-process handler');\n }\n\n onMessagePostProcess(handler: MessageHandler): void {\n this.postProcessHandler = handler;\n LOGGER.log('Registered post-process handler');\n }\n\n onFlow(type: FlowTypeEnum, handler: FlowHandler): void {\n this.flowHandlers.set(type, handler);\n LOGGER.log(`Registered flow handler for ${type}`);\n }\n\n getClient(): WhatsApp {\n return this.client;\n }\n\n getConfig(): WabaConfigType {\n return this.config;\n }\n}\n","import { WhatsAppConfig } from '../../../types/config';\nimport { WebhookProcessor } from '../WebhookProcessor';\nimport { constructFullUrl } from '../utils/webhookUtils';\n\n// Generic request/response interfaces for framework abstraction\nexport interface BaseRequest {\n method?: string;\n url?: string;\n headers: Record<string, string | string[] | undefined>;\n body?: any;\n query?: Record<string, any> | URLSearchParams;\n rawBody?: any;\n}\n\nexport interface BaseResponse<T = any> {\n status(code: number): T;\n json?(data: any): T | void;\n send?(data?: any): T | void;\n setHeader?(name: string, value: string): void;\n}\n\n// Base configuration interface\nexport interface BaseWebhookConfig extends WhatsAppConfig {\n // Framework-specific configs can extend this\n}\n\n// Response result interface for consistent return types\nexport interface WebhookResult {\n status: number;\n headers: Record<string, string>;\n body: any;\n}\n\n/**\n * Abstract base class for framework-agnostic webhook handlers\n * Provides common architecture and functionality across all frameworks\n */\nexport abstract class BaseWebhookHandler<TRequest extends BaseRequest, TResponse extends BaseResponse> {\n protected processor: WebhookProcessor;\n\n constructor(config: BaseWebhookConfig) {\n this.processor = new WebhookProcessor(config);\n }\n\n /**\n * Abstract method for handling GET requests (webhook verification)\n * Each framework implements this based on their request/response patterns\n */\n protected abstract handleGet(req: TRequest, res: TResponse, ...args: any[]): Promise<any>;\n\n /**\n * Abstract method for handling POST requests (webhook processing)\n * Each framework implements this based on their request/response patterns\n */\n protected abstract handlePost(req: TRequest, res: TResponse, ...args: any[]): Promise<any>;\n\n /**\n * Abstract method for handling flow requests\n * Each framework implements this based on their request/response patterns\n */\n protected abstract handleFlow(req: TRequest, res: TResponse, ...args: any[]): Promise<any>;\n\n /**\n * Common webhook verification logic\n */\n protected async processVerification(\n mode: string | null,\n token: string | null,\n challenge: string | null,\n ): Promise<WebhookResult> {\n return await this.processor.processVerification(mode, token, challenge);\n }\n\n /**\n * Common webhook processing logic\n */\n protected async processWebhook(request: Request): Promise<WebhookResult> {\n return await this.processor.processWebhook(request);\n }\n\n /**\n * Common flow processing logic\n */\n protected async processFlow(request: Request): Promise<WebhookResult> {\n return await this.processor.processFlow(request);\n }\n\n /**\n * Helper to construct full URL from headers and path\n */\n protected constructFullUrl(headers: Record<string, string | string[] | undefined>, url: string = ''): string {\n return constructFullUrl(headers, url);\n }\n\n /**\n * Helper to apply result headers to response\n */\n protected applyHeaders(result: WebhookResult, res: TResponse): void {\n if (res.setHeader) {\n Object.entries(result.headers).forEach(([key, value]) => {\n res.setHeader!(key, value);\n });\n }\n }\n\n /**\n * Auto-routing method handler that dispatches based on request method\n */\n protected async autoRoute(req: TRequest, res: TResponse, ...args: any[]): Promise<any> {\n const method = req.method?.toUpperCase();\n\n switch (method) {\n case 'GET':\n return await this.handleGet(req, res, ...args);\n case 'POST':\n return await this.handlePost(req, res, ...args);\n default:\n if (res.status && res.json) {\n return res.status(405).json({ error: 'Method Not Allowed' });\n }\n throw new Error('Method Not Allowed');\n }\n }\n\n /**\n * Get the processor instance for handler registration\n */\n get webhookProcessor(): WebhookProcessor {\n return this.processor;\n }\n\n /**\n * Abstract method to return the clean handler object\n * Each framework implements this to return their specific handler structure\n */\n abstract getHandlers(): {\n GET: (...args: any[]) => Promise<any>;\n POST: (...args: any[]) => Promise<any>;\n webhook: (...args: any[]) => Promise<any>;\n flow: (...args: any[]) => Promise<any>;\n processor: WebhookProcessor;\n };\n}\n","import { BaseRequest, BaseResponse, BaseWebhookConfig, BaseWebhookHandler } from '../handler';\n\n// Express-like interfaces to avoid direct Express dependency\nexport interface ExpressRequest extends BaseRequest {\n method: string;\n url: string;\n headers: Record<string, string | string[] | undefined>;\n body?: any;\n query: Record<string, any>;\n rawBody?: any;\n}\n\nexport interface ExpressResponse extends BaseResponse<ExpressResponse> {\n status(code: number): ExpressResponse;\n json(data: any): ExpressResponse;\n send(data?: any): ExpressResponse;\n setHeader(name: string, value: string): void;\n}\n\nexport interface NextFunction {\n (error?: any): void;\n}\n\nexport interface ExpressWebhookConfig extends BaseWebhookConfig {\n path?: string;\n}\n\n/**\n * Express-specific webhook handler extending the base handler\n */\nclass ExpressWebhookHandler extends BaseWebhookHandler<ExpressRequest, ExpressResponse> {\n constructor(config: ExpressWebhookConfig) {\n super(config);\n }\n\n protected async handleGet(req: ExpressRequest, res: ExpressResponse, next: NextFunction): Promise<ExpressResponse> {\n try {\n const { 'hub.mode': mode, 'hub.verify_token': token, 'hub.challenge': challenge } = req.query;\n\n const result = await this.processVerification(\n (mode as string) || null,\n (token as string) || null,\n (challenge as string) || null,\n );\n\n this.applyHeaders(result, res);\n return res.status(result.status).send(result.body);\n } catch (error) {\n next(error);\n return res;\n }\n }\n\n protected async handlePost(\n req: ExpressRequest,\n res: ExpressResponse,\n next: NextFunction,\n ): Promise<ExpressResponse> {\n try {\n const fullUrl = this.constructFullUrl(req.headers, req.url);\n const webRequest = new globalThis.Request(fullUrl, {\n method: req.method,\n headers: req.headers as HeadersInit,\n body: JSON.stringify(req.body),\n });\n\n const result = await this.processWebhook(webRequest);\n this.applyHeaders(result, res);\n return res.status(result.status).send(result.body);\n } catch (error) {\n next(error);\n return res;\n }\n }\n\n protected async handleFlow(\n req: ExpressRequest,\n res: ExpressResponse,\n next: NextFunction,\n ): Promise<ExpressResponse> {\n try {\n const fullUrl = this.constructFullUrl(req.headers, req.url);\n const webRequest = new globalThis.Request(fullUrl, {\n method: req.method,\n headers: req.headers as HeadersInit,\n body: req.method === 'POST' ? JSON.stringify(req.body) : undefined,\n });\n\n const result = await this.processFlow(webRequest);\n this.applyHeaders(result, res);\n return res.status(result.status).send(result.body);\n } catch (error) {\n next(error);\n return res;\n }\n }\n\n getHandlers() {\n return {\n // Method handlers for clean destructuring\n GET: (req: ExpressRequest, res: ExpressResponse, next: NextFunction) => this.handleGet(req, res, next),\n POST: (req: ExpressRequest, res: ExpressResponse, next: NextFunction) => this.handlePost(req, res, next),\n\n // Auto-routing webhook handler\n webhook: (req: ExpressRequest, res: ExpressResponse, next: NextFunction) => this.autoRoute(req, res, next),\n\n // Flow handler\n flow: (req: ExpressRequest, res: ExpressResponse, next: NextFunction) => this.handleFlow(req, res, next),\n\n // Expose processor for handler registration\n processor: this.webhookProcessor,\n };\n }\n}\n\nexport function expressWebhookHandler(config: ExpressWebhookConfig) {\n const handler = new ExpressWebhookHandler(config);\n return handler.getHandlers();\n}\n","import { BaseRequest, BaseResponse, BaseWebhookConfig, BaseWebhookHandler } from '../handler';\n\n// Next.js specific interfaces\nexport interface BaseApiRequest extends BaseRequest {\n method?: string;\n url?: string;\n headers: Record<string, string | string[] | undefined>;\n body?: any;\n query: Partial<Record<string, string | string[]>>;\n rawBody?: any;\n}\n\nexport interface BaseApiResponse extends BaseResponse {\n status(code: number): any;\n json(data: any): void | any;\n send(data?: any): void | any;\n setHeader(name: string, value: string): void;\n}\n\nexport interface NextJsWebhookConfig extends BaseWebhookConfig {\n // Next.js specific config can be added here\n}\n\n/**\n * Next.js Page Router webhook handler extending the base handler\n */\nclass NextJsWebhookHandler<\n TRequest extends BaseApiRequest,\n TResponse extends BaseApiResponse,\n> extends BaseWebhookHandler<TRequest, TResponse> {\n constructor(config: NextJsWebhookConfig) {\n super(config);\n }\n\n // Helper function to parse request body for POST requests\n private async parseRequestBody(req: TRequest): Promise<void> {\n if (req.method === 'POST' && !req.body) {\n const chunks: Buffer[] = [];\n\n // Check if req is a stream (has Symbol.asyncIterator)\n if (typeof (req as any)[Symbol.asyncIterator] === 'function') {\n for await (const chunk of req as any) {\n chunks.push(chunk);\n }\n\n const body = Buffer.concat(chunks).toString();\n\n // Only attempt to parse if there's actual content\n if (body.trim()) {\n try {\n req.body = JSON.parse(body);\n } catch (error) {\n throw new Error('Invalid JSON in request body');\n }\n } else {\n req.body = {};\n }\n }\n }\n }\n\n protected async handleGet(req: TRequest, res: TResponse): Promise<any> {\n try {\n const { 'hub.mode': mode, 'hub.verify_token': token, 'hub.challenge': challenge } = req.query;\n\n const result = await this.processVerification(\n (mode as string) || null,\n (token as string) || null,\n (challenge as string) || null,\n );\n\n this.applyHeaders(result, res);\n return res.status(result.status).send(result.body);\n } catch (error) {\n console.error('Webhook verification error:', error);\n return res.status(500).json({ error: 'Internal Server Error' });\n }\n }\n\n protected async handlePost(req: TRequest, res: TResponse): Promise<any> {\n try {\n // Auto-parse body if needed\n await this.parseRequestBody(req);\n } catch (error) {\n console.error('Webhook processing error:', error);\n\n // Handle JSON parsing errors specifically\n if (error instanceof Error && error.message === 'Invalid JSON in request body') {\n return res.status(400).json({ error: 'Invalid JSON' });\n }\n\n return res.status(500).json({ error: 'Internal Server Error' });\n }\n\n try {\n const fullUrl = this.constructFullUrl(req.headers, req.url);\n\n const webRequest = new Request(fullUrl, {\n method: 'POST',\n headers: req.headers as HeadersInit,\n body: JSON.stringify(req.body),\n });\n\n const result = await this.processWebhook(webRequest);\n this.applyHeaders(result, res);\n return res.status(result.status).send(result.body);\n } catch (error) {\n console.error('Webhook processing error:', error);\n return res.status(500).json({ error: 'Internal Server Error' });\n }\n }\n\n protected async handleFlow(req: TRequest, res: TResponse): Promise<any> {\n try {\n const fullUrl = this.constructFullUrl(req.headers, req.url);\n\n const webRequest = new Request(fullUrl, {\n method: req.method,\n headers: req.headers as HeadersInit,\n body: req.method === 'POST' ? JSON.stringify(req.body) : undefined,\n });\n\n const result = await this.processFlow(webRequest);\n this.applyHeaders(result, res);\n return res.status(result.status).send(result.body);\n } catch (error) {\n console.error('Flow error:', error);\n return res.status(500).json({ error: 'Internal Server Error' });\n }\n }\n\n getHandlers() {\n return {\n // Method handlers for clean destructuring\n GET: (req: TRequest, res: TResponse) => this.handleGet(req, res),\n POST: (req: TRequest, res: TResponse) => this.handlePost(req, res),\n\n // Auto-routing webhook handler\n webhook: (req: TRequest, res: TResponse) => this.autoRoute(req, res),\n\n // Flow handler\n flow: (req: TRequest, res: TResponse) => this.handleFlow(req, res),\n\n // Expose processor for handler registration\n processor: this.webhookProcessor,\n };\n }\n}\n\n// Generic webhook handler that accepts any compatible request/response types\nexport function nextjsWebhookHandler<TRequest extends BaseApiRequest, TResponse extends BaseApiResponse>(\n config: NextJsWebhookConfig,\n) {\n const handler = new NextJsWebhookHandler<TRequest, TResponse>(config);\n return handler.getHandlers();\n}\n","import { WhatsAppConfig } from '../../../../types/config';\nimport { WebhookProcessor } from '../../WebhookProcessor';\n\n// Define Next.js types locally to avoid requiring Next.js as a dependency\nexport interface NextRequest extends Request {\n nextUrl: {\n searchParams: URLSearchParams;\n };\n}\n\nexport interface NextResponse {\n json(data: any): NextResponse;\n}\n\nexport interface NextJsAppWebhookConfig extends WhatsAppConfig {\n // App Router specific config (currently none, but interface reserved for future use)\n}\n\nexport function nextjsAppWebhookHandler(config: NextJsAppWebhookConfig) {\n const processor = new WebhookProcessor(config);\n\n return {\n // Clean GET/POST handlers following whatsapp-api-js methodology\n GET: async (request: NextRequest) => {\n try {\n const { searchParams } = new URL(request.url);\n const mode = searchParams.get('hub.mode');\n const token = searchParams.get('hub.verify_token');\n const challenge = searchParams.get('hub.challenge');\n\n const result = await processor.processVerification(mode, token, challenge);\n\n // Return plain text response for webhook verification\n return new Response(result.body, {\n status: result.status,\n headers: result.headers,\n });\n } catch (error) {\n console.error('Webhook verification error:', error);\n return new Response('Internal Server Error', { status: 500 });\n }\n },\n\n POST: async (request: NextRequest) => {\n try {\n const result = await processor.processWebhook(request);\n\n // Return JSON response for webhook processing\n return new Response(result.body, {\n status: result.status,\n headers: result.headers,\n });\n } catch (error) {\n console.error('Webhook processing error:', error);\n return new Response('Internal Server Error', { status: 500 });\n }\n },\n\n // Legacy webhook object for backward compatibility\n webhook: {\n GET: async (request: NextRequest) => {\n try {\n const { searchParams } = new URL(request.url);\n const mode = searchParams.get('hub.mode');\n const token = searchParams.get('hub.verify_token');\n const challenge = searchParams.get('hub.challenge');\n\n const result = await processor.processVerification(mode, token, challenge);\n return new Response(result.body, {\n status: result.status,\n headers: result.headers,\n });\n } catch (error) {\n console.error('Webhook verification error:', error);\n return new Response('Internal Server Error', { status: 500 });\n }\n },\n\n POST: async (request: NextRequest) => {\n try {\n const result = await processor.processWebhook(request);\n return new Response(result.body, {\n status: result.status,\n headers: result.headers,\n });\n } catch (error) {\n console.error('Webhook processing error:', error);\n return new Response('Internal Server Error', { status: 500 });\n }\n },\n },\n\n // Flow handler for App Router\n flow: {\n GET: async (request: NextRequest) => {\n try {\n const result = await processor.processFlow(request);\n\n return Response.json(result.body, {\n status: result.status,\n headers: result.headers,\n });\n } catch (error) {\n console.error('Flow GET error:', error);\n return new Response('Internal Server Error', { status: 500 });\n }\n },\n\n POST: async (request: NextRequest) => {\n try {\n const result = await processor.processFlow(request);\n\n return Response.json(result.body, {\n status: result.status,\n headers: result.headers,\n });\n } catch (error) {\n console.error('Flow POST error:', error);\n return new Response('Internal Server Error', { status: 500 });\n }\n },\n },\n\n // Expose processor for handler registration\n processor,\n };\n}\n","import * as crypto from 'crypto';\n\nexport const generateXHub256Sig = (body: string, appSecret: string) => {\n return crypto.createHmac('sha256', appSecret).update(body, 'utf-8').digest('hex');\n};\n"],"mappings":"o0BAAA,IAAY,EAAA,SAAA,EAAL,OACH,GAAA,eAAA,iBACA,EAAA,UAAA,YACA,EAAA,QAAA,iBAGQ,EAAA,SAAA,EAAL,OACH,GAAA,SAAA,WACA,EAAA,QAAA,UACA,EAAA,SAAA,kBAGQ,EAAA,SAAA,EAAL,OACH,GAAA,IAAA,MACA,EAAA,KAAA,OACA,EAAA,IAAA,MACA,EAAA,OAAA,gBAGQ,EAAA,SAAA,EAAL,OACH,GAAA,MAAA,QACA,EAAA,SAAA,WACA,EAAA,SAAA,WACA,EAAA,MAAA,QACA,EAAA,YAAA,cACA,EAAA,SAAA,WACA,EAAA,SAAA,WACA,EAAA,QAAA,UACA,EAAA,SAAA,WACA,EAAA,KAAA,OACA,EAAA,MAAA,QACA,EAAA,OAAA,SACA,EAAA,MAAA,QACA,EAAA,OAAA,SACA,EAAA,QAAA,UACA,EAAA,SAAA,WACA,EAAA,KAAA,WAGQ,EAAA,SAAA,EAAL,OACH,GAAA,OAAA,SACA,EAAA,WAAA,cACA,EAAA,SAAA,WACA,EAAA,SAAA,YACA,EAAA,SAAA,WACA,EAAA,iBAAA,qBACA,EAAA,MAAA,QACA,EAAA,iBAAA,qBACA,EAAA,SAAA,WACA,EAAA,YAAA,eACA,EAAA,QAAA,UACA,EAAA,QAAA,UACA,EAAA,KAAA,OACA,EAAA,WAAA,cACA,EAAA,MAAA,QACA,EAAA,mBAAA,s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