meta-cloud-api 3.10.1 → 3.10.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/dist/node/index.d.mts +2 -2
- package/dist/node/index.mjs +2 -2
- package/dist/node/index.mjs.map +1 -1
- package/dist/types/index.d.ts +1 -1
- package/dist/utils/index.d.ts +2 -2
- package/dist/utils/index.js +1 -1
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/node/index.d.ts +2 -2
- package/dist/utils/node/index.js +1 -1
- package/dist/utils/node/index.js.map +1 -1
- package/package.json +1 -1
package/dist/node/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["LOGGER","LOGGER","LOGGER","LOGGER","LOGGER","MessageApi","SDKEnums","LOGGER","handlerCache","getCacheKey","handlerCache","getCacheKey","createHandlers","handlerCache","getCacheKey","createHandlers","handlerCache","getCacheKey"],"sources":["../../src/config/defaults.ts","../../src/types/base.ts","../../src/types/enums.ts","../../src/utils/objectToQueryString.ts","../../src/utils/isMetaError.ts","../../src/utils/validate.ts","../../src/api/blockUsers/BlockUsersApi.ts","../../src/api/business/BusinessApi.ts","../../src/api/calling/CallingApi.ts","../../src/api/commerce/CommerceApi.ts","../../src/api/contactBook/ContactBookApi.ts","../../src/api/encryption/EncryptionApi.ts","../../src/api/flow/FlowApi.ts","../../src/api/flow/types/common.ts","../../src/api/groups/GroupsApi.ts","../../src/api/marketingMessages/MarketingMessagesApi.ts","../../src/api/media/MediaApi.ts","../../src/api/messageHistory/MessageHistoryApi.ts","../../src/api/messages/MessageApi.ts","../../src/api/payments/PaymentsApi.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/solutions/SolutionsApi.ts","../../src/api/template/factories/index.ts","../../src/api/template/TemplateApi.ts","../../src/api/threadControl/ThreadControlApi.ts","../../src/api/twoStepVerification/TwoStepVerificationApi.ts","../../src/api/waba/WabaApi.ts","../../src/api/waba/types/common.ts","../../src/utils/logger.ts","../../src/utils/runtimeCrypto.node.ts","../../src/utils/runtime.ts","../../src/config/importConfig.ts","../../src/utils/configTable.ts","../../src/utils/flowEncryptionUtils.ts","../../src/utils/rateLimit.ts","../../src/utils/http/httpsClient.ts","../../src/utils/http/request.ts","../../src/utils/logoConsole.ts","../../src/utils/version.ts","../../src/core/whatsapp/WhatsApp.ts","../../src/core/webhook/dedupe.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/fastify/fastify.ts","../../src/core/webhook/frameworks/hono/hono.ts","../../src/core/webhook/frameworks/nextjs-app/nextjs-app.ts","../../src/core/webhook/frameworks/nextjs-page/nextjs-page.ts","../../src/core/webhook/utils/extractMessageText.ts","../../src/core/webhook/utils/generateXHub256Sig.ts","../../src/core/webhook/utils/messageHelpers.ts","../../src/types/constants.ts","../../src/utils/customerServiceWindow.ts"],"sourcesContent":["export const DEFAULT_CLOUD_API_VERSION = 'v23.0';\nexport const DEFAULT_LISTENER_PORT = 3000;\nexport const DEFAULT_MAX_RETRIES_AFTER_WAIT = 30;\nexport const DEFAULT_REQUEST_TIMEOUT = 20000;\n\nexport const DEFAULT_RETRY_MAX_ATTEMPTS = 3;\nexport const DEFAULT_RETRY_INITIAL_DELAY_MS = 1000;\nexport const DEFAULT_RETRY_BACKOFF = 'exponential';\nexport const DEFAULT_RETRY_MAX_SERVER_DELAY_MS = 30000;\n\nexport const GRAPH_API_HOST = 'graph.facebook.com';\nexport const GRAPH_API_PROTOCOL = 'https:';\n\nexport const WHATSAPP_MESSAGING_PRODUCT = 'whatsapp';\n","import type { WabaConfigType } from './config';\n\nexport declare class BaseClass {\n constructor(config: WabaConfigType);\n}\n\nimport type { HttpMethodsEnum } from './enums';\nimport type { RequesterClass, UrlEncodedFormBody } 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 /** Send a request and return the raw `Response` (for binary bodies). Errors still throw `WhatsAppError`s. */\n protected async sendRaw(method: HttpMethodsEnum, endpoint: string, timeout: number): Promise<Response> {\n const response = await this.client.sendRequest(method, endpoint, timeout);\n return response.rawResponse();\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: UrlEncodedFormBody,\n ): Promise<T> {\n return this.client.sendUrlEncodedForm<T>(method, endpoint, timeout, body);\n }\n}\n","export enum CategoryEnum {\n Authentication = 'AUTHENTICATION',\n Marketing = 'MARKETING',\n Utility = 'UTILITY',\n}\n\n/**\n * Direct Send message categories, sent as the top-level `category` field on\n * `POST /{PHONE_NUMBER_ID}/messages`.\n *\n * Omitting the field is equivalent to `Service` and keeps the existing\n * free-form send behavior (outside Direct Send).\n *\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/direct-send/send-utility-and-authentication-messages | Direct Send}\n */\nexport enum MessageCategoryEnum {\n Authentication = 'authentication',\n Service = 'service',\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 Edit = 'edit',\n Revoke = 'revoke',\n Unsupported = 'unsupported',\n Unknown = 'unknown',\n /**\n * @deprecated Use WebhookProcessor.onStatus() instead of onMessage(MessageTypesEnum.Statuses)\n */\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 CatalogMessage = 'catalog_message',\n CallPermissionRequest = 'call_permission_request',\n CtaUrl = 'cta_url',\n Carousel = 'carousel',\n LocationRequest = 'location_request_message',\n AddressMessage = 'address_message',\n Flow = 'flow',\n VoiceCall = 'voice_call',\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 PaymentRequest = 'PAYMENT_REQUEST',\n PhoneNumber = 'PHONE_NUMBER',\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 /** @deprecated Meta renamed this to `user_changed_number`. Use {@link SystemChangeTypesEnum.UserChangedNumber}. */\n CustomerChangedNumber = 'customer_changed_number',\n /** @deprecated Meta renamed this to `user_identity_changed`. Use {@link SystemChangeTypesEnum.UserIdentityChanged}. */\n CustomerIdentityChanged = 'customer_identity_changed',\n UserChangedNumber = 'user_changed_number',\n UserIdentityChanged = 'user_identity_changed',\n /** The user's business-scoped user ID (BSUID) changed. */\n UserChangedUserId = 'user_changed_user_id',\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","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 type { RateLimitInfo } from './rateLimit';\n\nexport type MetaErrorData = {\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\nexport interface MetaError extends Error {\n error: MetaErrorData;\n}\n\nexport const WHATSAPP_ERROR_CODES = [\n 0, 1, 2, 3, 4, 10, 33, 100, 190, 200, 299, 368, 613, 80007, 130429, 130472, 130497, 131000, 131005, 131008, 131009,\n 131016, 131020, 131021, 131026, 131030, 131031, 131037, 131041, 131042, 131044, 131045, 131047, 131048, 131049,\n 131050, 131051, 131052, 131053, 131055, 131056, 131057, 131059, 131061, 131062, 131063, 131065, 131201, 131202,\n 131203, 131204, 131207, 131208, 131209, 131210, 131211, 131212, 131213, 131214, 131215, 132000, 132001, 132005,\n 132007, 132008, 132012, 132015, 132016, 132068, 132069, 133000, 133004, 133005, 133006, 133008, 133009, 133010,\n 133015, 133016, 134011, 134100, 134101, 134102, 135000, 137000, 138000, 138001, 138002, 138003, 138004, 138005,\n 138006, 138007, 138009, 138012, 138013, 138018, 138038, 139000, 139001, 139002, 139003, 139004, 139100, 139101,\n 139102, 139103, 147005, 200005, 200006, 200007, 1752041, 2388001, 2388012, 2388019, 2388040, 2388047, 2388072,\n 2388073, 2388091, 2388093, 2388103, 2388293, 2388299, 2494100, 2494191, 2593079, 2593085, 2593107, 2593108,\n] as const;\n\nconst WHATSAPP_ERROR_CODE_SET = new Set<number>(WHATSAPP_ERROR_CODES);\n\nexport type ApiPermissionErrorCode = number;\nexport type WhatsAppErrorCode = (typeof WHATSAPP_ERROR_CODES)[number] | ApiPermissionErrorCode;\n\nexport const AUTHORIZATION_ERROR_CODES = [0, 3, 10, 190] as const;\nexport const THROTTLING_ERROR_CODES = [4, 80007, 130429, 131048, 131056] as const;\nexport const INTEGRITY_ERROR_CODES = [368, 130497, 131031] as const;\nexport const SEND_MESSAGE_ERROR_CODES = [\n 130472, 131000, 131005, 131008, 131009, 131016, 131021, 131026, 131030, 131042, 131044, 131045, 131047, 131050,\n 131051, 131052, 131053, 131056, 131057, 131048, 131061, 131062, 131063, 131065, 132000, 132001, 132005, 132007,\n 132008, 132012, 132015, 132016, 132068, 132069, 135000, 137000,\n] as const;\nexport const FLOW_ERROR_CODES = [139000, 139001, 139002, 139003, 139004] as const;\nexport const BLOCK_USER_ERROR_CODES = [139100, 139101, 139102, 139103] as const;\nexport const CALLING_ERROR_CODES = [\n 138000, 138001, 138002, 138003, 138004, 138005, 138006, 138007, 138009, 138012, 138013, 138018, 138038, 613,\n] as const;\nexport const GROUP_ERROR_CODES = [\n 131020, 131041, 131059, 131201, 131202, 131203, 131204, 131207, 131208, 131209, 131210, 131211, 131212, 131213,\n 131214, 131215,\n] as const;\n\nconst AUTHORIZATION_ERROR_CODE_SET = new Set<number>(AUTHORIZATION_ERROR_CODES);\nconst THROTTLING_ERROR_CODE_SET = new Set<number>(THROTTLING_ERROR_CODES);\nconst INTEGRITY_ERROR_CODE_SET = new Set<number>(INTEGRITY_ERROR_CODES);\nconst SEND_MESSAGE_ERROR_CODE_SET = new Set<number>(SEND_MESSAGE_ERROR_CODES);\nconst FLOW_ERROR_CODE_SET = new Set<number>(FLOW_ERROR_CODES);\nconst BLOCK_USER_ERROR_CODE_SET = new Set<number>(BLOCK_USER_ERROR_CODES);\nconst CALLING_ERROR_CODE_SET = new Set<number>(CALLING_ERROR_CODES);\nconst GROUP_ERROR_CODE_SET = new Set<number>(GROUP_ERROR_CODES);\n\nexport function isWhatsAppErrorCode(code: number): code is WhatsAppErrorCode {\n if (isApiPermissionErrorCode(code)) return true;\n return WHATSAPP_ERROR_CODE_SET.has(code);\n}\n\nexport function isApiPermissionErrorCode(code: number): code is ApiPermissionErrorCode {\n return code >= 200 && code < 300;\n}\n\nexport function isAuthorizationErrorCode(\n code: number,\n): code is ApiPermissionErrorCode | (typeof AUTHORIZATION_ERROR_CODES)[number] {\n return isApiPermissionErrorCode(code) || AUTHORIZATION_ERROR_CODE_SET.has(code);\n}\n\nexport function isThrottlingErrorCode(code: number): code is (typeof THROTTLING_ERROR_CODES)[number] {\n return THROTTLING_ERROR_CODE_SET.has(code);\n}\n\nexport function isIntegrityErrorCode(code: number): code is (typeof INTEGRITY_ERROR_CODES)[number] {\n return INTEGRITY_ERROR_CODE_SET.has(code);\n}\n\nexport function isSendMessageErrorCode(code: number): code is (typeof SEND_MESSAGE_ERROR_CODES)[number] {\n return SEND_MESSAGE_ERROR_CODE_SET.has(code);\n}\n\nexport function isFlowErrorCode(code: number): code is (typeof FLOW_ERROR_CODES)[number] {\n return FLOW_ERROR_CODE_SET.has(code);\n}\n\nexport function isBlockUserErrorCode(code: number): code is (typeof BLOCK_USER_ERROR_CODES)[number] {\n return BLOCK_USER_ERROR_CODE_SET.has(code);\n}\n\nexport function isCallingErrorCode(code: number): code is (typeof CALLING_ERROR_CODES)[number] {\n return CALLING_ERROR_CODE_SET.has(code);\n}\n\nexport function isGroupErrorCode(code: number): code is (typeof GROUP_ERROR_CODES)[number] {\n return GROUP_ERROR_CODE_SET.has(code);\n}\n\nexport class WhatsAppError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'WhatsAppError';\n }\n}\n\nexport class WhatsAppApiError extends WhatsAppError {\n readonly error: MetaErrorData;\n readonly statusCode?: number;\n /**\n * Rate limit headers of the failed response, when it carried any. Set by the SDK's requester;\n * use `rateLimit.retryDelayMs` to reschedule a throttled call.\n */\n rateLimit?: RateLimitInfo;\n\n constructor(message: string, error: MetaErrorData, statusCode?: number) {\n super(message);\n this.name = 'WhatsAppApiError';\n this.error = error;\n this.statusCode = statusCode;\n }\n}\n\nexport class WhatsAppAuthorizationError extends WhatsAppApiError {\n constructor(message: string, error: MetaErrorData, statusCode?: number) {\n super(message, error, statusCode);\n this.name = 'WhatsAppAuthorizationError';\n }\n}\n\nexport class WhatsAppThrottlingError extends WhatsAppApiError {\n constructor(message: string, error: MetaErrorData, statusCode?: number) {\n super(message, error, statusCode);\n this.name = 'WhatsAppThrottlingError';\n }\n}\n\nexport class WhatsAppIntegrityError extends WhatsAppApiError {\n constructor(message: string, error: MetaErrorData, statusCode?: number) {\n super(message, error, statusCode);\n this.name = 'WhatsAppIntegrityError';\n }\n}\n\nexport class WhatsAppSendMessageError extends WhatsAppApiError {\n constructor(message: string, error: MetaErrorData, statusCode?: number) {\n super(message, error, statusCode);\n this.name = 'WhatsAppSendMessageError';\n }\n}\n\nexport class WhatsAppFlowError extends WhatsAppApiError {\n constructor(message: string, error: MetaErrorData, statusCode?: number) {\n super(message, error, statusCode);\n this.name = 'WhatsAppFlowError';\n }\n}\n\nexport class WhatsAppBlockUserError extends WhatsAppApiError {\n constructor(message: string, error: MetaErrorData, statusCode?: number) {\n super(message, error, statusCode);\n this.name = 'WhatsAppBlockUserError';\n }\n}\n\nexport class WhatsAppCallingError extends WhatsAppApiError {\n constructor(message: string, error: MetaErrorData, statusCode?: number) {\n super(message, error, statusCode);\n this.name = 'WhatsAppCallingError';\n }\n}\n\nexport class WhatsAppGroupError extends WhatsAppApiError {\n constructor(message: string, error: MetaErrorData, statusCode?: number) {\n super(message, error, statusCode);\n this.name = 'WhatsAppGroupError';\n }\n}\n\nexport function createWhatsAppApiError(error: MetaErrorData, statusCode?: number): WhatsAppApiError {\n const code = error.code;\n\n if (isAuthorizationErrorCode(code)) {\n return new WhatsAppAuthorizationError(error.message, error, statusCode);\n }\n if (isThrottlingErrorCode(code)) {\n return new WhatsAppThrottlingError(error.message, error, statusCode);\n }\n if (isIntegrityErrorCode(code)) {\n return new WhatsAppIntegrityError(error.message, error, statusCode);\n }\n if (isSendMessageErrorCode(code)) {\n return new WhatsAppSendMessageError(error.message, error, statusCode);\n }\n if (isFlowErrorCode(code)) {\n return new WhatsAppFlowError(error.message, error, statusCode);\n }\n if (isBlockUserErrorCode(code)) {\n return new WhatsAppBlockUserError(error.message, error, statusCode);\n }\n if (isCallingErrorCode(code)) {\n return new WhatsAppCallingError(error.message, error, statusCode);\n }\n if (isGroupErrorCode(code)) {\n return new WhatsAppGroupError(error.message, error, statusCode);\n }\n\n return new WhatsAppApiError(error.message, error, statusCode);\n}\n\nexport class WhatsAppNetworkError extends WhatsAppError {\n readonly cause?: unknown;\n\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = 'WhatsAppNetworkError';\n this.cause = cause;\n }\n}\n\nexport class WhatsAppUnknownError extends WhatsAppError {\n readonly cause?: unknown;\n\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = 'WhatsAppUnknownError';\n this.cause = cause;\n }\n}\n\n/**\n * Thrown when an API method receives invalid input (e.g., malformed phone number,\n * empty required array). This error is thrown client-side before any API call is made.\n */\nexport class WhatsAppValidationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'WhatsAppValidationError';\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 if (error == null || typeof error !== 'object') return false;\n if (!('error' in error) || typeof error.error !== 'object' || error.error == null) return false;\n\n const metaError = error.error as Record<string, unknown>;\n\n if (typeof metaError.message !== 'string') return false;\n if (typeof metaError.type !== 'string') return false;\n if (typeof metaError.code !== 'number') return false;\n if (typeof metaError.fbtrace_id !== 'string') return false;\n\n if ('error_data' in metaError && metaError.error_data != null) {\n if (typeof metaError.error_data !== 'object') return false;\n const errorData = metaError.error_data as Record<string, unknown>;\n if ('messaging_product' in errorData && errorData.messaging_product !== 'whatsapp') return false;\n if ('details' in errorData && typeof errorData.details !== 'string') return false;\n }\n\n if ('error_subcode' in metaError && typeof metaError.error_subcode !== 'number') return false;\n\n return true;\n}\n\nexport function isWhatsAppApiErrorResponse(error: any): error is MetaError & { error: { code: WhatsAppErrorCode } } {\n return isMetaError(error) && isWhatsAppErrorCode(error.error.code);\n}\n\nexport function isWhatsAppAuthorizationError(error: unknown): error is WhatsAppAuthorizationError {\n return error instanceof WhatsAppAuthorizationError;\n}\n\nexport function isWhatsAppThrottlingError(error: unknown): error is WhatsAppThrottlingError {\n return error instanceof WhatsAppThrottlingError;\n}\n\nexport function isWhatsAppIntegrityError(error: unknown): error is WhatsAppIntegrityError {\n return error instanceof WhatsAppIntegrityError;\n}\n\nexport function isWhatsAppSendMessageError(error: unknown): error is WhatsAppSendMessageError {\n return error instanceof WhatsAppSendMessageError;\n}\n\nexport function isWhatsAppFlowError(error: unknown): error is WhatsAppFlowError {\n return error instanceof WhatsAppFlowError;\n}\n\nexport function isWhatsAppBlockUserError(error: unknown): error is WhatsAppBlockUserError {\n return error instanceof WhatsAppBlockUserError;\n}\n\nexport function isWhatsAppCallingError(error: unknown): error is WhatsAppCallingError {\n return error instanceof WhatsAppCallingError;\n}\n\nexport function isWhatsAppGroupError(error: unknown): error is WhatsAppGroupError {\n return error instanceof WhatsAppGroupError;\n}\n\nexport function normalizeMetaError(errorData: unknown, statusCode?: number): MetaError {\n if (isMetaError(errorData)) return errorData;\n\n let message = 'Unknown error occurred';\n if (errorData && typeof errorData === 'object' && 'message' in errorData) {\n const candidate = (errorData as { message?: unknown }).message;\n if (typeof candidate === 'string') message = candidate;\n }\n\n return {\n name: 'MetaError',\n message,\n error: {\n message,\n type: 'UnknownError',\n code: typeof statusCode === 'number' ? statusCode : 500,\n fbtrace_id: '',\n },\n };\n}\n","import { WhatsAppValidationError } from './isMetaError';\n\n/**\n * Asserts that a phone number is in valid E.164 format.\n * Accepts numbers with or without leading '+'.\n * Must be 10-15 digits (not counting the '+').\n *\n * @throws WhatsAppValidationError if the phone number is invalid\n *\n * @example\n * assertPhoneNumber('+14155552671'); // ok\n * assertPhoneNumber('14155552671'); // ok\n * assertPhoneNumber('123'); // throws\n */\nexport function assertPhoneNumber(phone: string): void {\n if (!/^\\+?\\d{10,15}$/.test(phone)) {\n throw new WhatsAppValidationError(\n `Invalid phone number: \"${phone}\". Expected E.164 format (e.g. +14155552671 or 14155552671).`,\n );\n }\n}\n\n/**\n * Asserts that an array is non-empty.\n * Also guards against null/undefined to preserve backward compatibility\n * with callers that may pass untyped values.\n *\n * @throws WhatsAppValidationError if the array is null, undefined, or empty\n *\n * @example\n * assertNonEmpty(['user1'], 'users'); // ok\n * assertNonEmpty([], 'users'); // throws\n */\nexport function assertNonEmpty<T>(arr: T[] | null | undefined, name: string): void {\n if (!arr || arr.length === 0) {\n throw new WhatsAppValidationError(`\"${name}\" must contain at least one item.`);\n }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/block-users/\n\n// Endpoints:\n// - POST /{PHONE_NUMBER_ID}/block_users\n// - DELETE /{PHONE_NUMBER_ID}/block_users\n// - GET /{PHONE_NUMBER_ID}/block_users?limit&after&before\n\nimport { WHATSAPP_MESSAGING_PRODUCT } from '../../config/defaults';\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\nimport { assertNonEmpty } from '../../utils/validate';\nimport type * as blockUsers from './types/blockUsers';\n\n/**\n * API for blocking and unblocking WhatsApp users.\n *\n * Provides methods to block, unblock, and list blocked users for your\n * WhatsApp Business phone number.\n *\n * Limitations:\n * - Can only block users that have messaged your business in the last 24 hours\n * - 64k blocklist limit\n *\n * Endpoints covered:\n * - `POST /{PHONE_NUMBER_ID}/block_users` - Block one or more users\n * - `DELETE /{PHONE_NUMBER_ID}/block_users` - Unblock one or more users\n * - `GET /{PHONE_NUMBER_ID}/block_users` - List blocked users with pagination\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/block-users/\n */\nexport default class BlockUsersApi extends BaseAPI implements blockUsers.BlockUsersClass {\n private readonly endpoint = 'block_users';\n\n /**\n * Build the request body for block/unblock operations.\n *\n * @param users - Array of phone numbers or WhatsApp IDs.\n * @returns The formatted request body.\n */\n private buildBlockUsersBody(users: string[]): blockUsers.BlockUsersRequest {\n return {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n block_users: users.map((user) => ({ user })),\n };\n }\n\n /**\n * Block one or more WhatsApp users\n * @param users - Array of phone numbers or WhatsApp IDs to block\n * @returns Response with successfully blocked and failed users\n * @throws Error if users have not messaged in last 24 hours\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/block-users/\n *\n * @example\n * ```typescript\n * // Block single user\n * const result = await client.blockUsers.block(['1234567890']);\n *\n * // Block multiple users\n * const result = await client.blockUsers.block(['1234567890', '0987654321']);\n *\n * // Check results\n * console.log('Blocked:', result.block_users.added_users);\n * console.log('Failed:', result.block_users.failed_users);\n * ```\n */\n async block(users: string[]): Promise<blockUsers.BlockUsersResponse> {\n assertNonEmpty(users, 'users');\n\n const body = this.buildBlockUsersBody(users);\n\n return await this.sendJson<blockUsers.BlockUsersResponse>(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Unblock one or more WhatsApp users\n * @param users - Array of phone numbers or WhatsApp IDs to unblock\n * @returns Response with successfully unblocked and failed users\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/block-users/\n *\n * @example\n * ```typescript\n * // Unblock single user\n * const result = await client.blockUsers.unblock(['1234567890']);\n *\n * // Unblock multiple users\n * const result = await client.blockUsers.unblock(['1234567890', '0987654321']);\n *\n * // Check results\n * console.log('Unblocked:', result.block_users.added_users);\n * console.log('Failed:', result.block_users.failed_users);\n * ```\n */\n async unblock(users: string[]): Promise<blockUsers.BlockUsersResponse> {\n assertNonEmpty(users, 'users');\n\n const body = this.buildBlockUsersBody(users);\n\n return await this.sendJson<blockUsers.BlockUsersResponse>(\n HttpMethodsEnum.Delete,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Get list of blocked WhatsApp users with pagination\n * @param params - Optional pagination parameters\n * @returns List of blocked users with pagination info\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/block-users/\n *\n * @example\n * ```typescript\n * // Get first 10 blocked users\n * const result = await client.blockUsers.listBlockedUsers({ limit: 10 });\n *\n * // Pagination with cursor\n * const nextPage = await client.blockUsers.listBlockedUsers({\n * limit: 10,\n * after: result.paging?.cursors?.after\n * });\n *\n * // Get all blocked users\n * const allBlocked = await client.blockUsers.listBlockedUsers();\n * ```\n */\n async listBlockedUsers(params?: blockUsers.ListBlockedUsersParams): Promise<blockUsers.ListBlockedUsersResponse> {\n let endpoint = `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`;\n\n // Add query parameters if provided\n if (params) {\n const queryString = objectToQueryString(params);\n if (queryString) {\n endpoint += queryString;\n }\n }\n\n return await this.sendJson<blockUsers.ListBlockedUsersResponse>(\n HttpMethodsEnum.Get,\n endpoint,\n this.config[WabaConfigEnum.RequestTimeout],\n );\n }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/overview/\n\n// Endpoints:\n// - GET /{APPLICATION_ID}/connected_client_businesses\n// - POST /{BUSINESS_ID}/add_phone_numbers\n// - GET /{BUSINESS_ID}\n// - GET /{BUSINESS_ID}/preverified_numbers\n// - GET /{BUSINESS_ID}/client_whatsapp_business_accounts\n// - POST /{BUSINESS_ID}/onboard_partners_to_mm_lite\n// - GET /{BUSINESS_ID}/owned_whatsapp_business_accounts\n// - POST /{BUSINESS_ID}/share_preverified_numbers\n// - GET /{BUSINESS_ID}/extendedcredits\n// - GET /{USER_ID}/assigned_whatsapp_business_accounts\n// - GET /{WHATSAPP_ACCOUNT_NUMBER_ID}\n// - GET /{PRE_VERIFIED_PHONE_NUMBER_ID}\n// - DELETE /{PRE_VERIFIED_PHONE_NUMBER_ID}\n// - GET /{PRE_VERIFIED_PHONE_NUMBER_ID}/partners\n// - POST /{PRE_VERIFIED_PHONE_NUMBER_ID}/request_code\n// - POST /{PRE_VERIFIED_PHONE_NUMBER_ID}/verify_code\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { ResponseSuccess } from '../../types/request';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\n\nimport type * as business from './types';\n\nexport default class BusinessApi extends BaseAPI implements business.BusinessClass {\n private toQuery(params?: business.BusinessListParams): string {\n if (!params) return '';\n\n const fields = Array.isArray(params.fields) ? params.fields.join(',') : params.fields;\n const filtering = Array.isArray(params.filtering) ? JSON.stringify(params.filtering) : params.filtering;\n\n return objectToQueryString({\n fields,\n filtering,\n sort: params.sort,\n limit: params.limit,\n after: params.after,\n before: params.before,\n });\n }\n\n private fieldsQuery(fields?: business.BusinessFieldsParam): string {\n const fieldsValue = Array.isArray(fields) ? fields.join(',') : fields;\n return fieldsValue ? objectToQueryString({ fields: fieldsValue }) : '';\n }\n\n async getConnectedClientBusinesses(\n applicationId: string = this.config[WabaConfigEnum.AppId],\n params?: business.BusinessListParams,\n ): Promise<business.BusinessGraphListResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${applicationId}/connected_client_businesses${this.toQuery(params)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async addPhoneNumbers(businessId: string, request: business.AddPhoneNumbersRequest): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${businessId}/add_phone_numbers`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n async getBusinessPortfolio(\n businessId: string,\n fields?: business.BusinessFieldsParam,\n ): Promise<business.BusinessGraphObject> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${businessId}${this.fieldsQuery(fields)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async getPreVerifiedPhoneNumbers(\n businessId: string,\n params?: business.BusinessListParams,\n ): Promise<business.BusinessGraphListResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${businessId}/preverified_numbers${this.toQuery(params)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async getClientWhatsAppBusinessAccounts(\n businessId: string,\n params?: business.BusinessListParams,\n ): Promise<business.BusinessGraphListResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${businessId}/client_whatsapp_business_accounts${this.toQuery(params)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async onboardPartnersToMMLite(\n businessId: string,\n request: business.OnboardPartnersToMMLiteRequest,\n ): Promise<business.BusinessGraphObject> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${businessId}/onboard_partners_to_mm_lite`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n async getOwnedWhatsAppBusinessAccounts(\n businessId: string,\n params?: business.BusinessListParams,\n ): Promise<business.BusinessGraphListResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${businessId}/owned_whatsapp_business_accounts${this.toQuery(params)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async sharePreVerifiedPhoneNumber(\n businessId: string,\n request: business.SharePreVerifiedPhoneNumberRequest,\n ): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${businessId}/share_preverified_numbers`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n async getCreditLines(businessId: string): Promise<business.BusinessGraphListResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${businessId}/extendedcredits`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async getAssignedWhatsAppBusinessAccounts(\n userId: string,\n params?: business.BusinessListParams,\n ): Promise<business.BusinessGraphListResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${userId}/assigned_whatsapp_business_accounts${this.toQuery(params)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async getWhatsAppAccountNumberDetails(\n accountNumberId: string,\n fields?: business.BusinessFieldsParam,\n ): Promise<business.BusinessGraphObject> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${accountNumberId}${this.fieldsQuery(fields)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async getPreVerifiedPhoneNumberDetails(\n preVerifiedPhoneNumberId: string,\n fields?: business.BusinessFieldsParam,\n ): Promise<business.BusinessGraphObject> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${preVerifiedPhoneNumberId}${this.fieldsQuery(fields)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async deletePreVerifiedPhoneNumber(preVerifiedPhoneNumberId: string): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Delete,\n preVerifiedPhoneNumberId,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async getPreVerifiedPhoneNumberPartners(\n preVerifiedPhoneNumberId: string,\n params?: business.BusinessListParams,\n ): Promise<business.BusinessGraphListResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${preVerifiedPhoneNumberId}/partners${this.toQuery(params)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async requestPreVerifiedPhoneNumberCode(\n preVerifiedPhoneNumberId: string,\n request: business.RequestPreVerifiedPhoneNumberCodeRequest,\n ): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${preVerifiedPhoneNumberId}/request_code`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n async verifyPreVerifiedPhoneNumberCode(\n preVerifiedPhoneNumberId: string,\n request: business.VerifyPreVerifiedPhoneNumberCodeRequest,\n ): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${preVerifiedPhoneNumberId}/verify_code`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/reference/\n\n// Endpoints:\n// - POST /{PHONE_NUMBER_ID}/settings\n// - GET /{PHONE_NUMBER_ID}/settings?fields&include_sip_credentials\n// - GET /{PHONE_NUMBER_ID}/call_permissions?user_wa_id\n// - POST /{PHONE_NUMBER_ID}/calls\n\nimport { WHATSAPP_MESSAGING_PRODUCT } from '../../config/defaults';\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { ResponseSuccess } from '../../types/request';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\n\nimport type * as calling from './types';\n\n/**\n * API for WhatsApp Calling features.\n *\n * Provides methods to manage calling settings, permissions, and call lifecycle\n * (initiate, pre-accept, accept, reject, terminate).\n *\n * Endpoints covered:\n * - `POST /{PHONE_NUMBER_ID}/settings` - Update calling settings\n * - `GET /{PHONE_NUMBER_ID}/settings` - Get calling settings\n * - `GET /{PHONE_NUMBER_ID}/call_permissions` - Get call permissions for a user\n * - `POST /{PHONE_NUMBER_ID}/calls` - Initiate, pre-accept, accept, reject, or terminate a call\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/reference/\n */\nexport default class CallingApi extends BaseAPI implements calling.CallingClass {\n private readonly endpoint = 'calls';\n\n /**\n * Update calling settings for the phone number, such as enabling/disabling calling\n * or configuring SIP credentials.\n *\n * @param params - The calling settings to update.\n * @returns A success response confirming the settings were updated.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/reference/\n */\n async updateCallingSettings(params: calling.UpdateCallingSettingsRequest): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/settings`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(params),\n );\n }\n\n /**\n * Retrieve the current calling settings for the phone number.\n *\n * @param params - Optional query parameters to filter the response.\n * @param params.fields - Specific fields to include in the response.\n * @param params.include_sip_credentials - Whether to include SIP credentials in the response.\n * @returns The current calling settings configuration.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/reference/\n */\n async getCallingSettings(params?: {\n fields?: string[] | string;\n include_sip_credentials?: boolean;\n }): Promise<calling.CallingSettingsResponse> {\n const fieldsValue = Array.isArray(params?.fields) ? params?.fields.join(',') : params?.fields;\n const queryParams = objectToQueryString({\n ...(fieldsValue ? { fields: fieldsValue } : {}),\n ...(params?.include_sip_credentials !== undefined\n ? { include_sip_credentials: params.include_sip_credentials }\n : {}),\n });\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/settings${queryParams}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Get calling permissions for a specific WhatsApp user.\n *\n * @param params - The request parameters.\n * @param params.userWaId - The WhatsApp ID of the user to check permissions for.\n * @returns The call permissions for the specified user.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/reference/\n */\n async getCallPermissions(params: { userWaId: string }): Promise<calling.CallPermissionsResponse> {\n const queryParams = objectToQueryString({ user_wa_id: params.userWaId });\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/call_permissions${queryParams}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Initiate an outbound call to a WhatsApp user.\n *\n * @param params - The call initiation parameters.\n * @param params.to - The recipient's WhatsApp phone number.\n * @param params.session - The call session configuration.\n * @param params.biz_opaque_callback_data - Optional opaque data passed back in webhooks.\n * @param params.recording - Optional per-call recording configuration.\n * @param params.transcription - Optional per-call transcription configuration.\n * @returns The initiated call response with call ID and status.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/reference/\n */\n async initiateCall(params: calling.InitiateCallRequest): Promise<calling.InitiateCallResponse> {\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n to: params.to,\n action: 'connect',\n session: params.session,\n } as {\n messaging_product: 'whatsapp';\n to: string;\n action: calling.CallAction;\n session: calling.CallSession;\n biz_opaque_callback_data?: string;\n recording?: calling.CallRecordingConfig;\n transcription?: calling.CallTranscriptionConfig;\n };\n\n if (params.biz_opaque_callback_data) {\n body.biz_opaque_callback_data = params.biz_opaque_callback_data;\n }\n if (params.recording) body.recording = params.recording;\n if (params.transcription) body.transcription = params.transcription;\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Pre-accept an incoming call, signaling readiness to connect before full acceptance.\n *\n * @param params - The pre-accept request parameters.\n * @param params.call_id - The ID of the call to pre-accept.\n * @param params.session - Optional session configuration for the call.\n * @returns The call action response confirming the pre-accept.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/reference/\n */\n async preAcceptCall(params: calling.PreAcceptCallRequest): Promise<calling.CallActionResponse> {\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n call_id: params.call_id,\n action: 'pre_accept',\n } as {\n messaging_product: 'whatsapp';\n call_id: string;\n action: calling.CallAction;\n session?: calling.CallSession;\n };\n\n if (params.session) body.session = params.session;\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Accept an incoming call and establish the connection.\n *\n * @param params - The accept request parameters.\n * @param params.call_id - The ID of the call to accept.\n * @param params.session - Optional session configuration for the call.\n * @param params.biz_opaque_callback_data - Optional opaque data passed back in webhooks.\n * @param params.recording - Optional per-call recording configuration.\n * @param params.transcription - Optional per-call transcription configuration.\n * @returns The call action response confirming acceptance.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/reference/\n */\n async acceptCall(params: calling.AcceptCallRequest): Promise<calling.CallActionResponse> {\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n call_id: params.call_id,\n action: 'accept',\n } as {\n messaging_product: 'whatsapp';\n call_id: string;\n action: calling.CallAction;\n session?: calling.CallSession;\n biz_opaque_callback_data?: string;\n recording?: calling.CallRecordingConfig;\n transcription?: calling.CallTranscriptionConfig;\n };\n\n if (params.session) body.session = params.session;\n if (params.biz_opaque_callback_data) {\n body.biz_opaque_callback_data = params.biz_opaque_callback_data;\n }\n if (params.recording) body.recording = params.recording;\n if (params.transcription) body.transcription = params.transcription;\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Reject an incoming call.\n *\n * @param params - The reject request parameters.\n * @param params.call_id - The ID of the call to reject.\n * @returns The call action response confirming rejection.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/reference/\n */\n async rejectCall(params: calling.RejectCallRequest): Promise<calling.CallActionResponse> {\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n call_id: params.call_id,\n action: 'reject',\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Terminate an active call.\n *\n * @param params - The terminate request parameters.\n * @param params.call_id - The ID of the call to terminate.\n * @returns The call action response confirming termination.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/reference/\n */\n async terminateCall(params: calling.TerminateCallRequest): Promise<calling.CallActionResponse> {\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n call_id: params.call_id,\n action: 'terminate',\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/catalogs/sell-products-and-services/set-commerce-settings/\n\n// Endpoints:\n// - GET /{PHONE_NUMBER_ID}/whatsapp_commerce_settings\n// - POST /{PHONE_NUMBER_ID}/whatsapp_commerce_settings?is_cart_enabled&is_catalog_visible\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { ResponseSuccess } from '../../types/request';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\n\nimport type * as commerce from './types';\n\n/**\n * API for WhatsApp Commerce Settings.\n *\n * Provides methods to retrieve and update commerce settings such as cart\n * and catalog visibility for your WhatsApp Business phone number.\n *\n * Endpoints covered:\n * - `GET /{PHONE_NUMBER_ID}/whatsapp_commerce_settings` - Get commerce settings\n * - `POST /{PHONE_NUMBER_ID}/whatsapp_commerce_settings` - Update commerce settings\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/catalogs/sell-products-and-services/set-commerce-settings/\n */\nexport default class CommerceApi extends BaseAPI implements commerce.CommerceClass {\n private readonly endpoint = 'whatsapp_commerce_settings';\n\n /**\n * Retrieve the current commerce settings for the phone number.\n *\n * @returns The current commerce settings including cart and catalog visibility state.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/catalogs/sell-products-and-services/set-commerce-settings/\n */\n async getCommerceSettings(): Promise<commerce.CommerceSettingsResponse> {\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 * Update commerce settings for the phone number (e.g., enable/disable cart or catalog).\n *\n * @param params - The commerce settings to update (e.g., is_cart_enabled, is_catalog_visible).\n * @returns A success response confirming the settings were updated.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/catalogs/sell-products-and-services/set-commerce-settings/\n */\n async updateCommerceSettings(params: commerce.UpdateCommerceSettingsRequest): Promise<ResponseSuccess> {\n const queryParams = objectToQueryString(params);\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}${queryParams}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/business-scoped-user-ids/\n\n// Endpoints:\n// - DELETE /{PHONE_NUMBER_ID}/contact_book?messaging_product=whatsapp&bsuid={BSUID}\n\nimport { WHATSAPP_MESSAGING_PRODUCT } from '../../config/defaults';\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport { WhatsAppValidationError } from '../../utils/isMetaError';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\n\nimport type * as contactBook from './types/contactBook';\n\n/**\n * API for the Meta-hosted contact book.\n *\n * The contact book pairs a WhatsApp user's phone number with their\n * business-scoped user ID (BSUID). Meta populates it automatically: any message\n * or call between a business phone number in your portfolio and a user stores\n * that pairing, which is why webhooks keep including the phone number even after\n * the user adopts a username. It is scoped to the business portfolio, not to a\n * single phone number, and only captures interactions from early April 2026\n * onward — there is no historical backfill.\n *\n * Endpoints covered:\n * - `DELETE /{PHONE_NUMBER_ID}/contact_book` - Delete a user's contact book entry\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/business-scoped-user-ids/\n */\nexport default class ContactBookApi extends BaseAPI implements contactBook.ContactBookClass {\n private readonly endpoint = 'contact_book';\n\n /**\n * Delete a user's entry from your contact book.\n *\n * Once deleted, the user's phone number and BSUID are no longer included in\n * webhook payloads for any business phone number in the portfolio — unless\n * the number is still in the 30-day cache, or a new interaction recreates the\n * entry.\n *\n * Unknown, malformed, and other-portfolio BSUIDs no longer raise an API error\n * (changed August 25, 2026): the request resolves with `deleted: false`, so\n * check that flag instead of relying on a thrown error to detect a miss.\n *\n * @param params - Delete parameters.\n * @param params.bsuid - BSUID of the entry to delete (e.g. \"US.13491208655302741918\").\n * @returns Response reporting whether the entry was deleted (`deleted: false` when no entry matched).\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/business-scoped-user-ids/\n *\n * @example\n * ```typescript\n * const result = await client.contactBook.deleteEntry({ bsuid: 'US.13491208655302741918' });\n * // true when an entry was removed, false when the BSUID had no entry in the portfolio\n * console.log(result.deleted);\n * ```\n */\n async deleteEntry(\n params: contactBook.DeleteContactBookEntryParams,\n ): Promise<contactBook.DeleteContactBookEntryResponse> {\n if (!params?.bsuid) {\n throw new WhatsAppValidationError('\"bsuid\" is required to delete a contact book entry.');\n }\n\n const query = objectToQueryString({\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n bsuid: params.bsuid,\n });\n\n return await this.sendJson<contactBook.DeleteContactBookEntryResponse>(\n HttpMethodsEnum.Delete,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}${query}`,\n this.config[WabaConfigEnum.RequestTimeout],\n );\n }\n}\n","// Docs: https://developers.facebook.com/docs/whatsapp/cloud-api/reference/whatsapp-business-encryption/\n\n// Endpoints:\n// - GET /{PHONE_NUMBER_ID}/whatsapp_business_encryption\n// - POST /{PHONE_NUMBER_ID}/whatsapp_business_encryption\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { ResponseSuccess } from '../../types/request';\nimport type { EncryptionClass, EncryptionPublicKeyResponse } from './types';\n\n/**\n * API for managing WhatsApp Business Encryption keys.\n *\n * Provides methods to get and set the public encryption key used for\n * end-to-end encrypted messaging with WhatsApp Business.\n *\n * Endpoints covered:\n * - `GET /{PHONE_NUMBER_ID}/whatsapp_business_encryption` - Get the current public encryption key\n * - `POST /{PHONE_NUMBER_ID}/whatsapp_business_encryption` - Set a new public encryption key\n *\n * @see https://developers.facebook.com/docs/whatsapp/cloud-api/reference/whatsapp-business-encryption/\n */\nexport default class EncryptionApi extends BaseAPI implements EncryptionClass {\n private readonly endpoint = 'whatsapp_business_encryption';\n\n /**\n * Retrieve the current public encryption key for the phone number.\n *\n * @returns The current public encryption key.\n * @see https://developers.facebook.com/docs/whatsapp/cloud-api/reference/whatsapp-business-encryption/\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 /**\n * Set a new public encryption key for the phone number.\n *\n * @param businessPublicKey - The PEM-encoded public key string to set.\n * @returns A success response confirming the key was set.\n * @see https://developers.facebook.com/docs/whatsapp/cloud-api/reference/whatsapp-business-encryption/\n */\n async setEncryptionPublicKey(businessPublicKey: string): Promise<ResponseSuccess> {\n const formData = new FormData();\n formData.append('business_public_key', businessPublicKey);\n\n return this.sendFormData(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n formData,\n );\n }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/flows/\n\n// Endpoints:\n// - GET /{WABA_ID}/flows\n// - POST /{WABA_ID}/flows\n// - GET /{FLOW_ID}?fields&date_format\n// - POST /{FLOW_ID}\n// - DELETE /{FLOW_ID}\n// - GET /{FLOW_ID}/assets\n// - POST /{FLOW_ID}/assets\n// - POST /{FLOW_ID}/publish\n// - POST /{FLOW_ID}/deprecate\n// - POST /{DESTINATION_WABA_ID}/migrate_flows\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { ResponseSuccess } from '../../types/request';\n\nimport type * as flow from './types';\n\n/**\n * API for managing WhatsApp Flows.\n *\n * WhatsApp Flows allow businesses to build structured, interactive experiences\n * within WhatsApp conversations. Flows can be used for appointment booking,\n * lead generation, customer support, surveys, and more.\n *\n * This API allows you to:\n * - List flows for a WhatsApp Business Account (`GET /{WABA_ID}/flows`)\n * - Create new flows (`POST /{WABA_ID}/flows`)\n * - Get flow details and previews (`GET /{FLOW_ID}`)\n * - Update flow metadata (`POST /{FLOW_ID}`)\n * - Delete draft flows (`DELETE /{FLOW_ID}`)\n * - List flow assets / download Flow JSON (`GET /{FLOW_ID}/assets`)\n * - Upload or update Flow JSON (`POST /{FLOW_ID}/assets`)\n * - Publish flows (`POST /{FLOW_ID}/publish`)\n * - Deprecate flows (`POST /{FLOW_ID}/deprecate`)\n * - Migrate flows between WABAs (`POST /{DESTINATION_WABA_ID}/migrate_flows`)\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi | Flows API Reference}\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/flows/ | WhatsApp Flows Documentation}\n */\nexport default class FlowApi extends BaseAPI implements flow.FlowClass {\n private appendFormValue(\n formData: FormData,\n key: string,\n value?: string | boolean | string[] | flow.FlowCategoryEnum[],\n ) {\n if (value === undefined) return;\n formData.append(key, Array.isArray(value) ? JSON.stringify(value) : String(value));\n }\n\n /**\n * List all flows belonging to a WhatsApp Business Account.\n *\n * Retrieves a paginated list of all flows associated with the given WABA ID,\n * including their IDs, names, statuses, and categories.\n *\n * @param wabaId - The WhatsApp Business Account ID to list flows for.\n * @returns A promise that resolves with the list of flows and pagination info.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#list | List Flows}\n *\n * @example\n * ```ts\n * const response = await whatsappClient.flow.listFlows('WABA_ID');\n * for (const flow of response.data) {\n * console.log(flow.id, flow.name, flow.status);\n * }\n * ```\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 a new flow for a WhatsApp Business Account.\n *\n * Creates a new flow in DRAFT status. You can optionally clone an existing flow,\n * provide initial Flow JSON, and even publish the flow immediately upon creation.\n *\n * @param wabaId - The WhatsApp Business Account ID to create the flow under.\n * @param data - The flow creation parameters.\n * @param data.name - The name of the flow.\n * @param data.categories - Optional array of flow categories (e.g., LEAD_GENERATION, APPOINTMENT_BOOKING).\n * @param data.endpoint_uri - Optional URI for the flow endpoint that will receive flow action payloads.\n * @param data.clone_flow_id - Optional ID of an existing flow to clone.\n * @param data.flow_json - Optional Flow JSON definition as a string.\n * @param data.publish - Optional flag to publish the flow immediately after creation.\n * @returns A promise that resolves with the created flow ID and any validation errors.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#create | Create Flow}\n *\n * @example\n * ```ts\n * const result = await whatsappClient.flow.createFlow('WABA_ID', {\n * name: 'Appointment Booking',\n * categories: ['APPOINTMENT_BOOKING'],\n * endpoint_uri: 'https://example.com/flow-endpoint',\n * });\n * console.log(result.id); // New flow ID\n * ```\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 const formData = new FormData();\n this.appendFormValue(formData, 'name', data.name);\n this.appendFormValue(formData, 'categories', data.categories);\n this.appendFormValue(formData, 'endpoint_uri', data.endpoint_uri);\n this.appendFormValue(formData, 'clone_flow_id', data.clone_flow_id);\n this.appendFormValue(formData, 'flow_json', data.flow_json);\n this.appendFormValue(formData, 'publish', data.publish);\n\n return this.sendFormData(\n HttpMethodsEnum.Post,\n `/${wabaId}/flows`,\n this.config[WabaConfigEnum.RequestTimeout],\n formData,\n );\n }\n\n /**\n * Get details of a specific flow.\n *\n * Retrieves flow information such as name, status, categories, JSON validation errors,\n * and optionally a preview URL. Use the `fields` parameter to request specific fields\n * or the preview endpoint.\n *\n * @param flowId - The ID of the flow to retrieve.\n * @param fields - Optional comma-separated list of fields to return (e.g., `'name,status,preview.invalidate(false)'`).\n * @param dateFormat - Optional date format string for date fields in the response.\n * @returns A promise that resolves with the flow details or preview response.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#details | Get Flow Details}\n *\n * @example\n * ```ts\n * // Get all flow details\n * const flow = await whatsappClient.flow.getFlow('FLOW_ID');\n * console.log(flow.name, flow.status);\n *\n * // Get specific fields only\n * const flow = await whatsappClient.flow.getFlow('FLOW_ID', 'name,status,categories');\n * ```\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 a preview URL for a flow.\n *\n * Generates a shareable preview URL that allows viewing the flow without publishing it.\n * The preview can optionally be invalidated to force generation of a fresh URL.\n *\n * @param flowId - The ID of the flow to preview.\n * @param invalidate - If `true`, invalidates the existing preview and generates a new one. Defaults to `false`.\n * @returns A promise that resolves with the flow preview details including the preview URL.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#details | Get Flow Preview}\n *\n * @example\n * ```ts\n * // Get existing preview URL\n * const preview = await whatsappClient.flow.getFlowPreview('FLOW_ID');\n * console.log(preview.preview.preview_url);\n *\n * // Force a new preview URL\n * const freshPreview = await whatsappClient.flow.getFlowPreview('FLOW_ID', true);\n * ```\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 the metadata of an existing flow.\n *\n * Allows updating a flow's name, categories, endpoint URI, or associated application ID.\n * The flow must be in DRAFT status to update certain fields.\n *\n * @param flowId - The ID of the flow to update.\n * @param data - The metadata fields to update.\n * @param data.name - Optional new name for the flow.\n * @param data.categories - Optional new categories for the flow.\n * @param data.endpoint_uri - Optional new endpoint URI for flow action payloads.\n * @param data.application_id - Optional application ID to associate with the flow.\n * @returns A promise that resolves with a success indicator.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#update | Update Flow}\n *\n * @example\n * ```ts\n * await whatsappClient.flow.updateFlowMetadata('FLOW_ID', {\n * name: 'Updated Flow Name',\n * endpoint_uri: 'https://example.com/new-endpoint',\n * });\n * ```\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 const formData = new FormData();\n this.appendFormValue(formData, 'name', data.name);\n this.appendFormValue(formData, 'categories', data.categories);\n this.appendFormValue(formData, 'endpoint_uri', data.endpoint_uri);\n this.appendFormValue(formData, 'application_id', data.application_id);\n\n return this.sendFormData(\n HttpMethodsEnum.Post,\n `/${flowId}`,\n this.config[WabaConfigEnum.RequestTimeout],\n formData,\n );\n }\n\n /**\n * Delete a flow.\n *\n * Permanently deletes a flow. Only flows in DRAFT status can be deleted.\n * Published or deprecated flows cannot be deleted.\n *\n * @param flowId - The ID of the flow to delete.\n * @returns A promise that resolves with a success indicator.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#delete | Delete Flow}\n *\n * @example\n * ```ts\n * await whatsappClient.flow.deleteFlow('FLOW_ID');\n * ```\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 associated with a flow.\n *\n * Retrieves the list of assets (e.g., Flow JSON) associated with the flow.\n * The response includes download URLs for each asset.\n *\n * @param flowId - The ID of the flow to list assets for.\n * @returns A promise that resolves with the list of assets including download URLs.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#asset-list | List Flow Assets}\n *\n * @example\n * ```ts\n * const assets = await whatsappClient.flow.listAssets('FLOW_ID');\n * for (const asset of assets.data) {\n * console.log(asset.name, asset.download_url);\n * }\n * ```\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 * Upload or update the Flow JSON for a flow.\n *\n * Uploads a Flow JSON definition to the flow's assets. The JSON defines the screens,\n * layout, and logic of the flow. Accepts a Buffer, plain JSON object, or Blob.\n *\n * @param flowId - The ID of the flow to update.\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 A promise that resolves with the upload status and any validation errors.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#asset-upload | Upload Flow JSON}\n *\n * @example\n * ```ts\n * // Upload from a JSON object\n * const result = await whatsappClient.flow.updateFlowJson('FLOW_ID', {\n * file: {\n * version: '5.0',\n * screens: [{ id: 'WELCOME', layout: { type: 'SingleColumnLayout', children: [] } }],\n * },\n * });\n *\n * // Upload from a Buffer\n * const jsonBuffer = Buffer.from(JSON.stringify(flowDefinition));\n * await whatsappClient.flow.updateFlowJson('FLOW_ID', { file: jsonBuffer });\n * ```\n */\n async updateFlowJson(\n flowId: string,\n data: {\n file: Blob | Uint8Array | 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 Uint8Array) {\n // Buffer or Uint8Array - convert to Uint8Array for BlobPart compatibility\n fileContent = new globalThis.Blob([new Uint8Array(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 without publishing.\n *\n * This is a convenience method that uploads the Flow JSON and checks for validation\n * errors. The API does not have a dedicated validation endpoint, so this method\n * performs an update and inspects the response for errors.\n *\n * @param flowId - The ID of the flow to validate against (must exist, can be in DRAFT status).\n * @param flowJsonData - The Flow JSON content as a Buffer, JSON object, or Blob.\n * @returns A promise that resolves with validation results, including a `valid` boolean\n * and any `validation_errors` found.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#asset-upload | Upload Flow JSON (validation)}\n *\n * @example\n * ```ts\n * const result = await whatsappClient.flow.validateFlowJson('FLOW_ID', {\n * version: '5.0',\n * screens: [{ id: 'WELCOME', layout: { type: 'SingleColumnLayout', children: [] } }],\n * });\n * if (result.valid) {\n * console.log('Flow JSON is valid');\n * } else {\n * console.error('Validation errors:', result.validation_errors);\n * }\n * ```\n */\n async validateFlowJson(\n flowId: string,\n flowJsonData: Blob | Uint8Array | object,\n ): Promise<flow.ValidateFlowJsonResponse> {\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 }\n\n /**\n * Publish a flow.\n *\n * Transitions a flow from DRAFT status to PUBLISHED. Once published, the flow\n * can be sent to users in WhatsApp messages. A published flow's JSON can no longer\n * be updated.\n *\n * @param flowId - The ID of the flow to publish.\n * @returns A promise that resolves with a success indicator.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#publish | Publish Flow}\n *\n * @example\n * ```ts\n * await whatsappClient.flow.publishFlow('FLOW_ID');\n * ```\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 a flow.\n *\n * Transitions a flow from PUBLISHED status to DEPRECATED. A deprecated flow\n * can no longer be sent to users but existing sessions will continue to work.\n * This action cannot be undone.\n *\n * @param flowId - The ID of the flow to deprecate.\n * @returns A promise that resolves with a success indicator.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#deprecate | Deprecate Flow}\n *\n * @example\n * ```ts\n * await whatsappClient.flow.deprecateFlow('FLOW_ID');\n * ```\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 WhatsApp Business Accounts.\n *\n * Copies flows from a source WABA to a destination WABA. You can optionally\n * specify which flows to migrate by name. Migrated flows are created in DRAFT\n * status in the destination WABA.\n *\n * @param destinationWabaId - The ID of the destination WhatsApp Business Account.\n * @param data - The migration parameters.\n * @param data.source_waba_id - The ID of the source WhatsApp Business Account to migrate flows from.\n * @param data.source_flow_names - Optional array of flow names to migrate. If omitted, all flows are migrated.\n * @returns A promise that resolves with migration results including successes and failures.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#migrate | Migrate Flows}\n *\n * @example\n * ```ts\n * // Migrate all flows from one WABA to another\n * const result = await whatsappClient.flow.migrateFlows('DEST_WABA_ID', {\n * source_waba_id: 'SOURCE_WABA_ID',\n * });\n *\n * // Migrate specific flows by name\n * const result = await whatsappClient.flow.migrateFlows('DEST_WABA_ID', {\n * source_waba_id: 'SOURCE_WABA_ID',\n * source_flow_names: ['Appointment Booking', 'Lead Gen Form'],\n * });\n * console.log(result.migrated_flows, result.failed_flows);\n * ```\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 const formData = new FormData();\n this.appendFormValue(formData, 'source_waba_id', data.source_waba_id);\n this.appendFormValue(formData, 'source_flow_names', data.source_flow_names);\n\n return this.sendFormData(\n HttpMethodsEnum.Post,\n `/${destinationWabaId}/migrate_flows`,\n this.config[WabaConfigEnum.RequestTimeout],\n formData,\n );\n }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/flows/\n\nimport type { IncomingHttpHeaders, IncomingMessage } from 'node:http';\nimport type { ResponseSuccess } from '../../../types';\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 | Uint8Array | 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 | Uint8Array | 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","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n\n// Endpoints:\n// - POST /{PHONE_NUMBER_ID}/groups\n// - DELETE /{GROUP_ID}\n// - GET /{GROUP_ID}?fields\n// - GET /{PHONE_NUMBER_ID}/groups?limit&after&before\n// - GET /{GROUP_ID}/invite_link\n// - POST /{GROUP_ID}/invite_link\n// - DELETE /{GROUP_ID}/invite_link\n// - GET /{GROUP_ID}/join_requests\n// - POST /{GROUP_ID}/join_requests\n// - DELETE /{GROUP_ID}/join_requests\n// - POST /{GROUP_ID}/participants\n// - DELETE /{GROUP_ID}/participants\n// - POST /{GROUP_ID}\n\nimport { WHATSAPP_MESSAGING_PRODUCT } from '../../config/defaults';\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { ResponseSuccess } from '../../types/request';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\nimport { assertNonEmpty } from '../../utils/validate';\n\nimport type * as groups from './types';\n\n/**\n * API for managing WhatsApp Groups.\n *\n * This API allows you to:\n * - Create and delete groups\n * - Approve/reject join requests\n * - Manage group invite links\n * - Remove participants\n * - Update group settings\n * - Fetch group metadata and active groups\n *\n * Endpoints covered:\n * - `POST /{PHONE_NUMBER_ID}/groups` - Create a new group\n * - `DELETE /{GROUP_ID}` - Delete a group\n * - `GET /{GROUP_ID}` - Get group info\n * - `GET /{PHONE_NUMBER_ID}/groups` - List active groups\n * - `GET /{GROUP_ID}/invite_link` - Get group invite link\n * - `POST /{GROUP_ID}/invite_link` - Reset group invite link\n * - `GET /{GROUP_ID}/join_requests` - Get pending join requests\n * - `POST /{GROUP_ID}/join_requests` - Approve join requests\n * - `DELETE /{GROUP_ID}/join_requests` - Reject join requests\n * - `DELETE /{GROUP_ID}/participants` - Remove participants\n * - `POST /{GROUP_ID}` - Update group settings\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\nexport default class GroupsApi extends BaseAPI implements groups.GroupsClass {\n /**\n * Create a new WhatsApp group.\n *\n * @param params - The group creation parameters.\n * @param params.subject - The name/subject of the group.\n * @param params.description - Optional description for the group.\n * @param params.join_approval_mode - Optional join approval mode setting.\n * @returns The created group response with group ID.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n async createGroup(params: groups.GroupCreateRequest): Promise<groups.GroupCreateResponse> {\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n subject: params.subject,\n } as { messaging_product: 'whatsapp'; subject: string; description?: string; join_approval_mode?: string };\n\n if (params.description) body.description = params.description;\n if (params.join_approval_mode) body.join_approval_mode = params.join_approval_mode;\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/groups`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Delete a WhatsApp group.\n *\n * @param groupId - The ID of the group to delete.\n * @returns A success response confirming deletion.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n async deleteGroup(groupId: string): Promise<ResponseSuccess> {\n return this.sendJson(HttpMethodsEnum.Delete, groupId, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n /**\n * Retrieve metadata and information about a specific group.\n *\n * @param groupId - The ID of the group to retrieve.\n * @param fields - Optional fields to include in the response (e.g., subject, description, participants).\n * @returns The group information including metadata and requested fields.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n async getGroupInfo(groupId: string, fields?: groups.GroupInfoFieldsParam): Promise<groups.GroupInfoResponse> {\n const fieldValue = Array.isArray(fields) ? fields.join(',') : fields;\n const queryParams = fieldValue ? objectToQueryString({ fields: fieldValue }) : '';\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${groupId}${queryParams}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * List all active groups for the phone number with optional pagination.\n *\n * @param params - Optional pagination parameters.\n * @param params.limit - Maximum number of groups to return.\n * @param params.after - Cursor for forward pagination.\n * @param params.before - Cursor for backward pagination.\n * @returns A paginated list of active groups.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n async getActiveGroups(params?: groups.GroupListParams): Promise<groups.GroupListResponse> {\n const queryParams = params ? objectToQueryString(params) : '';\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/groups${queryParams}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Get the current invite link for a group.\n *\n * @param groupId - The ID of the group.\n * @returns The group invite link.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n async getGroupInviteLink(groupId: string): Promise<groups.GroupInviteLinkResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${groupId}/invite_link`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Create a group invite link.\n *\n * @param groupId - The ID of the group.\n * @returns The group invite link.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n async createGroupInviteLink(groupId: string): Promise<groups.GroupInviteLinkResponse> {\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n };\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${groupId}/invite_link`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Reset and regenerate the invite link for a group, invalidating the previous link.\n *\n * @param groupId - The ID of the group.\n * @returns The new group invite link.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n async resetGroupInviteLink(groupId: string): Promise<groups.GroupInviteLinkResponse> {\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n };\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${groupId}/invite_link`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Delete the current invite link for a group.\n *\n * @param groupId - The ID of the group.\n * @returns A success response confirming deletion.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n async deleteGroupInviteLink(groupId: string): Promise<ResponseSuccess> {\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n };\n return this.sendJson(\n HttpMethodsEnum.Delete,\n `${groupId}/invite_link`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Get pending join requests for a group.\n *\n * @param groupId - The ID of the group.\n * @returns A list of pending join requests.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n async getJoinRequests(groupId: string): Promise<groups.GroupJoinRequestsResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${groupId}/join_requests`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Approve one or more pending join requests for a group.\n *\n * @param groupId - The ID of the group.\n * @param joinRequestIds - Array of join request IDs to approve.\n * @returns The result of the approval action.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n async approveJoinRequests(\n groupId: string,\n joinRequestIds: string[],\n ): Promise<groups.GroupJoinRequestsActionResponse> {\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n join_requests: joinRequestIds,\n };\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${groupId}/join_requests`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Reject one or more pending join requests for a group.\n *\n * @param groupId - The ID of the group.\n * @param joinRequestIds - Array of join request IDs to reject.\n * @returns The result of the rejection action.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n async rejectJoinRequests(\n groupId: string,\n joinRequestIds: string[],\n ): Promise<groups.GroupJoinRequestsActionResponse> {\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n join_requests: joinRequestIds,\n };\n return this.sendJson(\n HttpMethodsEnum.Delete,\n `${groupId}/join_requests`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Add one or more participants to a group.\n *\n * @param groupId - The ID of the group.\n * @param participants - Array of user WhatsApp IDs to add to the group.\n * @returns A success response confirming the addition.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n async addParticipants(groupId: string, participants: string[]): Promise<ResponseSuccess> {\n assertNonEmpty(participants, 'participants');\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n participants: participants.map((user) => ({ user })),\n };\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${groupId}/participants`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Remove one or more participants from a group.\n *\n * @param groupId - The ID of the group.\n * @param participants - Array of user WhatsApp IDs to remove from the group.\n * @returns A success response confirming removal.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n async removeParticipants(groupId: string, participants: string[]): Promise<ResponseSuccess> {\n assertNonEmpty(participants, 'participants');\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n participants: participants.map((user) => ({ user })),\n };\n return this.sendJson(\n HttpMethodsEnum.Delete,\n `${groupId}/participants`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Update group settings such as subject, description, or profile picture.\n *\n * @param groupId - The ID of the group to update.\n * @param params - The settings to update.\n * @param params.subject - Optional new group subject/name.\n * @param params.description - Optional new group description.\n * @param params.profilePictureFile - Optional profile picture as a Buffer or Blob.\n * @returns The updated group settings response.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n async updateGroupSettings(\n groupId: string,\n params: groups.UpdateGroupSettingsRequest,\n ): Promise<groups.GroupSettingsResponse> {\n if (params.profilePictureFile) {\n const formData = new FormData();\n formData.append('messaging_product', WHATSAPP_MESSAGING_PRODUCT);\n if (params.subject) formData.append('subject', params.subject);\n if (params.description) formData.append('description', params.description);\n\n if (params.profilePictureFile instanceof Uint8Array) {\n const fileBlob = new globalThis.Blob([new Uint8Array(params.profilePictureFile)], {\n type: 'image/jpeg',\n });\n formData.append('file', fileBlob as unknown as Blob);\n } else if (params.profilePictureFile instanceof Blob) {\n formData.append('file', params.profilePictureFile);\n } else {\n throw new Error('Invalid profile picture file type. Use a Buffer or Blob.');\n }\n\n return this.sendFormData(\n HttpMethodsEnum.Post,\n groupId,\n this.config[WabaConfigEnum.RequestTimeout],\n formData,\n );\n }\n\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n } as { messaging_product: 'whatsapp'; subject?: string; description?: string };\n\n if (params.subject) body.subject = params.subject;\n if (params.description) body.description = params.description;\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n groupId,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/marketing-messages/send-marketing-messages/\n\n// Endpoints:\n// - POST /{PHONE_NUMBER_ID}/marketing_messages\n\nimport { WHATSAPP_MESSAGING_PRODUCT } from '../../config/defaults';\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport { WhatsAppValidationError } from '../../utils/isMetaError';\n\nimport type { MessagesResponse } from '../messages/types';\nimport type * as marketing from './types';\n\n/**\n * API for WhatsApp Marketing Messages.\n *\n * Provides methods to send marketing template messages to WhatsApp users,\n * with support for message activity sharing opt-in.\n *\n * Endpoints covered:\n * - `POST /{PHONE_NUMBER_ID}/marketing_messages` - Send a marketing template message\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/marketing-messages/send-marketing-messages/\n */\nexport default class MarketingMessagesApi extends BaseAPI implements marketing.MarketingMessagesClass {\n private readonly endpoint = 'marketing_messages';\n\n /**\n * Send a marketing template message to a WhatsApp user.\n *\n * Address the user either by phone number (`to`) or by business-scoped user ID\n * (`recipient`). Exactly one of the two is required.\n *\n * @param params - The marketing message request parameters.\n * @param params.to - The recipient's WhatsApp phone number.\n * @param params.recipient - The recipient's BSUID or parent BSUID, used instead of `to`.\n * @param params.template - The template configuration (name, language, components).\n * @param params.message_activity_sharing - Optional flag to enable message activity sharing.\n * @param params.product_policy - Optional product policy for marketing messages.\n * @param params.bid_spec - Optional send-time multiplier applied to the template's max price.\n * @returns The messages response with message ID and status.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/marketing-messages/send-marketing-messages/\n */\n async sendTemplateMessage(params: marketing.MarketingMessageRequest): Promise<MessagesResponse> {\n if (!params.to === !params.recipient) {\n throw new WhatsAppValidationError('Provide exactly one of \"to\" (phone number) or \"recipient\" (BSUID).');\n }\n\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n recipient_type: 'individual',\n type: 'template',\n template: params.template,\n } as {\n messaging_product: 'whatsapp';\n recipient_type: 'individual';\n to?: string;\n recipient?: string;\n type: 'template';\n template: marketing.MarketingMessageRequest['template'];\n message_activity_sharing?: boolean;\n product_policy?: marketing.MarketingMessageRequest['product_policy'];\n bid_spec?: marketing.MarketingMessageRequest['bid_spec'];\n };\n\n if (params.to !== undefined) {\n body.to = params.to;\n }\n\n if (params.recipient !== undefined) {\n body.recipient = params.recipient;\n }\n\n if (params.message_activity_sharing !== undefined) {\n body.message_activity_sharing = params.message_activity_sharing;\n }\n\n if (params.product_policy !== undefined) {\n body.product_policy = params.product_policy;\n }\n\n if (params.bid_spec !== undefined) {\n body.bid_spec = params.bid_spec;\n }\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/media/\n\n// Endpoints:\n// - GET /{MEDIA_ID}\n// - POST /{PHONE_NUMBER_ID}/media\n// - DELETE /{MEDIA_ID}\n// - GET {MEDIA_URL}\n\nimport { WHATSAPP_MESSAGING_PRODUCT } from '../../config/defaults';\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { ResponseSuccess } from '../../types/request';\nimport { WhatsAppValidationError } from '../../utils/isMetaError';\n\nimport type * as media from './types';\n\n/**\n * WhatsApp Media API client for uploading, retrieving, downloading, and deleting media.\n *\n * Media uploaded to the WhatsApp API can be used in messages (images, audio, video,\n * documents, stickers). Each media object is identified by a unique media ID.\n *\n * **Covered endpoints:**\n * - `GET /{MEDIA_ID}` - Retrieve media info ({@link MediaApi.getMediaById})\n * - `POST /{PHONE_NUMBER_ID}/media` - Upload media ({@link MediaApi.uploadMedia})\n * - `DELETE /{MEDIA_ID}` - Delete media ({@link MediaApi.deleteMedia})\n * - `GET {MEDIA_URL}` - Download media content ({@link MediaApi.downloadMedia})\n *\n * **Supported media types and size limits:**\n * | Type | MIME Types | Max Size |\n * |------|-----------|----------|\n * | Audio | audio/aac, audio/mp4, audio/mpeg, audio/amr, audio/ogg | 16 MB |\n * | Document | Various (PDF, DOC, DOCX, PPT, XLS, etc.) | 100 MB |\n * | Image | image/jpeg, image/png | 5 MB |\n * | Sticker | image/webp | 100 KB (animated), 500 KB (static) |\n * | Video | video/mp4, video/3gp | 16 MB |\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/media | WhatsApp Media API Reference}\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/media/ | WhatsApp Media Documentation}\n *\n * @example\n * ```ts\n * const client = new WhatsApp({ accessToken: '...', phoneNumberId: '...' });\n *\n * // Upload, send, then clean up\n * const { id } = await client.media.uploadMedia(file);\n * await client.messages.image({ body: { id }, to: '1234567890' });\n * await client.media.deleteMedia(id);\n * ```\n */\nexport default class MediaApi extends BaseAPI implements media.MediaClass {\n private readonly endpoint = 'media';\n\n /**\n * Retrieves media information by media ID.\n *\n * Returns metadata about the media object including its URL, MIME type, file size,\n * and SHA-256 hash. The returned URL can be used with {@link MediaApi.downloadMedia}\n * to fetch the actual media content.\n *\n * **Endpoint:** `GET /{MEDIA_ID}`\n *\n * @param mediaId - The unique identifier of the media to retrieve\n * @returns A promise resolving to the media metadata including `url`, `mime_type`, `sha256`, and `file_size`\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/media#get-media-id | Get Media ID Reference}\n *\n * @example\n * ```ts\n * const mediaInfo = await client.media.getMediaById('media_id_123');\n * console.log(mediaInfo.url); // URL to download the media\n * console.log(mediaInfo.mime_type); // e.g., \"image/jpeg\"\n * console.log(mediaInfo.file_size); // size in bytes\n * ```\n */\n async getMediaById(mediaId: string): Promise<media.MediaResponse> {\n return this.sendJson(HttpMethodsEnum.Get, `${mediaId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n /**\n * Uploads a media file to the WhatsApp Cloud API.\n *\n * The uploaded media is assigned a unique media ID that can be used to send\n * messages containing that media. Media is automatically encrypted and stored\n * on Meta's servers.\n *\n * **Endpoint:** `POST /{PHONE_NUMBER_ID}/media` (`multipart/form-data` with `file`, `type` and\n * `messaging_product`)\n *\n * Accepts a `File`, `Blob`, `Uint8Array` (including a Node.js `Buffer`), `ArrayBuffer` or web\n * `ReadableStream<Uint8Array>` on every runtime. Pass the MIME type in `options.type` unless the\n * input is a `Blob`/`File` that already has one.\n *\n * **Memory:** a `ReadableStream` is read fully into a `Blob` before the request is sent. Meta\n * requires a multipart body and `fetch` only accepts `Blob` parts in `FormData`, so the upload is\n * not streamed end to end. Peak memory can exceed the file size (Meta caps media at 100 MB for\n * documents, 16 MB for audio/video, 5 MB for images). Buffering once also lets a throttled upload\n * be retried. Blob construction snapshots byte inputs; allow room for these copies.\n *\n * @param file - The content to upload\n * @param optionsOrMessagingProduct - Upload options, or the messaging product string (legacy form,\n * defaults to `'whatsapp'`)\n * @returns A promise resolving to the upload response containing the assigned `id` (media ID)\n * @throws WhatsAppValidationError when no MIME type is available or the input type is unsupported\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/media#upload-media | Upload Media Reference}\n *\n * @example\n * ```ts\n * const file = new File([buffer], 'image.jpg', { type: 'image/jpeg' });\n * const { id } = await client.media.uploadMedia(file);\n *\n * // Bytes or a web stream (e.g. a fetch() body) need a MIME type\n * const res = await fetch('https://example.com/report.pdf');\n * await client.media.uploadMedia(res.body!, { type: 'application/pdf', filename: 'report.pdf' });\n * ```\n */\n async uploadMedia(file: File, messagingProduct?: string): Promise<media.UploadMediaResponse>;\n async uploadMedia(\n file: media.UploadMediaInput,\n options?: media.UploadMediaOptions,\n ): Promise<media.UploadMediaResponse>;\n async uploadMedia(\n file: media.UploadMediaInput,\n optionsOrMessagingProduct?: media.UploadMediaOptions | string,\n ): Promise<media.UploadMediaResponse> {\n const options: media.UploadMediaOptions =\n typeof optionsOrMessagingProduct === 'string'\n ? { messagingProduct: optionsOrMessagingProduct }\n : (optionsOrMessagingProduct ?? {});\n const messagingProduct = options.messagingProduct ?? WHATSAPP_MESSAGING_PRODUCT;\n\n const mimeType = options.type || (file instanceof Blob ? file.type : '');\n if (!mimeType) {\n throw new WhatsAppValidationError(\n 'uploadMedia needs a MIME type: pass options.type (e.g. \"image/jpeg\") or a Blob/File with a type',\n );\n }\n\n const blob = await toUploadBlob(file, options.type);\n const formData = new FormData();\n if (blob === file && !options.type && !options.filename) {\n // Unchanged legacy path: append the caller's File/Blob as is.\n formData.append('file', blob);\n } else {\n formData.append('file', blob, options.filename ?? fileNameOf(file) ?? 'file');\n }\n formData.append('messaging_product', messagingProduct);\n formData.append('type', mimeType);\n\n return this.sendFormData(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n formData,\n );\n }\n\n /**\n * Deletes a media file from WhatsApp servers.\n *\n * Once deleted, the media ID can no longer be used in messages. Any messages\n * already sent with this media will continue to display the media.\n *\n * **Endpoint:** `DELETE /{MEDIA_ID}`\n *\n * @param mediaId - The unique identifier of the media to delete\n * @returns A promise resolving to a success response (`{ success: true }`)\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/media#delete-media | Delete Media Reference}\n *\n * @example\n * ```ts\n * const result = await client.media.deleteMedia('media_id_123');\n * console.log(result.success); // true\n * ```\n */\n async deleteMedia(mediaId: string): Promise<ResponseSuccess> {\n return this.sendJson(HttpMethodsEnum.Delete, `${mediaId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n /**\n * Downloads media content from a WhatsApp media URL.\n *\n * Use {@link MediaApi.getMediaById} first to obtain the media URL, then pass it\n * to this method to download the actual file content. The returned URL from\n * `getMediaById` is only valid for a limited time.\n *\n * **Endpoint:** `GET {MEDIA_URL}`\n *\n * @param mediaUrl - The media download URL obtained from {@link MediaApi.getMediaById}\n * @returns A promise resolving to a `Blob` containing the raw media data\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/media#download-media | Download Media Reference}\n *\n * @example\n * ```ts\n * // First get the media URL, then download it\n * const mediaInfo = await client.media.getMediaById('media_id_123');\n * const blob = await client.media.downloadMedia(mediaInfo.url);\n * ```\n */\n async downloadMedia(mediaUrl: string): Promise<Blob> {\n // The media URL returns the file bytes, not JSON, so read the body as a Blob.\n const response = await this.sendRaw(HttpMethodsEnum.Get, mediaUrl, this.config[WabaConfigEnum.RequestTimeout]);\n return response.blob();\n }\n}\n\nfunction fileNameOf(input: unknown): string | undefined {\n const name = (input as { name?: unknown } | null)?.name;\n return typeof name === 'string' && name !== '' ? name : undefined;\n}\n\nfunction isReadableStream(input: unknown): input is ReadableStream<Uint8Array> {\n return (\n typeof ReadableStream !== 'undefined' &&\n (input instanceof ReadableStream || typeof (input as ReadableStream | null)?.getReader === 'function')\n );\n}\n\nasync function toUploadBlob(input: media.UploadMediaInput, type: string | undefined): Promise<Blob> {\n if (input instanceof Blob) {\n // Re-label only when the caller overrides the MIME type; slice() does not copy the bytes.\n return type && type !== input.type ? input.slice(0, input.size, type) : input;\n }\n const blobOptions = type ? { type } : undefined;\n if (input instanceof ArrayBuffer) {\n return new Blob([input], blobOptions);\n }\n if (input instanceof Uint8Array) {\n // Blob parts must be backed by an ArrayBuffer; copy only SharedArrayBuffer-backed views.\n const bytes = input.buffer instanceof ArrayBuffer ? (input as Uint8Array<ArrayBuffer>) : new Uint8Array(input);\n return new Blob([bytes], blobOptions);\n }\n if (isReadableStream(input)) {\n const collected = await new Response(input).blob();\n return type ? collected.slice(0, collected.size, type) : collected;\n }\n throw new WhatsAppValidationError(\n 'uploadMedia accepts a File, Blob, Uint8Array, ArrayBuffer or ReadableStream<Uint8Array>',\n );\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/overview/\n\n// Endpoints:\n// - GET /{PHONE_NUMBER_ID}/message_history\n// - GET /{MESSAGE_HISTORY_ID}/events\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\n\nimport type * as messageHistory from './types';\n\nexport default class MessageHistoryApi extends BaseAPI implements messageHistory.MessageHistoryClass {\n private resolveFields(fields?: messageHistory.MessageHistoryFieldsParam): string | undefined {\n return Array.isArray(fields) ? fields.join(',') : fields;\n }\n\n async getMessageHistory(\n params?: messageHistory.MessageHistoryListParams,\n ): Promise<messageHistory.MessageHistoryResponse> {\n const query = params\n ? objectToQueryString({\n fields: this.resolveFields(params.fields),\n message_id: params.message_id,\n start_time: params.start_time,\n end_time: params.end_time,\n limit: params.limit,\n after: params.after,\n before: params.before,\n })\n : '';\n\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/message_history${query}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async getMessageHistoryEvents(\n messageHistoryId: string,\n params?: messageHistory.MessageHistoryEventListParams,\n ): Promise<messageHistory.MessageHistoryResponse> {\n const query = params\n ? objectToQueryString({\n fields: this.resolveFields(params.fields),\n status_filter: params.status_filter,\n limit: params.limit,\n after: params.after,\n before: params.before,\n })\n : '';\n\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${messageHistoryId}/events${query}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/messages/\n\n// Endpoints:\n// - POST /{PHONE_NUMBER_ID}/messages\n// - POST /{PHONE_NUMBER_ID}/messages_encrypted\n\nimport { WHATSAPP_MESSAGING_PRODUCT } from '../../config/defaults';\nimport { BaseAPI } from '../../types/base';\nimport {\n type ComponentTypesEnum,\n HttpMethodsEnum,\n type InteractiveTypesEnum,\n MessageCategoryEnum,\n MessageTypesEnum,\n WabaConfigEnum,\n} from '../../types/enums';\nimport { assertPhoneNumber } from '../../utils/validate';\nimport type * as m from './types';\n\n/**\n * Maps each message type to its appropriate payload type.\n *\n * This conditional type resolves the correct payload interface based on the {@link MessageTypesEnum} value,\n * ensuring type-safe message construction at compile time.\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\n/**\n * WhatsApp Messages API client for sending various message types.\n *\n * Provides methods to send text, media, interactive, template, location, contact,\n * reaction, and status messages through the WhatsApp Cloud API.\n *\n * **Endpoint:** `POST /{PHONE_NUMBER_ID}/messages`\n *\n * **Covered operations:**\n * - {@link MessagesApi.text | text} - Send plain text messages\n * - {@link MessagesApi.audio | audio} - Send audio messages\n * - {@link MessagesApi.image | image} - Send image messages\n * - {@link MessagesApi.video | video} - Send video messages\n * - {@link MessagesApi.document | document} - Send document messages\n * - {@link MessagesApi.sticker | sticker} - Send sticker messages\n * - {@link MessagesApi.location | location} - Send location messages\n * - {@link MessagesApi.contacts | contacts} - Send contact card(s)\n * - {@link MessagesApi.template | template} - Send template messages\n * - {@link MessagesApi.interactive | interactive} - Send interactive messages (generic)\n * - {@link MessagesApi.interactiveList | interactiveList} - Send list interactive messages\n * - {@link MessagesApi.interactiveCtaUrl | interactiveCtaUrl} - Send CTA URL interactive messages\n * - {@link MessagesApi.interactiveVoiceCall | interactiveVoiceCall} - Send \"Call on WhatsApp\" voice call button messages\n * - {@link MessagesApi.interactiveLocationRequest | interactiveLocationRequest} - Send location request messages\n * - {@link MessagesApi.interactiveAddressMessage | interactiveAddressMessage} - Send address message interactive messages\n * - {@link MessagesApi.interactiveReplyButtons | interactiveReplyButtons} - Send reply button interactive messages\n * - {@link MessagesApi.interactiveFlow | interactiveFlow} - Send flow interactive messages\n * - {@link MessagesApi.interactiveCarousel | interactiveCarousel} - Send carousel interactive messages\n * - {@link MessagesApi.reaction | reaction} - Send reaction emoji to a message\n * - {@link MessagesApi.status | status} - Update message status (read, typing)\n * - {@link MessagesApi.markAsRead | markAsRead} - Mark a message as read\n * - {@link MessagesApi.showTypingIndicator | showTypingIndicator} - Show typing indicator\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages | WhatsApp Messages API Reference}\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/messages/ | WhatsApp Messages Documentation}\n *\n * @example\n * ```ts\n * const client = new WhatsApp({ accessToken: '...', phoneNumberId: '...' });\n *\n * // Send a text message\n * await client.messages.text({ body: 'Hello!', to: '1234567890' });\n *\n * // Send an image\n * await client.messages.image({ body: { link: 'https://example.com/image.jpg' }, to: '1234567890' });\n * ```\n */\nexport default class MessagesApi extends BaseAPI implements m.MessagesClass {\n private readonly commonMethod = HttpMethodsEnum.Post;\n private readonly commonEndpoint = 'messages';\n\n /**\n * Builds the request body for WhatsApp API messages.\n *\n * Constructs a properly formatted message payload including the messaging product,\n * recipient type, recipient phone number, message type, and optional reply context.\n *\n * @param type - The type of message to send (e.g., text, image, template)\n * @param payload - The message payload object matching the specified type\n * @param to - The recipient's phone number in international format (e.g., \"1234567890\")\n * @param replyMessageId - Optional message ID to reply to, setting the message context\n * @param recipientType - Whether `to` addresses an individual or a group\n * @param directSend - Optional Direct Send options (`category` and `directSendConfig`)\n * @returns The formatted request body ready to be serialized and sent\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages | Messages API Reference}\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/direct-send/ | Direct Send}\n *\n * @example\n * ```ts\n * const body = messagesApi.bodyBuilder(\n * MessageTypesEnum.Text,\n * { body: 'Hello!' },\n * '1234567890',\n * );\n * ```\n */\n bodyBuilder<T extends MessageTypesEnum>(\n type: T,\n payload: MessagePayloadType<T>,\n to: string,\n replyMessageId?: string,\n recipientType: m.MessageRecipientType = 'individual',\n directSend?: m.DirectSendOptions,\n ) {\n if (recipientType === 'individual') assertPhoneNumber(to);\n const body: m.MessageRequestBody<T> = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n recipient_type: recipientType,\n to,\n type,\n [type]: payload,\n };\n\n if (replyMessageId) body.context = { message_id: replyMessageId };\n if (directSend?.category) body.category = directSend.category;\n if (directSend?.directSendConfig) body.direct_send_config = directSend.directSendConfig;\n\n return body;\n }\n\n /**\n * Sends a request to the WhatsApp Cloud API messages endpoint.\n *\n * Internal method that dispatches the serialized JSON body to\n * `POST /{PHONE_NUMBER_ID}/messages`.\n *\n * @param body - The serialized JSON request body to send\n * @returns A promise resolving to the WhatsApp messages API response containing the message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages | Messages API Reference}\n */\n private send<T = m.MessagesResponse>(body: BodyInit | null): Promise<T> {\n return this.sendJson<T>(\n this.commonMethod,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.commonEndpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n body,\n );\n }\n\n private sendEncrypted<T = m.EncryptedMessagesResponse>(body: BodyInit | null): Promise<T> {\n return this.sendJson<T>(\n this.commonMethod,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/messages_encrypted`,\n this.config[WabaConfigEnum.RequestTimeout],\n body,\n );\n }\n\n /**\n * Sends an audio message via the WhatsApp Cloud API.\n *\n * The audio can be specified by a media ID (previously uploaded) or a public URL link.\n * Supported formats: audio/aac, audio/mp4, audio/mpeg, audio/amr, audio/ogg (with opus codec).\n * Maximum file size: 16 MB.\n *\n * @param params - The audio message parameters\n * @param params.body - Audio media object containing either `id` (media ID) or `link` (URL)\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#audio-object | Audio Object Reference}\n *\n * @example\n * ```ts\n * // Send audio by URL\n * await client.messages.audio({\n * body: { link: 'https://example.com/audio.mp3' },\n * to: '1234567890',\n * });\n *\n * // Send audio by media ID\n * await client.messages.audio({\n * body: { id: 'media_id_123' },\n * to: '1234567890',\n * });\n * ```\n */\n async audio(params: m.MessageRequestParams<m.AudioMediaObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId, recipientType, category, directSendConfig } = params;\n return this.send(\n JSON.stringify(\n this.bodyBuilder(MessageTypesEnum.Audio, body, to, replyMessageId, recipientType, {\n category,\n directSendConfig,\n }),\n ),\n );\n }\n\n /**\n * Sends one or more contact cards via the WhatsApp Cloud API.\n *\n * Contact messages allow sharing structured contact information including names,\n * phone numbers, email addresses, and more.\n *\n * @param params - The contact message parameters\n * @param params.body - Array of {@link m.ContactObject} containing contact details (name, phones, emails, etc.)\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#contacts-object | Contacts Object Reference}\n *\n * @example\n * ```ts\n * await client.messages.contacts({\n * body: [{\n * name: { formatted_name: 'John Doe', first_name: 'John', last_name: 'Doe' },\n * phones: [{ phone: '+1234567890', type: 'MOBILE' }],\n * }],\n * to: '1234567890',\n * });\n * ```\n */\n async contacts(params: m.MessageRequestParams<m.ContactObject[]>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId, recipientType, category, directSendConfig } = params;\n return this.send(\n JSON.stringify(\n this.bodyBuilder(MessageTypesEnum.Contacts, body, to, replyMessageId, recipientType, {\n category,\n directSendConfig,\n }),\n ),\n );\n }\n\n /**\n * Sends a document message via the WhatsApp Cloud API.\n *\n * Documents can be specified by media ID or public URL. Supports various formats\n * including PDF, DOC, DOCX, PPT, PPTX, XLS, XLSX, and more.\n * Maximum file size: 100 MB.\n *\n * @param params - The document message parameters\n * @param params.body - Document media object containing `id` or `link`, and optional `caption` and `filename`\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#document-object | Document Object Reference}\n *\n * @example\n * ```ts\n * await client.messages.document({\n * body: {\n * link: 'https://example.com/report.pdf',\n * caption: 'Monthly Report',\n * filename: 'report.pdf',\n * },\n * to: '1234567890',\n * });\n * ```\n */\n async document(params: m.MessageRequestParams<m.DocumentMediaObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId, recipientType, category, directSendConfig } = params;\n return this.send(\n JSON.stringify(\n this.bodyBuilder(MessageTypesEnum.Document, body, to, replyMessageId, recipientType, {\n category,\n directSendConfig,\n }),\n ),\n );\n }\n\n /**\n * Sends an image message via the WhatsApp Cloud API.\n *\n * Images can be specified by media ID or public URL.\n * Supported formats: image/jpeg, image/png. Maximum file size: 5 MB.\n *\n * @param params - The image message parameters\n * @param params.body - Image media object containing `id` or `link`, and optional `caption`\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#image-object | Image Object Reference}\n *\n * @example\n * ```ts\n * await client.messages.image({\n * body: { link: 'https://example.com/photo.jpg', caption: 'Check this out!' },\n * to: '1234567890',\n * });\n * ```\n */\n async image(params: m.MessageRequestParams<m.ImageMediaObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId, recipientType, category, directSendConfig } = params;\n return this.send(\n JSON.stringify(\n this.bodyBuilder(MessageTypesEnum.Image, body, to, replyMessageId, recipientType, {\n category,\n directSendConfig,\n }),\n ),\n );\n }\n\n /**\n * Sends an interactive message via the WhatsApp Cloud API.\n *\n * Interactive messages allow rich user interactions such as lists, buttons, CTAs,\n * flows, location requests, address messages, and carousels. For type-specific\n * convenience methods, see {@link MessagesApi.interactiveList}, {@link MessagesApi.interactiveReplyButtons}, etc.\n *\n * @param params - The interactive message parameters\n * @param params.body - Interactive object containing the `type` and type-specific action/body/header/footer\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#interactive-object | Interactive Object Reference}\n *\n * @example\n * ```ts\n * await client.messages.interactive({\n * body: {\n * type: 'button',\n * body: { text: 'Choose an option' },\n * action: {\n * buttons: [\n * { type: 'reply', reply: { id: 'btn1', title: 'Option 1' } },\n * { type: 'reply', reply: { id: 'btn2', title: 'Option 2' } },\n * ],\n * },\n * },\n * to: '1234567890',\n * });\n * ```\n */\n async interactive(params: m.MessageRequestParams<m.InteractiveObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId, recipientType, category, directSendConfig } = params;\n return this.send(\n JSON.stringify(\n this.bodyBuilder(MessageTypesEnum.Interactive, body, to, replyMessageId, recipientType, {\n category,\n directSendConfig,\n }),\n ),\n );\n }\n\n /**\n * Sends a location message via the WhatsApp Cloud API.\n *\n * Shares a geographic location with the recipient, displayed as a map pin.\n *\n * @param params - The location message parameters\n * @param params.body - Location object containing `latitude`, `longitude`, and optional `name` and `address`\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#location-object | Location Object Reference}\n *\n * @example\n * ```ts\n * await client.messages.location({\n * body: {\n * latitude: 37.4220936,\n * longitude: -122.083922,\n * name: 'Googleplex',\n * address: '1600 Amphitheatre Parkway, Mountain View, CA',\n * },\n * to: '1234567890',\n * });\n * ```\n */\n async location(params: m.MessageRequestParams<m.LocationObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId, recipientType, category, directSendConfig } = params;\n return this.send(\n JSON.stringify(\n this.bodyBuilder(MessageTypesEnum.Location, body, to, replyMessageId, recipientType, {\n category,\n directSendConfig,\n }),\n ),\n );\n }\n\n /**\n * Sends a sticker message via the WhatsApp Cloud API.\n *\n * Stickers can be specified by media ID or public URL.\n * Supported format: image/webp. Maximum file size: 100 KB (animated), 500 KB (static).\n *\n * @param params - The sticker message parameters\n * @param params.body - Sticker media object containing `id` or `link`\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#sticker-object | Sticker Object Reference}\n *\n * @example\n * ```ts\n * await client.messages.sticker({\n * body: { link: 'https://example.com/sticker.webp' },\n * to: '1234567890',\n * });\n * ```\n */\n async sticker(params: m.MessageRequestParams<m.StickerMediaObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId, recipientType, category, directSendConfig } = params;\n return this.send(\n JSON.stringify(\n this.bodyBuilder(MessageTypesEnum.Sticker, body, to, replyMessageId, recipientType, {\n category,\n directSendConfig,\n }),\n ),\n );\n }\n\n /**\n * Sends a template message via the WhatsApp Cloud API.\n *\n * Template messages use pre-approved message templates and can include header,\n * body, and button components with dynamic parameters. Templates must be\n * approved before use.\n *\n * @param params - The template message parameters\n * @param params.body - Template object containing `name`, `language`, and optional `components`\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#template-object | Template Object Reference}\n *\n * @example\n * ```ts\n * await client.messages.template({\n * body: {\n * name: 'hello_world',\n * language: { code: 'en_US' },\n * components: [\n * { type: 'body', parameters: [{ type: 'text', text: 'John' }] },\n * ],\n * },\n * to: '1234567890',\n * });\n * ```\n */\n async template(\n params: m.MessageRequestParams<m.MessageTemplateObject<ComponentTypesEnum>>,\n ): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId, recipientType, category, directSendConfig } = params;\n return this.send(\n JSON.stringify(\n this.bodyBuilder(MessageTypesEnum.Template, body, to, replyMessageId, recipientType, {\n category,\n directSendConfig,\n }),\n ),\n );\n }\n\n /**\n * Sends a text message via the WhatsApp Cloud API.\n *\n * Sends a plain text message. The `body` can be a string or a {@link m.TextObject}.\n * URL preview is enabled by default.\n *\n * @param params - The text message parameters\n * @param params.body - Message text as a string, or a {@link m.TextObject} with `body` and optional `preview_url`\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @param params.previewUrl - Whether to show a URL preview (defaults to `true`)\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#text-object | Text Object Reference}\n *\n * @example\n * ```ts\n * // Simple text\n * await client.messages.text({ body: 'Hello, World!', to: '1234567890' });\n *\n * // With URL preview disabled\n * await client.messages.text({\n * body: { body: 'Visit https://example.com', preview_url: false },\n * to: '1234567890',\n * });\n * ```\n */\n async text(params: m.TextMessageParams): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId, previewUrl, recipientType, category, directSendConfig } = 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(\n JSON.stringify(\n this.bodyBuilder(MessageTypesEnum.Text, textPayload, to, replyMessageId, recipientType, {\n category,\n directSendConfig,\n }),\n ),\n );\n }\n\n /**\n * Sends a video message via the WhatsApp Cloud API.\n *\n * Videos can be specified by media ID or public URL.\n * Supported formats: video/mp4, video/3gp. Maximum file size: 16 MB.\n * Only H.264 video codec and AAC audio codec are supported.\n *\n * @param params - The video message parameters\n * @param params.body - Video media object containing `id` or `link`, and optional `caption`\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#video-object | Video Object Reference}\n *\n * @example\n * ```ts\n * await client.messages.video({\n * body: { link: 'https://example.com/video.mp4', caption: 'Watch this!' },\n * to: '1234567890',\n * });\n * ```\n */\n async video(params: m.MessageRequestParams<m.VideoMediaObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId, recipientType, category, directSendConfig } = params;\n return this.send(\n JSON.stringify(\n this.bodyBuilder(MessageTypesEnum.Video, body, to, replyMessageId, recipientType, {\n category,\n directSendConfig,\n }),\n ),\n );\n }\n\n /**\n * Updates the status of a message (e.g., mark as read or show typing indicator).\n *\n * This is the low-level status method. For convenience, use {@link MessagesApi.markAsRead}\n * or {@link MessagesApi.showTypingIndicator} instead.\n *\n * @param params - The status update parameters\n * @param params.status - The status to set (e.g., `'read'`, `'typing'`)\n * @param params.messageId - The ID of the message to update\n * @param params.typingIndicator - Optional typing indicator configuration\n * @returns A promise resolving to the API response\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#status-object | Status Object Reference}\n *\n * @example\n * ```ts\n * await client.messages.status({\n * status: 'read',\n * messageId: 'wamid.ABC123',\n * });\n * ```\n */\n async status(params: m.StatusParams): Promise<m.StatusResponse> {\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n status: params.status,\n message_id: params.messageId,\n ...(params.typingIndicator && { typing_indicator: params.typingIndicator }),\n };\n\n return this.send<m.StatusResponse>(JSON.stringify(body));\n }\n\n /**\n * Marks a message as read, sending a read receipt to the sender.\n *\n * This is a convenience wrapper around {@link MessagesApi.status} that sets the status to `'read'`.\n * When a message is marked as read, all previous messages in the conversation are also marked as read.\n *\n * @param params - The parameters\n * @param params.messageId - The ID of the incoming message to mark as read (the `wamid` value)\n * @returns A promise resolving to the API response\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#status-object | Status Object Reference}\n *\n * @example\n * ```ts\n * await client.messages.markAsRead({ messageId: 'wamid.ABC123' });\n * ```\n */\n async markAsRead(params: { messageId: string }): Promise<m.StatusResponse> {\n return this.status({\n status: 'read',\n messageId: params.messageId,\n });\n }\n\n /**\n * Shows a typing indicator to the user, indicating that a response is being composed.\n *\n * The typing indicator is displayed for approximately 25 seconds or until a message\n * is sent, whichever comes first.\n *\n * @param params - The parameters\n * @param params.messageId - The ID of the incoming message to associate the typing indicator with\n * @returns A promise resolving to the API response\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#status-object | Status Object Reference}\n *\n * @example\n * ```ts\n * await client.messages.showTypingIndicator({ messageId: 'wamid.ABC123' });\n * ```\n */\n async showTypingIndicator(params: { messageId: string }): Promise<m.StatusResponse> {\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n status: 'typing',\n message_id: params.messageId,\n typing_indicator: { type: 'text' },\n };\n\n return this.send<m.StatusResponse>(JSON.stringify(body));\n }\n\n /**\n * Sends a list interactive message via the WhatsApp Cloud API.\n *\n * List messages present up to 10 selectable options in a menu-style list.\n * Each section can have a title and multiple rows with title, description, and ID.\n *\n * @param params - The list interactive message parameters\n * @param params.body - Interactive object with `type: 'list'` and action containing sections\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#list-messages | List Messages Reference}\n *\n * @example\n * ```ts\n * await client.messages.interactiveList({\n * body: {\n * type: 'list',\n * body: { text: 'Choose an option' },\n * action: {\n * button: 'View Options',\n * sections: [{ title: 'Section 1', rows: [{ id: '1', title: 'Option 1' }] }],\n * },\n * },\n * to: '1234567890',\n * });\n * ```\n */\n async interactiveList(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.List | 'list' }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive(params);\n }\n\n /**\n * Sends a Call-to-Action (CTA) URL button interactive message via the WhatsApp Cloud API.\n *\n * CTA URL messages display a button that opens a URL when tapped.\n *\n * @param params - The CTA URL interactive message parameters\n * @param params.body - Interactive object with `type: 'cta_url'` and action containing the URL and display text\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#interactive-object | Interactive Object Reference}\n *\n * @example\n * ```ts\n * await client.messages.interactiveCtaUrl({\n * body: {\n * type: 'cta_url',\n * body: { text: 'Visit our website' },\n * action: { name: 'cta_url', parameters: { display_text: 'Open', url: 'https://example.com' } },\n * },\n * to: '1234567890',\n * });\n * ```\n */\n async interactiveCtaUrl(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.CtaUrl | 'cta_url' }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive(params);\n }\n\n /**\n * Sends a \"Call on WhatsApp\" voice call button message via Direct Send.\n *\n * The button lets the recipient tap to start a WhatsApp voice call to your business\n * phone number. It is a Direct Send interactive type, so the request is always sent\n * with `category: 'utility'`; the button must be sent on its own and cannot be\n * combined with CTA URL or reply buttons, and footers are not supported.\n *\n * Calling must be enabled on the business phone number first\n * (`POST /{PHONE_NUMBER_ID}/settings` with `{ calling: { status: 'ENABLED' } }`) and the\n * app must be subscribed to the `calls` webhook field, otherwise the send fails with\n * error `138000`.\n *\n * @param params - The voice call interactive message parameters\n * @param params.body - Interactive object with `type: 'voice_call'` and a `voice_call` action\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @param params.directSendConfig - Optional Direct Send template attribution config\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/direct-send/supported-message-types | Direct Send supported message types}\n *\n * @example\n * ```ts\n * await client.messages.interactiveVoiceCall({\n * body: {\n * type: 'voice_call',\n * body: { text: 'Call our support team for help with your order.' },\n * action: { name: 'voice_call', parameters: { display_text: 'Call Support', ttl_minutes: 1440 } },\n * },\n * to: '1234567890',\n * });\n * ```\n */\n async interactiveVoiceCall(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.VoiceCall | 'voice_call' }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive({ ...params, category: params.category ?? MessageCategoryEnum.Utility });\n }\n\n /**\n * Sends a location request interactive message via the WhatsApp Cloud API.\n *\n * Prompts the recipient to share their current location.\n *\n * @param params - The location request interactive message parameters\n * @param params.body - Interactive object with `type: 'location_request_message'`\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#interactive-object | Interactive Object Reference}\n *\n * @example\n * ```ts\n * await client.messages.interactiveLocationRequest({\n * body: {\n * type: 'location_request_message',\n * body: { text: 'Please share your location' },\n * action: { name: 'send_location' },\n * },\n * to: '1234567890',\n * });\n * ```\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 via the WhatsApp Cloud API.\n *\n * Prompts the recipient to provide or confirm a shipping/delivery address.\n *\n * @param params - The address message interactive message parameters\n * @param params.body - Interactive object with `type: 'address_message'`\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#interactive-object | Interactive Object Reference}\n *\n * @example\n * ```ts\n * await client.messages.interactiveAddressMessage({\n * body: {\n * type: 'address_message',\n * body: { text: 'Please confirm your delivery address' },\n * action: { name: 'address_message', parameters: { country: 'US' } },\n * },\n * to: '1234567890',\n * });\n * ```\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 via the WhatsApp Cloud API.\n *\n * Reply button messages display up to 3 quick-reply buttons. Each button has\n * a unique ID and title (up to 20 characters).\n *\n * @param params - The reply buttons interactive message parameters\n * @param params.body - Interactive object with `type: 'button'` and action containing up to 3 reply buttons\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#reply-button | Reply Button Reference}\n *\n * @example\n * ```ts\n * await client.messages.interactiveReplyButtons({\n * body: {\n * type: 'button',\n * body: { text: 'Do you agree?' },\n * action: {\n * buttons: [\n * { type: 'reply', reply: { id: 'yes', title: 'Yes' } },\n * { type: 'reply', reply: { id: 'no', title: 'No' } },\n * ],\n * },\n * },\n * to: '1234567890',\n * });\n * ```\n */\n async interactiveReplyButtons(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.Button | 'button' }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive(params);\n }\n\n /**\n * Sends a flow interactive message via the WhatsApp Cloud API.\n *\n * Flow messages launch a WhatsApp Flow, which provides structured multi-step interactions\n * (forms, surveys, appointment booking, etc.) within the chat.\n *\n * @param params - The flow interactive message parameters\n * @param params.body - Interactive object with `type: 'flow'` and action containing the flow token and configuration\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#interactive-object | Interactive Object Reference}\n * @see {@link https://developers.facebook.com/docs/whatsapp/flows | WhatsApp Flows Documentation}\n *\n * @example\n * ```ts\n * await client.messages.interactiveFlow({\n * body: {\n * type: 'flow',\n * body: { text: 'Book an appointment' },\n * action: {\n * name: 'flow',\n * parameters: { flow_message_version: '3', flow_id: '123456', flow_cta: 'Book Now' },\n * },\n * },\n * to: '1234567890',\n * });\n * ```\n */\n async interactiveFlow(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.Flow | 'flow' }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive(params);\n }\n\n /**\n * Sends a carousel interactive message via the WhatsApp Cloud API.\n *\n * Carousel messages display a horizontally scrollable set of cards, each with\n * an image, body text, and up to 2 quick-reply buttons.\n *\n * @param params - The carousel interactive message parameters\n * @param params.body - Interactive object with `type: 'carousel'` and action containing carousel cards\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#interactive-object | Interactive Object Reference}\n *\n * @example\n * ```ts\n * await client.messages.interactiveCarousel({\n * body: {\n * type: 'carousel',\n * body: { text: 'Browse our products' },\n * action: {\n * cards: [\n * {\n * header: { type: 'image', image: { link: 'https://example.com/product1.jpg' } },\n * body: { text: 'Product 1 - $10' },\n * buttons: [{ type: 'reply', reply: { id: 'buy_1', title: 'Buy' } }],\n * },\n * ],\n * },\n * },\n * to: '1234567890',\n * });\n * ```\n */\n async interactiveCarousel(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.Carousel }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive(params);\n }\n\n /**\n * Sends a reaction emoji to an existing message via the WhatsApp Cloud API.\n *\n * Reactions allow users to respond to messages with a single emoji.\n * To remove a reaction, send an empty string as the emoji.\n *\n * @param params - The reaction parameters\n * @param params.messageId - The ID of the message to react to\n * @param params.emoji - The emoji character to react with (e.g., \"\\uD83D\\uDC4D\"), or empty string to remove reaction\n * @param params.to - Recipient phone number in international format\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#reaction-object | Reaction Object Reference}\n *\n * @example\n * ```ts\n * // Add a reaction\n * await client.messages.reaction({\n * messageId: 'wamid.ABC123',\n * emoji: '\\uD83D\\uDC4D',\n * to: '1234567890',\n * });\n *\n * // Remove a reaction\n * await client.messages.reaction({\n * messageId: 'wamid.ABC123',\n * emoji: '',\n * to: '1234567890',\n * });\n * ```\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(\n JSON.stringify(\n this.bodyBuilder(\n MessageTypesEnum.Reaction,\n reactionPayload,\n params.to,\n undefined,\n params.recipientType,\n ),\n ),\n );\n }\n\n /**\n * Send a message through the encrypted messages endpoint.\n *\n * The encrypted endpoint payload varies by encryption setup, so this method accepts\n * the Graph API payload shape directly while preserving the endpoint and response type.\n */\n async encrypted(params: m.EncryptedMessageRequest): Promise<m.EncryptedMessagesResponse> {\n return this.sendEncrypted(JSON.stringify(params));\n }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/payments/payments-in/onboarding-apis/\n\n// Endpoints:\n// - GET /{WABA_ID}/payment_configurations\n// - GET /{WABA_ID}/payment_configuration/{CONFIGURATION_NAME}\n// - POST /{WABA_ID}/payment_configuration\n// - POST /{WABA_ID}/payment_configuration/{CONFIGURATION_NAME}\n// - POST /{WABA_ID}/generate_payment_configuration_oauth_link\n// - DELETE /{WABA_ID}/payment_configuration\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { ResponseSuccess } from '../../types/request';\n\nimport type * as payments from './types';\n\n/**\n * API for WhatsApp Payments (India payment configuration).\n *\n * Provides methods to manage payment configurations for WhatsApp Business Accounts,\n * including creating, reading, updating, and deleting payment configurations,\n * as well as generating OAuth links for payment onboarding.\n *\n * Endpoints covered:\n * - `GET /{WABA_ID}/payment_configurations` - List all payment configurations\n * - `GET /{WABA_ID}/payment_configuration/{CONFIGURATION_NAME}` - Get a specific payment configuration\n * - `POST /{WABA_ID}/payment_configuration` - Create a new payment configuration\n * - `POST /{WABA_ID}/payment_configuration/{CONFIGURATION_NAME}` - Update a payment configuration\n * - `POST /{WABA_ID}/generate_payment_configuration_oauth_link` - Generate an OAuth link\n * - `DELETE /{WABA_ID}/payment_configuration` - Delete a payment configuration\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/payments/payments-in/onboarding-apis/\n */\nexport default class PaymentsApi extends BaseAPI implements payments.PaymentsClass {\n /**\n * List all payment configurations for a WhatsApp Business Account.\n *\n * @param wabaId - The WhatsApp Business Account ID.\n * @returns A list of all payment configurations.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/payments/payments-in/onboarding-apis/\n */\n async listPaymentConfigurations(wabaId: string): Promise<payments.PaymentConfigurationsResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `/${wabaId}/payment_configurations`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Get a specific payment configuration by name.\n *\n * @param wabaId - The WhatsApp Business Account ID.\n * @param configurationName - The name of the payment configuration to retrieve.\n * @returns The payment configuration details.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/payments/payments-in/onboarding-apis/\n */\n async getPaymentConfiguration(\n wabaId: string,\n configurationName: string,\n ): Promise<payments.PaymentConfigurationsResponse> {\n const encodedName = encodeURIComponent(configurationName);\n return this.sendJson(\n HttpMethodsEnum.Get,\n `/${wabaId}/payment_configuration/${encodedName}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Create a new payment configuration for a WhatsApp Business Account.\n *\n * @param wabaId - The WhatsApp Business Account ID.\n * @param params - The payment configuration details to create.\n * @returns The created payment configuration response.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/payments/payments-in/onboarding-apis/\n */\n async createPaymentConfiguration(\n wabaId: string,\n params: payments.PaymentConfigurationCreateRequest,\n ): Promise<payments.PaymentConfigurationCreateResponse> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${wabaId}/payment_configuration`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(params),\n );\n }\n\n /**\n * Update an existing payment configuration.\n *\n * @param wabaId - The WhatsApp Business Account ID.\n * @param configurationName - The name of the payment configuration to update.\n * @param params - The payment configuration fields to update.\n * @returns The updated payment configuration response.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/payments/payments-in/onboarding-apis/\n */\n async updatePaymentConfiguration(\n wabaId: string,\n configurationName: string,\n params: payments.PaymentConfigurationUpdateRequest,\n ): Promise<payments.PaymentConfigurationUpdateResponse> {\n const encodedName = encodeURIComponent(configurationName);\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${wabaId}/payment_configuration/${encodedName}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(params),\n );\n }\n\n /**\n * Generate an OAuth link for payment configuration onboarding.\n *\n * @param wabaId - The WhatsApp Business Account ID.\n * @param params - The OAuth link generation parameters.\n * @returns The generated OAuth link response.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/payments/payments-in/onboarding-apis/\n */\n async generatePaymentConfigurationOauthLink(\n wabaId: string,\n params: payments.PaymentConfigurationOauthLinkRequest,\n ): Promise<payments.PaymentConfigurationOauthLinkResponse> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${wabaId}/generate_payment_configuration_oauth_link`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(params),\n );\n }\n\n /**\n * Delete a payment configuration from a WhatsApp Business Account.\n *\n * @param wabaId - The WhatsApp Business Account ID.\n * @param params - The payment configuration deletion parameters (includes configuration name).\n * @returns A success response confirming deletion.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/payments/payments-in/onboarding-apis/\n */\n async deletePaymentConfiguration(\n wabaId: string,\n params: payments.PaymentConfigurationDeleteRequest,\n ): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Delete,\n `/${wabaId}/payment_configuration`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(params),\n );\n }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/phone-numbers/\n\n// Endpoints:\n// - GET /{PHONE_NUMBER_ID}?fields\n// - POST /{PHONE_NUMBER_ID}\n// - GET /{WABA_ID}/phone_numbers\n// - POST /{WABA_ID}/phone_numbers\n// - POST /{PHONE_NUMBER_ID}/request_code\n// - POST /{PHONE_NUMBER_ID}/verify_code\n// - GET /{PHONE_NUMBER_ID}/settings\n// - POST /{PHONE_NUMBER_ID}/settings\n// - POST /{PHONE_NUMBER_ID}/conversational_automation\n// - GET /{PHONE_NUMBER_ID}?fields=conversational_automation\n// - GET /{PHONE_NUMBER_ID}?fields=throughput\n// - GET /{PHONE_NUMBER_ID}/official_business_account\n// - POST /{PHONE_NUMBER_ID}/official_business_account\n// - GET /{PHONE_NUMBER_ID}/business_compliance_info\n// - POST /{PHONE_NUMBER_ID}/business_compliance_info\n// - GET /{PHONE_NUMBER_ID}/username\n// - POST /{PHONE_NUMBER_ID}/username\n// - DELETE /{PHONE_NUMBER_ID}/username\n// - GET /{PHONE_NUMBER_ID}/username_suggestions\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { ResponseSuccess } from '../../types/request';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\n\nimport type * as phoneNumber from './types';\n\n/**\n * API for managing WhatsApp Business phone numbers.\n *\n * This API provides methods for phone number management, verification,\n * and conversational automation configuration within the WhatsApp Business Platform.\n *\n * Covered endpoints:\n * - Get phone number info by ID (`GET /{PHONE_NUMBER_ID}`)\n * - List all phone numbers for a WABA (`GET /{WABA_ID}/phone_numbers`)\n * - Request a verification code (`POST /{PHONE_NUMBER_ID}/request_code`)\n * - Verify a phone number with a code (`POST /{PHONE_NUMBER_ID}/verify_code`)\n * - Set conversational automation config (`POST /{PHONE_NUMBER_ID}/conversational_automation`)\n * - Get conversational automation config (`GET /{PHONE_NUMBER_ID}?fields=conversational_automation`)\n * - Get throughput info (`GET /{PHONE_NUMBER_ID}?fields=throughput`)\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/phone-numbers | Phone Numbers API Reference}\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/phone-numbers/ | Phone Numbers Documentation}\n */\nexport default class PhoneNumberApi extends BaseAPI implements phoneNumber.PhoneNumberClass {\n private readonly endpoint = 'phone_numbers';\n\n /**\n * Get phone number information by ID.\n *\n * Retrieves details about the configured phone number, including display phone number,\n * verified name, quality rating, platform type, and more. Use the `fields` parameter\n * to request only specific fields.\n *\n * @param fields - Optional fields to include in the response. Can be a comma-separated\n * string (e.g., `'display_phone_number,verified_name'`) or an array of field names.\n * @returns A promise that resolves with the phone number information.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/phone-numbers#get-single | Get Phone Number}\n *\n * @example\n * ```ts\n * // Get all available fields\n * const phoneNumber = await whatsappClient.phoneNumber.getPhoneNumberById();\n *\n * // Get specific fields as a comma-separated string\n * const phoneNumber = await whatsappClient.phoneNumber.getPhoneNumberById(\n * 'display_phone_number,verified_name,quality_rating'\n * );\n *\n * // Get specific fields as an array\n * const phoneNumber = await whatsappClient.phoneNumber.getPhoneNumberById(\n * ['display_phone_number', 'verified_name']\n * );\n * ```\n */\n async getPhoneNumberById(fields?: phoneNumber.PhoneNumberFieldsParam): Promise<phoneNumber.PhoneNumberResponse> {\n const fieldValue = Array.isArray(fields) ? fields.join(',') : fields;\n const queryParams = fieldValue ? objectToQueryString({ fields: fieldValue }) : '';\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 associated with the WhatsApp Business Account.\n *\n * Returns a list of all phone numbers registered under the configured WABA,\n * including their verification status, quality rating, and display information.\n *\n * @param params - Optional list query parameters such as fields, filtering, sort, and paging.\n * @returns A promise that resolves with the list of phone numbers.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/phone-numbers#get-all | List Phone Numbers}\n *\n * @example\n * ```ts\n * const response = await whatsappClient.phoneNumber.getPhoneNumbers();\n * for (const number of response.data) {\n * console.log(number.display_phone_number, number.verified_name);\n * }\n * ```\n */\n async getPhoneNumbers(params?: phoneNumber.PhoneNumbersListParams): Promise<phoneNumber.PhoneNumbersResponse> {\n const fields = Array.isArray(params?.fields) ? params.fields.join(',') : params?.fields;\n const filtering = Array.isArray(params?.filtering) ? JSON.stringify(params.filtering) : params?.filtering;\n const queryParams = objectToQueryString({\n fields,\n filtering,\n sort: params?.sort,\n limit: params?.limit,\n after: params?.after,\n before: params?.before,\n });\n\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.BusinessAcctId]}/${this.endpoint}${queryParams}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Create a phone number under a WABA.\n *\n * @param request - Phone number creation payload from the Graph API.\n * @param wabaId - Optional WABA ID. Defaults to the configured business account ID.\n */\n async createPhoneNumber(\n request: phoneNumber.CreatePhoneNumberRequest,\n wabaId: string = this.config[WabaConfigEnum.BusinessAcctId],\n ): Promise<phoneNumber.CreatePhoneNumberResponse> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${wabaId}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n /**\n * Update phone number status or configuration on the phone number node.\n */\n async updatePhoneNumberStatus(request: phoneNumber.UpdatePhoneNumberStatusRequest): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n /**\n * Request a verification code for the phone number.\n *\n * Sends a verification code to the configured phone number via SMS or voice call.\n * This is the first step of the phone number verification process.\n *\n * @param request - The verification code request parameters.\n * @param request.code_method - The delivery method for the code: `'SMS'` or `'VOICE'`.\n * @param request.language - The language code for the verification message (e.g., `'en_US'`).\n * @returns A promise that resolves with a success indicator.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/phone-numbers#request-verification-code | Request Verification Code}\n *\n * @example\n * ```ts\n * await whatsappClient.phoneNumber.requestVerificationCode({\n * code_method: 'SMS',\n * language: 'en_US',\n * });\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 a received verification code.\n *\n * Completes the phone number verification process by submitting the code\n * received via SMS or voice call from {@link requestVerificationCode}.\n *\n * @param request - The verification request parameters.\n * @param request.code - The 6-digit verification code received via SMS or voice call.\n * @returns A promise that resolves with a success indicator.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/phone-numbers#verify-code | Verify Code}\n *\n * @example\n * ```ts\n * await whatsappClient.phoneNumber.verifyCode({\n * code: '123456',\n * });\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 /**\n * Get general phone number settings.\n *\n * Calling-specific settings can also be accessed through `calling.getCallingSettings()`.\n */\n async getPhoneNumberSettings(\n params?: phoneNumber.PhoneNumberSettingsParams,\n ): Promise<phoneNumber.PhoneNumberSettingsResponse> {\n const fieldsValue = Array.isArray(params?.fields) ? params.fields.join(',') : params?.fields;\n const queryParams = objectToQueryString({\n ...(fieldsValue ? { fields: fieldsValue } : {}),\n ...(params?.include_sip_credentials !== undefined\n ? { include_sip_credentials: params.include_sip_credentials }\n : {}),\n });\n\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/settings${queryParams}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Update general phone number settings.\n */\n async updatePhoneNumberSettings(params: phoneNumber.UpdatePhoneNumberSettingsRequest): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/settings`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(params),\n );\n }\n\n /**\n * Configure conversational automation features for the phone number.\n *\n * Sets up welcome messages, ice breakers (prompts), and commands that users\n * see when they open a conversation with the business phone number.\n *\n * @param request - The conversational automation configuration.\n * @param request.enable_welcome_message - Optional. Enable or disable the welcome message.\n * @param request.commands - Optional. Array of command objects with `command_name` and `command_description`.\n * @param request.prompts - Optional. Array of ice breaker prompt strings shown to users.\n * @returns A promise that resolves with a success indicator.\n *\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/phone-numbers/ | Conversational Automation}\n *\n * @example\n * ```ts\n * // Enable welcome message\n * await whatsappClient.phoneNumber.setConversationalAutomation({\n * enable_welcome_message: true,\n * });\n *\n * // Configure commands and ice breakers\n * await whatsappClient.phoneNumber.setConversationalAutomation({\n * enable_welcome_message: true,\n * commands: [\n * { command_name: 'tickets', command_description: 'Book flight tickets' },\n * { command_name: 'hotel', command_description: 'Book a hotel room' },\n * ],\n * prompts: ['Book a flight', 'Plan a vacation'],\n * });\n * ```\n */\n async setConversationalAutomation(request: phoneNumber.ConversationalAutomationRequest): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/conversational_automation`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n /**\n * Get the current conversational automation configuration for the phone number.\n *\n * Retrieves the current settings for welcome messages, ice breakers (prompts),\n * and commands configured on the phone number.\n *\n * @returns A promise that resolves with the current conversational automation settings,\n * including welcome message status, commands, and prompts.\n *\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/phone-numbers/ | Conversational Automation}\n *\n * @example\n * ```ts\n * const config = await whatsappClient.phoneNumber.getConversationalAutomation();\n * console.log(config.enable_welcome_message); // true or false\n * console.log(config.commands); // Array of command objects\n * console.log(config.prompts); // Array of ice breaker strings\n * ```\n */\n async getConversationalAutomation(): Promise<phoneNumber.ConversationalAutomationResponse> {\n const queryParams = objectToQueryString({ fields: 'conversational_automation' });\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 the current throughput level for the phone number.\n *\n * Throughput represents the maximum messages per second (MPS) that can be\n * sent or received on this phone number.\n *\n * Throughput levels:\n * - **STANDARD**: 80 MPS (default for most numbers)\n * - **HIGH**: 1,000 MPS (automatic upgrade for eligible numbers)\n * - **NOT_APPLICABLE**: Fixed at 5 MPS (WhatsApp Business app coexistence numbers)\n *\n * @returns A promise that resolves with the current throughput information,\n * including the throughput level.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/phone-numbers | Phone Numbers - Throughput}\n *\n * @example\n * ```ts\n * const throughput = await whatsappClient.phoneNumber.getThroughput();\n * console.log(throughput.throughput.level); // 'STANDARD' | 'HIGH' | 'NOT_APPLICABLE'\n * ```\n */\n async getThroughput(): Promise<phoneNumber.ThroughputResponse> {\n const queryParams = objectToQueryString({ fields: 'throughput' });\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}${queryParams}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async getOfficialBusinessAccountStatus(): Promise<phoneNumber.OfficialBusinessAccountStatusResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/official_business_account`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async updateOfficialBusinessAccountStatus(\n params: phoneNumber.UpdateOfficialBusinessAccountStatusRequest,\n ): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/official_business_account`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(params),\n );\n }\n\n async getBusinessComplianceInfo(): Promise<phoneNumber.BusinessComplianceInfoResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/business_compliance_info`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async updateBusinessComplianceInfo(\n params: phoneNumber.UpdateBusinessComplianceInfoRequest,\n ): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/business_compliance_info`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(params),\n );\n }\n\n /**\n * Get the username currently associated with the business phone number.\n *\n * @returns A promise that resolves with the username and its status\n * (`'approved'` or `'reserved'`).\n *\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/usernames/ | Usernames}\n */\n async getUsername(): Promise<phoneNumber.UsernameResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/username`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Adopt or change the username for the business phone number.\n *\n * If the desired username is already in use by another phone number in your\n * portfolio, the API responds with error code `147005`; retry with\n * `transfer_action: 'force_transfer'` to move the username to this number.\n *\n * @param params - The username request.\n * @param params.username - The desired username.\n * @param params.transfer_action - Optional. `'none'` (default) or `'force_transfer'`.\n * @returns A promise that resolves with a success indicator.\n *\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/usernames/ | Usernames}\n *\n * @example\n * ```ts\n * await whatsappClient.phoneNumbers.updateUsername({\n * username: 'jaspersmarket',\n * transfer_action: 'force_transfer',\n * });\n * ```\n */\n async updateUsername(params: phoneNumber.UpdateUsernameRequest): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/username`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(params),\n );\n }\n\n /**\n * Delete the username associated with the business phone number.\n *\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/usernames/ | Usernames}\n */\n async deleteUsername(): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Delete,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/username`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Get username suggestions for the business phone number.\n *\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/usernames/ | Usernames}\n */\n async getUsernameSuggestions(): Promise<phoneNumber.UsernameSuggestionsResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/username_suggestions`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\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","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/business-profiles/\n\n// Endpoints:\n// - GET /{PHONE_NUMBER_ID}/whatsapp_business_profile?fields\n// - POST /{PHONE_NUMBER_ID}/whatsapp_business_profile\n// - POST /app/uploads?file_length&file_type&file_name\n// - POST /{UPLOAD_ID}\n// - GET /{UPLOAD_ID}\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { 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 * Business profiles let customers see relevant information about your business,\n * such as a description, email, address, website, and profile picture.\n *\n * Covered endpoints:\n * - Get business profile (`GET /{PHONE_NUMBER_ID}/whatsapp_business_profile`)\n * - Update business profile (`POST /{PHONE_NUMBER_ID}/whatsapp_business_profile`)\n * - Create an upload session for profile pictures (`POST /app/uploads`)\n * - Upload file binary data (`POST /{UPLOAD_ID}`)\n * - Get upload handle (`GET /{UPLOAD_ID}`)\n *\n * Profile picture upload follows a three-step process:\n * 1. Create an upload session ({@link createUploadSession})\n * 2. Upload the image binary data ({@link uploadMedia})\n * 3. Get the upload handle ({@link getUploadHandle}) and pass it to {@link updateBusinessProfile}\n *\n * Available business profile fields: `about`, `address`, `description`, `email`,\n * `profile_picture_url`, `websites`, `vertical`, `messaging_product`.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/business-profiles | Business Profiles API Reference}\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/business-profiles/ | Business Profiles Documentation}\n */\nexport default class BusinessProfileApi extends BaseAPI implements bp.BusinessProfileClass {\n private readonly endpoint = 'whatsapp_business_profile';\n\n /**\n * Get your WhatsApp Business profile information.\n *\n * Retrieves the business profile details for the configured phone number.\n * You can request all fields or specify a subset using the `fields` parameter.\n *\n * @param fields - Optional fields to return. Can be a comma-separated string\n * (e.g., `'about,address,email'`) or an array of field names. If omitted,\n * all fields are returned. Available fields: `about`, `address`, `description`,\n * `email`, `profile_picture_url`, `websites`, `vertical`.\n * @returns A promise that resolves with the business profile information.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/business-profiles#get-business-profile | Get Business Profile}\n *\n * @example\n * ```ts\n * // Get all business profile fields\n * const profile = await whatsappClient.businessProfile.getBusinessProfile();\n *\n * // Get specific fields as a string\n * const profile = await whatsappClient.businessProfile.getBusinessProfile('about,address,email');\n *\n * // Get specific fields as an array\n * const profile = await whatsappClient.businessProfile.getBusinessProfile(['about', 'address', 'email']);\n * ```\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 WhatsApp Business profile.\n *\n * Updates one or more fields of the business profile for the configured phone number.\n * Only the fields included in the request body are updated; omitted fields remain unchanged.\n *\n * @param updateRequest - The profile fields to update.\n * @param updateRequest.messaging_product - Required. Must be set to `'whatsapp'`.\n * @param updateRequest.about - Optional. Business About text (1-139 characters).\n * @param updateRequest.address - Optional. Business address (max 256 characters).\n * @param updateRequest.description - Optional. Business description (max 512 characters).\n * @param updateRequest.vertical - Optional. Business industry/category.\n * @param updateRequest.email - Optional. Contact email address (max 128 characters).\n * @param updateRequest.websites - Optional. Up to 2 website URLs (max 256 characters each).\n * @param updateRequest.profile_picture_handle - Optional. Handle obtained from the upload process.\n * @returns A promise that resolves with a success indicator.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/business-profiles#update-business-profile | Update Business Profile}\n *\n * @example\n * ```ts\n * await whatsappClient.businessProfile.updateBusinessProfile({\n * messaging_product: 'whatsapp',\n * about: 'We provide excellent service',\n * description: 'Your trusted partner for quality products',\n * email: 'contact@example.com',\n * websites: ['https://example.com'],\n * });\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 **step 1** of the three-step profile picture upload process.\n * It initializes a resumable upload session on the server and returns a session ID\n * to use in subsequent upload calls.\n *\n * @param fileLength - The size of the file in bytes.\n * @param fileType - The MIME type of the file (e.g., `'image/jpeg'`, `'image/png'`).\n * @param fileName - The file name with extension (e.g., `'profile.jpg'`).\n * @returns A promise that resolves with the upload session ID.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/business-profiles | Business Profiles - Upload}\n *\n * @example\n * ```ts\n * const session = await whatsappClient.businessProfile.createUploadSession(\n * fileBuffer.length,\n * 'image/jpeg',\n * 'profile.jpg',\n * );\n * console.log(session.upload_session_id);\n * ```\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 binary data to an upload session.\n *\n * This is **step 2** of the three-step profile picture upload process.\n * Uploads the raw binary content of the image to the previously created upload session.\n *\n * @param uploadId - The upload session ID returned from {@link createUploadSession}.\n * @param file - The binary data of the file as a Buffer.\n * @returns A promise that resolves with the upload response.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/business-profiles | Business Profiles - Upload}\n *\n * @example\n * ```ts\n * const fileBuffer = fs.readFileSync('profile.jpg');\n * await whatsappClient.businessProfile.uploadMedia(\n * session.upload_session_id,\n * fileBuffer,\n * );\n * ```\n */\n async uploadMedia(uploadId: string, file: Uint8Array): Promise<bp.UploadBusinessProfileResponse> {\n return this.sendJson(HttpMethodsEnum.Post, `${uploadId}`, this.config[WabaConfigEnum.RequestTimeout], file);\n }\n\n /**\n * Get the upload handle for a completed upload.\n *\n * This is **step 3** of the three-step profile picture upload process.\n * After uploading the file binary, retrieve the handle to use when updating\n * the business profile's `profile_picture_handle` field.\n *\n * @param uploadId - The upload session ID returned from {@link createUploadSession}.\n * @returns A promise that resolves with the upload handle information.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/business-profiles | Business Profiles - Upload}\n *\n * @example\n * ```ts\n * // Complete three-step profile picture upload\n * const session = await whatsappClient.businessProfile.createUploadSession(\n * fileBuffer.length, 'image/jpeg', 'profile.jpg',\n * );\n * await whatsappClient.businessProfile.uploadMedia(session.upload_session_id, fileBuffer);\n * const handleInfo = await whatsappClient.businessProfile.getUploadHandle(session.upload_session_id);\n *\n * // Use the handle to update the profile picture\n * await whatsappClient.businessProfile.updateBusinessProfile({\n * messaging_product: 'whatsapp',\n * profile_picture_handle: handleInfo.handle,\n * });\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","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/qr-codes/\n\n// Endpoints:\n// - POST /{PHONE_NUMBER_ID}/message_qrdls\n// - GET /{PHONE_NUMBER_ID}/message_qrdls\n// - GET /{PHONE_NUMBER_ID}/message_qrdls/{QR_CODE_ID}\n// - POST /{PHONE_NUMBER_ID}/message_qrdls\n// - DELETE /{PHONE_NUMBER_ID}/message_qrdls/{QR_CODE_ID}\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { 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 *\n * Endpoints covered:\n * - `POST /{PHONE_NUMBER_ID}/message_qrdls` - Create a new QR code\n * - `GET /{PHONE_NUMBER_ID}/message_qrdls` - Get all QR codes\n * - `GET /{PHONE_NUMBER_ID}/message_qrdls/{QR_CODE_ID}` - Get a specific QR code\n * - `POST /{PHONE_NUMBER_ID}/message_qrdls/{QR_CODE_ID}` - Update a QR code\n * - `DELETE /{PHONE_NUMBER_ID}/message_qrdls/{QR_CODE_ID}` - Delete a QR code\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/qr-codes/\n */\nexport default class QrCodeApi extends BaseAPI implements qrCode.QrCodeClass {\n private readonly endpoint = 'message_qrdls';\n\n /**\n * Create a new QR code with a prefilled message.\n *\n * @param request - The QR code creation request containing the prefilled message and optional image format.\n * @returns QR code information including code, deep link URL, and optional image URL.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/qr-codes/\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 * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/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 * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/qr-codes/\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 * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/qr-codes/\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 * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/qr-codes/\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","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/registration/\n\n// Endpoints:\n// - POST /{PHONE_NUMBER_ID}/register\n// - POST /{PHONE_NUMBER_ID}/deregister\n\nimport { WHATSAPP_MESSAGING_PRODUCT } from '../../config/defaults';\nimport { BaseAPI } from '../../types/base';\nimport { type DataLocalizationRegionEnum, HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { 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 *\n * Endpoints covered:\n * - `POST /{PHONE_NUMBER_ID}/register` - Register a phone number\n * - `POST /{PHONE_NUMBER_ID}/deregister` - Deregister a phone number\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/registration/\n */\nexport default class RegistrationApi extends BaseAPI implements registration.RegistrationClass {\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 for storage compliance.\n * @returns Response indicating success or failure.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/registration/\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_MESSAGING_PRODUCT,\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 * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/registration/\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","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/whatsapp-business-accounts/\n\n// Endpoints:\n// - POST /{APPLICATION_ID}/whatsapp_business_solution\n// - GET /{APPLICATION_ID}/whatsapp_business_solutions\n// - GET /{SOLUTION_ID}/access_token\n// - POST /{SOLUTION_ID}/accept_deactivation_request\n// - POST /{SOLUTION_ID}/accept\n// - GET /{SOLUTION_ID}\n// - POST /{SOLUTION_ID}/reject_deactivation_request\n// - POST /{SOLUTION_ID}/reject\n// - POST /{SOLUTION_ID}/send_deactivation_request\n// - GET /{MIGRATION_INTENT_ID}\n// - GET /{WABA_ID}/solutions\n// - POST /{WABA_ID}/set_solution_migration_intent\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { ResponseSuccess } from '../../types/request';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\n\nimport type * as solutions from './types';\n\nexport default class SolutionsApi extends BaseAPI implements solutions.SolutionsClass {\n private toQuery(params?: solutions.SolutionListParams): string {\n if (!params) return '';\n\n const fields = Array.isArray(params.fields) ? params.fields.join(',') : params.fields;\n return objectToQueryString({\n fields,\n role: params.role,\n status: params.status,\n limit: params.limit,\n after: params.after,\n before: params.before,\n });\n }\n\n private fieldsQuery(fields?: solutions.SolutionFieldsParam): string {\n const fieldsValue = Array.isArray(fields) ? fields.join(',') : fields;\n return fieldsValue ? objectToQueryString({ fields: fieldsValue }) : '';\n }\n\n async createWhatsAppBusinessSolution(\n applicationId: string,\n request: solutions.CreateWhatsAppBusinessSolutionRequest,\n ): Promise<solutions.SolutionGraphObject> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${applicationId}/whatsapp_business_solution`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n async getApplicationWhatsAppBusinessSolutions(\n applicationId: string,\n params?: solutions.SolutionListParams,\n ): Promise<solutions.SolutionListResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${applicationId}/whatsapp_business_solutions${this.toQuery(params)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async getSolutionAccessToken(\n solutionId: string,\n fields?: solutions.SolutionFieldsParam,\n ): Promise<solutions.SolutionGraphObject> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${solutionId}/access_token${this.fieldsQuery(fields)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async acceptSolutionDeactivationRequest(\n solutionId: string,\n request: solutions.SolutionDeactivationRequest = {},\n ): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${solutionId}/accept_deactivation_request`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n async acceptSolution(solutionId: string, request: solutions.AcceptSolutionRequest = {}): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${solutionId}/accept`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n async getSolutionDetails(\n solutionId: string,\n fields?: solutions.SolutionFieldsParam,\n ): Promise<solutions.SolutionGraphObject> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${solutionId}${this.fieldsQuery(fields)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async rejectSolutionDeactivationRequest(\n solutionId: string,\n request: solutions.SolutionDeactivationRequest = {},\n ): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${solutionId}/reject_deactivation_request`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n async rejectSolutionRequest(\n solutionId: string,\n request: solutions.RejectSolutionRequest = {},\n ): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${solutionId}/reject`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n async sendSolutionDeactivationRequest(\n solutionId: string,\n request: solutions.SolutionDeactivationRequest = {},\n ): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${solutionId}/send_deactivation_request`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n async getMigrationIntentDetails(\n migrationIntentId: string,\n fields?: solutions.SolutionFieldsParam,\n ): Promise<solutions.SolutionGraphObject> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${migrationIntentId}${this.fieldsQuery(fields)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async listWabaSolutions(\n wabaId: string = this.config[WabaConfigEnum.BusinessAcctId],\n params?: solutions.SolutionListParams,\n ): Promise<solutions.SolutionListResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${wabaId}/solutions${this.toQuery(params)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async setSolutionMigrationIntent(\n wabaId: string,\n request: solutions.SetSolutionMigrationIntentRequest,\n ): Promise<solutions.SolutionGraphObject> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${wabaId}/set_solution_migration_intent`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/\n\nimport { CategoryEnum } from '../../../types/enums';\nimport type {\n AuthenticationTemplateOptions,\n BodyOptions,\n ButtonOptions,\n CatalogTemplateOptions,\n ComponentTypes,\n CouponTemplateOptions,\n FooterOptions,\n HeaderOptions,\n LimitedTimeOfferTemplateOptions,\n MediaCardCarouselTemplateOptions,\n MediaCarouselCard,\n MPMTemplateOptions,\n OTPTemplateOptions,\n ProductCardCarouselTemplateOptions,\n ProductCarouselCard,\n SPMTemplateOptions,\n TemplateBody,\n TemplateButton,\n TemplateButtons,\n TemplateFooter,\n TemplateHeader,\n TemplateOptions,\n TemplateParameter,\n TemplateRequestBody,\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","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/\n\n// Endpoints:\n// - GET /{TEMPLATE_ID}\n// - POST /{TEMPLATE_ID}\n// - GET /{WABA_ID}/message_templates?...\n// - POST /{WABA_ID}/message_templates\n// - DELETE /{WABA_ID}/message_templates?...\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { 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\n/**\n * WhatsApp Message Templates API client for managing message templates.\n *\n * Message templates are pre-approved message formats that businesses can use to\n * send notifications and customer care messages. Templates must be approved by\n * Meta before they can be used to send messages.\n *\n * **Covered endpoints:**\n * - `GET /{TEMPLATE_ID}` - Get a single template ({@link TemplateApi.getTemplate})\n * - `POST /{TEMPLATE_ID}` - Update an existing template ({@link TemplateApi.updateTemplate})\n * - `GET /{WABA_ID}/message_templates` - List all templates ({@link TemplateApi.getTemplates})\n * - `POST /{WABA_ID}/message_templates` - Create a new template ({@link TemplateApi.createTemplate})\n * - `DELETE /{WABA_ID}/message_templates` - Delete a template ({@link TemplateApi.deleteTemplate})\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/message-templates | Message Templates API Reference}\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/ | WhatsApp Templates Documentation}\n *\n * @example\n * ```ts\n * const client = new WhatsApp({ accessToken: '...', phoneNumberId: '...', businessAcctId: '...' });\n *\n * // Create a template\n * const template = await client.template.createTemplate({\n * name: 'hello_world',\n * language: 'en_US',\n * category: 'MARKETING',\n * components: [{ type: 'BODY', text: 'Hello {{1}}!' }],\n * });\n *\n * // List all templates\n * const templates = await client.template.getTemplates();\n * ```\n */\nexport default class TemplateApi extends BaseAPI implements TemplateClass {\n private readonly endpoint = 'message_templates';\n\n /**\n * Retrieves a single message template by its ID.\n *\n * Returns the full template definition including name, language, status,\n * category, and components.\n *\n * **Endpoint:** `GET /{TEMPLATE_ID}`\n *\n * @param templateId - The unique identifier of the template to retrieve\n * @returns A promise resolving to the template details\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/message-templates | Message Templates Reference}\n *\n * @example\n * ```ts\n * const template = await client.template.getTemplate('template_id_123');\n * console.log(template.name); // e.g., \"hello_world\"\n * console.log(template.status); // e.g., \"APPROVED\"\n * ```\n */\n async getTemplate(templateId: string): Promise<TemplateResponse> {\n return this.sendJson(HttpMethodsEnum.Get, `${templateId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n /**\n * Updates an existing message template.\n *\n * Allows modifying template components and other properties. Note that editing\n * an approved template will resubmit it for review, changing its status back\n * to `PENDING`.\n *\n * Marketing templates also accept `optimization_spec` here. As of\n * August 31, 2026, an eligible template can be switched between standard rate\n * card pricing and max price without creating a new template, and an existing\n * max price can be updated in place. Approved templates allow up to 100 edits\n * per hour and 2,400 per day.\n *\n * **Endpoint:** `POST /{TEMPLATE_ID}`\n *\n * @param templateId - The unique identifier of the template to update\n * @param template - Partial template body containing only the fields to update\n * @returns A promise resolving to a success response (`{ success: true }`)\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/message-templates | Message Templates Reference}\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/marketing-messages/pricing | Max price for marketing messages}\n *\n * @example\n * ```ts\n * await client.template.updateTemplate('template_id_123', {\n * components: [{ type: 'BODY', text: 'Updated greeting: Hello {{1}}!' }],\n * });\n *\n * // Switch an eligible marketing template onto max price (or change the cap).\n * await client.template.updateTemplate('template_id_123', {\n * optimization_spec: { bid_strategy: 'LOWEST_COST_WITH_BID_CAP', bid_amount: 25000 },\n * });\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 /**\n * Lists message templates for the WhatsApp Business Account.\n *\n * Returns a paginated list of templates, optionally filtered by query parameters\n * such as category, language, name, status, or quality score.\n *\n * **Endpoint:** `GET /{WABA_ID}/message_templates`\n *\n * @param params - Optional query parameters to filter results\n * @param params.category - Filter by template category (e.g., `'MARKETING'`, `'UTILITY'`)\n * @param params.content - Filter by template content\n * @param params.language - Filter by language code (e.g., `'en_US'`)\n * @param params.name - Filter by exact template name\n * @param params.name_or_content - Filter by name or content (search)\n * @param params.quality_score - Filter by quality score\n * @param params.status - Filter by template status (e.g., `'APPROVED'`, `'PENDING'`, `'REJECTED'`)\n * @returns A promise resolving to a paginated response containing an array of templates\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/message-templates | Message Templates Reference}\n *\n * @example\n * ```ts\n * // List all templates\n * const allTemplates = await client.template.getTemplates();\n *\n * // Filter by category and status\n * const approved = await client.template.getTemplates({\n * category: 'MARKETING',\n * status: 'APPROVED',\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 /**\n * Creates a new message template for the WhatsApp Business Account.\n *\n * The template will be submitted for review. Once approved, it can be used\n * to send template messages via {@link MessagesApi.template}.\n *\n * **Endpoint:** `POST /{WABA_ID}/message_templates`\n *\n * @param template - The template definition\n * @param template.name - Template name (lowercase alphanumeric and underscores only)\n * @param template.language - Language code (e.g., `'en_US'`)\n * @param template.category - Template category (`'MARKETING'`, `'UTILITY'`, or `'AUTHENTICATION'`)\n * @param template.components - Array of template components (header, body, footer, buttons)\n * @param template.allow_category_change - Whether Meta can auto-assign a different category\n * @param template.parameter_format - Parameter format (`'POSITIONAL'` or `'NAMED'`)\n * @param template.sub_category - Optional sub-category for the template\n * @param template.message_send_ttl_seconds - Optional TTL in seconds for message delivery attempts\n * @returns A promise resolving to the created template response with its assigned `id` and `status`\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/message-templates | Message Templates Reference}\n *\n * @example\n * ```ts\n * const template = await client.template.createTemplate({\n * name: 'order_confirmation',\n * language: 'en_US',\n * category: 'UTILITY',\n * components: [\n * { type: 'BODY', text: 'Your order {{1}} has been confirmed.' },\n * ],\n * });\n * console.log(template.id); // Template ID\n * console.log(template.status); // \"PENDING\"\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 /**\n * Deletes a message template from the WhatsApp Business Account.\n *\n * Deleting a template removes all language variations of that template.\n * To delete a specific language version, provide the `hsm_id` parameter.\n *\n * **Endpoint:** `DELETE /{WABA_ID}/message_templates`\n *\n * @param params - The delete parameters\n * @param params.name - The name of the template to delete (required)\n * @param params.hsm_id - Optional template ID to delete a specific language version\n * @returns A promise resolving to a success response (`{ success: true }`)\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/message-templates | Message Templates Reference}\n *\n * @example\n * ```ts\n * // Delete all language versions of a template\n * await client.template.deleteTemplate({ name: 'old_template' });\n *\n * // Delete a specific language version\n * await client.template.deleteTemplate({ name: 'old_template', hsm_id: '123456' });\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","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/conversation-routing/thread-control/\n\n// Endpoints:\n// - POST /{PHONE_NUMBER_ID}/thread_control\n\nimport { WHATSAPP_MESSAGING_PRODUCT } from '../../config/defaults';\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport { WhatsAppValidationError } from '../../utils/isMetaError';\n\nimport type * as threadControl from './types/threadControl';\n\nconst METADATA_MAX_LENGTH = 2000;\n\ntype ThreadControlAction = 'pass' | 'release' | 'take';\n\n/**\n * API for Conversation Routing thread control.\n *\n * When more than one responder shares a WhatsApp account, Conversation Routing\n * gives each thread exactly one owner. Thread control lets a responder pass\n * ownership to another role, release the thread back to idle, or (escalation\n * partner only) take it. Routing itself is configured by the business in Meta\n * Business Suite, not through the API, and the account must be enrolled for\n * thread control before this endpoint accepts requests.\n *\n * There is no endpoint that reports the current owner: track ownership locally\n * from inbound messages, `messaging_handovers` events (`processor.onMessagingHandovers`),\n * and standby events, and reconcile after 24 hours of user inactivity, when the\n * thread returns to idle on its own.\n *\n * Endpoints covered:\n * - `POST /{PHONE_NUMBER_ID}/thread_control` - Pass, release, or take a thread\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/conversation-routing/thread-control/\n */\nexport default class ThreadControlApi extends BaseAPI implements threadControl.ThreadControlClass {\n private readonly endpoint = 'thread_control';\n\n /**\n * Pass thread ownership from you (the current owner) to another responder.\n *\n * Without `control_pass`, control goes to the account's escalation partner.\n * With `control_pass.target_role`, control goes to that role. Meta rejects the\n * request if the thread is idle, you do not own it, the target is not enabled,\n * or the target already owns the thread. The new owner receives a\n * `control_passed` `messaging_handovers` event.\n *\n * @param params - The WhatsApp user (`to` or `recipient`), optional `metadata`, and optional `control_pass`.\n * @returns `{ messaging_product, request_id }`.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/conversation-routing/thread-control/#pass\n *\n * @example\n * ```typescript\n * const { request_id } = await client.threadControl.pass({\n * recipient: 'US.13491208655302741918',\n * metadata: 'WhatsApp user requested human agent',\n * control_pass: { target_role: 'customer_service' },\n * });\n * ```\n */\n async pass(params: threadControl.PassThreadControlParams): Promise<threadControl.ThreadControlResponse> {\n return this.send('pass', params);\n }\n\n /**\n * Release the thread back to idle. The WhatsApp user's next message is\n * re-routed by entry point. Releasing an idle thread succeeds; releasing a\n * thread you do not own is rejected (the escalation partner must take it first).\n * No `messaging_handovers` event fires for a release.\n *\n * @param params - The WhatsApp user (`to` or `recipient`) and optional `metadata`.\n * @returns `{ messaging_product, request_id }`.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/conversation-routing/thread-control/#release\n */\n async release(params: threadControl.ReleaseThreadControlParams): Promise<threadControl.ThreadControlResponse> {\n return this.send('release', params);\n }\n\n /**\n * Take thread ownership. Only the account's designated escalation partner can\n * take a thread, regardless of who owns it; the previous owner receives a\n * `control_taken` `messaging_handovers` event. Sending a Service message as the\n * escalation partner takes the thread implicitly, without this call.\n *\n * @param params - The WhatsApp user (`to` or `recipient`) and optional `metadata`.\n * @returns `{ messaging_product, request_id }`.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/conversation-routing/thread-control/#take\n */\n async take(params: threadControl.TakeThreadControlParams): Promise<threadControl.ThreadControlResponse> {\n return this.send('take', params);\n }\n\n private async send(\n action: ThreadControlAction,\n params: threadControl.PassThreadControlParams,\n ): Promise<threadControl.ThreadControlResponse> {\n const hasTo = Boolean(params?.to);\n const hasRecipient = Boolean(params?.recipient);\n if (hasTo === hasRecipient) {\n throw new WhatsAppValidationError('Exactly one of \"to\" or \"recipient\" is required for thread control.');\n }\n if (params.metadata && params.metadata.length > METADATA_MAX_LENGTH) {\n throw new WhatsAppValidationError(\n `\"metadata\" must be at most ${METADATA_MAX_LENGTH} characters for thread control.`,\n );\n }\n if (action !== 'pass' && params.control_pass) {\n throw new WhatsAppValidationError('\"control_pass\" is only supported for the pass action.');\n }\n\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n ...(hasTo ? { to: params.to } : { recipient: params.recipient }),\n action,\n ...(params.metadata !== undefined && { metadata: params.metadata }),\n ...(params.control_pass && { control_pass: params.control_pass }),\n };\n\n return await this.sendJson<threadControl.ThreadControlResponse>(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/two-step-verification/\n\n// Endpoints:\n// - POST /{PHONE_NUMBER_ID}\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { 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 *\n * Endpoints covered:\n * - `POST /{PHONE_NUMBER_ID}` - Set two-step verification PIN\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/two-step-verification/\n */\nexport default class TwoStepVerificationApi extends BaseAPI implements twoStepVerification.TwoStepVerificationClass {\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 * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/two-step-verification/\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","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/whatsapp-business-accounts/\n\n// Endpoints:\n// - GET /{WABA_ID}?fields\n// - POST /{WABA_ID}\n// - GET /{WABA_ID}/activities\n// - GET /{WABA_ID}/subscribed_apps\n// - POST /{WABA_ID}/subscribed_apps\n// - DELETE /{WABA_ID}/subscribed_apps\n// - GET /{WABA_ID}/assigned_users\n// - POST /{WABA_ID}/assigned_users\n// - DELETE /{WABA_ID}/assigned_users\n// - GET /{WABA_ID}/in_progress_onbehalf_request\n// - GET /{OBO_MOBILITY_INTENT_ID}\n// - POST /{WABA_ID}/obo_mobility_intent\n// - POST /{WABA_ID}/set_obo_mobility_intent\n// - GET /{WABA_ID}/schedules\n// - POST /{WABA_ID}/schedules\n// - GET /{WABA_BOT_ID}\n// - GET /{WHATSAPP_BUSINESS_PROFILE_ID}\n// - POST /{WHATSAPP_BUSINESS_PROFILE_ID}\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { ResponseSuccess } from '../../types/request';\nimport { buildFieldsQueryString } from '../../utils/buildFieldsQueryString';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\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 *\n * Endpoints covered:\n * - `GET /{WABA_ID}` - Get WABA account information\n * - `GET /{WABA_ID}/subscribed_apps` - Get all WABA subscriptions\n * - `POST /{WABA_ID}/subscribed_apps` - Update/create a WABA subscription\n * - `DELETE /{WABA_ID}/subscribed_apps` - Unsubscribe from WABA webhooks\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/whatsapp-business-accounts/\n */\nexport default class WabaApi extends BaseAPI implements waba.WABAClass {\n private toQuery(params?: waba.WabaListParams): string {\n if (!params) return '';\n\n const fields = Array.isArray(params.fields) ? params.fields.join(',') : params.fields;\n const filtering = Array.isArray(params.filtering) ? JSON.stringify(params.filtering) : params.filtering;\n\n return objectToQueryString({\n fields,\n filtering,\n sort: params.sort,\n limit: params.limit,\n after: params.after,\n before: params.before,\n });\n }\n\n private fieldsQuery(fields?: waba.WabaFieldsParam): string {\n const fieldsValue = Array.isArray(fields) ? fields.join(',') : fields;\n return fieldsValue ? objectToQueryString({ fields: fieldsValue }) : '';\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 * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/whatsapp-business-accounts/\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 * Update WABA account fields such as name or timezone.\n */\n async updateWabaAccount(params: waba.UpdateWabaAccountRequest): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.BusinessAcctId]}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(params),\n );\n }\n\n /**\n * Get account activity events for a WABA.\n */\n async getWabaActivities(params?: waba.WabaListParams): Promise<waba.WabaListResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.BusinessAcctId]}/activities${this.toQuery(params)}`,\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 * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/whatsapp-business-accounts/\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 * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/whatsapp-business-accounts/\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 * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/whatsapp-business-accounts/\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 async getAssignedUsers(\n params: waba.AssignedUsersListParams,\n wabaId: string = this.config[WabaConfigEnum.BusinessAcctId],\n ): Promise<waba.WabaListResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${wabaId}/assigned_users${this.toQuery(params)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async addAssignedUser(\n params: waba.AssignedUserRequest,\n wabaId: string = this.config[WabaConfigEnum.BusinessAcctId],\n ): Promise<ResponseSuccess> {\n const body = {\n user: params.user,\n tasks: params.tasks,\n };\n\n return this.sendUrlEncodedForm(\n HttpMethodsEnum.Post,\n `${wabaId}/assigned_users`,\n this.config[WabaConfigEnum.RequestTimeout],\n body,\n );\n }\n\n async removeAssignedUser(\n params: waba.RemoveAssignedUserRequest,\n wabaId: string = this.config[WabaConfigEnum.BusinessAcctId],\n ): Promise<ResponseSuccess> {\n return this.sendUrlEncodedForm(\n HttpMethodsEnum.Delete,\n `${wabaId}/assigned_users`,\n this.config[WabaConfigEnum.RequestTimeout],\n { user: params.user },\n );\n }\n\n async getInProgressOnBehalfRequests(\n params?: waba.WabaListParams,\n wabaId: string = this.config[WabaConfigEnum.BusinessAcctId],\n ): Promise<waba.WabaListResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${wabaId}/in_progress_onbehalf_request${this.toQuery(params)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async getOBOMobilityIntent(\n oboMobilityIntentId: string,\n fields?: waba.WabaFieldsParam,\n ): Promise<waba.WabaGraphObject> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${oboMobilityIntentId}${this.fieldsQuery(fields)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async createOBOMobilityIntent(\n params: waba.CreateOBOMobilityIntentRequest,\n wabaId: string = this.config[WabaConfigEnum.BusinessAcctId],\n ): Promise<waba.WabaGraphObject> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${wabaId}/obo_mobility_intent`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(params),\n );\n }\n\n async setOBOMobilityIntent(\n params: waba.SetOBOMobilityIntentRequest,\n wabaId: string = this.config[WabaConfigEnum.BusinessAcctId],\n ): Promise<waba.WabaGraphObject> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${wabaId}/set_obo_mobility_intent`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(params),\n );\n }\n\n async getWabaSchedules(\n params?: waba.WabaListParams,\n wabaId: string = this.config[WabaConfigEnum.BusinessAcctId],\n ): Promise<waba.WabaListResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${wabaId}/schedules${this.toQuery(params)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async createWabaSchedule(\n params: waba.CreateScheduleRequest,\n wabaId: string = this.config[WabaConfigEnum.BusinessAcctId],\n ): Promise<waba.WabaGraphObject> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${wabaId}/schedules`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(params),\n );\n }\n\n async getWhatsAppBusinessBotDetails(botId: string, fields?: waba.WabaFieldsParam): Promise<waba.WabaGraphObject> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${botId}${this.fieldsQuery(fields)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async getWhatsAppBusinessProfileDetails(\n profileId: string,\n fields?: waba.WabaFieldsParam,\n ): Promise<waba.WabaGraphObject> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${profileId}${this.fieldsQuery(fields)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async updateWhatsAppBusinessProfile(\n profileId: string,\n params: waba.UpdateWhatsAppBusinessProfileRequest,\n ): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n profileId,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(params),\n );\n }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/whatsapp-business-accounts/\n\nimport type { Paging, ResponseSuccess } from '../../../types/request';\n\n/**\n * WhatsApp Business Account subscription configuration\n */\nexport type WabaSubscription = {\n whatsapp_business_api_data: {\n id: string;\n link: string;\n name: string;\n category: string;\n };\n override_callback_uri?: string;\n};\n\n/**\n * Parameters for updating WABA subscription\n */\nexport interface UpdateWabaSubscription {\n override_callback_uri: string;\n verify_token: string;\n}\n\n/**\n * Response containing all WABA subscriptions\n */\nexport interface WabaSubscriptions {\n data: Array<WabaSubscription>;\n}\n\n/**\n * WABA account review status enumeration\n */\nexport enum WabaAccountReviewStatus {\n Approved = 'APPROVED',\n Active = 'ACTIVE',\n Inactive = 'INACTIVE',\n Disabled = 'DISABLED',\n}\n\n/**\n * WABA health status for message sending capability\n */\nexport enum WabaHealthStatusCanSendMessage {\n Blocked = 'BLOCKED',\n Limited = 'LIMITED',\n Available = 'AVAILABLE',\n}\n\n/**\n * WABA account status enumeration\n */\nexport enum WabaAccountStatus {\n Approved = 'APPROVED',\n Active = 'ACTIVE',\n Inactive = 'INACTIVE',\n Disabled = 'DISABLED',\n}\n\n/**\n * Business verification status enumeration\n */\nexport enum WabaBusinessVerificationStatus {\n Verified = 'verified',\n PendingSubmission = 'pending_submission',\n Unverified = 'unverified',\n Rejected = 'rejected',\n}\n\n/**\n * WABA health status error details\n */\nexport interface WabaHealthStatusError {\n error_code?: number;\n error_description?: string;\n possible_solution?: string;\n}\n\n/**\n * WABA health status entity information\n */\nexport interface WabaHealthStatusEntity {\n entity_type?: string;\n id?: string;\n can_send_message?: string;\n errors?: WabaHealthStatusError[];\n}\n\n/**\n * Overall WABA health status\n */\nexport interface WabaHealthStatus {\n can_send_message?: WabaHealthStatusCanSendMessage;\n entities?: WabaHealthStatusEntity[];\n}\n\n/**\n * WhatsApp Business Account information\n */\nexport interface WabaAccount {\n account_review_status?: WabaAccountReviewStatus;\n id?: string;\n health_status?: WabaHealthStatus;\n status?: WabaAccountStatus;\n business_verification_status?: WabaBusinessVerificationStatus;\n message_template_namespace?: string;\n name?: string;\n ownership_type?: string;\n timezone_id?: string;\n primary_business_location?: Record<string, unknown> | string;\n currency?: string;\n country?: string;\n analytics?: Record<string, unknown>;\n is_enabled_for_insights?: boolean;\n is_shared_with_partners?: boolean;\n marketing_messages_lite_api_status?: string;\n marketing_messages_onboarding_status?: string;\n on_behalf_of_business_info?: Record<string, unknown>;\n primary_funding_id?: string;\n purchase_order_number?: string;\n whatsapp_business_manager_messaging_limit?: string;\n}\n\n/**\n * Available fields for WABA account queries\n */\nexport type WabaAccountFields =\n | 'id'\n | 'name'\n | 'timezone_id'\n | 'account_review_status'\n | 'auth_international_rate_eligibility'\n | 'business_verification_status'\n | 'country'\n | 'currency'\n | 'health_status'\n | 'status'\n | 'ownership_type'\n | 'message_template_namespace'\n | 'primary_business_location'\n | 'analytics'\n | 'is_enabled_for_insights'\n | 'is_shared_with_partners'\n | 'marketing_messages_lite_api_status'\n | 'marketing_messages_onboarding_status'\n | 'on_behalf_of_business_info'\n | 'primary_funding_id'\n | 'purchase_order_number'\n | 'whatsapp_business_manager_messaging_limit';\n\n/**\n * Parameter type for specifying which WABA account fields to retrieve\n */\nexport type WabaAccountFieldsParam = WabaAccountFields[];\n\nexport type WabaGraphObject = Record<string, unknown>;\n\nexport type WabaFieldsParam = string[] | string;\n\nexport type WabaListParams = {\n fields?: WabaFieldsParam;\n filtering?: WabaGraphObject[] | string;\n sort?: string;\n limit?: number;\n after?: string;\n before?: string;\n};\n\nexport type WabaListResponse<T = WabaGraphObject> = {\n data: T[];\n paging?: Paging;\n summary?: WabaGraphObject;\n};\n\nexport type UpdateWabaAccountRequest = {\n name?: string;\n timezone_id?: string;\n [key: string]: unknown;\n};\n\nexport type AssignedUsersListParams = WabaListParams & {\n business: string;\n};\n\nexport type AssignedUserRequest = {\n user: string;\n tasks: string[];\n};\n\nexport type RemoveAssignedUserRequest = {\n user: string;\n [key: string]: unknown;\n};\n\nexport type CreateOBOMobilityIntentRequest = {\n intent?: string;\n [key: string]: unknown;\n};\n\nexport type SetOBOMobilityIntentRequest = {\n [key: string]: unknown;\n};\n\nexport type CreateScheduleRequest = {\n name?: string;\n schedule_type?: string;\n [key: string]: unknown;\n};\n\nexport type UpdateWhatsAppBusinessProfileRequest = {\n [key: string]: unknown;\n};\n\n/**\n * Interface defining all WABA API methods\n */\nexport interface WABAClass {\n getWabaAccount(fields?: WabaAccountFieldsParam): Promise<WabaAccount>;\n updateWabaAccount(params: UpdateWabaAccountRequest): Promise<ResponseSuccess>;\n getWabaActivities(params?: WabaListParams): Promise<WabaListResponse>;\n getAllWabaSubscriptions(): Promise<WabaSubscriptions>;\n updateWabaSubscription(params: UpdateWabaSubscription): Promise<ResponseSuccess>;\n unsubscribeFromWaba(): Promise<ResponseSuccess>;\n getAssignedUsers(params: AssignedUsersListParams, wabaId?: string): Promise<WabaListResponse>;\n addAssignedUser(params: AssignedUserRequest, wabaId?: string): Promise<ResponseSuccess>;\n removeAssignedUser(params: RemoveAssignedUserRequest, wabaId?: string): Promise<ResponseSuccess>;\n getInProgressOnBehalfRequests(params?: WabaListParams, wabaId?: string): Promise<WabaListResponse>;\n getOBOMobilityIntent(oboMobilityIntentId: string, fields?: WabaFieldsParam): Promise<WabaGraphObject>;\n createOBOMobilityIntent(params: CreateOBOMobilityIntentRequest, wabaId?: string): Promise<WabaGraphObject>;\n setOBOMobilityIntent(params: SetOBOMobilityIntentRequest, wabaId?: string): Promise<WabaGraphObject>;\n getWabaSchedules(params?: WabaListParams, wabaId?: string): Promise<WabaListResponse>;\n createWabaSchedule(params: CreateScheduleRequest, wabaId?: string): Promise<WabaGraphObject>;\n getWhatsAppBusinessBotDetails(botId: string, fields?: WabaFieldsParam): Promise<WabaGraphObject>;\n getWhatsAppBusinessProfileDetails(profileId: string, fields?: WabaFieldsParam): Promise<WabaGraphObject>;\n updateWhatsAppBusinessProfile(\n profileId: string,\n params: UpdateWhatsAppBusinessProfileRequest,\n ): Promise<ResponseSuccess>;\n}\n","import type { LoggerInterface } from '../types/logger';\n\nexport default class Logger implements LoggerInterface {\n private name: string;\n private debugEnabled: boolean;\n\n constructor(name: string, debug: boolean = false) {\n this.name = name;\n this.debugEnabled = debug;\n }\n\n private formatData(data: any[]): string {\n return data.map((item) => (typeof item === 'object' && item !== null ? stringify(item) : item)).join(' ');\n }\n\n log(...data: any[]) {\n if (this.debugEnabled) {\n let prefix = `[ ${Date.now()} ]`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.log(prefix, ': ', this.formatData(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(prefix, ': ', this.formatData(data));\n }\n\n warn(...data: any[]) {\n if (this.debugEnabled) {\n let prefix = `[ ${Date.now()} ] - WARN`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.warn(prefix, ': ', this.formatData(data));\n }\n }\n\n info(...data: any[]) {\n if (this.debugEnabled) {\n let prefix = `[ ${Date.now()} ] - INFO`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.info(prefix, ': ', this.formatData(data));\n }\n }\n\n debug(...data: any[]) {\n if (this.debugEnabled) {\n let prefix = `[ ${Date.now()} ] - DEBUG`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.debug(prefix, ': ', this.formatData(data));\n }\n }\n}\n\n/**\n * Serialize log data without `node:util` so logging works on every runtime.\n * Errors keep their message and stack; circular references are marked.\n */\nfunction stringify(value: object): string {\n if (value instanceof Error) {\n return value.stack || `${value.name}: ${value.message}`;\n }\n const seen = new WeakSet<object>();\n try {\n return JSON.stringify(\n value,\n (_key, val) => {\n if (val instanceof Error) {\n return { name: val.name, message: val.message, stack: val.stack };\n }\n if (typeof val === 'bigint') return val.toString();\n if (typeof val === 'object' && val !== null) {\n if (seen.has(val)) return '[Circular]';\n seen.add(val);\n }\n return val;\n },\n 2,\n );\n } catch {\n return String(value);\n }\n}\n","// Selected only by the Node conditional package entry during the build.\nimport * as crypto from 'node:crypto';\n\nexport const nodeCrypto = crypto;\n","import { nodeCrypto } from './runtimeCrypto';\n\n/**\n * Runtime helpers that keep the SDK free of static `node:*` imports, so the\n * universal bundle loads on Bun, Deno, Cloudflare Workers and Vercel Edge.\n * Node conditional entries inject crypto for versions lacking getBuiltinModule.\n */\n\ntype NodeCrypto = typeof import('node:crypto');\n\ntype ProcessLike = {\n env?: Record<string, string | undefined>;\n version?: string;\n versions?: Record<string, string | undefined>;\n getBuiltinModule?: (id: string) => unknown;\n};\n\nfunction getProcess(): ProcessLike | undefined {\n const proc = (globalThis as { process?: ProcessLike }).process;\n return typeof proc === 'object' && proc !== null ? proc : undefined;\n}\n\n/**\n * Read an environment variable. Returns undefined on runtimes without\n * `process.env` (e.g. Cloudflare Workers without `nodejs_compat`).\n */\nexport function readEnv(name: string): string | undefined {\n return getProcess()?.env?.[name];\n}\n\n/** True when the `DEBUG` environment variable is `'true'`. */\nexport function isDebugEnv(): boolean {\n return readEnv('DEBUG') === 'true';\n}\n\n/**\n * Load `node:crypto` synchronously without a static import, via\n * `process.getBuiltinModule` (Node.js >= 20.16, Bun, Deno, workerd with\n * `nodejs_compat`), or the Node entry module. Returns undefined\n * when it is not available.\n */\nexport function getNodeCrypto(): NodeCrypto | undefined {\n const getBuiltinModule = getProcess()?.getBuiltinModule;\n if (typeof getBuiltinModule !== 'function') return getProcess() ? nodeCrypto : undefined;\n try {\n return getBuiltinModule('node:crypto') as NodeCrypto;\n } catch {\n return undefined;\n }\n}\n\n/** Like {@link getNodeCrypto} but throws a descriptive error when missing. */\nexport function requireNodeCrypto(feature: string): NodeCrypto {\n const crypto = getNodeCrypto();\n if (!crypto) {\n throw new Error(\n `${feature} needs the node:crypto module, which is not available in this runtime. ` +\n 'Use the async Web Crypto variant instead, or run on Node.js >= 20.12, Bun or Deno.',\n );\n }\n return crypto;\n}\n\n/** Web Crypto `SubtleCrypto`, available on every supported runtime. */\nexport function getSubtle(): SubtleCrypto {\n const subtle = globalThis.crypto?.subtle;\n if (!subtle) {\n throw new Error('Web Crypto (globalThis.crypto.subtle) is not available in this runtime.');\n }\n return subtle;\n}\n\n/** Human-readable runtime name for the User-Agent header. */\nexport function describeRuntime(): string {\n const g = globalThis as {\n Bun?: { version?: string };\n Deno?: { version?: { deno?: string } };\n EdgeRuntime?: string;\n navigator?: { userAgent?: string };\n };\n if (g.Bun?.version) return `Bun ${g.Bun.version}`;\n if (g.Deno?.version?.deno) return `Deno ${g.Deno.version.deno}`;\n if (typeof g.EdgeRuntime === 'string') return `Edge Runtime ${g.EdgeRuntime}`;\n if (g.navigator?.userAgent === 'Cloudflare-Workers') return 'Cloudflare Workers';\n const version = getProcess()?.version;\n if (version) return `Node.js ${version}`;\n return 'unknown runtime';\n}\n\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\nexport function utf8Encode(value: string): Uint8Array<ArrayBuffer> {\n return textEncoder.encode(value) as Uint8Array<ArrayBuffer>;\n}\n\nexport function utf8Decode(value: Uint8Array): string {\n return textDecoder.decode(value);\n}\n\nexport function base64ToBytes(value: string): Uint8Array<ArrayBuffer> {\n const binary = atob(value);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n\nexport function bytesToBase64(bytes: Uint8Array): string {\n let binary = '';\n const chunk = 0x8000;\n for (let i = 0; i < bytes.length; i += chunk) {\n binary += String.fromCharCode(...bytes.subarray(i, i + chunk));\n }\n return btoa(binary);\n}\n\nexport function bytesToHex(bytes: Uint8Array): string {\n let hex = '';\n for (const byte of bytes) {\n hex += byte.toString(16).padStart(2, '0');\n }\n return hex;\n}\n\n/** Constant-time string comparison (length is not secret). */\nexport function timingSafeEqualString(a: string, b: string): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) {\n diff |= a.charCodeAt(i) ^ b.charCodeAt(i);\n }\n return diff === 0;\n}\n\n/** HMAC-SHA256 hex digest using Web Crypto. */\nexport async function hmacSha256Hex(key: string, data: string): Promise<string> {\n const subtle = getSubtle();\n const cryptoKey = await subtle.importKey('raw', utf8Encode(key), { name: 'HMAC', hash: 'SHA-256' }, false, [\n 'sign',\n ]);\n const signature = await subtle.sign('HMAC', cryptoKey, utf8Encode(data));\n return bytesToHex(new Uint8Array(signature));\n}\n","import type { WabaConfigType, WhatsAppConfig } from '../types/config';\nimport { WabaConfigEnum } from '../types/enums';\nimport Logger from '../utils/logger';\nimport { isDebugEnv, readEnv } from '../utils/runtime';\nimport {\n DEFAULT_CLOUD_API_VERSION,\n DEFAULT_LISTENER_PORT,\n DEFAULT_MAX_RETRIES_AFTER_WAIT,\n DEFAULT_REQUEST_TIMEOUT,\n} from './defaults';\n\nconst LIB_NAME = 'UTILS';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, isDebugEnv() || LOG_LOCAL);\n\nconst emptyConfigChecker = (config: WhatsAppConfig | undefined) => {\n if (!readEnv(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 || readEnv('M4D_APP_ID') || '',\n [WabaConfigEnum.AppSecret]: inputConfig?.appSecret || readEnv('M4D_APP_SECRET') || '',\n [WabaConfigEnum.PhoneNumberId]:\n inputConfig?.phoneNumberId || (readEnv('WA_PHONE_NUMBER_ID') ? Number(readEnv('WA_PHONE_NUMBER_ID')) : 0),\n [WabaConfigEnum.BusinessAcctId]: inputConfig?.businessAcctId || readEnv('WA_BUSINESS_ACCOUNT_ID') || '',\n [WabaConfigEnum.APIVersion]:\n inputConfig?.apiVersion || readEnv('CLOUD_API_VERSION') || DEFAULT_CLOUD_API_VERSION,\n [WabaConfigEnum.AccessToken]: inputConfig?.accessToken || readEnv('CLOUD_API_ACCESS_TOKEN') || '',\n [WabaConfigEnum.WebhookEndpoint]: inputConfig?.webhookEndpoint || readEnv('WEBHOOK_ENDPOINT') || '',\n [WabaConfigEnum.WebhookVerificationToken]:\n inputConfig?.webhookVerificationToken || readEnv('WEBHOOK_VERIFICATION_TOKEN') || '',\n [WabaConfigEnum.ListenerPort]:\n inputConfig?.listenerPort || parseInt(readEnv('LISTENER_PORT') || '', 10) || DEFAULT_LISTENER_PORT,\n [WabaConfigEnum.MaxRetriesAfterWait]:\n inputConfig?.maxRetriesAfterWait ||\n parseInt(readEnv('MAX_RETRIES_AFTER_WAIT') || '', 10) ||\n DEFAULT_MAX_RETRIES_AFTER_WAIT,\n [WabaConfigEnum.RequestTimeout]:\n inputConfig?.requestTimeout || parseInt(readEnv('REQUEST_TIMEOUT') || '', 10) || DEFAULT_REQUEST_TIMEOUT,\n [WabaConfigEnum.Debug]: inputConfig?.debug || isDebugEnv(),\n [WabaConfigEnum.PrivatePem]: inputConfig?.privatePem || readEnv('FLOW_API_PRIVATE_PEM') || '',\n [WabaConfigEnum.Passphrase]: inputConfig?.passphrase || readEnv('FLOW_API_PASSPHRASE') || '',\n retry: inputConfig?.retry,\n onRateLimitInfo: inputConfig?.onRateLimitInfo,\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","/**\n * WhatsApp Flow Encryption/Decryption Utilities\n * Handles encryption and decryption of WhatsApp Flow requests and responses\n * @see https://developers.facebook.com/docs/whatsapp/cloud-api/reference/whatsapp-business-encryption/\n */\n\nimport type { KeyObject } from 'node:crypto';\n\nimport type { FlowEndpointRequest } from '../api/flow';\nimport type { WabaConfigType } from '../types/config';\nimport Logger from './logger';\nimport {\n base64ToBytes,\n bytesToBase64,\n getNodeCrypto,\n getSubtle,\n isDebugEnv,\n readEnv,\n requireNodeCrypto,\n utf8Decode,\n utf8Encode,\n} from './runtime';\n\nconst LIB_NAME = 'FLOW_ENCRYPTION_UTILS';\nconst LOGGER = new Logger(LIB_NAME, isDebugEnv());\n\n/**\n * Environment model for encryption keys\n */\nexport type EncryptionKeyPair = {\n passphrase: string;\n privateKey: string;\n publicKey: string;\n};\n\n/**\n * Validates that the code is running in a Node.js environment\n * @throws {Error} If not running in Node.js environment\n */\nfunction validateNodeEnvironment(): typeof import('node:crypto') {\n const crypto = getNodeCrypto();\n // Check if crypto module exists and has required methods\n if (!crypto || typeof crypto.generateKeyPairSync !== 'function') {\n const error = new Error(\n 'This utility requires Node.js environment with crypto module. ' +\n 'It cannot be used in browser or edge runtime environments.',\n );\n LOGGER.error('Environment validation failed:', error);\n throw error;\n }\n\n // Check if running in browser\n if (typeof window !== 'undefined') {\n const error = new Error(\n 'This utility cannot run in a browser environment. ' +\n 'Please use it in a Node.js server environment only.',\n );\n LOGGER.error('Browser environment detected:', error);\n throw error;\n }\n\n // Check Node.js version (crypto.generateKeyPairSync requires Node.js 10.12.0+)\n const nodeVersionString = (globalThis as { process?: { versions?: { node?: string } } }).process?.versions?.node;\n if (nodeVersionString) {\n const nodeVersion = nodeVersionString.split('.').map(Number);\n const major = nodeVersion[0] ?? 0;\n const minor = nodeVersion[1] ?? 0;\n\n if (major < 10 || (major === 10 && minor < 12)) {\n const error = new Error(\n `Node.js version ${nodeVersionString} is not supported. ` +\n 'Please upgrade to Node.js 10.12.0 or higher.',\n );\n LOGGER.error('Node.js version check failed:', error);\n throw error;\n }\n }\n\n return crypto;\n}\n\n/**\n * Generates RSA key pair for WhatsApp Business Flow API encryption\n *\n * This function generates a 2048-bit RSA key pair with:\n * - Public key in SPKI format (PEM)\n * - Private key in PKCS#8 format (PEM) encrypted with AES-256-CBC\n *\n * @param passphrase - Passphrase to encrypt the private key. If not provided, uses FLOW_API_PASSPHRASE from environment\n * @returns Object containing passphrase, privateKey, and publicKey\n * @throws {Error} If passphrase is empty or key generation fails\n * @throws {Error} If not running in Node.js environment\n *\n * @example\n * ```typescript\n * import { WhatsApp } from 'meta-cloud-api';\n *\n * const wa = new WhatsApp();\n *\n * try {\n * // Uses FLOW_API_PASSPHRASE from environment\n * const keys = wa.generateEncryption();\n * console.log('Public Key:', keys.publicKey);\n * console.log('Private Key:', keys.privateKey);\n *\n * // Or provide custom passphrase\n * const customKeys = wa.generateEncryption('my-secret-passphrase');\n * } catch (error) {\n * console.error('Failed to generate keys:', error.message);\n * }\n * ```\n */\nexport function generateEncryption(passphrase?: string): EncryptionKeyPair {\n LOGGER.info('[generateEncryption] Starting key pair generation');\n\n // Validate environment first\n const crypto = validateNodeEnvironment();\n\n // Get passphrase from parameter or environment variable\n const effectivePassphrase = passphrase || readEnv('FLOW_API_PASSPHRASE');\n\n // Validate passphrase\n if (!effectivePassphrase || effectivePassphrase.trim().length === 0) {\n const error = new Error(\n 'Passphrase is empty. Please provide a passphrase as parameter or set FLOW_API_PASSPHRASE environment variable.',\n );\n LOGGER.error('[generateEncryption] Passphrase validation failed:', error);\n throw error;\n }\n\n // Warn if passphrase is too short\n if (effectivePassphrase.length < 8) {\n LOGGER.warn(\n '[generateEncryption] Passphrase is shorter than 8 characters. Consider using a longer passphrase for better security.',\n );\n }\n\n try {\n LOGGER.info('[generateEncryption] Generating 2048-bit RSA key pair');\n\n // Generate RSA key pair\n const keyPair = crypto.generateKeyPairSync('rsa', {\n modulusLength: 2048,\n publicKeyEncoding: {\n type: 'spki',\n format: 'pem',\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'pem',\n cipher: 'aes-256-cbc',\n passphrase: effectivePassphrase,\n },\n });\n\n LOGGER.info('[generateEncryption] Key pair generated successfully');\n\n return {\n passphrase: effectivePassphrase,\n privateKey: keyPair.privateKey,\n publicKey: keyPair.publicKey,\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n const generationError = new Error(`Failed to generate key pair: ${errorMessage}`);\n LOGGER.error('[generateEncryption] Key generation failed:', generationError);\n throw generationError;\n }\n}\n\n/**\n * Decrypt a WhatsApp Flow request (Node.js only; see {@link decryptFlowRequestAsync} for every runtime)\n * @param body - Encrypted request body containing encrypted_aes_key, encrypted_flow_data, and initial_vector\n * @param config - WABA configuration containing FLOW_API_PRIVATE_PEM and FLOW_API_PASSPHRASE\n * @returns Decrypted flow request body, AES key buffer, and initial vector buffer\n * @throws {Error} If required encryption properties are missing or decryption fails\n */\nexport function decryptFlowRequest(\n body: any,\n config: WabaConfigType,\n): {\n decryptedBody: FlowEndpointRequest;\n aesKeyBuffer: Buffer;\n initialVectorBuffer: Buffer;\n} {\n LOGGER.info('[decryptFlowRequest] Starting Flow request decryption');\n\n const crypto = requireNodeCrypto('decryptFlowRequest');\n\n // Validate required environment variables\n if (!config.FLOW_API_PRIVATE_PEM || config.FLOW_API_PRIVATE_PEM.trim() === '') {\n const error = new Error(\n 'Missing FLOW_API_PRIVATE_PEM. Please set the FLOW_API_PRIVATE_PEM environment variable or pass privatePem via config.',\n );\n LOGGER.error('[decryptFlowRequest] Configuration error:', error);\n throw error;\n }\n\n if (!config.FLOW_API_PASSPHRASE || config.FLOW_API_PASSPHRASE.trim() === '') {\n const error = new Error(\n 'Missing FLOW_API_PASSPHRASE. Please set the FLOW_API_PASSPHRASE environment variable or pass passphrase via config.',\n );\n LOGGER.error('[decryptFlowRequest] Configuration error:', error);\n throw error;\n }\n\n LOGGER.info('[decryptFlowRequest] Configuration validated');\n\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('[decryptFlowRequest] Missing required encryption properties in request body');\n throw new Error('Missing required encryption properties');\n }\n\n LOGGER.info('[decryptFlowRequest] Request body validated');\n\n // Handle both escaped and unescaped newlines\n let privatePem = config.FLOW_API_PRIVATE_PEM;\n if (privatePem.includes('\\\\n')) {\n privatePem = privatePem.replace(/\\\\n/g, '\\n');\n }\n\n const passphrase = config.FLOW_API_PASSPHRASE;\n\n const isPKCS1 = privatePem.includes('-----BEGIN RSA PRIVATE KEY-----');\n const isPKCS8 =\n privatePem.includes('-----BEGIN PRIVATE KEY-----') ||\n privatePem.includes('-----BEGIN ENCRYPTED PRIVATE KEY-----');\n\n LOGGER.info('[decryptFlowRequest] Loading private key', {\n format: isPKCS8 ? 'PKCS#8' : isPKCS1 ? 'PKCS#1' : 'Unknown',\n });\n\n let privateKey: KeyObject;\n try {\n // Try to create private key with passphrase\n if (passphrase) {\n privateKey = crypto.createPrivateKey({\n key: privatePem,\n format: 'pem',\n passphrase,\n });\n } else {\n privateKey = crypto.createPrivateKey(privatePem);\n }\n LOGGER.info('[decryptFlowRequest] Private key loaded successfully');\n } catch (error) {\n LOGGER.error('[decryptFlowRequest] Failed to load private key (first attempt):', {\n error: error instanceof Error ? error.message : error,\n hasPassphrase: !!passphrase,\n format: isPKCS8 ? 'PKCS#8' : isPKCS1 ? 'PKCS#1' : 'Unknown',\n });\n\n // If PKCS#1 key failed, try to convert it to PKCS#8 format automatically\n if (isPKCS1 && passphrase) {\n try {\n LOGGER.info('[decryptFlowRequest] Attempting to convert PKCS#1 to PKCS#8 format');\n\n // First, load the PKCS#1 key with passphrase\n const pkcs1Key = crypto.createPrivateKey({\n key: privatePem,\n format: 'pem',\n passphrase,\n });\n\n // Export it as PKCS#8 with the same passphrase\n const pkcs8Pem = pkcs1Key.export({\n type: 'pkcs8',\n format: 'pem',\n cipher: 'aes-256-cbc',\n passphrase,\n });\n\n // Now create the private key from PKCS#8 format\n privateKey = crypto.createPrivateKey({\n key: pkcs8Pem as string,\n format: 'pem',\n passphrase,\n });\n\n LOGGER.info('[decryptFlowRequest] Successfully converted PKCS#1 to PKCS#8 and loaded private key');\n } catch (conversionError) {\n LOGGER.error('[decryptFlowRequest] Failed to convert PKCS#1 to PKCS#8:', {\n error: conversionError instanceof Error ? conversionError.message : conversionError,\n });\n\n // Provide helpful error message\n let errorMessage = `Failed to parse private key. Error: ${error instanceof Error ? error.message : error}`;\n errorMessage += '\\n\\nYour key is in PKCS#1 format with unsupported encryption (DES-EDE3-CBC).';\n errorMessage += '\\nPlease convert it to PKCS#8 format using:';\n errorMessage += '\\n openssl pkcs8 -topk8 -inform PEM -outform PEM -in old_key.pem -out new_key.pem';\n\n throw new Error(errorMessage);\n }\n } else {\n // Provide helpful error message\n let errorMessage = `Failed to parse private key. Error: ${error instanceof Error ? error.message : error}`;\n\n if (isPKCS1) {\n errorMessage += '\\n\\nYour key is in PKCS#1 format (-----BEGIN RSA PRIVATE KEY-----).';\n errorMessage += '\\nPlease convert it to PKCS#8 format using:';\n errorMessage += '\\n openssl pkcs8 -topk8 -inform PEM -outform PEM -in old_key.pem -out new_key.pem';\n } else if (!isPKCS8) {\n errorMessage += '\\n\\nYour key format is not recognized. Please ensure it is in PKCS#8 format.';\n }\n\n throw new Error(errorMessage);\n }\n }\n\n let decryptedAesKey: Buffer;\n\n try {\n LOGGER.info('[decryptFlowRequest] Decrypting AES key with RSA private 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 LOGGER.info('[decryptFlowRequest] AES key decrypted successfully');\n } catch (error) {\n LOGGER.error('[decryptFlowRequest] 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('[decryptFlowRequest] Decrypting flow data with AES-128-GCM');\n\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('[decryptFlowRequest] Flow request decrypted successfully');\n\n return {\n decryptedBody: JSON.parse(decryptedJSONString),\n aesKeyBuffer: decryptedAesKey,\n initialVectorBuffer,\n };\n}\n\n/**\n * Encrypt a WhatsApp Flow response (Node.js only; see {@link encryptFlowResponseAsync} for every runtime)\n * @param response - Response object to encrypt\n * @param aesKeyBuffer - AES key buffer from the decrypted request\n * @param initialVectorBuffer - Initial vector buffer from the decrypted request\n * @returns Base64-encoded encrypted response\n * @throws {Error} If encryption fails\n */\nexport function encryptFlowResponse(response: any, aesKeyBuffer: Buffer, initialVectorBuffer: Buffer): string {\n LOGGER.info('[encryptFlowResponse] Starting Flow response encryption');\n\n const crypto = requireNodeCrypto('encryptFlowResponse');\n\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 LOGGER.info('[encryptFlowResponse] Encrypting response with AES-128-GCM');\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('[encryptFlowResponse] Flow response encrypted successfully');\n\n return encryptedResponse;\n } catch (error) {\n LOGGER.error('[encryptFlowResponse] Response encryption failed:', error);\n throw new Error('Failed to encrypt response. Internal server error.');\n }\n}\n\n/**\n * Result of {@link decryptFlowRequestAsync}. Pass `aesKeyBuffer` and\n * `initialVectorBuffer` to {@link encryptFlowResponseAsync}.\n */\nexport type DecryptedFlowRequest = {\n decryptedBody: FlowEndpointRequest;\n aesKeyBuffer: Uint8Array<ArrayBuffer>;\n initialVectorBuffer: Uint8Array<ArrayBuffer>;\n};\n\nconst PEM_PATTERN = /-----BEGIN ([A-Z ]+)-----([\\s\\S]*?)-----END \\1-----/;\n\nlet cachedPrivateKey: { pem: string; passphrase: string; key: Promise<CryptoKey> } | undefined;\n\n/**\n * Turn a PEM private key into PKCS#8 DER bytes that Web Crypto can import.\n * Unencrypted PKCS#8 (`BEGIN PRIVATE KEY`) works everywhere. Encrypted PKCS#8\n * and PKCS#1 keys need `node:crypto` to unwrap, because Web Crypto has no\n * passphrase support; on runtimes without it a descriptive error is thrown.\n */\nfunction privatePemToPkcs8Der(privatePem: string, passphrase: string): Uint8Array<ArrayBuffer> {\n const match = PEM_PATTERN.exec(privatePem);\n if (!match) {\n throw new Error('Failed to parse private key. Expected a PEM encoded PKCS#8 private key.');\n }\n const label = match[1];\n if (label === 'PRIVATE KEY') {\n return base64ToBytes((match[2] ?? '').replace(/\\s+/g, ''));\n }\n\n const crypto = getNodeCrypto();\n if (!crypto) {\n throw new Error(\n `Failed to parse private key. \"${label}\" keys need node:crypto, which this runtime lacks. ` +\n 'Convert the key to an unencrypted PKCS#8 key and keep it in a secret store:' +\n '\\n openssl pkcs8 -topk8 -nocrypt -in private.pem -out private-pkcs8.pem',\n );\n }\n try {\n const keyObject = crypto.createPrivateKey({\n key: privatePem,\n format: 'pem',\n passphrase: passphrase || undefined,\n });\n const der = keyObject.export({ type: 'pkcs8', format: 'der' });\n return new Uint8Array(der);\n } catch (error) {\n throw new Error(`Failed to parse private key. Error: ${error instanceof Error ? error.message : error}`);\n }\n}\n\nfunction importFlowPrivateKey(privatePem: string, passphrase: string): Promise<CryptoKey> {\n if (cachedPrivateKey && cachedPrivateKey.pem === privatePem && cachedPrivateKey.passphrase === passphrase) {\n return cachedPrivateKey.key;\n }\n const key = (async () =>\n getSubtle().importKey(\n 'pkcs8',\n privatePemToPkcs8Der(privatePem, passphrase),\n { name: 'RSA-OAEP', hash: 'SHA-256' },\n false,\n ['decrypt'],\n ))();\n cachedPrivateKey = { pem: privatePem, passphrase, key };\n // Do not keep a rejected promise around; a corrected config should retry.\n key.catch(() => {\n if (cachedPrivateKey?.key === key) cachedPrivateKey = undefined;\n });\n return key;\n}\n\n/**\n * Decrypt a WhatsApp Flow request with Web Crypto. Works on Node.js, Bun, Deno,\n * Cloudflare Workers and Vercel Edge.\n *\n * On runtimes without `node:crypto` the private key must be an unencrypted\n * PKCS#8 PEM (`-----BEGIN PRIVATE KEY-----`); the passphrase is then ignored.\n *\n * @param body - Encrypted request body containing encrypted_aes_key, encrypted_flow_data, and initial_vector\n * @param config - WABA configuration containing FLOW_API_PRIVATE_PEM and (for encrypted keys) FLOW_API_PASSPHRASE\n * @throws {Error} If required encryption properties are missing or decryption fails\n */\nexport async function decryptFlowRequestAsync(body: any, config: WabaConfigType): Promise<DecryptedFlowRequest> {\n if (!config.FLOW_API_PRIVATE_PEM || config.FLOW_API_PRIVATE_PEM.trim() === '') {\n throw new Error(\n 'Missing FLOW_API_PRIVATE_PEM. Please set the FLOW_API_PRIVATE_PEM environment variable or pass privatePem via config.',\n );\n }\n\n const { encrypted_aes_key, encrypted_flow_data, initial_vector } = body ?? {};\n if (!encrypted_aes_key || !encrypted_flow_data || !initial_vector) {\n throw new Error('Missing required encryption properties');\n }\n\n let privatePem = config.FLOW_API_PRIVATE_PEM;\n if (privatePem.includes('\\\\n')) {\n privatePem = privatePem.replace(/\\\\n/g, '\\n');\n }\n\n const subtle = getSubtle();\n const privateKey = await importFlowPrivateKey(privatePem, config.FLOW_API_PASSPHRASE || '');\n\n let aesKeyBuffer: Uint8Array<ArrayBuffer>;\n try {\n aesKeyBuffer = new Uint8Array(\n await subtle.decrypt({ name: 'RSA-OAEP' }, privateKey, base64ToBytes(encrypted_aes_key)),\n );\n } catch (error) {\n LOGGER.error('[decryptFlowRequestAsync] Failed to decrypt AES key:', error);\n throw new Error('Failed to decrypt the request. Please verify your private key.');\n }\n\n const initialVectorBuffer = base64ToBytes(initial_vector);\n const aesKey = await subtle.importKey('raw', aesKeyBuffer, { name: 'AES-GCM' }, false, ['decrypt']);\n // Meta sends ciphertext || 16-byte tag, which is exactly what Web Crypto expects.\n const decrypted = await subtle.decrypt(\n { name: 'AES-GCM', iv: initialVectorBuffer, tagLength: 128 },\n aesKey,\n base64ToBytes(encrypted_flow_data),\n );\n\n return {\n decryptedBody: JSON.parse(utf8Decode(new Uint8Array(decrypted))),\n aesKeyBuffer,\n initialVectorBuffer,\n };\n}\n\n/**\n * Encrypt a WhatsApp Flow response with Web Crypto. Works on every runtime.\n * @param response - Response object to encrypt\n * @param aesKeyBuffer - AES key from {@link decryptFlowRequestAsync} (a Node.js Buffer also works)\n * @param initialVectorBuffer - Initial vector from {@link decryptFlowRequestAsync} (a Node.js Buffer also works)\n * @returns Base64-encoded encrypted response\n */\nexport async function encryptFlowResponseAsync(\n response: any,\n aesKeyBuffer: Uint8Array,\n initialVectorBuffer: Uint8Array,\n): Promise<string> {\n const flippedIv = new Uint8Array(initialVectorBuffer.length);\n for (let i = 0; i < initialVectorBuffer.length; i++) {\n flippedIv[i] = ~(initialVectorBuffer[i] ?? 0) & 0xff;\n }\n\n try {\n const subtle = getSubtle();\n const aesKey = await subtle.importKey('raw', new Uint8Array(aesKeyBuffer), { name: 'AES-GCM' }, false, [\n 'encrypt',\n ]);\n const encrypted = await subtle.encrypt(\n { name: 'AES-GCM', iv: flippedIv, tagLength: 128 },\n aesKey,\n utf8Encode(JSON.stringify(response || {})),\n );\n return bytesToBase64(new Uint8Array(encrypted));\n } catch (error) {\n LOGGER.error('[encryptFlowResponseAsync] Response encryption failed:', error);\n throw new Error('Failed to encrypt response. Internal server error.');\n }\n}\n","// Docs: https://developers.facebook.com/docs/graph-api/overview/rate-limiting/\n\n/**\n * Usage percentages reported by Meta. Each value is the share (0-100+) of the allowance used in the\n * current rolling window.\n */\nexport interface RateLimitUsage {\n /** Percentage of calls made (`call_count`). */\n callCount?: number;\n /** Percentage of total CPU time used (`total_cputime`). */\n totalCputime?: number;\n /** Percentage of total time used (`total_time`). */\n totalTime?: number;\n}\n\n/** One entry of the `X-Business-Use-Case-Usage` header. */\nexport interface BusinessUseCaseUsage extends RateLimitUsage {\n /** The business object the entry belongs to (for WhatsApp, usually the WABA or phone number ID). */\n businessId: string;\n /** Rate limit type, e.g. `whatsapp_business_management` or `whatsapp`. */\n type?: string;\n /**\n * `estimated_time_to_regain_access`: \"Time, in minutes, until calls will no longer be throttled.\"\n * `0` when not throttled.\n */\n estimatedTimeToRegainAccessMinutes?: number;\n /** `ads_api_access_tier`, only sent for Marketing API use cases. */\n adsApiAccessTier?: string;\n}\n\n/**\n * Rate limit information parsed from a Graph API response.\n *\n * WhatsApp Cloud API responses carry `x-business-use-case-usage` (types\n * `whatsapp_business_management` and `whatsapp`) and `x-app-usage`; throttled responses may add\n * `Retry-After` (seconds).\n */\nexport interface RateLimitInfo {\n /** Parsed `X-App-Usage` header (platform rate limits). */\n appUsage?: RateLimitUsage;\n /** Parsed `X-Business-Use-Case-Usage` header, flattened across business IDs. Empty when absent. */\n businessUseCaseUsage: BusinessUseCaseUsage[];\n /** Parsed `Retry-After` header in milliseconds (seconds or HTTP-date form). */\n retryAfterMs?: number;\n /**\n * Highest usage percentage across every parsed metric, handy for alerting before Meta starts\n * throttling (it throttles at 100).\n */\n maxUsagePercent?: number;\n /**\n * How long Meta asks you to wait, in milliseconds: the larger of `retryAfterMs` and the largest\n * `estimatedTimeToRegainAccessMinutes`. Undefined when Meta gave no wait time.\n */\n retryDelayMs?: number;\n}\n\n/** Headers accepted by {@link parseRateLimitHeaders}. */\nexport type RateLimitHeadersInput =\n | Headers\n | Record<string, string | string[] | undefined>\n | { get(name: string): string | null };\n\nfunction readHeader(headers: RateLimitHeadersInput, name: string): string | undefined {\n if (typeof (headers as { get?: unknown }).get === 'function') {\n const value = (headers as { get(name: string): string | null }).get(name);\n return value ?? undefined;\n }\n const record = headers as Record<string, string | string[] | undefined>;\n const key = Object.keys(record).find((k) => k.toLowerCase() === name);\n if (key === undefined) return undefined;\n const value = record[key];\n return Array.isArray(value) ? value[0] : value;\n}\n\nfunction parseJson(value: string | undefined): unknown {\n if (value === undefined || value.trim() === '') return undefined;\n try {\n return JSON.parse(value);\n } catch {\n return undefined;\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction num(value: unknown): number | undefined {\n if (typeof value === 'number' && Number.isFinite(value)) return value;\n if (typeof value === 'string' && value.trim() !== '' && Number.isFinite(Number(value))) return Number(value);\n return undefined;\n}\n\nfunction str(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction parseUsage(value: Record<string, unknown>): RateLimitUsage {\n const usage: RateLimitUsage = {};\n const callCount = num(value.call_count);\n const totalCputime = num(value.total_cputime);\n const totalTime = num(value.total_time);\n if (callCount !== undefined) usage.callCount = callCount;\n if (totalCputime !== undefined) usage.totalCputime = totalCputime;\n if (totalTime !== undefined) usage.totalTime = totalTime;\n return usage;\n}\n\nfunction parseBusinessUseCaseUsage(value: unknown): BusinessUseCaseUsage[] {\n if (!isRecord(value)) return [];\n const entries: BusinessUseCaseUsage[] = [];\n for (const [businessId, list] of Object.entries(value)) {\n if (!Array.isArray(list)) continue;\n for (const item of list) {\n if (!isRecord(item)) continue;\n const entry: BusinessUseCaseUsage = { businessId, ...parseUsage(item) };\n const type = str(item.type);\n const regain = num(item.estimated_time_to_regain_access);\n const tier = str(item.ads_api_access_tier);\n if (type !== undefined) entry.type = type;\n if (regain !== undefined) entry.estimatedTimeToRegainAccessMinutes = regain;\n if (tier !== undefined) entry.adsApiAccessTier = tier;\n entries.push(entry);\n }\n }\n return entries;\n}\n\n/**\n * Parses a `Retry-After` value (delta-seconds or HTTP-date) into milliseconds.\n * Returns undefined for missing or malformed values.\n */\nexport function parseRetryAfter(value: string | null | undefined, now: number = Date.now()): number | undefined {\n if (value === null || value === undefined) return undefined;\n const trimmed = value.trim();\n if (trimmed === '') return undefined;\n if (/^\\d+(\\.\\d+)?$/.test(trimmed)) return Math.round(Number(trimmed) * 1000);\n // An HTTP-date always names a weekday/month; this rejects values such as \"-1\" that Date.parse accepts.\n if (!/[a-z]/i.test(trimmed)) return undefined;\n const date = Date.parse(trimmed);\n if (!Number.isFinite(date)) return undefined;\n return Math.max(0, date - now);\n}\n\n/**\n * Parses Meta's rate limit headers (`X-App-Usage`, `X-Business-Use-Case-Usage`, `Retry-After`).\n * Header names are matched case-insensitively. Malformed JSON or values are ignored, never thrown.\n *\n * Returns undefined when none of the headers are present.\n *\n * @see {@link https://developers.facebook.com/docs/graph-api/overview/rate-limiting/ | Graph API rate limiting}\n *\n * @example\n * ```ts\n * const info = parseRateLimitHeaders(response.headers);\n * if ((info?.maxUsagePercent ?? 0) > 80) slowDown();\n * ```\n */\nexport function parseRateLimitHeaders(headers: RateLimitHeadersInput | null | undefined): RateLimitInfo | undefined {\n if (!headers) return undefined;\n\n const appRaw = readHeader(headers, 'x-app-usage');\n const bucRaw = readHeader(headers, 'x-business-use-case-usage');\n const retryAfterRaw = readHeader(headers, 'retry-after');\n if (appRaw === undefined && bucRaw === undefined && retryAfterRaw === undefined) return undefined;\n\n const info: RateLimitInfo = { businessUseCaseUsage: [] };\n\n const appJson = parseJson(appRaw);\n if (isRecord(appJson)) info.appUsage = parseUsage(appJson);\n\n info.businessUseCaseUsage = parseBusinessUseCaseUsage(parseJson(bucRaw));\n\n const retryAfterMs = parseRetryAfter(retryAfterRaw);\n if (retryAfterMs !== undefined) info.retryAfterMs = retryAfterMs;\n\n const usages: RateLimitUsage[] = [...(info.appUsage ? [info.appUsage] : []), ...info.businessUseCaseUsage];\n const percents = usages.flatMap((u) =>\n [u.callCount, u.totalCputime, u.totalTime].filter((v): v is number => v !== undefined),\n );\n if (percents.length > 0) info.maxUsagePercent = Math.max(...percents);\n\n const waits = [\n ...(retryAfterMs !== undefined ? [retryAfterMs] : []),\n ...info.businessUseCaseUsage\n .map((u) => u.estimatedTimeToRegainAccessMinutes)\n .filter((m): m is number => m !== undefined && m > 0)\n .map((m) => m * 60_000),\n ];\n if (waits.length > 0) info.retryDelayMs = Math.max(...waits);\n\n return info;\n}\n","import type { HttpMethodsEnum } from '../../types/enums';\nimport type {\n HttpsClientClass,\n HttpsClientResponseClass,\n ResponseHeaders,\n ResponseJSONBody,\n} from '../../types/httpsClient';\nimport Logger from '../logger';\nimport { isDebugEnv } from '../runtime';\n\nconst LIB_NAME = 'HttpsClient';\nconst LOGGER = new Logger(LIB_NAME, isDebugEnv());\n\nexport default class HttpsClient implements HttpsClientClass {\n /**\n * Kept for backwards compatibility. Requests go through the global `fetch`,\n * which manages its own connection pool, so there is nothing to clear.\n */\n clearSockets(): boolean {\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 const error = new Error(`Failed to parse response body to JSON: ${(err as Error).message}`);\n error.cause = err;\n throw error;\n }\n }\n}\n","import {\n DEFAULT_CLOUD_API_VERSION,\n DEFAULT_RETRY_BACKOFF,\n DEFAULT_RETRY_INITIAL_DELAY_MS,\n DEFAULT_RETRY_MAX_ATTEMPTS,\n DEFAULT_RETRY_MAX_SERVER_DELAY_MS,\n GRAPH_API_HOST,\n GRAPH_API_PROTOCOL,\n} from '../../config/defaults';\nimport type { RateLimitInfoListener, RetryConfig } from '../../types/config';\nimport type { HttpMethodsEnum } from '../../types/enums';\nimport type { RequesterClass, UrlEncodedFormBody } from '../../types/request';\nimport {\n createWhatsAppApiError,\n isMetaError,\n normalizeMetaError,\n WhatsAppError,\n WhatsAppNetworkError,\n WhatsAppThrottlingError,\n} from '../isMetaError';\nimport Logger from '../logger';\nimport { parseRateLimitHeaders, type RateLimitInfo } from '../rateLimit';\nimport { isDebugEnv } from '../runtime';\nimport HttpsClient from './httpsClient';\n\nconst LIB_NAME = 'REQUESTER';\nconst LOGGER = new Logger(LIB_NAME, isDebugEnv());\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\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> = GRAPH_API_PROTOCOL;\n private retryConfig: RetryConfig | undefined;\n private onRateLimitInfo: RateLimitInfoListener | undefined;\n private lastRateLimitInfo: RateLimitInfo | undefined;\n\n constructor(\n apiVersion: string,\n phoneNumberId: number,\n accessToken: string,\n businessAcctId: string,\n userAgent: string,\n retryConfig?: RetryConfig,\n onRateLimitInfo?: RateLimitInfoListener,\n ) {\n this.client = new HttpsClient();\n this.host = GRAPH_API_HOST;\n this.apiVersion = this.normalizeApiVersion(apiVersion);\n this.phoneNumberId = phoneNumberId;\n this.accessToken = accessToken;\n this.businessAcctId = businessAcctId;\n this.userAgent = userAgent;\n this.retryConfig = retryConfig;\n this.onRateLimitInfo = onRateLimitInfo;\n }\n\n /**\n * Rate limit headers of the most recent response that carried any, or undefined.\n * With concurrent requests this is whichever response finished last; use the\n * `onRateLimitInfo` config callback to see every response.\n */\n getLastRateLimitInfo(): RateLimitInfo | undefined {\n return this.lastRateLimitInfo;\n }\n\n private captureRateLimitInfo(\n response: { headers?: () => unknown; statusCode?: () => number },\n method: string,\n endpoint: string,\n ): RateLimitInfo | undefined {\n if (typeof response.headers !== 'function') return undefined;\n const info = parseRateLimitHeaders(response.headers() as Parameters<typeof parseRateLimitHeaders>[0]);\n if (!info) return undefined;\n\n this.lastRateLimitInfo = info;\n if (this.onRateLimitInfo) {\n try {\n const statusCode = typeof response.statusCode === 'function' ? response.statusCode() : 0;\n // Observe asynchronous failures too, without delaying the API response on telemetry.\n void Promise.resolve(this.onRateLimitInfo(info, { method, endpoint, statusCode })).catch(\n (error: unknown) => {\n LOGGER.log(`onRateLimitInfo listener threw: ${error instanceof Error ? error.message : error}`);\n },\n );\n } catch (error) {\n LOGGER.log(`onRateLimitInfo listener threw: ${error instanceof Error ? error.message : error}`);\n }\n }\n return info;\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 `${this.apiVersion}/${endpoint}`;\n }\n\n private normalizeApiVersion(apiVersion?: string): string {\n if (!apiVersion) return DEFAULT_CLOUD_API_VERSION;\n\n const trimmed = apiVersion.trim();\n if (/^v\\d+\\.\\d+$/.test(trimmed)) return trimmed;\n if (/^\\d+\\.\\d+$/.test(trimmed)) return `v${trimmed}`;\n if (/^v\\d+$/.test(trimmed)) return `${trimmed}.0`;\n if (/^\\d+$/.test(trimmed)) return `v${trimmed}.0`;\n\n return trimmed;\n }\n\n private buildRequestTarget(endpoint: string): { host: string; path: string; displayUrl: string } {\n if (/^https?:\\/\\//.test(endpoint)) {\n const url = new URL(endpoint);\n const path = `${url.pathname}${url.search}`.replace(/^\\//, '');\n return {\n host: url.host,\n path,\n displayUrl: url.toString(),\n };\n }\n\n const path = this.buildCAPIPath(endpoint.replace(/^\\//, ''));\n return {\n host: this.host,\n path,\n displayUrl: `${this.protocol.toLowerCase()}//${this.host}/${path}`,\n };\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 const maxAttempts = this.retryConfig?.maxAttempts ?? DEFAULT_RETRY_MAX_ATTEMPTS;\n const initialDelayMs = this.retryConfig?.initialDelayMs ?? DEFAULT_RETRY_INITIAL_DELAY_MS;\n const backoff = this.retryConfig?.backoff ?? DEFAULT_RETRY_BACKOFF;\n const respectServerDelay = this.retryConfig?.respectServerDelay ?? true;\n const maxServerDelayMs = this.retryConfig?.maxServerDelayMs ?? DEFAULT_RETRY_MAX_SERVER_DELAY_MS;\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 requestTarget = this.buildRequestTarget(endpoint);\n LOGGER.log(`${method} : ${requestTarget.displayUrl} (${effectiveContentType})`);\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n const shouldSendBody = method === 'POST' || method === 'PUT' || method === 'DELETE';\n\n const response = await this.client.sendRequest(\n requestTarget.host,\n requestTarget.path,\n method,\n this.buildHeader(effectiveContentType, additionalHeaders),\n timeout,\n shouldSendBody ? body : undefined,\n );\n\n const rateLimit = this.captureRateLimitInfo(response, method, endpoint);\n\n if (!response.rawResponse().ok) {\n let errorData: unknown = null;\n try {\n errorData = await response.json();\n } catch {\n errorData = null;\n }\n\n const metaError = normalizeMetaError(errorData, response.statusCode());\n const apiError = createWhatsAppApiError(metaError.error, response.statusCode());\n if (rateLimit) apiError.rateLimit = rateLimit;\n throw apiError;\n }\n\n return response;\n } catch (error) {\n if (error instanceof WhatsAppThrottlingError && attempt < maxAttempts) {\n const backoffDelay =\n backoff === 'exponential' ? initialDelayMs * 2 ** (attempt - 1) : initialDelayMs;\n const serverDelay = respectServerDelay ? error.rateLimit?.retryDelayMs : undefined;\n const delay =\n serverDelay !== undefined\n ? Math.max(backoffDelay, Math.min(serverDelay, Math.max(0, maxServerDelayMs)))\n : backoffDelay;\n LOGGER.log(`Throttled (attempt ${attempt}/${maxAttempts}). Retrying in ${delay}ms...`);\n await sleep(delay);\n continue;\n }\n\n if (error instanceof WhatsAppError) {\n throw error;\n }\n if (isMetaError(error)) {\n throw createWhatsAppApiError(error.error);\n }\n\n const message = error instanceof Error ? error.message : 'Network error occurred';\n throw new WhatsAppNetworkError(message, error);\n }\n }\n\n // Unreachable in practice — loop always returns or throws.\n // Required for TypeScript return type inference.\n throw new WhatsAppThrottlingError(\n 'Max retry attempts exceeded',\n { message: 'Max retry attempts exceeded', type: 'ThrottlingError', code: 130429, fbtrace_id: '' },\n 429,\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 updateTimeout(timeout: number): void {\n LOGGER.log(`Timeout updated to ${timeout}ms`);\n }\n\n updateAccessToken(accessToken: string): void {\n (this as { accessToken: string }).accessToken = accessToken;\n LOGGER.log('Access token updated');\n }\n\n async sendUrlEncodedForm<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n formData: UrlEncodedFormBody,\n additionalHeaders?: Record<string, string>,\n ): Promise<T> {\n const urlParams = new URLSearchParams();\n for (const [key, value] of Object.entries(formData)) {\n if (Array.isArray(value)) {\n for (const item of value) {\n urlParams.append(key, item);\n }\n } else {\n urlParams.append(key, value);\n }\n }\n\n const urlEncodedBody = urlParams.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 { readEnv } from './runtime';\n\nexport function printLogo() {\n // Skip logo output in test environment\n if (\n readEnv('NODE_ENV') === 'test' ||\n readEnv('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 { describeRuntime } from './runtime';\n\n/**\n * SDK version, replaced with the package.json version at build time\n * (see `define` in tsdown.config.ts and vitest.config.ts).\n */\ndeclare const __SDK_VERSION__: string;\n\n/**\n * Get SDK version from package.json\n */\nexport function getVersion(): string {\n return typeof __SDK_VERSION__ === 'string' ? __SDK_VERSION__ : 'unknown';\n}\n\n/**\n * Generate User-Agent string following official SDK pattern\n */\nexport function getUserAgent(): string {\n return `WhatsApp-Nodejs-SDK/${getVersion()} (${describeRuntime()})`;\n}\n","import {\n BlockUsersApi,\n BusinessApi,\n BusinessProfileApi,\n CallingApi,\n CommerceApi,\n ContactBookApi,\n EncryptionApi,\n FlowApi,\n GroupsApi,\n MarketingMessagesApi,\n MediaApi,\n MessageApi,\n MessageHistoryApi,\n PaymentsApi,\n PhoneNumberApi,\n QrCodeApi,\n RegistrationApi,\n SolutionsApi,\n TemplateApi,\n ThreadControlApi,\n TwoStepVerificationApi,\n WabaApi,\n} from '../../api';\nimport { importConfig } from '../../config/importConfig';\nimport type { WabaConfigType, WhatsAppConfig } from '../../types/config';\nimport * as SDKEnums from '../../types/enums';\nimport { formatConfigTable } from '../../utils/configTable';\nimport { type EncryptionKeyPair, generateEncryption } from '../../utils/flowEncryptionUtils';\nimport Requester from '../../utils/http/request';\nimport Logger from '../../utils/logger';\nimport { printLogo } from '../../utils/logoConsole';\nimport type { RateLimitInfo } from '../../utils/rateLimit';\nimport { isDebugEnv } from '../../utils/runtime';\nimport { getUserAgent, getVersion } from '../../utils/version';\n\nconst LIB_NAME = 'WHATSAPP';\nconst LOGGER = new Logger(LIB_NAME, isDebugEnv());\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 blockUsers: BlockUsersApi;\n business: BusinessApi;\n calling: CallingApi;\n commerce: CommerceApi;\n contactBook: ContactBookApi;\n groups: GroupsApi;\n marketingMessages: MarketingMessagesApi;\n messageHistory: MessageHistoryApi;\n messages: MessageApi;\n media: MediaApi;\n payments: PaymentsApi;\n phoneNumbers: PhoneNumberApi;\n solutions: SolutionsApi;\n threadControl: ThreadControlApi;\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 this.config.retry,\n this.config.onRateLimitInfo,\n );\n\n this.blockUsers = new BlockUsersApi(this.config, this.requester);\n this.business = new BusinessApi(this.config, this.requester);\n this.calling = new CallingApi(this.config, this.requester);\n this.commerce = new CommerceApi(this.config, this.requester);\n this.contactBook = new ContactBookApi(this.config, this.requester);\n this.groups = new GroupsApi(this.config, this.requester);\n this.marketingMessages = new MarketingMessagesApi(this.config, this.requester);\n this.messageHistory = new MessageHistoryApi(this.config, this.requester);\n this.messages = new MessageApi(this.config, this.requester);\n this.media = new MediaApi(this.config, this.requester);\n this.payments = new PaymentsApi(this.config, this.requester);\n this.phoneNumbers = new PhoneNumberApi(this.config, this.requester);\n this.solutions = new SolutionsApi(this.config, this.requester);\n this.threadControl = new ThreadControlApi(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 this.requester.updateTimeout(timeout);\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 this.requester.updateAccessToken(accessToken);\n LOGGER.log('Access token updated');\n }\n\n /**\n * Rate limit headers (`X-App-Usage`, `X-Business-Use-Case-Usage`, `Retry-After`) of the most\n * recent response that carried any, or undefined before the first such response. With\n * concurrent requests this reflects whichever finished last; pass `onRateLimitInfo` in the\n * config to observe every response.\n */\n getLastRateLimitInfo(): RateLimitInfo | undefined {\n return this.requester.getLastRateLimitInfo();\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 /**\n * Generate RSA encryption key pair for WhatsApp Business Flow API\n *\n * This method generates a 2048-bit RSA key pair with:\n * - Public key in SPKI format (PEM)\n * - Private key in PKCS#8 format (PEM) encrypted with AES-256-CBC\n *\n * @param passphrase - Optional passphrase to encrypt the private key. If not provided, uses FLOW_API_PASSPHRASE from config\n * @returns Object containing passphrase, privateKey, and publicKey\n * @throws {Error} If passphrase is empty or key generation fails\n * @throws {Error} If not running in Node.js environment\n *\n * @see https://developers.facebook.com/docs/whatsapp/cloud-api/reference/whatsapp-business-encryption/\n *\n * @example\n * ```typescript\n * const wa = new WhatsApp();\n *\n * // Uses FLOW_API_PASSPHRASE from environment/config\n * const keys = wa.generateEncryption();\n *\n * // Or provide custom passphrase\n * const customKeys = wa.generateEncryption('my-secret-passphrase');\n *\n * console.log('Public Key:', keys.publicKey);\n * console.log('Private Key:', keys.privateKey);\n * ```\n */\n generateEncryption(passphrase?: string): EncryptionKeyPair {\n // If no passphrase provided, try to use from config\n const effectivePassphrase = passphrase || this.config[SDKEnums.WabaConfigEnum.Passphrase];\n return generateEncryption(effectivePassphrase);\n }\n}\n","import type { DedupeStore, WebhookDedupeConfig } from '../../types/config';\n\n/** Default time a dedupe key is remembered: 24 hours. */\nexport const DEFAULT_DEDUPE_TTL_SECONDS = 86_400;\n\n/** Default number of keys kept by {@link MemoryDedupeStore}. */\nexport const DEFAULT_MEMORY_DEDUPE_MAX_ENTRIES = 10_000;\n\nexport interface MemoryDedupeStoreOptions {\n /** Most keys kept at once; the least recently seen key is dropped first. Defaults to 10,000. */\n maxEntries?: number;\n}\n\n/**\n * Bounded in-memory {@link DedupeStore} with per-key TTL and least recently\n * seen eviction. This is the default store for `dedupe`.\n *\n * Single instance only: it lives in this process's memory, so it does not see\n * deliveries handled by other instances and forgets everything on restart (and\n * on each cold start of a serverless function). Use a shared store such as\n * Redis when you run more than one instance.\n */\nexport class MemoryDedupeStore implements DedupeStore {\n private readonly maxEntries: number;\n /** key -> expiry time in ms. Map order doubles as recency order (oldest first). */\n private readonly entries = new Map<string, number>();\n\n constructor(options: MemoryDedupeStoreOptions = {}) {\n const maxEntries = options.maxEntries ?? DEFAULT_MEMORY_DEDUPE_MAX_ENTRIES;\n if (!Number.isInteger(maxEntries) || maxEntries < 1) {\n throw new Error(`MemoryDedupeStore maxEntries must be a positive integer, got ${maxEntries}`);\n }\n this.maxEntries = maxEntries;\n }\n\n async has(key: string): Promise<boolean> {\n return this.lookup(key, Date.now()) !== undefined;\n }\n\n async setIfAbsent(key: string, ttlSeconds: number): Promise<boolean> {\n const now = Date.now();\n const expiresAt = this.lookup(key, now);\n if (expiresAt !== undefined) {\n // Mark as recently seen without extending the TTL.\n this.entries.delete(key);\n this.entries.set(key, expiresAt);\n return false;\n }\n this.entries.set(key, now + ttlSeconds * 1000);\n this.evict(now);\n return true;\n }\n\n /** Number of keys currently held (expired keys may still be counted until evicted). */\n get size(): number {\n return this.entries.size;\n }\n\n /** Forget every key. */\n clear(): void {\n this.entries.clear();\n }\n\n private lookup(key: string, now: number): number | undefined {\n const expiresAt = this.entries.get(key);\n if (expiresAt === undefined) return undefined;\n if (expiresAt <= now) {\n this.entries.delete(key);\n return undefined;\n }\n return expiresAt;\n }\n\n private evict(now: number): void {\n // Recency changes on duplicate deliveries without extending TTL, so\n // expiry order can differ from Map order. Reclaim expired keys first.\n for (const [key, expiresAt] of this.entries) {\n if (expiresAt <= now) this.entries.delete(key);\n }\n for (const key of this.entries.keys()) {\n if (this.entries.size <= this.maxEntries) break;\n this.entries.delete(key);\n }\n }\n}\n\n/** Dedupe settings after defaults are applied. */\nexport type ResolvedDedupe = {\n store: DedupeStore;\n ttlSeconds: number;\n};\n\n/** Apply defaults to the `dedupe` config option. Returns undefined when dedupe is off. */\nexport function resolveDedupe(config: boolean | WebhookDedupeConfig | undefined): ResolvedDedupe | undefined {\n if (!config) return undefined;\n const options = config === true ? {} : config;\n const ttlSeconds = options.ttlSeconds ?? DEFAULT_DEDUPE_TTL_SECONDS;\n if (!Number.isFinite(ttlSeconds) || ttlSeconds <= 0) {\n throw new Error(`dedupe.ttlSeconds must be a positive number, got ${ttlSeconds}`);\n }\n return { store: options.store ?? new MemoryDedupeStore(), ttlSeconds };\n}\n","import {\n FlowActionEnum,\n type FlowDataExchangeRequest,\n type FlowEndpointRequest,\n type FlowErrorNotificationRequest,\n type 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 type { FlowEndpointRequest } from '../../../api/flow';\nimport { FlowTypeEnum } from '../../../api/flow/types';\nimport type { DedupeStore, WabaConfigType } from '../../../types/config';\nimport { MessageTypesEnum, WabaConfigEnum } from '../../../types/enums';\nimport { decryptFlowRequestAsync, encryptFlowResponseAsync } from '../../../utils/flowEncryptionUtils';\nimport { isFlowDataExchangeRequest, isFlowErrorRequest, isFlowPingRequest } from '../../../utils/flowTypeGuards';\nimport Logger from '../../../utils/logger';\nimport { hmacSha256Hex, isDebugEnv, requireNodeCrypto, timingSafeEqualString } from '../../../utils/runtime';\nimport type WhatsApp from '../../whatsapp/WhatsApp';\nimport { DEFAULT_DEDUPE_TTL_SECONDS } from '../dedupe';\nimport type {\n ConversationContext,\n MessageWebhookValue,\n NonMessageWebhookField,\n StatusWebhook,\n StatusWebhookValue,\n UserAction,\n UserActionsWebhookValue,\n WebhookFieldType,\n WebhookFieldValueMap,\n WebhookPayload,\n WebhookValue,\n WhatsAppMessage,\n} from '../types';\n\nconst LIB_NAME = 'WEBHOOK_UTILS';\nconst LOGGER = new Logger(LIB_NAME, isDebugEnv());\n\n/**\n * Processed message with metadata for handlers\n */\nexport type ProcessedMessage = {\n wabaId: string;\n phoneNumberId: string;\n displayPhoneNumber: string;\n profileName: string;\n message: WhatsAppMessage;\n /**\n * The message ID extracted from the appropriate location based on message type.\n * For most messages, this comes from message.id\n * For certain types like nfm_reply, this comes from message.context.id\n */\n messageId: string;\n /**\n * AI-generated conversation summary from `value.conversation_context`, present\n * under Conversation Routing when a thread is assigned to you without standby\n * history. Optional; never parse `summary.text`.\n */\n conversationContext?: ConversationContext;\n};\n\n/**\n * Processed status with metadata for handlers\n */\nexport type ProcessedStatus = {\n wabaId: string;\n phoneNumberId: string;\n displayPhoneNumber: string;\n status: StatusWebhook;\n};\n\n/**\n * Processed marketing message user action (link click or landing page view)\n * delivered as `user_actions` on the `messages` field. Marketing Messages API\n * for WhatsApp only. Branch on `action.action_type` and ignore unknown values.\n */\nexport type ProcessedUserAction = {\n wabaId: string;\n phoneNumberId: string;\n displayPhoneNumber: string;\n action: UserAction;\n};\n\n/**\n * What a handler for a non-`messages` webhook field receives: the WhatsApp\n * Business Account id and the change's `value`, typed by field name.\n */\nexport type ProcessedWebhookField<F extends NonMessageWebhookField> = {\n wabaId: string;\n value: WebhookFieldValueMap[F];\n};\n\n/**\n * Processed webhook field types for specialized handlers\n */\nexport type ProcessedAccountUpdate = ProcessedWebhookField<'account_update'>;\nexport type ProcessedAccountReviewUpdate = ProcessedWebhookField<'account_review_update'>;\nexport type ProcessedAccountAlerts = ProcessedWebhookField<'account_alerts'>;\nexport type ProcessedBusinessCapabilityUpdate = ProcessedWebhookField<'business_capability_update'>;\nexport type ProcessedPhoneNumberNameUpdate = ProcessedWebhookField<'phone_number_name_update'>;\nexport type ProcessedPhoneNumberQualityUpdate = ProcessedWebhookField<'phone_number_quality_update'>;\nexport type ProcessedMessageTemplateStatusUpdate = ProcessedWebhookField<'message_template_status_update'>;\nexport type ProcessedTemplateCategoryUpdate = ProcessedWebhookField<'template_category_update'>;\nexport type ProcessedMessageTemplateQualityUpdate = ProcessedWebhookField<'message_template_quality_update'>;\nexport type ProcessedFlows = ProcessedWebhookField<'flows'>;\nexport type ProcessedSecurity = ProcessedWebhookField<'security'>;\nexport type ProcessedHistory = ProcessedWebhookField<'history'>;\nexport type ProcessedSmbMessageEchoes = ProcessedWebhookField<'smb_message_echoes'>;\nexport type ProcessedSmbAppStateSync = ProcessedWebhookField<'smb_app_state_sync'>;\nexport type ProcessedAccountSettingsUpdate = ProcessedWebhookField<'account_settings_update'>;\nexport type ProcessedAutomaticEvents = ProcessedWebhookField<'automatic_events'>;\nexport type ProcessedBusinessStatusUpdate = ProcessedWebhookField<'business_status_update'>;\nexport type ProcessedBusinessUsernameUpdates = ProcessedWebhookField<'business_username_updates'>;\nexport type ProcessedCalls = ProcessedWebhookField<'calls'>;\nexport type ProcessedGroupLifecycleUpdate = ProcessedWebhookField<'group_lifecycle_update'>;\nexport type ProcessedGroupParticipantsUpdate = ProcessedWebhookField<'group_participants_update'>;\nexport type ProcessedGroupSettingsUpdate = ProcessedWebhookField<'group_settings_update'>;\nexport type ProcessedGroupStatusUpdate = ProcessedWebhookField<'group_status_update'>;\nexport type ProcessedMessageEchoes = ProcessedWebhookField<'message_echoes'>;\nexport type ProcessedMessageTemplateComponentsUpdate = ProcessedWebhookField<'message_template_components_update'>;\nexport type ProcessedMessagingHandovers = ProcessedWebhookField<'messaging_handovers'>;\nexport type ProcessedPartnerSolutions = ProcessedWebhookField<'partner_solutions'>;\nexport type ProcessedPaymentConfigurationUpdate = ProcessedWebhookField<'payment_configuration_update'>;\nexport type ProcessedStandby = ProcessedWebhookField<'standby'>;\nexport type ProcessedTemplateCorrectCategoryDetection = ProcessedWebhookField<'template_correct_category_detection'>;\nexport type ProcessedTrackingEvents = ProcessedWebhookField<'tracking_events'>;\nexport type ProcessedUserPreferences = ProcessedWebhookField<'user_preferences'>;\n\n// Type-specific processed messages for specialized handlers\nexport type TextProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Text }>;\n};\n\nexport type ImageProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Image }>;\n};\n\nexport type VideoProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Video }>;\n};\n\nexport type AudioProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Audio }>;\n};\n\nexport type DocumentProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Document }>;\n};\n\nexport type StickerProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Sticker }>;\n};\n\nexport type InteractiveProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Interactive }>;\n};\n\nexport type ButtonProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Button }>;\n};\n\nexport type LocationProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Location }>;\n};\n\nexport type ContactsProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Contacts }>;\n};\n\nexport type ReactionProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Reaction }>;\n};\n\nexport type OrderProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Order }>;\n};\n\nexport type SystemProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.System }>;\n};\n\n/**\n * Original HTTP request context for WhatsApp webhook handlers.\n *\n * The `rawBody` and `headers` values preserve the incoming webhook request so\n * callers can forward or verify the request according to Meta's request syntax.\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/create-webhook-endpoint/#request-syntax-1\n */\nexport type WebhookHandlerContext = {\n /** Original request headers from the incoming webhook request. */\n headers: Headers;\n /** Original request body string before JSON parsing or field filtering. */\n rawBody: string;\n /** Original request method. */\n method: string;\n /** Original request URL. */\n url: string;\n};\n\ntype WebhookHandler<TProcessed, TReturn = void> = (\n whatsapp: WhatsApp,\n processed: TProcessed,\n context: WebhookHandlerContext,\n) => TReturn | Promise<TReturn>;\n\nexport type MessageHandler = WebhookHandler<ProcessedMessage>;\nexport type StatusHandler = WebhookHandler<ProcessedStatus>;\nexport type UserActionHandler = WebhookHandler<ProcessedUserAction>;\nexport type FlowHandler = WebhookHandler<FlowEndpointRequest, any>;\nexport type RawWebhookHandler = WebhookHandler<WebhookPayload>;\n\n/** Handler for a non-`messages` webhook field; `processed.value` is typed by the field name. */\nexport type WebhookFieldHandler<F extends NonMessageWebhookField> = WebhookHandler<ProcessedWebhookField<F>>;\n\n/** Registered field handlers keyed by field name, as kept by `WebhookProcessor`. */\nexport type WebhookFieldHandlerMap = ReadonlyMap<NonMessageWebhookField, AnyWebhookFieldHandler>;\n\n/**\n * Field handler with the field type erased, for storage in a map. `on()`\n * guarantees each stored handler matches its key.\n */\n// biome-ignore lint/suspicious/noExplicitAny: the value type depends on the map key\ntype AnyWebhookFieldHandler = WebhookHandler<{ wabaId: string; value: any }>;\n\n// Webhook field handlers\nexport type AccountUpdateHandler = WebhookFieldHandler<'account_update'>;\nexport type AccountReviewUpdateHandler = WebhookFieldHandler<'account_review_update'>;\nexport type AccountAlertsHandler = WebhookFieldHandler<'account_alerts'>;\nexport type BusinessCapabilityUpdateHandler = WebhookFieldHandler<'business_capability_update'>;\nexport type PhoneNumberNameUpdateHandler = WebhookFieldHandler<'phone_number_name_update'>;\nexport type PhoneNumberQualityUpdateHandler = WebhookFieldHandler<'phone_number_quality_update'>;\nexport type MessageTemplateStatusUpdateHandler = WebhookFieldHandler<'message_template_status_update'>;\nexport type TemplateCategoryUpdateHandler = WebhookFieldHandler<'template_category_update'>;\nexport type MessageTemplateQualityUpdateHandler = WebhookFieldHandler<'message_template_quality_update'>;\nexport type FlowsHandler = WebhookFieldHandler<'flows'>;\nexport type SecurityHandler = WebhookFieldHandler<'security'>;\nexport type HistoryHandler = WebhookFieldHandler<'history'>;\nexport type SmbMessageEchoesHandler = WebhookFieldHandler<'smb_message_echoes'>;\nexport type SmbAppStateSyncHandler = WebhookFieldHandler<'smb_app_state_sync'>;\nexport type AccountSettingsUpdateHandler = WebhookFieldHandler<'account_settings_update'>;\nexport type AutomaticEventsHandler = WebhookFieldHandler<'automatic_events'>;\nexport type BusinessStatusUpdateHandler = WebhookFieldHandler<'business_status_update'>;\nexport type BusinessUsernameUpdatesHandler = WebhookFieldHandler<'business_username_updates'>;\nexport type CallsHandler = WebhookFieldHandler<'calls'>;\nexport type GroupLifecycleUpdateHandler = WebhookFieldHandler<'group_lifecycle_update'>;\nexport type GroupParticipantsUpdateHandler = WebhookFieldHandler<'group_participants_update'>;\nexport type GroupSettingsUpdateHandler = WebhookFieldHandler<'group_settings_update'>;\nexport type GroupStatusUpdateHandler = WebhookFieldHandler<'group_status_update'>;\nexport type MessageEchoesHandler = WebhookFieldHandler<'message_echoes'>;\nexport type MessageTemplateComponentsUpdateHandler = WebhookFieldHandler<'message_template_components_update'>;\nexport type MessagingHandoversHandler = WebhookFieldHandler<'messaging_handovers'>;\nexport type PartnerSolutionsHandler = WebhookFieldHandler<'partner_solutions'>;\nexport type PaymentConfigurationUpdateHandler = WebhookFieldHandler<'payment_configuration_update'>;\nexport type StandbyHandler = WebhookFieldHandler<'standby'>;\nexport type TemplateCorrectCategoryDetectionHandler = WebhookFieldHandler<'template_correct_category_detection'>;\nexport type TrackingEventsHandler = WebhookFieldHandler<'tracking_events'>;\nexport type UserPreferencesHandler = WebhookFieldHandler<'user_preferences'>;\n\n// Type-specific handlers for specialized methods\nexport type TextMessageHandler = WebhookHandler<TextProcessedMessage>;\nexport type ImageMessageHandler = WebhookHandler<ImageProcessedMessage>;\nexport type VideoMessageHandler = WebhookHandler<VideoProcessedMessage>;\nexport type AudioMessageHandler = WebhookHandler<AudioProcessedMessage>;\nexport type DocumentMessageHandler = WebhookHandler<DocumentProcessedMessage>;\nexport type StickerMessageHandler = WebhookHandler<StickerProcessedMessage>;\nexport type InteractiveMessageHandler = WebhookHandler<InteractiveProcessedMessage>;\nexport type ButtonMessageHandler = WebhookHandler<ButtonProcessedMessage>;\nexport type LocationMessageHandler = WebhookHandler<LocationProcessedMessage>;\nexport type ContactsMessageHandler = WebhookHandler<ContactsProcessedMessage>;\nexport type ReactionMessageHandler = WebhookHandler<ReactionProcessedMessage>;\nexport type OrderMessageHandler = WebhookHandler<OrderProcessedMessage>;\nexport type SystemMessageHandler = WebhookHandler<SystemProcessedMessage>;\n\n/**\n * Named handler options accepted by {@link processWebhookMessages}, one per\n * webhook field except `messages`. Kept for backward compatibility; new code\n * can pass `fieldHandlers` instead.\n */\nexport type WebhookFieldHandlerOptions = {\n accountUpdateHandler?: AccountUpdateHandler;\n accountReviewUpdateHandler?: AccountReviewUpdateHandler;\n accountAlertsHandler?: AccountAlertsHandler;\n businessCapabilityUpdateHandler?: BusinessCapabilityUpdateHandler;\n phoneNumberNameUpdateHandler?: PhoneNumberNameUpdateHandler;\n phoneNumberQualityUpdateHandler?: PhoneNumberQualityUpdateHandler;\n messageTemplateStatusUpdateHandler?: MessageTemplateStatusUpdateHandler;\n templateCategoryUpdateHandler?: TemplateCategoryUpdateHandler;\n messageTemplateQualityUpdateHandler?: MessageTemplateQualityUpdateHandler;\n flowsHandler?: FlowsHandler;\n securityHandler?: SecurityHandler;\n historyHandler?: HistoryHandler;\n smbMessageEchoesHandler?: SmbMessageEchoesHandler;\n smbAppStateSyncHandler?: SmbAppStateSyncHandler;\n accountSettingsUpdateHandler?: AccountSettingsUpdateHandler;\n automaticEventsHandler?: AutomaticEventsHandler;\n businessStatusUpdateHandler?: BusinessStatusUpdateHandler;\n businessUsernameUpdatesHandler?: BusinessUsernameUpdatesHandler;\n callsHandler?: CallsHandler;\n groupLifecycleUpdateHandler?: GroupLifecycleUpdateHandler;\n groupParticipantsUpdateHandler?: GroupParticipantsUpdateHandler;\n groupSettingsUpdateHandler?: GroupSettingsUpdateHandler;\n groupStatusUpdateHandler?: GroupStatusUpdateHandler;\n messageEchoesHandler?: MessageEchoesHandler;\n messageTemplateComponentsUpdateHandler?: MessageTemplateComponentsUpdateHandler;\n messagingHandoversHandler?: MessagingHandoversHandler;\n partnerSolutionsHandler?: PartnerSolutionsHandler;\n paymentConfigurationUpdateHandler?: PaymentConfigurationUpdateHandler;\n standbyHandler?: StandbyHandler;\n templateCorrectCategoryDetectionHandler?: TemplateCorrectCategoryDetectionHandler;\n trackingEventsHandler?: TrackingEventsHandler;\n userPreferencesHandler?: UserPreferencesHandler;\n};\n\n/** The {@link WebhookFieldHandlerOptions} key whose handler type matches field `F`. */\ntype HandlerOptionKeyFor<F extends NonMessageWebhookField> = {\n [K in keyof WebhookFieldHandlerOptions]-?: NonNullable<WebhookFieldHandlerOptions[K]> extends WebhookFieldHandler<F>\n ? K\n : never;\n}[keyof WebhookFieldHandlerOptions];\n\n/**\n * Registry of every webhook field except `messages`, mapping each field to its\n * named handler option. Dispatch is driven by this table: a field listed here\n * is routed to its handler, anything else is logged as unhandled. Adding a\n * field to `WebhookFieldValueMap` without an entry here fails type checking.\n */\nexport const WEBHOOK_FIELD_REGISTRY = {\n account_update: 'accountUpdateHandler',\n account_review_update: 'accountReviewUpdateHandler',\n account_alerts: 'accountAlertsHandler',\n account_settings_update: 'accountSettingsUpdateHandler',\n automatic_events: 'automaticEventsHandler',\n business_capability_update: 'businessCapabilityUpdateHandler',\n business_status_update: 'businessStatusUpdateHandler',\n business_username_updates: 'businessUsernameUpdatesHandler',\n calls: 'callsHandler',\n flows: 'flowsHandler',\n group_lifecycle_update: 'groupLifecycleUpdateHandler',\n group_participants_update: 'groupParticipantsUpdateHandler',\n group_settings_update: 'groupSettingsUpdateHandler',\n group_status_update: 'groupStatusUpdateHandler',\n history: 'historyHandler',\n message_echoes: 'messageEchoesHandler',\n message_template_components_update: 'messageTemplateComponentsUpdateHandler',\n message_template_quality_update: 'messageTemplateQualityUpdateHandler',\n message_template_status_update: 'messageTemplateStatusUpdateHandler',\n messaging_handovers: 'messagingHandoversHandler',\n partner_solutions: 'partnerSolutionsHandler',\n payment_configuration_update: 'paymentConfigurationUpdateHandler',\n phone_number_name_update: 'phoneNumberNameUpdateHandler',\n phone_number_quality_update: 'phoneNumberQualityUpdateHandler',\n security: 'securityHandler',\n smb_app_state_sync: 'smbAppStateSyncHandler',\n smb_message_echoes: 'smbMessageEchoesHandler',\n standby: 'standbyHandler',\n template_category_update: 'templateCategoryUpdateHandler',\n template_correct_category_detection: 'templateCorrectCategoryDetectionHandler',\n tracking_events: 'trackingEventsHandler',\n user_preferences: 'userPreferencesHandler',\n} as const satisfies { [F in NonMessageWebhookField]: HandlerOptionKeyFor<F> };\n\n/** True when `field` is a webhook field other than `messages` that the SDK knows. */\nexport function isNonMessageWebhookField(field: string): field is NonMessageWebhookField {\n return Object.hasOwn(WEBHOOK_FIELD_REGISTRY, field);\n}\n\n/**\n * Dedupe keys for non-`messages` fields that carry a natural id. Fields not\n * listed here are never deduped. A change is a duplicate only when its whole\n * set of ids was seen before.\n */\nconst FIELD_DEDUPE_KEYS: { [F in NonMessageWebhookField]?: (value: WebhookFieldValueMap[F]) => string | undefined } = {\n calls: (value) =>\n joinDedupeIds(\n 'calls',\n mapArray(value?.calls, (call) =>\n call?.id ? `${call.id}:${call.event}${call.call_status ? `:${call.call_status}` : ''}` : undefined,\n ),\n ),\n smb_message_echoes: (value) =>\n joinDedupeIds(\n 'smb_message_echoes',\n mapArray(value?.message_echoes, (echo) => echo?.id),\n ),\n message_echoes: (value) =>\n joinDedupeIds(\n 'message_echoes',\n mapArray(value?.messaging, (entry) => entry?.message?.mid),\n ),\n};\n\nfunction mapArray<T>(\n items: T[] | undefined,\n fn: (item: T) => string | undefined,\n): Array<string | undefined> | undefined {\n return Array.isArray(items) ? items.map(fn) : undefined;\n}\n\nfunction joinDedupeIds(prefix: string, ids: Array<string | undefined> | undefined): string | undefined {\n if (!ids || ids.length === 0 || ids.some((id) => !id)) return undefined;\n return `${prefix}:${ids.join(',')}`;\n}\n\n/** Dedupe key for one change of a non-`messages` field, or undefined when it has no natural id. */\nexport function getWebhookFieldDedupeKey<F extends NonMessageWebhookField>(\n field: F,\n value: WebhookFieldValueMap[F],\n): string | undefined {\n const keyFn = FIELD_DEDUPE_KEYS[field] as ((value: WebhookFieldValueMap[F]) => string | undefined) | undefined;\n return keyFn?.(value);\n}\n\n/** Dedupe settings for {@link processWebhookMessages}. */\nexport type WebhookDedupeOptions = {\n store: DedupeStore;\n /** Defaults to 86400 (24 hours). */\n ttlSeconds?: number;\n};\n\n/** Options for {@link processWebhookMessages}. */\nexport type ProcessWebhookOptions = WebhookSignatureOptions & {\n /** Skip handlers for deliveries already seen. Duplicates still get a 200 response. */\n dedupe?: WebhookDedupeOptions;\n};\n\ntype ResolvedDedupeOptions = { store: DedupeStore; ttlSeconds: number };\n\n/**\n * Claim a dedupe key. Resolves true when the delivery was already seen.\n * Store errors fail open: the delivery is processed and the error is logged.\n */\nasync function isDuplicateDelivery(\n dedupe: ResolvedDedupeOptions | undefined,\n key: string | undefined,\n): Promise<boolean> {\n if (!dedupe || !key) return false;\n try {\n const stored = await dedupe.store.setIfAbsent(key, dedupe.ttlSeconds);\n if (!stored) {\n LOGGER.log(`Skipping duplicate webhook delivery: ${key}`);\n return true;\n }\n return false;\n } catch (error) {\n LOGGER.error('Dedupe store failed; processing the webhook anyway:', { key, error });\n return false;\n }\n}\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 statusHandler?: StatusHandler;\n userActionHandler?: UserActionHandler;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n rawHandler?: RawWebhookHandler;\n rawHandlerFields?: WebhookFieldType[];\n /**\n * Handlers for non-`messages` fields keyed by field name. Takes\n * precedence over the named `xxxHandler` option for the same field.\n */\n fieldHandlers?: WebhookFieldHandlerMap;\n } & WebhookFieldHandlerOptions,\n options: ProcessWebhookOptions = {},\n): Promise<Response> {\n try {\n const rawBody = await request.text();\n\n if (options.verifySignature) {\n if (!options.appSecret) {\n LOGGER.error('verifyWebhookSignature is on but appSecret is not configured; rejecting webhook');\n return new Response(JSON.stringify({ error: 'Webhook signature verification misconfigured' }), {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n if (\n !(await verifyWebhookSignature(rawBody, request.headers.get('x-hub-signature-256'), options.appSecret))\n ) {\n LOGGER.warn('Rejected webhook with missing or invalid X-Hub-Signature-256');\n return new Response(JSON.stringify({ error: 'Invalid signature' }), {\n status: 401,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n }\n\n const body = JSON.parse(rawBody);\n const context: WebhookHandlerContext = {\n headers: request.headers,\n rawBody,\n method: request.method,\n url: request.url,\n };\n const dedupe: ResolvedDedupeOptions | undefined = options.dedupe\n ? { store: options.dedupe.store, ttlSeconds: options.dedupe.ttlSeconds ?? DEFAULT_DEDUPE_TTL_SECONDS }\n : undefined;\n\n if (handlers.rawHandler) {\n const { rawHandler, rawHandlerFields } = handlers;\n let payload = body as WebhookPayload;\n if (rawHandlerFields && rawHandlerFields.length > 0) {\n const filtered: WebhookPayload = {\n ...payload,\n entry: payload.entry\n .map((entry) => ({\n ...entry,\n changes: entry.changes.filter((change) =>\n rawHandlerFields.includes(change.field as WebhookFieldType),\n ),\n }))\n .filter((entry) => entry.changes.length > 0),\n };\n if (filtered.entry.length === 0) {\n payload = null as any;\n } else {\n payload = filtered;\n }\n }\n if (payload) {\n await rawHandler(whatsapp, payload, context);\n }\n }\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);\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 const changes = entry.changes;\n for (const change of changes) {\n const field: string = change.field;\n if (field === 'messages') {\n await processMessages(entry.id, change.value, whatsapp, handlers, context, dedupe);\n } else if (isNonMessageWebhookField(field)) {\n const handler =\n handlers.fieldHandlers?.get(field) ??\n (handlers[WEBHOOK_FIELD_REGISTRY[field]] as AnyWebhookFieldHandler | undefined);\n await processWebhookField(\n entry.id,\n { field, value: change.value },\n handler,\n whatsapp,\n context,\n dedupe,\n );\n } else {\n LOGGER.warn(`Unhandled webhook field: ${change.field}`);\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 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 * Create a standard ping response for WhatsApp Flow health checks\n * @returns Flow ping response object\n */\nexport function createFlowPingResponse() {\n return {\n version: '3.0',\n data: { status: 'active' },\n };\n}\n\n/**\n * Create a standard error response for WhatsApp Flow error notifications\n * @returns Acknowledgement response for error notification\n */\nexport function createFlowErrorResponse() {\n return {\n data: {\n acknowledged: true,\n },\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 const body = await request.text();\n const context: WebhookHandlerContext = {\n headers: request.headers,\n rawBody: body,\n method: request.method,\n url: request.url,\n };\n const signature = request.headers.get('x-hub-signature-256');\n\n // Meta signs Flow requests with the App Secret. Older versions of this SDK\n // keyed the HMAC with the webhook verification token, which never matches\n // a real Meta request; that key is kept only as a fallback when no App\n // Secret is configured.\n const signingKey = config[WabaConfigEnum.AppSecret] || config.WEBHOOK_VERIFICATION_TOKEN || '';\n if (!config[WabaConfigEnum.AppSecret]) {\n LOGGER.warn('appSecret not configured; verifying Flow signature with the webhook verification token');\n }\n if (!(await verifyWebhookSignature(body, signature, signingKey))) {\n LOGGER.warn('Invalid request signature');\n return new Response(JSON.stringify({ error: 'Unauthorized' }), { status: 401 });\n }\n\n const data = JSON.parse(body);\n\n // Decrypt the request and get decrypted AES key and IV\n const { decryptedBody, aesKeyBuffer, initialVectorBuffer } = await decryptFlowRequestAsync(data, config);\n\n // Determine flow type\n const isPing = isFlowPingRequest(decryptedBody);\n const isError = isFlowErrorRequest(decryptedBody);\n const isDataExchange = isFlowDataExchangeRequest(decryptedBody);\n\n let flowType: FlowTypeEnum;\n if (isPing) {\n flowType = FlowTypeEnum.Ping;\n } else if (isError) {\n flowType = FlowTypeEnum.Error;\n } else if (isDataExchange) {\n flowType = FlowTypeEnum.Change;\n } else {\n flowType = FlowTypeEnum.All;\n }\n\n // Get the flow handler based on type\n let handler = flowHandlers.get(flowType);\n\n // For Ping and Error, use default handlers if not registered\n if (!handler) {\n if (flowType === FlowTypeEnum.Ping) {\n handler = () => createFlowPingResponse();\n } else if (flowType === FlowTypeEnum.Error) {\n handler = () => createFlowErrorResponse();\n } else {\n // For Change and other types, try All handler as fallback\n handler = flowHandlers.get(FlowTypeEnum.All);\n if (!handler) {\n LOGGER.warn('No handler registered for flow type:', { flowType, action: decryptedBody.action });\n return new Response(JSON.stringify({ error: 'Handler not found' }), { status: 404 });\n }\n }\n }\n\n // Call the user's handler for the flow type\n const result = await handler(whatsapp, decryptedBody, context);\n\n // Return response based on flow type\n if (isError) {\n LOGGER.warn('Flow error notification received', { error: decryptedBody.data });\n\n // If user handler didn't return a response, use default acknowledgement\n const errorResponse = result || createFlowErrorResponse();\n\n return new Response(JSON.stringify(errorResponse), {\n status: 200,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n // Both ping and data_exchange responses need to be encrypted\n if (isPing || isDataExchange) {\n // Encrypt the response using decrypted AES key and IV\n const encryptedResponse = await encryptFlowResponseAsync(result, aesKeyBuffer, initialVectorBuffer);\n\n // Meta expects the encrypted response as a plain base64 string (not wrapped in JSON)\n return new Response(encryptedResponse, {\n status: 200,\n headers: { 'Content-Type': 'text/plain' },\n });\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\nexport type WebhookSignatureOptions = {\n /** Meta App Secret used as the HMAC key. */\n appSecret?: string;\n /** When true, reject requests without a valid `X-Hub-Signature-256`. */\n verifySignature?: boolean;\n};\n\n/**\n * Check an `X-Hub-Signature-256` header (`sha256=<hex>`) against the raw\n * request body using Web Crypto, so it works on every runtime. Constant-time;\n * resolves to false instead of throwing on malformed or wrong-length input.\n */\nexport async function verifyWebhookSignature(\n rawBody: string,\n signatureHeader: string | null,\n appSecret: string,\n): Promise<boolean> {\n if (!signatureHeader || !appSecret) return false;\n const provided = signatureHeader.startsWith('sha256=') ? signatureHeader.slice(7) : signatureHeader;\n const expected = await hmacSha256Hex(appSecret, rawBody);\n return timingSafeEqualString(provided.toLowerCase(), expected);\n}\n\n/**\n * Synchronous variant of {@link verifyWebhookSignature}. Needs `node:crypto`\n * (Node.js >= 20.12, Bun, Deno); prefer the async variant on edge runtimes.\n */\nexport function isValidWebhookSignature(rawBody: string, signatureHeader: string | null, appSecret: string): boolean {\n if (!signatureHeader || !appSecret) return false;\n const crypto = requireNodeCrypto('isValidWebhookSignature');\n const provided = signatureHeader.startsWith('sha256=') ? signatureHeader.slice(7) : signatureHeader;\n const expected = crypto.createHmac('sha256', appSecret).update(rawBody, 'utf8').digest('hex');\n return timingSafeEqualString(provided.toLowerCase(), expected);\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 * Extract message ID based on message type\n * Some message types (like nfm_reply) have ID in context instead of root level\n */\nfunction extractMessageId(message: WhatsAppMessage): string {\n // If message has id at root level, use it\n if (message.id) {\n return message.id;\n }\n\n // For interactive and button messages, check context.id\n if (message.type === MessageTypesEnum.Interactive || message.type === MessageTypesEnum.Button) {\n if ('context' in message && message.context?.id) {\n return message.context.id;\n }\n }\n\n // Fallback to empty string if no ID found\n return '';\n}\n\n/**\n * Private helper functions\n */\nasync function processMessages(\n waba_id: string,\n value: WebhookValue,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n statusHandler?: StatusHandler;\n userActionHandler?: UserActionHandler;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n context: WebhookHandlerContext,\n dedupe?: ResolvedDedupeOptions,\n): Promise<void> {\n const metadata = value.metadata;\n const wabaId = waba_id;\n const displayPhoneNumber = metadata.display_phone_number;\n const phoneNumberId = metadata.phone_number_id;\n\n // Handle marketing message user actions (link clicks, landing page views)\n if ('user_actions' in value && value.user_actions) {\n const userActionsValue = value as UserActionsWebhookValue;\n for (const action of userActionsValue.user_actions) {\n const processed: ProcessedUserAction = {\n wabaId,\n phoneNumberId,\n displayPhoneNumber,\n action,\n };\n\n await executeUserActionHandler(handlers.userActionHandler, whatsapp, processed, context);\n }\n return;\n }\n\n // Handle status webhooks\n if ('statuses' in value && value.statuses) {\n const statusValue = value as StatusWebhookValue;\n for (const status of statusValue.statuses) {\n if (!handlers.statusHandler) continue;\n if (await isDuplicateDelivery(dedupe, status.id ? `status:${status.id}:${status.status}` : undefined)) {\n continue;\n }\n const processed: ProcessedStatus = {\n wabaId,\n phoneNumberId,\n displayPhoneNumber,\n status,\n };\n\n await executeStatusHandler(handlers.statusHandler, whatsapp, processed, context);\n }\n return;\n }\n\n // Handle message webhooks\n if ('messages' in value && value.messages) {\n const messageValue = value as MessageWebhookValue;\n const profileName = messageValue.contacts?.[0]?.profile?.name || '';\n\n for (const message of messageValue.messages) {\n const processed: ProcessedMessage = {\n wabaId,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n message,\n messageId: extractMessageId(message),\n ...(messageValue.conversation_context && { conversationContext: messageValue.conversation_context }),\n };\n\n const messageType = message.type;\n const messageHandler = handlers.messageHandlers.get(messageType);\n if (!handlers.preProcessHandler && !messageHandler && !handlers.postProcessHandler) continue;\n if (await isDuplicateDelivery(dedupe, processed.messageId ? `message:${processed.messageId}` : undefined)) {\n continue;\n }\n\n // Execute handlers in sequence\n await executeMessageHandler(handlers.preProcessHandler, whatsapp, processed, context, 'pre-process');\n await executeMessageHandler(messageHandler, whatsapp, processed, context, messageType);\n await executeMessageHandler(handlers.postProcessHandler, whatsapp, processed, context, 'post-process');\n }\n }\n}\n\nasync function executeMessageHandler(\n handler: MessageHandler | undefined,\n whatsapp: WhatsApp,\n processed: ProcessedMessage,\n context: WebhookHandlerContext,\n handlerType: string,\n): Promise<void> {\n if (handler) {\n try {\n await handler(whatsapp, processed, context);\n } catch (error) {\n LOGGER.error(`Error in ${handlerType} handler:`, { error, messageId: processed.messageId });\n }\n }\n}\n\nasync function executeStatusHandler(\n handler: StatusHandler | undefined,\n whatsapp: WhatsApp,\n processed: ProcessedStatus,\n context: WebhookHandlerContext,\n): Promise<void> {\n if (handler) {\n try {\n await handler(whatsapp, processed, context);\n } catch (error) {\n LOGGER.error('Error in status handler:', { error, statusId: processed.status.id });\n }\n }\n}\n\nasync function executeUserActionHandler(\n handler: UserActionHandler | undefined,\n whatsapp: WhatsApp,\n processed: ProcessedUserAction,\n context: WebhookHandlerContext,\n): Promise<void> {\n if (handler) {\n try {\n await handler(whatsapp, processed, context);\n } catch (error) {\n LOGGER.error('Error in user action handler:', { error, actionType: processed.action.action_type });\n }\n }\n}\n\n/**\n * Generic webhook field processor\n * Processes webhook fields other than 'messages'\n */\nasync function processWebhookField<F extends NonMessageWebhookField>(\n wabaId: string,\n webhookValue: { field: F; value: WebhookFieldValueMap[F] },\n handler: WebhookFieldHandler<F> | AnyWebhookFieldHandler | undefined,\n whatsapp: WhatsApp,\n context: WebhookHandlerContext,\n dedupe?: ResolvedDedupeOptions,\n): Promise<void> {\n if (!handler) return;\n if (await isDuplicateDelivery(dedupe, getWebhookFieldDedupeKey(webhookValue.field, webhookValue.value))) return;\n try {\n await handler(\n whatsapp,\n {\n wabaId,\n value: webhookValue.value,\n },\n context,\n );\n } catch (error) {\n LOGGER.error(`Error in ${webhookValue.field} handler:`, { error, wabaId });\n }\n}\n","import type { FlowTypeEnum } from '../../api/flow/types';\nimport { importConfig } from '../../config/importConfig';\nimport type { WabaConfigType, WhatsAppConfig } from '../../types/config';\nimport { MessageTypesEnum, WabaConfigEnum } from '../../types/enums';\nimport Logger from '../../utils/logger';\nimport { isDebugEnv } from '../../utils/runtime';\nimport { WhatsApp } from '../whatsapp';\nimport { type ResolvedDedupe, resolveDedupe } from './dedupe';\nimport type { NonMessageWebhookField, WebhookFieldType } from './types';\nimport {\n type AccountAlertsHandler,\n type AccountReviewUpdateHandler,\n type AccountSettingsUpdateHandler,\n type AccountUpdateHandler,\n type AudioMessageHandler,\n type AutomaticEventsHandler,\n type BusinessCapabilityUpdateHandler,\n type BusinessStatusUpdateHandler,\n type BusinessUsernameUpdatesHandler,\n type ButtonMessageHandler,\n type CallsHandler,\n type ContactsMessageHandler,\n type DocumentMessageHandler,\n type FlowHandler,\n type FlowsHandler,\n type GroupLifecycleUpdateHandler,\n type GroupParticipantsUpdateHandler,\n type GroupSettingsUpdateHandler,\n type GroupStatusUpdateHandler,\n type HistoryHandler,\n type ImageMessageHandler,\n type InteractiveMessageHandler,\n isNonMessageWebhookField,\n type LocationMessageHandler,\n type MessageEchoesHandler,\n type MessageHandler,\n type MessageTemplateComponentsUpdateHandler,\n type MessageTemplateQualityUpdateHandler,\n type MessageTemplateStatusUpdateHandler,\n type MessagingHandoversHandler,\n type OrderMessageHandler,\n type PartnerSolutionsHandler,\n type PaymentConfigurationUpdateHandler,\n type PhoneNumberNameUpdateHandler,\n type PhoneNumberQualityUpdateHandler,\n processFlowRequest,\n processWebhookMessages,\n type RawWebhookHandler,\n type ReactionMessageHandler,\n type SecurityHandler,\n type SmbAppStateSyncHandler,\n type SmbMessageEchoesHandler,\n type StandbyHandler,\n type StatusHandler,\n type StickerMessageHandler,\n type SystemMessageHandler,\n type TemplateCategoryUpdateHandler,\n type TemplateCorrectCategoryDetectionHandler,\n type TextMessageHandler,\n type TrackingEventsHandler,\n type UserActionHandler,\n type UserPreferencesHandler,\n type VideoMessageHandler,\n type WebhookFieldHandler,\n} from './utils/webhookUtils';\n\nconst LOGGER = new Logger('WEBHOOK_PROCESSOR', isDebugEnv());\n\nfunction assertNonMessageField(field: string, method: 'on' | 'off'): void {\n if (field === 'messages') {\n throw new Error(\n `${method}('messages') is not supported. Use onMessage/onText/... for messages, ` +\n 'onStatus for statuses and onUserAction for marketing user actions.',\n );\n }\n if (!isNonMessageWebhookField(field)) {\n throw new Error(`${method}('${field}'): unknown webhook field`);\n }\n}\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 statusHandler: StatusHandler | undefined = undefined;\n private userActionHandler: UserActionHandler | undefined = undefined;\n private preProcessHandler: MessageHandler | undefined = undefined;\n private postProcessHandler: MessageHandler | undefined = undefined;\n private rawHandler: { handler: RawWebhookHandler; fields?: WebhookFieldType[] } | undefined = undefined;\n private flowHandlers: Map<FlowTypeEnum, FlowHandler> = new Map();\n\n /** Handlers for every webhook field except `messages`, keyed by field name. */\n private fieldHandlers: Map<NonMessageWebhookField, WebhookFieldHandler<NonMessageWebhookField>> = new Map();\n\n private verifySignature: boolean;\n private dedupe: ResolvedDedupe | undefined;\n\n constructor(config: WhatsAppConfig) {\n this.config = importConfig(config);\n this.verifySignature = config.verifyWebhookSignature === true;\n this.dedupe = resolveDedupe(config.dedupe);\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(\n request,\n this.client,\n {\n messageHandlers: this.messageHandlers,\n statusHandler: this.statusHandler,\n userActionHandler: this.userActionHandler,\n preProcessHandler: this.preProcessHandler,\n postProcessHandler: this.postProcessHandler,\n rawHandler: this.rawHandler?.handler,\n rawHandlerFields: this.rawHandler?.fields,\n fieldHandlers: this.fieldHandlers,\n },\n {\n appSecret: this.config[WabaConfigEnum.AppSecret],\n verifySignature: this.verifySignature,\n dedupe: this.dedupe,\n },\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') || 'text/plain';\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 | string, handler: MessageHandler): void {\n if (type === ('statuses' as MessageTypesEnum)) {\n throw new Error(\n 'MessageTypesEnum.Statuses is deprecated. Use onStatus(handler) instead of onMessage(MessageTypesEnum.Statuses, handler)',\n );\n }\n this.messageHandlers.set(type as MessageTypesEnum, handler);\n LOGGER.log(`Registered message handler for ${type}`);\n }\n\n onStatus(handler: StatusHandler): void {\n this.statusHandler = handler;\n LOGGER.log('Registered status handler');\n }\n\n /**\n * Register a handler for marketing message user actions delivered as\n * `user_actions` on the `messages` webhook field (Marketing Messages API\n * for WhatsApp only): `marketing_messages_link_click` and\n * `landing_page_view`. `action_type` is an open enum — ignore unknown values.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/marketing-messages/track-landing-page-views\n */\n onUserAction(handler: UserActionHandler): void {\n this.userActionHandler = handler;\n LOGGER.log('Registered user action handler');\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 onRaw(handler: RawWebhookHandler, fields?: WebhookFieldType[]): void {\n this.rawHandler = { handler, fields };\n LOGGER.log(`Registered raw webhook handler${fields ? ` for fields: ${fields.join(', ')}` : ''}`);\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 /**\n * Register a handler for any webhook field except `messages`. The type of\n * `processed.value` follows from the field name. Replaces any handler\n * already registered for that field, including one set with the matching\n * `onXxx` method (for example `onCalls` is `on('calls', handler)`).\n *\n * `messages` is not accepted: use `onMessage`, the typed message methods\n * (`onText`, ...), `onStatus` or `onUserAction`, which split that field\n * into messages, statuses and user actions.\n *\n * @example\n * ```typescript\n * processor.on('calls', async (whatsapp, { value }) => {\n * for (const call of value.calls) console.log(call.id, call.event);\n * });\n * ```\n */\n on<F extends NonMessageWebhookField>(field: F, handler: WebhookFieldHandler<F>): void {\n assertNonMessageField(field, 'on');\n this.fieldHandlers.set(field, handler as unknown as WebhookFieldHandler<NonMessageWebhookField>);\n LOGGER.log(`Registered ${field} handler`);\n }\n\n /**\n * Remove the handler for a webhook field registered with `on()` or the\n * matching `onXxx` method. `messages` is not accepted (see {@link on}).\n */\n off(field: NonMessageWebhookField): void {\n assertNonMessageField(field, 'off');\n this.fieldHandlers.delete(field);\n LOGGER.log(`Removed ${field} handler`);\n }\n\n // ============================================================================\n // Specialized type-safe message handlers\n // ============================================================================\n\n /**\n * Register a handler for text messages\n * @param handler Type-safe handler that receives text messages with guaranteed text field\n */\n onText(handler: TextMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Text, handler as MessageHandler);\n LOGGER.log('Registered text message handler');\n }\n\n /**\n * Register a handler for image messages\n * @param handler Type-safe handler that receives image messages with guaranteed image field\n */\n onImage(handler: ImageMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Image, handler as MessageHandler);\n LOGGER.log('Registered image message handler');\n }\n\n /**\n * Register a handler for video messages\n * @param handler Type-safe handler that receives video messages with guaranteed video field\n */\n onVideo(handler: VideoMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Video, handler as MessageHandler);\n LOGGER.log('Registered video message handler');\n }\n\n /**\n * Register a handler for audio messages\n * @param handler Type-safe handler that receives audio messages with guaranteed audio field\n */\n onAudio(handler: AudioMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Audio, handler as MessageHandler);\n LOGGER.log('Registered audio message handler');\n }\n\n /**\n * Register a handler for document messages\n * @param handler Type-safe handler that receives document messages with guaranteed document field\n */\n onDocument(handler: DocumentMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Document, handler as MessageHandler);\n LOGGER.log('Registered document message handler');\n }\n\n /**\n * Register a handler for sticker messages\n * @param handler Type-safe handler that receives sticker messages with guaranteed sticker field\n */\n onSticker(handler: StickerMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Sticker, handler as MessageHandler);\n LOGGER.log('Registered sticker message handler');\n }\n\n /**\n * Register a handler for interactive messages (buttons, lists, flows)\n * @param handler Type-safe handler that receives interactive messages with guaranteed interactive field\n */\n onInteractive(handler: InteractiveMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Interactive, handler as MessageHandler);\n LOGGER.log('Registered interactive message handler');\n }\n\n /**\n * Register a handler for button messages\n * @param handler Type-safe handler that receives button messages with guaranteed button field\n */\n onButton(handler: ButtonMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Button, handler as MessageHandler);\n LOGGER.log('Registered button message handler');\n }\n\n /**\n * Register a handler for location messages\n * @param handler Type-safe handler that receives location messages with guaranteed location field\n */\n onLocation(handler: LocationMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Location, handler as MessageHandler);\n LOGGER.log('Registered location message handler');\n }\n\n /**\n * Register a handler for contact messages\n * @param handler Type-safe handler that receives contact messages with guaranteed contacts field\n */\n onContacts(handler: ContactsMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Contacts, handler as MessageHandler);\n LOGGER.log('Registered contacts message handler');\n }\n\n /**\n * Register a handler for reaction messages\n * @param handler Type-safe handler that receives reaction messages with guaranteed reaction field\n */\n onReaction(handler: ReactionMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Reaction, handler as MessageHandler);\n LOGGER.log('Registered reaction message handler');\n }\n\n /**\n * Register a handler for order messages\n * @param handler Type-safe handler that receives order messages with guaranteed order field\n */\n onOrder(handler: OrderMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Order, handler as MessageHandler);\n LOGGER.log('Registered order message handler');\n }\n\n /**\n * Register a handler for system messages\n * @param handler Type-safe handler that receives system messages with guaranteed system field\n */\n onSystem(handler: SystemMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.System, handler as MessageHandler);\n LOGGER.log('Registered system message handler');\n }\n\n // ============================================================================\n // Webhook field handlers\n // @see https://developers.facebook.com/docs/graph-api/webhooks/reference/whatsapp-business-account\n // ============================================================================\n\n /**\n * Register a handler for account_update webhook field\n * @see https://developers.facebook.com/docs/whatsapp/business-management-api/webhooks/components#account_update\n */\n onAccountUpdate(handler: AccountUpdateHandler): void {\n this.on('account_update', handler);\n }\n\n /**\n * Register a handler for account_review_update webhook field\n * @see https://developers.facebook.com/docs/whatsapp/business-management-api/webhooks/components#account_review_update\n */\n onAccountReviewUpdate(handler: AccountReviewUpdateHandler): void {\n this.on('account_review_update', handler);\n }\n\n /**\n * Register a handler for account_alerts webhook field\n * @see https://developers.facebook.com/docs/whatsapp/business-management-api/webhooks/components#account_alerts\n */\n onAccountAlerts(handler: AccountAlertsHandler): void {\n this.on('account_alerts', handler);\n }\n\n /**\n * Register a handler for business_capability_update webhook field\n * @see https://developers.facebook.com/docs/whatsapp/business-management-api/webhooks/components#business_capability_update\n */\n onBusinessCapabilityUpdate(handler: BusinessCapabilityUpdateHandler): void {\n this.on('business_capability_update', handler);\n }\n\n /**\n * Register a handler for phone_number_name_update webhook field\n * @see https://developers.facebook.com/docs/whatsapp/business-management-api/webhooks/components#phone_number_name_update\n */\n onPhoneNumberNameUpdate(handler: PhoneNumberNameUpdateHandler): void {\n this.on('phone_number_name_update', handler);\n }\n\n /**\n * Register a handler for phone_number_quality_update webhook field\n * @see https://developers.facebook.com/docs/whatsapp/business-management-api/webhooks/components#phone_number_quality_update\n */\n onPhoneNumberQualityUpdate(handler: PhoneNumberQualityUpdateHandler): void {\n this.on('phone_number_quality_update', handler);\n }\n\n /**\n * Register a handler for message_template_status_update webhook field\n * @see https://developers.facebook.com/docs/whatsapp/business-management-api/webhooks/components#message_template_status_update\n */\n onMessageTemplateStatusUpdate(handler: MessageTemplateStatusUpdateHandler): void {\n this.on('message_template_status_update', handler);\n }\n\n /**\n * Register a handler for template_category_update webhook field\n * @see https://developers.facebook.com/docs/whatsapp/business-management-api/webhooks/components#template_category_update\n */\n onTemplateCategoryUpdate(handler: TemplateCategoryUpdateHandler): void {\n this.on('template_category_update', handler);\n }\n\n /**\n * Register a handler for message_template_quality_update webhook field\n * @see https://developers.facebook.com/docs/whatsapp/business-management-api/webhooks/components#message_template_quality_update\n */\n onMessageTemplateQualityUpdate(handler: MessageTemplateQualityUpdateHandler): void {\n this.on('message_template_quality_update', handler);\n }\n\n /**\n * Register a handler for flows webhook field\n * @see https://developers.facebook.com/docs/whatsapp/flows/guides/implementingyourflowendpoint#webhooks\n */\n onFlows(handler: FlowsHandler): void {\n this.on('flows', handler);\n }\n\n /**\n * Register a handler for security webhook field\n * @see https://developers.facebook.com/docs/whatsapp/business-management-api/webhooks/components#security\n */\n onSecurity(handler: SecurityHandler): void {\n this.on('security', handler);\n }\n\n /**\n * Register a handler for history webhook field\n * @see https://developers.facebook.com/docs/graph-api/webhooks/reference/whatsapp-business-account#history\n */\n onHistory(handler: HistoryHandler): void {\n this.on('history', handler);\n }\n\n /**\n * Register a handler for smb_message_echoes webhook field\n * @see https://developers.facebook.com/docs/graph-api/webhooks/reference/whatsapp-business-account#smb_message_echoes\n */\n onSmbMessageEchoes(handler: SmbMessageEchoesHandler): void {\n this.on('smb_message_echoes', handler);\n }\n\n /**\n * Register a handler for smb_app_state_sync webhook field\n * @see https://developers.facebook.com/docs/graph-api/webhooks/reference/whatsapp-business-account#smb_app_state_sync\n */\n onSmbAppStateSync(handler: SmbAppStateSyncHandler): void {\n this.on('smb_app_state_sync', handler);\n }\n\n /**\n * Register a handler for account_settings_update webhook field\n */\n onAccountSettingsUpdate(handler: AccountSettingsUpdateHandler): void {\n this.on('account_settings_update', handler);\n }\n\n /**\n * Register a handler for automatic_events webhook field\n */\n onAutomaticEvents(handler: AutomaticEventsHandler): void {\n this.on('automatic_events', handler);\n }\n\n /**\n * Register a handler for business_status_update webhook field\n */\n onBusinessStatusUpdate(handler: BusinessStatusUpdateHandler): void {\n this.on('business_status_update', handler);\n }\n\n /**\n * Register a handler for business_username_updates webhook field.\n * Check `value.context === 'revoked'` to tell a Meta revocation from a change the business made.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/business-scoped-user-ids#business_username_updates-webhook\n */\n onBusinessUsernameUpdates(handler: BusinessUsernameUpdatesHandler): void {\n this.on('business_username_updates', handler);\n }\n\n /**\n * Register a handler for calls webhook field\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/reference/\n */\n onCalls(handler: CallsHandler): void {\n this.on('calls', handler);\n }\n\n /**\n * Register a handler for group_lifecycle_update webhook field\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n onGroupLifecycleUpdate(handler: GroupLifecycleUpdateHandler): void {\n this.on('group_lifecycle_update', handler);\n }\n\n /**\n * Register a handler for group_participants_update webhook field\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n onGroupParticipantsUpdate(handler: GroupParticipantsUpdateHandler): void {\n this.on('group_participants_update', handler);\n }\n\n /**\n * Register a handler for group_settings_update webhook field\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n onGroupSettingsUpdate(handler: GroupSettingsUpdateHandler): void {\n this.on('group_settings_update', handler);\n }\n\n /**\n * Register a handler for group_status_update webhook field\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n onGroupStatusUpdate(handler: GroupStatusUpdateHandler): void {\n this.on('group_status_update', handler);\n }\n\n /**\n * Register a handler for message_echoes webhook field\n * @see https://developers.facebook.com/docs/graph-api/webhooks/reference/whatsapp-business-account#message_echoes\n */\n onMessageEchoes(handler: MessageEchoesHandler): void {\n this.on('message_echoes', handler);\n }\n\n /**\n * Register a handler for message_template_components_update webhook field\n */\n onMessageTemplateComponentsUpdate(handler: MessageTemplateComponentsUpdateHandler): void {\n this.on('message_template_components_update', handler);\n }\n\n /**\n * Register a handler for messaging_handovers webhook field\n */\n onMessagingHandovers(handler: MessagingHandoversHandler): void {\n this.on('messaging_handovers', handler);\n }\n\n /**\n * Register a handler for partner_solutions webhook field\n */\n onPartnerSolutions(handler: PartnerSolutionsHandler): void {\n this.on('partner_solutions', handler);\n }\n\n /**\n * Register a handler for payment_configuration_update webhook field\n */\n onPaymentConfigurationUpdate(handler: PaymentConfigurationUpdateHandler): void {\n this.on('payment_configuration_update', handler);\n }\n\n /**\n * Register a handler for standby webhook field\n */\n onStandby(handler: StandbyHandler): void {\n this.on('standby', handler);\n }\n\n /**\n * Register a handler for template_correct_category_detection webhook field\n */\n onTemplateCorrectCategoryDetection(handler: TemplateCorrectCategoryDetectionHandler): void {\n this.on('template_correct_category_detection', handler);\n }\n\n /**\n * Register a handler for tracking_events webhook field\n */\n onTrackingEvents(handler: TrackingEventsHandler): void {\n this.on('tracking_events', handler);\n }\n\n /**\n * Register a handler for user_preferences webhook field\n */\n onUserPreferences(handler: UserPreferencesHandler): void {\n this.on('user_preferences', handler);\n }\n\n // ============================================================================\n // Handler removal methods\n // ============================================================================\n\n /**\n * Remove a registered message handler by type\n */\n offMessage(type: MessageTypesEnum | string): void {\n this.messageHandlers.delete(type as MessageTypesEnum);\n LOGGER.log(`Removed message handler for ${type}`);\n }\n\n /**\n * Remove the pre-process handler\n */\n offMessagePreProcess(): void {\n this.preProcessHandler = undefined;\n LOGGER.log('Removed pre-process handler');\n }\n\n /**\n * Remove the post-process handler\n */\n offMessagePostProcess(): void {\n this.postProcessHandler = undefined;\n LOGGER.log('Removed post-process handler');\n }\n\n /**\n * Remove the status handler\n */\n offStatus(): void {\n this.statusHandler = undefined;\n LOGGER.log('Removed status handler');\n }\n\n /**\n * Remove the user action handler\n */\n offUserAction(): void {\n this.userActionHandler = undefined;\n LOGGER.log('Removed user action handler');\n }\n\n /**\n * Remove the raw webhook handler\n */\n offRaw(): void {\n this.rawHandler = undefined;\n LOGGER.log('Removed raw webhook handler');\n }\n\n /**\n * Remove a registered flow handler by type\n */\n offFlow(type: FlowTypeEnum): void {\n this.flowHandlers.delete(type);\n LOGGER.log(`Removed flow handler for ${type}`);\n }\n\n /**\n * Remove all registered handlers\n */\n removeAllHandlers(): void {\n this.messageHandlers.clear();\n this.statusHandler = undefined;\n this.userActionHandler = undefined;\n this.preProcessHandler = undefined;\n this.postProcessHandler = undefined;\n this.rawHandler = undefined;\n this.flowHandlers.clear();\n\n this.fieldHandlers.clear();\n\n LOGGER.log('Removed all handlers');\n }\n\n getClient(): WhatsApp {\n return this.client;\n }\n\n getConfig(): WabaConfigType {\n return this.config;\n }\n}\n","import type { WhatsAppConfig } from '../../../types/config';\nimport { constructFullUrl } from '../utils/webhookUtils';\nimport { WebhookProcessor } from '../WebhookProcessor';\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 | undefined;\n send?(data?: any): T | undefined;\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 type { WebhookResponse } from '../../WebhookProcessor';\nimport { type BaseRequest, type BaseResponse, type 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 type NextFunction = (error?: any) => void;\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 protected async handleGet(req: ExpressRequest, res: ExpressResponse, next: NextFunction): Promise<WebhookResponse> {\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 res.status(result.status).send(result.body);\n return result;\n } catch (error) {\n next(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 protected async handlePost(\n req: ExpressRequest,\n res: ExpressResponse,\n next: NextFunction,\n ): Promise<WebhookResponse> {\n try {\n const fullUrl = this.constructFullUrl(req.headers, req.url);\n const bodyContent = req.rawBody ?? (req.method === 'POST' ? JSON.stringify(req.body) : undefined);\n const webRequest = new globalThis.Request(fullUrl, {\n method: req.method,\n headers: req.headers as HeadersInit,\n body: bodyContent,\n });\n\n const result = await this.processWebhook(webRequest);\n this.applyHeaders(result, res);\n res.status(result.status).send(result.body);\n return result;\n } catch (error) {\n next(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 protected async handleFlow(\n req: ExpressRequest,\n res: ExpressResponse,\n next: NextFunction,\n ): Promise<WebhookResponse> {\n try {\n const fullUrl = this.constructFullUrl(req.headers, req.url);\n\n // Use raw body if available (for signature verification), otherwise stringify parsed body\n const bodyContent = req.rawBody ?? (req.method === 'POST' ? JSON.stringify(req.body) : undefined);\n\n const webRequest = new globalThis.Request(fullUrl, {\n method: req.method,\n headers: req.headers as HeadersInit,\n body: bodyContent,\n });\n\n const result = await this.processFlow(webRequest);\n this.applyHeaders(result, res);\n res.status(result.status).send(result.body);\n return result;\n } catch (error) {\n next(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 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\n// Singleton cache keyed by phoneNumberId\nconst handlerCache = new Map<string, ReturnType<ExpressWebhookHandler['getHandlers']> & { destroy: () => void }>();\n\nfunction getCacheKey(config: ExpressWebhookConfig): string {\n return `express:${config.phoneNumberId ?? 'default'}`;\n}\n\nexport function expressWebhookHandler(config: ExpressWebhookConfig) {\n const key = getCacheKey(config);\n const cached = handlerCache.get(key);\n if (cached) return cached;\n\n const handler = new ExpressWebhookHandler(config);\n const handlers = {\n ...handler.getHandlers(),\n /**\n * Destroy this handler instance: removes all registered handlers\n * and clears it from the singleton cache so the next call creates a fresh instance.\n */\n destroy: () => {\n handler.webhookProcessor.removeAllHandlers();\n handlerCache.delete(key);\n },\n };\n\n handlerCache.set(key, handlers);\n return handlers;\n}\n","// Docs: https://fastify.dev/docs/latest/Reference/ContentTypeParser/\nimport type { WhatsAppConfig } from '../../../../types/config';\nimport { constructFullUrl } from '../../utils/webhookUtils';\nimport { WebhookProcessor, type WebhookResponse } from '../../WebhookProcessor';\n\n// Fastify-like interfaces to avoid a direct Fastify dependency\nexport interface FastifyWebhookRequest {\n method: string;\n url: string;\n headers: Record<string, string | string[] | undefined>;\n body?: unknown;\n query?: unknown;\n /**\n * The unparsed request body. Fastify does not keep it by default: set it in\n * a content-type parser or with the `fastify-raw-body` plugin. Required for\n * `verifyWebhookSignature: true`, because re-serializing the parsed body\n * does not reproduce the bytes Meta signed.\n */\n rawBody?: string | Uint8Array;\n}\n\nexport interface FastifyWebhookReply {\n code(statusCode: number): FastifyWebhookReply;\n header(name: string, value: string): FastifyWebhookReply;\n send(payload?: any): FastifyWebhookReply;\n}\n\nexport interface FastifyWebhookConfig extends WhatsAppConfig {\n // Fastify specific config (currently none, but interface reserved for future use)\n}\n\n/** The object returned by {@link fastifyWebhookHandler}. */\nexport type FastifyWebhookHandlers = ReturnType<typeof createHandlers>;\n\n// Singleton cache keyed by phoneNumberId\nconst handlerCache = new Map<string, FastifyWebhookHandlers>();\n\nfunction getCacheKey(config: FastifyWebhookConfig): string {\n return `fastify:${config.phoneNumberId ?? 'default'}`;\n}\n\nfunction sendResult(reply: FastifyWebhookReply, result: WebhookResponse): FastifyWebhookReply {\n reply.code(result.status);\n for (const [name, value] of Object.entries(result.headers)) {\n reply.header(name, value);\n }\n return reply.send(result.body);\n}\n\nfunction sendInternalError(reply: FastifyWebhookReply): FastifyWebhookReply {\n return reply\n .code(500)\n .header('Content-Type', 'application/json')\n .send(JSON.stringify({ error: 'Internal Server Error' }));\n}\n\nfunction getQueryParam(query: unknown, name: string): string | null {\n if (typeof query !== 'object' || query === null) return null;\n const value = (query as Record<string, unknown>)[name];\n if (Array.isArray(value)) return typeof value[0] === 'string' ? value[0] : null;\n return typeof value === 'string' ? value : null;\n}\n\nfunction toHeaders(headers: FastifyWebhookRequest['headers']): Headers {\n const result = new Headers();\n for (const [name, value] of Object.entries(headers)) {\n if (value === undefined) continue;\n // The body is re-sent from memory, so the original framing headers no longer apply.\n if (name === 'content-length' || name === 'transfer-encoding') continue;\n result.set(name, Array.isArray(value) ? value.join(', ') : value);\n }\n return result;\n}\n\nfunction getBody(request: FastifyWebhookRequest): string | Uint8Array | undefined {\n if (request.rawBody !== undefined) return request.rawBody;\n if (request.body === undefined || request.body === null) return undefined;\n // Fallback: re-serialize the parsed body. Signature verification only\n // passes if this reproduces Meta's bytes exactly, so provide `rawBody`.\n return typeof request.body === 'string' ? request.body : JSON.stringify(request.body);\n}\n\nfunction toWebRequest(request: FastifyWebhookRequest): Request {\n const body = request.method === 'GET' || request.method === 'HEAD' ? undefined : getBody(request);\n return new Request(constructFullUrl(request.headers, request.url), {\n method: request.method,\n headers: toHeaders(request.headers),\n body: body as BodyInit | undefined,\n });\n}\n\n/**\n * Fastify webhook handler.\n *\n * @example\n * const wa = fastifyWebhookHandler(config);\n * wa.processor.onText(async (whatsapp, { message }) => { ... });\n * app.get('/webhook', wa.GET);\n * app.post('/webhook', wa.POST);\n * app.post('/flow', wa.flow);\n */\nexport function fastifyWebhookHandler(config: FastifyWebhookConfig): FastifyWebhookHandlers {\n const key = getCacheKey(config);\n const cached = handlerCache.get(key);\n if (cached) return cached;\n\n const handlers = createHandlers(config, key);\n handlerCache.set(key, handlers);\n return handlers;\n}\n\nfunction createHandlers(config: FastifyWebhookConfig, key: string) {\n const processor = new WebhookProcessor(config);\n\n const GET = async (request: FastifyWebhookRequest, reply: FastifyWebhookReply): Promise<FastifyWebhookReply> => {\n try {\n const result = await processor.processVerification(\n getQueryParam(request.query, 'hub.mode'),\n getQueryParam(request.query, 'hub.verify_token'),\n getQueryParam(request.query, 'hub.challenge'),\n );\n return sendResult(reply, result);\n } catch (error) {\n console.error('Webhook verification error:', error);\n return sendInternalError(reply);\n }\n };\n\n const POST = async (request: FastifyWebhookRequest, reply: FastifyWebhookReply): Promise<FastifyWebhookReply> => {\n try {\n return sendResult(reply, await processor.processWebhook(toWebRequest(request)));\n } catch (error) {\n console.error('Webhook processing error:', error);\n return sendInternalError(reply);\n }\n };\n\n const handlers = {\n GET,\n POST,\n\n // Auto-routing webhook handler (`app.route({ method: ['GET', 'POST'], url, handler: wa.webhook })`)\n webhook: async (request: FastifyWebhookRequest, reply: FastifyWebhookReply): Promise<FastifyWebhookReply> => {\n switch (request.method.toUpperCase()) {\n case 'GET':\n return GET(request, reply);\n case 'POST':\n return POST(request, reply);\n default:\n return reply\n .code(405)\n .header('Content-Type', 'application/json')\n .header('Allow', 'GET, POST')\n .send(JSON.stringify({ error: 'Method Not Allowed' }));\n }\n },\n\n // Flow handler\n flow: async (request: FastifyWebhookRequest, reply: FastifyWebhookReply): Promise<FastifyWebhookReply> => {\n try {\n return sendResult(reply, await processor.processFlow(toWebRequest(request)));\n } catch (error) {\n console.error('Flow processing error:', error);\n return sendInternalError(reply);\n }\n },\n\n // Expose processor for handler registration\n processor,\n\n /**\n * Destroy this handler instance: removes all registered handlers\n * and clears it from the singleton cache so the next call creates a fresh instance.\n */\n destroy: () => {\n processor.removeAllHandlers();\n handlerCache.delete(key);\n },\n };\n\n return handlers;\n}\n","// Docs: https://hono.dev/docs/api/context\nimport type { WhatsAppConfig } from '../../../../types/config';\nimport { WebhookProcessor, type WebhookResponse } from '../../WebhookProcessor';\n\n/**\n * The part of Hono's `Context` this adapter uses, typed locally so `hono` is\n * not a dependency. Any Hono `Context` satisfies it: `c.req.raw` is the\n * underlying web `Request`.\n */\nexport interface HonoWebhookContext {\n req: {\n raw: Request;\n /** Hono's cached body reader, used when middleware already consumed `raw`. */\n text?: () => Promise<string>;\n };\n}\n\nexport interface HonoWebhookConfig extends WhatsAppConfig {\n // Hono specific config (currently none, but interface reserved for future use)\n}\n\n/** The object returned by {@link honoWebhookHandler}. */\nexport type HonoWebhookHandlers = ReturnType<typeof createHandlers>;\n\n// Singleton cache keyed by phoneNumberId\nconst handlerCache = new Map<string, HonoWebhookHandlers>();\n\nfunction getCacheKey(config: HonoWebhookConfig): string {\n return `hono:${config.phoneNumberId ?? 'default'}`;\n}\n\nfunction toResponse(result: WebhookResponse): Response {\n return new Response(result.body, { status: result.status, headers: result.headers });\n}\n\nfunction internalError(): Response {\n return new Response(JSON.stringify({ error: 'Internal Server Error' }), {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n });\n}\n\n/**\n * Return the web Request for this context. If middleware already read the body\n * (e.g. `await c.req.json()`), rebuild the request from Hono's body cache.\n */\nasync function getRequest(c: HonoWebhookContext): Promise<Request> {\n const raw = c.req.raw;\n if (!raw.bodyUsed || !c.req.text) return raw;\n return new Request(raw.url, { method: raw.method, headers: raw.headers, body: await c.req.text() });\n}\n\n/**\n * Hono webhook handler. Works on every runtime Hono runs on (Node.js, Bun,\n * Deno, Cloudflare Workers, Vercel Edge).\n *\n * @example\n * const wa = honoWebhookHandler(config);\n * wa.processor.onText(async (whatsapp, { message }) => { ... });\n * app.get('/webhook', wa.GET);\n * app.post('/webhook', wa.POST);\n * app.post('/flow', wa.flow);\n */\nexport function honoWebhookHandler(config: HonoWebhookConfig): HonoWebhookHandlers {\n const key = getCacheKey(config);\n const cached = handlerCache.get(key);\n if (cached) return cached;\n\n const handlers = createHandlers(config, key);\n handlerCache.set(key, handlers);\n return handlers;\n}\n\nfunction createHandlers(config: HonoWebhookConfig, key: string) {\n const processor = new WebhookProcessor(config);\n\n const GET = async (c: HonoWebhookContext): Promise<Response> => {\n try {\n const { searchParams } = new URL(c.req.raw.url);\n const result = await processor.processVerification(\n searchParams.get('hub.mode'),\n searchParams.get('hub.verify_token'),\n searchParams.get('hub.challenge'),\n );\n return toResponse(result);\n } catch (error) {\n console.error('Webhook verification error:', error);\n return internalError();\n }\n };\n\n const POST = async (c: HonoWebhookContext): Promise<Response> => {\n try {\n return toResponse(await processor.processWebhook(await getRequest(c)));\n } catch (error) {\n console.error('Webhook processing error:', error);\n return internalError();\n }\n };\n\n const handlers = {\n GET,\n POST,\n\n // Auto-routing webhook handler (`app.all('/webhook', wa.webhook)`)\n webhook: async (c: HonoWebhookContext): Promise<Response> => {\n switch (c.req.raw.method.toUpperCase()) {\n case 'GET':\n return GET(c);\n case 'POST':\n return POST(c);\n default:\n return new Response(JSON.stringify({ error: 'Method Not Allowed' }), {\n status: 405,\n headers: { 'Content-Type': 'application/json', Allow: 'GET, POST' },\n });\n }\n },\n\n // Flow handler\n flow: async (c: HonoWebhookContext): Promise<Response> => {\n try {\n return toResponse(await processor.processFlow(await getRequest(c)));\n } catch (error) {\n console.error('Flow processing error:', error);\n return internalError();\n }\n },\n\n // Expose processor for handler registration\n processor,\n\n /**\n * Destroy this handler instance: removes all registered handlers\n * and clears it from the singleton cache so the next call creates a fresh instance.\n */\n destroy: () => {\n processor.removeAllHandlers();\n handlerCache.delete(key);\n },\n };\n\n return handlers;\n}\n","import type { 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\n// Singleton cache keyed by phoneNumberId\nconst handlerCache = new Map<string, NextJsAppWebhookHandlers>();\n\nfunction getCacheKey(config: NextJsAppWebhookConfig): string {\n return `nextjs-app:${config.phoneNumberId ?? 'default'}`;\n}\n\n/** The object returned by {@link nextjsAppWebhookHandler}. */\nexport type NextJsAppWebhookHandlers = ReturnType<typeof createHandlers>;\n\n// Next.js App Router webhook handler\nexport function nextjsAppWebhookHandler(config: NextJsAppWebhookConfig): NextJsAppWebhookHandlers {\n const key = getCacheKey(config);\n const cached = handlerCache.get(key);\n if (cached) return cached;\n\n const handlers = createHandlers(config, key);\n handlerCache.set(key, handlers);\n return handlers;\n}\n\nfunction createHandlers(config: NextJsAppWebhookConfig, key: string) {\n const processor = new WebhookProcessor(config);\n\n const handlers = {\n // Clean GET/POST handlers following whatsapp-api-js methodology\n GET: async (request: Request) => {\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: Request) => {\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: Request) => {\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: Request) => {\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: Request) => {\n try {\n const result = await processor.processFlow(request);\n\n // result.body is already a JSON string, don't double-encode it\n return new Response(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(JSON.stringify({ error: 'Internal Server Error' }), {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n },\n\n POST: async (request: Request) => {\n try {\n const result = await processor.processFlow(request);\n\n // result.body is already a JSON string, don't double-encode it\n return new Response(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(JSON.stringify({ error: 'Internal Server Error' }), {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n },\n },\n\n // Expose processor for handler registration\n processor,\n\n /**\n * Destroy this handler instance: removes all registered handlers\n * and clears it from the singleton cache so the next call creates a fresh instance.\n */\n destroy: () => {\n processor.removeAllHandlers();\n handlerCache.delete(key);\n },\n };\n\n return handlers;\n}\n","import type { WebhookResponse } from '../../WebhookProcessor';\nimport { type BaseRequest, type BaseResponse, type 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): undefined | any;\n send(data?: any): undefined | 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 // Helper function to parse request body for POST requests\n private async parseRequestBody(req: TRequest, preserveRaw: boolean = false): 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 // Store raw body if requested (for signature verification)\n if (preserveRaw) {\n req.rawBody = body;\n }\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<WebhookResponse> {\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 res.status(result.status).send(result.body);\n return result;\n } catch (error) {\n console.error('Webhook verification error:', error);\n res.status(500).json({ error: 'Internal Server 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 protected async handlePost(req: TRequest, res: TResponse): Promise<WebhookResponse> {\n try {\n // Auto-parse body if needed\n await this.parseRequestBody(req, true);\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 res.status(400).json({ error: 'Invalid JSON' });\n return {\n status: 400,\n body: JSON.stringify({ error: 'Invalid JSON' }),\n headers: { 'Content-Type': 'application/json' },\n };\n }\n\n res.status(500).json({ error: 'Internal Server Error' });\n return {\n status: 500,\n body: JSON.stringify({ error: 'Internal Server Error' }),\n headers: { 'Content-Type': 'application/json' },\n };\n }\n\n try {\n const fullUrl = this.constructFullUrl(req.headers, req.url);\n const bodyContent = req.rawBody ?? (req.method === 'POST' ? JSON.stringify(req.body) : undefined);\n\n const webRequest = new Request(fullUrl, {\n method: 'POST',\n headers: req.headers as HeadersInit,\n body: bodyContent,\n });\n\n const result = await this.processWebhook(webRequest);\n this.applyHeaders(result, res);\n res.status(result.status).send(result.body);\n return result;\n } catch (error) {\n console.error('Webhook processing error:', error);\n res.status(500).json({ error: 'Internal Server 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 protected async handleFlow(req: TRequest, res: TResponse): Promise<WebhookResponse> {\n try {\n // Parse body and preserve raw body for signature verification\n await this.parseRequestBody(req, true);\n } catch (error) {\n console.error('Flow body parsing error:', error);\n\n // Handle JSON parsing errors specifically\n if (error instanceof Error && error.message === 'Invalid JSON in request body') {\n res.status(400).json({ error: 'Invalid JSON' });\n return {\n status: 400,\n body: JSON.stringify({ error: 'Invalid JSON' }),\n headers: { 'Content-Type': 'application/json' },\n };\n }\n\n res.status(500).json({ error: 'Internal Server Error' });\n return {\n status: 500,\n body: JSON.stringify({ error: 'Internal Server Error' }),\n headers: { 'Content-Type': 'application/json' },\n };\n }\n\n try {\n const fullUrl = this.constructFullUrl(req.headers, req.url);\n\n // Use raw body if available (for signature verification), otherwise stringify parsed body\n const bodyContent = req.rawBody ?? (req.method === 'POST' ? JSON.stringify(req.body) : undefined);\n\n const webRequest = new Request(fullUrl, {\n method: req.method,\n headers: req.headers as HeadersInit,\n body: bodyContent,\n });\n\n const result = await this.processFlow(webRequest);\n this.applyHeaders(result, res);\n res.status(result.status).send(result.body);\n\n // Return result for user's custom handling\n return result;\n } catch (error) {\n console.error('Flow error:', error);\n res.status(500).json({ error: 'Internal Server 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 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// Singleton cache keyed by phoneNumberId\nconst handlerCache = new Map<\n string,\n ReturnType<NextJsWebhookHandler<any, any>['getHandlers']> & { destroy: () => void }\n>();\n\nfunction getCacheKey(config: NextJsWebhookConfig): string {\n return `nextjs-page:${config.phoneNumberId ?? 'default'}`;\n}\n\n// Next.js Pages Router webhook handler\nexport function nextjsPagesWebhookHandler<TRequest extends BaseApiRequest, TResponse extends BaseApiResponse>(\n config: NextJsWebhookConfig,\n) {\n const key = getCacheKey(config);\n const cached = handlerCache.get(key);\n if (cached) return cached;\n\n const handler = new NextJsWebhookHandler<TRequest, TResponse>(config);\n const handlers = {\n ...handler.getHandlers(),\n /**\n * Destroy this handler instance: removes all registered handlers\n * and clears it from the singleton cache so the next call creates a fresh instance.\n */\n destroy: () => {\n handler.webhookProcessor.removeAllHandlers();\n handlerCache.delete(key);\n },\n };\n\n handlerCache.set(key, handlers);\n return handlers;\n}\n","import { MessageTypesEnum } from '../../../types/enums';\nimport type { WhatsAppMessage } from '../types/message';\n\n/**\n * Extracts a human-readable display text from any incoming WhatsApp message.\n *\n * Useful for logging, notifications, chat previews, and storing message summaries.\n *\n * @param message - The incoming WhatsApp message from a webhook handler\n * @returns A display-friendly string representing the message content\n *\n * @example\n * ```ts\n * handler.processor.onText(async (whatsapp, processed) => {\n * const text = extractMessageText(processed.message);\n * console.log(`Message from ${processed.message.from}: ${text}`);\n * });\n * ```\n */\nexport function extractMessageText(message: WhatsAppMessage): string {\n switch (message.type) {\n case MessageTypesEnum.Text:\n return message.text.body;\n\n case MessageTypesEnum.Image:\n return message.image.caption || '[Image]';\n\n case MessageTypesEnum.Video:\n return message.video.caption || '[Video]';\n\n case MessageTypesEnum.Audio:\n return message.audio.voice ? '[Voice Message]' : '[Audio]';\n\n case MessageTypesEnum.Document:\n return message.document.caption || message.document.filename || '[Document]';\n\n case MessageTypesEnum.Sticker:\n return message.sticker.animated ? '[Animated Sticker]' : '[Sticker]';\n\n case MessageTypesEnum.Interactive: {\n const interactive = message.interactive;\n if (interactive.type === 'button_reply') {\n return interactive.button_reply.title;\n }\n if (interactive.type === 'list_reply') {\n return interactive.list_reply.title;\n }\n if (interactive.type === 'nfm_reply') {\n return interactive.nfm_reply.body || interactive.nfm_reply.name || '[Form Reply]';\n }\n return '[Interactive]';\n }\n\n case MessageTypesEnum.Button:\n return message.button.text;\n\n case MessageTypesEnum.Location:\n return (\n message.location.name ||\n message.location.address ||\n `📍 ${message.location.latitude}, ${message.location.longitude}`\n );\n\n case MessageTypesEnum.Contacts: {\n const names = message.contacts.map((c) => c.name.formatted_name);\n return names.length === 1 ? `👤 ${names[0]}` : `👤 ${names.length} contacts`;\n }\n\n case MessageTypesEnum.Reaction:\n return message.reaction.emoji || '[Reaction removed]';\n\n case MessageTypesEnum.Order: {\n const count = message.order.product_items.length;\n return `🛒 Order: ${count} item${count > 1 ? 's' : ''}`;\n }\n\n case MessageTypesEnum.System:\n return message.system.body;\n\n case MessageTypesEnum.Unsupported:\n return '[Unsupported message]';\n\n default:\n return `[${(message as any).type}]`;\n }\n}\n","import { hmacSha256Hex, requireNodeCrypto } from '../../../utils/runtime';\n\n/**\n * Compute the hex HMAC-SHA256 that Meta sends in `X-Hub-Signature-256`\n * (without the `sha256=` prefix). Needs `node:crypto`; use\n * {@link generateXHub256SigAsync} on edge runtimes.\n */\nexport const generateXHub256Sig = (body: string, appSecret: string) => {\n return requireNodeCrypto('generateXHub256Sig').createHmac('sha256', appSecret).update(body, 'utf-8').digest('hex');\n};\n\n/** Web Crypto variant of {@link generateXHub256Sig}; works on every runtime. */\nexport const generateXHub256SigAsync = (body: string, appSecret: string): Promise<string> => {\n return hmacSha256Hex(appSecret, body);\n};\n","import { MessageTypesEnum } from '../../../types/enums';\nimport type {\n AudioMessage,\n ButtonMessage,\n ContactsMessage,\n DocumentMessage,\n ImageMessage,\n InteractiveButtonReplyMessage,\n InteractiveListReplyMessage,\n InteractiveMessage,\n InteractiveNfmReplyMessage,\n LocationMessage,\n OrderMessage,\n ReactionMessage,\n StickerMessage,\n SystemMessage,\n TextMessage,\n VideoMessage,\n WhatsAppMessage,\n} from '../types/message';\n\n// ============================================================================\n// Type Guards — narrow WhatsAppMessage to specific types\n// ============================================================================\n\nexport function isTextMessage(msg: WhatsAppMessage): msg is TextMessage {\n return msg.type === MessageTypesEnum.Text;\n}\n\nexport function isImageMessage(msg: WhatsAppMessage): msg is ImageMessage {\n return msg.type === MessageTypesEnum.Image;\n}\n\nexport function isVideoMessage(msg: WhatsAppMessage): msg is VideoMessage {\n return msg.type === MessageTypesEnum.Video;\n}\n\nexport function isAudioMessage(msg: WhatsAppMessage): msg is AudioMessage {\n return msg.type === MessageTypesEnum.Audio;\n}\n\nexport function isDocumentMessage(msg: WhatsAppMessage): msg is DocumentMessage {\n return msg.type === MessageTypesEnum.Document;\n}\n\nexport function isStickerMessage(msg: WhatsAppMessage): msg is StickerMessage {\n return msg.type === MessageTypesEnum.Sticker;\n}\n\nexport function isInteractiveMessage(msg: WhatsAppMessage): msg is InteractiveMessage {\n return msg.type === MessageTypesEnum.Interactive;\n}\n\nexport function isButtonMessage(msg: WhatsAppMessage): msg is ButtonMessage {\n return msg.type === MessageTypesEnum.Button;\n}\n\nexport function isLocationMessage(msg: WhatsAppMessage): msg is LocationMessage {\n return msg.type === MessageTypesEnum.Location;\n}\n\nexport function isContactsMessage(msg: WhatsAppMessage): msg is ContactsMessage {\n return msg.type === MessageTypesEnum.Contacts;\n}\n\nexport function isReactionMessage(msg: WhatsAppMessage): msg is ReactionMessage {\n return msg.type === MessageTypesEnum.Reaction;\n}\n\nexport function isOrderMessage(msg: WhatsAppMessage): msg is OrderMessage {\n return msg.type === MessageTypesEnum.Order;\n}\n\nexport function isSystemMessage(msg: WhatsAppMessage): msg is SystemMessage {\n return msg.type === MessageTypesEnum.System;\n}\n\n// Interactive sub-type guards\nexport function isButtonReply(msg: WhatsAppMessage): msg is InteractiveButtonReplyMessage {\n return isInteractiveMessage(msg) && msg.interactive.type === 'button_reply';\n}\n\nexport function isListReply(msg: WhatsAppMessage): msg is InteractiveListReplyMessage {\n return isInteractiveMessage(msg) && msg.interactive.type === 'list_reply';\n}\n\nexport function isNfmReply(msg: WhatsAppMessage): msg is InteractiveNfmReplyMessage {\n return isInteractiveMessage(msg) && msg.interactive.type === 'nfm_reply';\n}\n\n// ============================================================================\n// Structured data extractors — type-safe parsed data from messages\n// ============================================================================\n\nexport type MediaInfo = {\n id: string;\n mimeType: string;\n sha256: string;\n caption?: string;\n filename?: string;\n animated?: boolean;\n voice?: boolean;\n};\n\n/**\n * Extract media info from image/video/audio/document/sticker messages.\n * Returns null if the message is not a media message.\n *\n * @example\n * ```ts\n * const media = getMediaInfo(message);\n * if (media) {\n * const url = await sdk.media.get(media.id);\n * }\n * ```\n */\nexport function getMediaInfo(msg: WhatsAppMessage): MediaInfo | null {\n if (isImageMessage(msg)) {\n return {\n id: msg.image.id,\n mimeType: msg.image.mime_type,\n sha256: msg.image.sha256,\n caption: msg.image.caption,\n };\n }\n if (isVideoMessage(msg)) {\n return {\n id: msg.video.id,\n mimeType: msg.video.mime_type,\n sha256: msg.video.sha256,\n caption: msg.video.caption,\n };\n }\n if (isAudioMessage(msg)) {\n return { id: msg.audio.id, mimeType: msg.audio.mime_type, sha256: msg.audio.sha256, voice: msg.audio.voice };\n }\n if (isDocumentMessage(msg)) {\n return {\n id: msg.document.id,\n mimeType: msg.document.mime_type,\n sha256: msg.document.sha256,\n caption: msg.document.caption,\n filename: msg.document.filename,\n };\n }\n if (isStickerMessage(msg)) {\n return {\n id: msg.sticker.id,\n mimeType: msg.sticker.mime_type,\n sha256: msg.sticker.sha256,\n animated: msg.sticker.animated,\n };\n }\n return null;\n}\n\nexport type InteractiveReply = {\n type: 'button_reply' | 'list_reply' | 'nfm_reply';\n id: string;\n title: string;\n description?: string;\n responseJson?: string;\n};\n\n/**\n * Extract the user's selection from interactive messages (button reply, list reply, nfm reply).\n * Returns null if not an interactive message.\n *\n * @example\n * ```ts\n * const reply = getInteractiveReply(message);\n * if (reply) {\n * console.log(`User selected: ${reply.title} (id: ${reply.id})`);\n * }\n * ```\n */\nexport function getInteractiveReply(msg: WhatsAppMessage): InteractiveReply | null {\n if (!isInteractiveMessage(msg)) return null;\n\n if (msg.interactive.type === 'button_reply') {\n return {\n type: 'button_reply',\n id: msg.interactive.button_reply.id,\n title: msg.interactive.button_reply.title,\n };\n }\n if (msg.interactive.type === 'list_reply') {\n return {\n type: 'list_reply',\n id: msg.interactive.list_reply.id,\n title: msg.interactive.list_reply.title,\n description: msg.interactive.list_reply.description,\n };\n }\n if (msg.interactive.type === 'nfm_reply') {\n return {\n type: 'nfm_reply',\n id: msg.interactive.nfm_reply.name,\n title: msg.interactive.nfm_reply.body,\n responseJson: msg.interactive.nfm_reply.response_json,\n };\n }\n return null;\n}\n\nexport type LocationInfo = {\n latitude: number;\n longitude: number;\n name?: string;\n address?: string;\n url?: string;\n};\n\n/**\n * Extract location data from a location message.\n * Returns null if not a location message.\n */\nexport function getLocationInfo(msg: WhatsAppMessage): LocationInfo | null {\n if (!isLocationMessage(msg)) return null;\n return {\n latitude: msg.location.latitude,\n longitude: msg.location.longitude,\n name: msg.location.name,\n address: msg.location.address,\n url: msg.location.url,\n };\n}\n\nexport type ContactInfo = {\n formattedName: string;\n firstName?: string;\n lastName?: string;\n phones: string[];\n emails: string[];\n};\n\n/**\n * Extract contact info from a contacts message.\n * Returns empty array if not a contacts message.\n */\nexport function getContactsInfo(msg: WhatsAppMessage): ContactInfo[] {\n if (!isContactsMessage(msg)) return [];\n return msg.contacts.map((c) => ({\n formattedName: c.name.formatted_name,\n firstName: c.name.first_name,\n lastName: c.name.last_name,\n phones: c.phones?.map((p) => p.phone) || [],\n emails: c.emails?.map((e) => e.email) || [],\n }));\n}\n\nexport type ReactionInfo = {\n messageId: string;\n emoji: string | null; // null = reaction removed\n};\n\n/**\n * Extract reaction data from a reaction message.\n * Returns null if not a reaction message.\n */\nexport function getReactionInfo(msg: WhatsAppMessage): ReactionInfo | null {\n if (!isReactionMessage(msg)) return null;\n return {\n messageId: msg.reaction.message_id,\n emoji: msg.reaction.emoji || null,\n };\n}\n\nexport type OrderInfo = {\n catalogId: string;\n text?: string;\n items: Array<{\n productId: string;\n quantity: number;\n price: number;\n currency: string;\n }>;\n};\n\n/**\n * Extract order data from an order message.\n * Returns null if not an order message.\n */\nexport function getOrderInfo(msg: WhatsAppMessage): OrderInfo | null {\n if (!isOrderMessage(msg)) return null;\n return {\n catalogId: msg.order.catalog_id,\n text: msg.order.text,\n items: msg.order.product_items.map((item) => ({\n productId: item.product_retailer_id,\n quantity: item.quantity,\n price: item.item_price,\n currency: item.currency,\n })),\n };\n}\n","/**\n * As-const alternatives to enums.\n *\n * Every enum in enums.ts gets a matching `as const` object and a union type here.\n * Use whichever style you prefer:\n * - Enum: CategoryEnum.Marketing\n * - Const: Category.Marketing (value: 'MARKETING')\n * - Type: CategoryType (union: 'AUTHENTICATION' | 'MARKETING' | 'UTILITY')\n */\n\n// ---- Category ----\nexport const Category = {\n Authentication: 'AUTHENTICATION',\n Marketing: 'MARKETING',\n Utility: 'UTILITY',\n} as const;\nexport type CategoryType = (typeof Category)[keyof typeof Category];\n\n// ---- MessageCategory (Direct Send) ----\nexport const MessageCategory = {\n Authentication: 'authentication',\n Service: 'service',\n Utility: 'utility',\n} as const;\nexport type MessageCategoryType = (typeof MessageCategory)[keyof typeof MessageCategory];\n\n// ---- TemplateStatus ----\nexport const TemplateStatus = {\n Approved: 'APPROVED',\n Pending: 'PENDING',\n Rejected: 'REJECTED',\n} as const;\nexport type TemplateStatusType = (typeof TemplateStatus)[keyof typeof TemplateStatus];\n\n// ---- HttpMethods ----\nexport const HttpMethods = {\n Get: 'GET',\n Post: 'POST',\n Put: 'PUT',\n Delete: 'DELETE',\n} as const;\nexport type HttpMethodsType = (typeof HttpMethods)[keyof typeof HttpMethods];\n\n// ---- MessageTypes ----\nexport const MessageTypes = {\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 Unsupported: 'unsupported',\n Unknown: 'unknown',\n /** @deprecated Use WebhookProcessor.onStatus() instead */\n Statuses: 'statuses',\n All: '*',\n} as const;\nexport type MessageTypesType = (typeof MessageTypes)[keyof typeof MessageTypes];\n\n// ---- ParametersTypes ----\nexport const ParametersTypes = {\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} as const;\nexport type ParametersTypesType = (typeof ParametersTypes)[keyof typeof ParametersTypes];\n\n// ---- InteractiveTypes ----\nexport const InteractiveTypes = {\n Button: 'button',\n List: 'list',\n Product: 'product',\n ProductList: 'product_list',\n CtaUrl: 'cta_url',\n Carousel: 'carousel',\n LocationRequest: 'location_request_message',\n AddressMessage: 'address_message',\n Flow: 'flow',\n VoiceCall: 'voice_call',\n} as const;\nexport type InteractiveTypesType = (typeof InteractiveTypes)[keyof typeof InteractiveTypes];\n\n// ---- ButtonPosition ----\nexport const ButtonPosition = {\n First: 1,\n Second: 2,\n Third: 3,\n Fourth: 4,\n Fifth: 5,\n} as const;\nexport type ButtonPositionType = (typeof ButtonPosition)[keyof typeof ButtonPosition];\n\n// ---- SubType ----\nexport const SubType = {\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} as const;\nexport type SubTypeType = (typeof SubType)[keyof typeof SubType];\n\n// ---- ComponentTypes (template) ----\nexport const ComponentType = {\n Header: 'HEADER',\n Body: 'BODY',\n Button: 'BUTTON',\n Footer: 'FOOTER',\n} as const;\nexport type ComponentTypeType = (typeof ComponentType)[keyof typeof ComponentType];\n\n// ---- ConversationTypes ----\nexport const ConversationTypes = {\n BusinessInitiated: 'business_initiated',\n CustomerInitiated: 'customer_initiated',\n ReferralConversion: 'referral_conversion',\n} as const;\nexport type ConversationTypesType = (typeof ConversationTypes)[keyof typeof ConversationTypes];\n\n// ---- Status ----\nexport const Status = {\n Delivered: 'delivered',\n Read: 'read',\n Sent: 'sent',\n} as const;\nexport type StatusType = (typeof Status)[keyof typeof Status];\n\n// ---- VideoMediaTypes ----\nexport const VideoMediaTypes = {\n Mp4: 'video/mp4',\n Threegp: 'video/3gp',\n} as const;\nexport type VideoMediaTypesType = (typeof VideoMediaTypes)[keyof typeof VideoMediaTypes];\n\n// ---- StickerMediaTypes ----\nexport const StickerMediaTypes = {\n Webp: 'image/webp',\n} as const;\nexport type StickerMediaTypesType = (typeof StickerMediaTypes)[keyof typeof StickerMediaTypes];\n\n// ---- ImageMediaTypes ----\nexport const ImageMediaTypes = {\n Jpeg: 'image/jpeg',\n Png: 'image/png',\n} as const;\nexport type ImageMediaTypesType = (typeof ImageMediaTypes)[keyof typeof ImageMediaTypes];\n\n// ---- DocumentMediaTypes ----\nexport const DocumentMediaTypes = {\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} as const;\nexport type DocumentMediaTypesType = (typeof DocumentMediaTypes)[keyof typeof DocumentMediaTypes];\n\n// ---- AudioMediaTypes ----\nexport const AudioMediaTypes = {\n Aac: 'audio/aac',\n Mp4: 'audio/mp4',\n Mpeg: 'audio/mpeg',\n Amr: 'audio/amr',\n Ogg: 'audio/ogg',\n} as const;\nexport type AudioMediaTypesType = (typeof AudioMediaTypes)[keyof typeof AudioMediaTypes];\n\n// ---- WebhookTypes ----\nexport const WebhookTypes = {\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} as const;\nexport type WebhookTypesType = (typeof WebhookTypes)[keyof typeof WebhookTypes];\n\n// ---- SystemChangeTypes ----\nexport const SystemChangeTypes = {\n /** @deprecated Meta renamed this to `user_changed_number`. Use `UserChangedNumber`. */\n CustomerChangedNumber: 'customer_changed_number',\n /** @deprecated Meta renamed this to `user_identity_changed`. Use `UserIdentityChanged`. */\n CustomerIdentityChanged: 'customer_identity_changed',\n UserChangedNumber: 'user_changed_number',\n UserIdentityChanged: 'user_identity_changed',\n /** The user's business-scoped user ID (BSUID) changed. */\n UserChangedUserId: 'user_changed_user_id',\n} as const;\nexport type SystemChangeTypesType = (typeof SystemChangeTypes)[keyof typeof SystemChangeTypes];\n\n// ---- ReferralSourceTypes ----\nexport const ReferralSourceTypes = {\n Ad: 'ad',\n Post: 'post',\n} as const;\nexport type ReferralSourceTypesType = (typeof ReferralSourceTypes)[keyof typeof ReferralSourceTypes];\n\n// ---- RequestCodeMethods ----\nexport const RequestCodeMethods = {\n Sms: 'SMS',\n Voice: 'VOICE',\n} as const;\nexport type RequestCodeMethodsType = (typeof RequestCodeMethods)[keyof typeof RequestCodeMethods];\n\n// ---- Languages ----\nexport const Languages = {\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} as const;\nexport type LanguagesType = (typeof Languages)[keyof typeof Languages];\n\n// ---- DataLocalizationRegion ----\nexport const DataLocalizationRegion = {\n AU: 'AU',\n ID: 'ID',\n IN: 'IN',\n JP: 'JP',\n SG: 'SG',\n KR: 'KR',\n DE: 'DE',\n CH: 'CH',\n GB: 'GB',\n BR: 'BR',\n BH: 'BH',\n ZA: 'ZA',\n AE: 'AE',\n CA: 'CA',\n} as const;\nexport type DataLocalizationRegionType = (typeof DataLocalizationRegion)[keyof typeof DataLocalizationRegion];\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/messages/send-messages/\n\nimport { WhatsAppValidationError } from './isMetaError';\n\nconst HOUR_MS = 60 * 60 * 1000;\n\n/**\n * Length of the customer service window: 24 hours.\n *\n * \"When a WhatsApp user messages you or calls you, a 24-hour timer called a customer service window\n * starts. If the user messages or calls you again before the timer expires, the timer resets to\n * 24 hours. [...] When the window closes, you can only send pre-approved template messages.\"\n *\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/messages/send-messages/ | Send messages: customer service windows}\n */\nexport const CUSTOMER_SERVICE_WINDOW_MS = 24 * HOUR_MS;\n\n/**\n * SDK fallback length of a free entry point (FEP) window: 72 hours.\n * Prefer the expiry supplied by Meta; this fallback does not establish billing eligibility.\n *\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/pricing/ | Pricing: free entry point windows}\n */\nexport const FREE_ENTRY_POINT_WINDOW_MS = 72 * HOUR_MS;\n\n/**\n * Longest free entry point window Meta documents: up to 7 days for conversations started from an\n * ad that clicks to WhatsApp.\n *\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/pricing/ | Pricing: free entry point windows}\n */\nexport const MAX_FREE_ENTRY_POINT_WINDOW_MS = 7 * 24 * HOUR_MS;\n\n/**\n * A point in time accepted by the window helpers:\n * - `Date`\n * - `number`: Unix epoch in milliseconds, or in seconds when below `1e11` (before the year 5138 in\n * seconds, before March 1973 in milliseconds), so both `Date.now()` and webhook timestamps work\n * - `string`: a numeric string such as the webhook `messages[].timestamp` (`\"1727856000\"`, Unix\n * seconds, same rule as numbers), or any string `Date.parse` understands (ISO 8601)\n */\nexport type WindowTimestamp = Date | number | string;\n\n/** State of a messaging window at a given instant. */\nexport interface MessagingWindow {\n /** True while the window is open (`now < expiresAt`). */\n isOpen: boolean;\n /** When the window closes, or `null` when there is no window (no inbound message yet). */\n expiresAt: Date | null;\n /** Milliseconds until the window closes, `0` once closed. Never more than the window length. */\n remainingMs: number;\n}\n\nexport interface CustomerServiceWindowOptions {\n /** The instant to evaluate. Defaults to `Date.now()`. */\n now?: WindowTimestamp;\n /**\n * Treat the window as closing this many milliseconds early. Use it to absorb clock drift between\n * your servers and Meta and the time a send spends in flight. Defaults to `0`.\n */\n safetyMarginMs?: number;\n}\n\nexport interface FreeEntryPointWindowOptions extends CustomerServiceWindowOptions {\n /**\n * Window length. Defaults to {@link FREE_ENTRY_POINT_WINDOW_MS} (72 hours). Meta may keep a\n * click-to-WhatsApp ad window open for up to {@link MAX_FREE_ENTRY_POINT_WINDOW_MS} (7 days)\n * without saying how long a given window lasts, so prefer `expiresAt` when you have it.\n */\n durationMs?: number;\n /**\n * Exact expiry when known, for example the status webhook's `conversation.expiration_timestamp`\n * (Unix seconds). Overrides `durationMs`.\n */\n expiresAt?: WindowTimestamp;\n}\n\nconst SECONDS_THRESHOLD = 1e11;\n\nfunction toEpochMs(value: WindowTimestamp, name: string): number {\n let ms: number;\n\n if (value instanceof Date) {\n ms = value.getTime();\n } else if (typeof value === 'number') {\n ms = Math.abs(value) < SECONDS_THRESHOLD ? value * 1000 : value;\n } else if (typeof value === 'string') {\n const trimmed = value.trim();\n if (/^\\d+(\\.\\d+)?$/.test(trimmed)) {\n const num = Number(trimmed);\n ms = num < SECONDS_THRESHOLD ? num * 1000 : num;\n } else {\n ms = trimmed === '' ? Number.NaN : Date.parse(trimmed);\n }\n } else {\n ms = Number.NaN;\n }\n\n if (!Number.isFinite(ms) || !Number.isFinite(new Date(ms).getTime())) {\n throw new WhatsAppValidationError(`${name} is not a valid timestamp: ${String(value)}`);\n }\n return ms;\n}\n\nfunction toNonNegativeMs(value: number | undefined, name: string, fallback: number): number {\n if (value === undefined) return fallback;\n if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {\n throw new WhatsAppValidationError(`${name} must be a non-negative number of milliseconds`);\n }\n return value;\n}\n\nfunction computeWindow(startMs: number, endMs: number, nowMs: number, safetyMarginMs: number): MessagingWindow {\n if (!Number.isFinite(new Date(endMs).getTime())) {\n throw new WhatsAppValidationError('Window expiry is outside the supported timestamp range');\n }\n const lengthMs = Math.max(0, endMs - startMs);\n const effectiveEndMs = endMs - safetyMarginMs;\n // A start in the future means the clocks disagree; never report more than one full window.\n const remainingMs = Math.min(Math.max(0, effectiveEndMs - nowMs), lengthMs);\n return {\n isOpen: remainingMs > 0,\n expiresAt: new Date(endMs),\n remainingMs,\n };\n}\n\nconst CLOSED: MessagingWindow = Object.freeze({ isOpen: false, expiresAt: null, remainingMs: 0 }) as MessagingWindow;\n\n/**\n * Returns the state of the 24-hour customer service window opened by the user's last inbound\n * message (or call).\n *\n * Free-form (non-template) messages can only be sent while it is open; outside it only approved\n * template messages are delivered (Meta rejects others with error `131047`). The window is exactly\n * 24 hours from the user's last message: at `lastInboundAt + 24h` it is closed.\n *\n * Pass the webhook message `timestamp` (Unix seconds string) of the latest message from the user.\n * Messages you send do not extend the window. Pass `null`/`undefined` when the user has never\n * messaged you; that returns a closed window with `expiresAt: null`.\n *\n * A free entry point window does not reopen this window: \"the customer service window is independent\n * of the FEP window, so if the customer service window closes, you will only be able to send template\n * messages.\" Use {@link getFreeEntryPointWindow} for the pricing side.\n *\n * @throws WhatsAppValidationError when a timestamp or `safetyMarginMs` is malformed.\n *\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/messages/send-messages/ | Send messages: customer service windows}\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/pricing/ | Pricing}\n *\n * @example\n * ```ts\n * const { isOpen, expiresAt } = getCustomerServiceWindow(message.timestamp);\n * if (!isOpen) await sendTemplateInstead();\n * ```\n */\nexport function getCustomerServiceWindow(\n lastInboundAt: WindowTimestamp | null | undefined,\n options: CustomerServiceWindowOptions = {},\n): MessagingWindow {\n const safetyMarginMs = toNonNegativeMs(options.safetyMarginMs, 'safetyMarginMs', 0);\n const nowMs = options.now === undefined ? Date.now() : toEpochMs(options.now, 'now');\n if (lastInboundAt === null || lastInboundAt === undefined) return { ...CLOSED };\n\n const startMs = toEpochMs(lastInboundAt, 'lastInboundAt');\n return computeWindow(startMs, startMs + CUSTOMER_SERVICE_WINDOW_MS, nowMs, safetyMarginMs);\n}\n\n/**\n * True when a free-form (non-template) message can be sent: the customer service window opened by\n * the user's last inbound message is still open. See {@link getCustomerServiceWindow}.\n *\n * @throws WhatsAppValidationError when a timestamp or `safetyMarginMs` is malformed.\n */\nexport function canSendFreeformMessage(\n lastInboundAt: WindowTimestamp | null | undefined,\n options: CustomerServiceWindowOptions = {},\n): boolean {\n return getCustomerServiceWindow(lastInboundAt, options).isOpen;\n}\n\n/**\n * Returns the state of a free entry point (FEP) window.\n *\n * For eligible click-to-WhatsApp ad traffic, replying within the customer service window opens\n * a billing window from the time of your reply. Pass that first reply time as `openedAt`.\n *\n * Meta documents windows lasting up to 7 days for ads that click to WhatsApp. This helper uses\n * a 72-hour fallback estimate. Pass `expiresAt` (the status webhook's\n * `conversation.expiration_timestamp`) when you have it, or set `durationMs`.\n *\n * This is a billing window only. It does not allow free-form messages after the customer service\n * window closes; check {@link canSendFreeformMessage} for that.\n *\n * @throws WhatsAppValidationError when a timestamp, `durationMs` or `safetyMarginMs` is malformed.\n *\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/pricing/ | Pricing: free entry point windows}\n */\nexport function getFreeEntryPointWindow(\n openedAt: WindowTimestamp | null | undefined,\n options: FreeEntryPointWindowOptions = {},\n): MessagingWindow {\n const safetyMarginMs = toNonNegativeMs(options.safetyMarginMs, 'safetyMarginMs', 0);\n const durationMs = toNonNegativeMs(options.durationMs, 'durationMs', FREE_ENTRY_POINT_WINDOW_MS);\n const nowMs = options.now === undefined ? Date.now() : toEpochMs(options.now, 'now');\n if (openedAt === null || openedAt === undefined) return { ...CLOSED };\n\n const startMs = toEpochMs(openedAt, 'openedAt');\n const endMs = options.expiresAt === undefined ? startMs + durationMs : toEpochMs(options.expiresAt, 'expiresAt');\n return computeWindow(startMs, endMs, nowMs, safetyMarginMs);\n}\n"],"mappings":"8DAAA,MAaa,EAA6B,WCJ1C,IAAa,EAAb,KAA0C,CACtC,OACA,OAEA,YAAY,EAAwB,EAAwB,CACxD,KAAK,OAAS,EACd,KAAK,OAAS,CAClB,CAEA,SAAsB,EAAyB,EAAkB,EAAiB,EAAwB,CACtG,OAAO,KAAK,OAAO,QAAW,EAAQ,EAAU,EAAS,CAAI,CACjE,CAGA,MAAgB,QAAQ,EAAyB,EAAkB,EAAoC,CAEnG,OAAO,MADgB,KAAK,OAAO,YAAY,EAAQ,EAAU,CAAO,EAAA,CACxD,YAAY,CAChC,CAEA,aAA0B,EAAyB,EAAkB,EAAiB,EAAwB,CAC1G,OAAO,KAAK,OAAO,aAAgB,EAAQ,EAAU,EAAS,CAAI,CACtE,CAEA,mBACI,EACA,EACA,EACA,EACU,CACV,OAAO,KAAK,OAAO,mBAAsB,EAAQ,EAAU,EAAS,CAAI,CAC5E,CACJ,kqBCxCA,IAAY,EAAL,SAAA,EAAA,OACH,G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i","SDKEnums","LOGGER","handlerCache","getCacheKey","handlerCache","getCacheKey","createHandlers","handlerCache","getCacheKey","createHandlers","handlerCache","getCacheKey"],"sources":["../../src/config/defaults.ts","../../src/types/base.ts","../../src/types/enums.ts","../../src/utils/objectToQueryString.ts","../../src/utils/isMetaError.ts","../../src/utils/validate.ts","../../src/api/blockUsers/BlockUsersApi.ts","../../src/api/business/BusinessApi.ts","../../src/api/calling/CallingApi.ts","../../src/api/commerce/CommerceApi.ts","../../src/api/contactBook/ContactBookApi.ts","../../src/api/encryption/EncryptionApi.ts","../../src/api/flow/FlowApi.ts","../../src/api/flow/types/common.ts","../../src/api/groups/GroupsApi.ts","../../src/api/marketingMessages/MarketingMessagesApi.ts","../../src/api/media/MediaApi.ts","../../src/api/messageHistory/MessageHistoryApi.ts","../../src/api/messages/MessageApi.ts","../../src/api/payments/PaymentsApi.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/solutions/SolutionsApi.ts","../../src/api/template/factories/index.ts","../../src/api/template/TemplateApi.ts","../../src/api/threadControl/ThreadControlApi.ts","../../src/api/twoStepVerification/TwoStepVerificationApi.ts","../../src/api/waba/WabaApi.ts","../../src/api/waba/types/common.ts","../../src/utils/logger.ts","../../src/utils/runtimeCrypto.node.ts","../../src/utils/runtime.ts","../../src/config/importConfig.ts","../../src/utils/configTable.ts","../../src/utils/flowEncryptionUtils.ts","../../src/utils/rateLimit.ts","../../src/utils/http/httpsClient.ts","../../src/utils/http/request.ts","../../src/utils/logoConsole.ts","../../src/utils/version.ts","../../src/core/whatsapp/WhatsApp.ts","../../src/core/webhook/dedupe.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/fastify/fastify.ts","../../src/core/webhook/frameworks/hono/hono.ts","../../src/core/webhook/frameworks/nextjs-app/nextjs-app.ts","../../src/core/webhook/frameworks/nextjs-page/nextjs-page.ts","../../src/core/webhook/utils/extractMessageText.ts","../../src/core/webhook/utils/generateXHub256Sig.ts","../../src/core/webhook/utils/messageHelpers.ts","../../src/types/constants.ts","../../src/utils/customerServiceWindow.ts"],"sourcesContent":["export const DEFAULT_CLOUD_API_VERSION = 'v23.0';\nexport const DEFAULT_LISTENER_PORT = 3000;\nexport const DEFAULT_MAX_RETRIES_AFTER_WAIT = 30;\nexport const DEFAULT_REQUEST_TIMEOUT = 20000;\n\nexport const DEFAULT_RETRY_MAX_ATTEMPTS = 3;\nexport const DEFAULT_RETRY_INITIAL_DELAY_MS = 1000;\nexport const DEFAULT_RETRY_BACKOFF = 'exponential';\nexport const DEFAULT_RETRY_MAX_SERVER_DELAY_MS = 30000;\n\nexport const GRAPH_API_HOST = 'graph.facebook.com';\nexport const GRAPH_API_PROTOCOL = 'https:';\n\nexport const WHATSAPP_MESSAGING_PRODUCT = 'whatsapp';\n","import type { WabaConfigType } from './config';\n\nexport declare class BaseClass {\n constructor(config: WabaConfigType);\n}\n\nimport type { HttpMethodsEnum } from './enums';\nimport type { RequesterClass, UrlEncodedFormBody } 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 /** Send a request and return the raw `Response` (for binary bodies). Errors still throw `WhatsAppError`s. */\n protected async sendRaw(method: HttpMethodsEnum, endpoint: string, timeout: number): Promise<Response> {\n const response = await this.client.sendRequest(method, endpoint, timeout);\n return response.rawResponse();\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: UrlEncodedFormBody,\n ): Promise<T> {\n return this.client.sendUrlEncodedForm<T>(method, endpoint, timeout, body);\n }\n}\n","export enum CategoryEnum {\n Authentication = 'AUTHENTICATION',\n Marketing = 'MARKETING',\n Utility = 'UTILITY',\n}\n\n/**\n * Direct Send message categories, sent as the top-level `category` field on\n * `POST /{PHONE_NUMBER_ID}/messages`.\n *\n * Omitting the field is equivalent to `Service` and keeps the existing\n * free-form send behavior (outside Direct Send).\n *\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/direct-send/send-utility-and-authentication-messages | Direct Send}\n */\nexport enum MessageCategoryEnum {\n Authentication = 'authentication',\n Service = 'service',\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 Edit = 'edit',\n Revoke = 'revoke',\n Unsupported = 'unsupported',\n Unknown = 'unknown',\n /**\n * @deprecated Use WebhookProcessor.onStatus() instead of onMessage(MessageTypesEnum.Statuses)\n */\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 CatalogMessage = 'catalog_message',\n CallPermissionRequest = 'call_permission_request',\n CtaUrl = 'cta_url',\n Carousel = 'carousel',\n LocationRequest = 'location_request_message',\n AddressMessage = 'address_message',\n Flow = 'flow',\n VoiceCall = 'voice_call',\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 PaymentRequest = 'PAYMENT_REQUEST',\n PhoneNumber = 'PHONE_NUMBER',\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 /** @deprecated Meta renamed this to `user_changed_number`. Use {@link SystemChangeTypesEnum.UserChangedNumber}. */\n CustomerChangedNumber = 'customer_changed_number',\n /** @deprecated Meta renamed this to `user_identity_changed`. Use {@link SystemChangeTypesEnum.UserIdentityChanged}. */\n CustomerIdentityChanged = 'customer_identity_changed',\n UserChangedNumber = 'user_changed_number',\n UserIdentityChanged = 'user_identity_changed',\n /** The user's business-scoped user ID (BSUID) changed. */\n UserChangedUserId = 'user_changed_user_id',\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","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 type { RateLimitInfo } from './rateLimit';\n\nexport type MetaErrorData = {\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\nexport interface MetaError extends Error {\n error: MetaErrorData;\n}\n\nexport const WHATSAPP_ERROR_CODES = [\n 0, 1, 2, 3, 4, 10, 33, 100, 190, 200, 299, 368, 613, 80007, 130429, 130472, 130497, 131000, 131005, 131008, 131009,\n 131016, 131020, 131021, 131026, 131030, 131031, 131037, 131041, 131042, 131044, 131045, 131047, 131048, 131049,\n 131050, 131051, 131052, 131053, 131055, 131056, 131057, 131059, 131061, 131062, 131063, 131065, 131070, 131201,\n 131202, 131203, 131204, 131207, 131208, 131209, 131210, 131211, 131212, 131213, 131214, 131215, 132000, 132001,\n 132005, 132007, 132008, 132012, 132015, 132016, 132068, 132069, 133000, 133004, 133005, 133006, 133008, 133009,\n 133010, 133015, 133016, 134011, 134100, 134101, 134102, 135000, 137000, 138000, 138001, 138002, 138003, 138004,\n 138005, 138006, 138007, 138009, 138012, 138013, 138018, 138038, 139000, 139001, 139002, 139003, 139004, 139100,\n 139101, 139102, 139103, 147005, 200005, 200006, 200007, 1752041, 2388001, 2388012, 2388019, 2388040, 2388047,\n 2388072, 2388073, 2388091, 2388093, 2388103, 2388293, 2388299, 2494100, 2494191, 2593079, 2593085, 2593107, 2593108,\n] as const;\n\nconst WHATSAPP_ERROR_CODE_SET = new Set<number>(WHATSAPP_ERROR_CODES);\n\nexport type ApiPermissionErrorCode = number;\nexport type WhatsAppErrorCode = (typeof WHATSAPP_ERROR_CODES)[number] | ApiPermissionErrorCode;\n\nexport const AUTHORIZATION_ERROR_CODES = [0, 3, 10, 190] as const;\nexport const THROTTLING_ERROR_CODES = [4, 80007, 130429, 131048, 131056] as const;\nexport const INTEGRITY_ERROR_CODES = [368, 130497, 131031] as const;\nexport const SEND_MESSAGE_ERROR_CODES = [\n 130472, 131000, 131005, 131008, 131009, 131016, 131021, 131026, 131030, 131042, 131044, 131045, 131047, 131050,\n 131051, 131052, 131053, 131056, 131057, 131048, 131061, 131062, 131063, 131065, 131070, 132000, 132001, 132005,\n 132007, 132008, 132012, 132015, 132016, 132068, 132069, 135000, 137000,\n] as const;\nexport const FLOW_ERROR_CODES = [139000, 139001, 139002, 139003, 139004] as const;\nexport const BLOCK_USER_ERROR_CODES = [139100, 139101, 139102, 139103] as const;\nexport const CALLING_ERROR_CODES = [\n 138000, 138001, 138002, 138003, 138004, 138005, 138006, 138007, 138009, 138012, 138013, 138018, 138038, 613,\n] as const;\nexport const GROUP_ERROR_CODES = [\n 131020, 131041, 131059, 131201, 131202, 131203, 131204, 131207, 131208, 131209, 131210, 131211, 131212, 131213,\n 131214, 131215,\n] as const;\n\nconst AUTHORIZATION_ERROR_CODE_SET = new Set<number>(AUTHORIZATION_ERROR_CODES);\nconst THROTTLING_ERROR_CODE_SET = new Set<number>(THROTTLING_ERROR_CODES);\nconst INTEGRITY_ERROR_CODE_SET = new Set<number>(INTEGRITY_ERROR_CODES);\nconst SEND_MESSAGE_ERROR_CODE_SET = new Set<number>(SEND_MESSAGE_ERROR_CODES);\nconst FLOW_ERROR_CODE_SET = new Set<number>(FLOW_ERROR_CODES);\nconst BLOCK_USER_ERROR_CODE_SET = new Set<number>(BLOCK_USER_ERROR_CODES);\nconst CALLING_ERROR_CODE_SET = new Set<number>(CALLING_ERROR_CODES);\nconst GROUP_ERROR_CODE_SET = new Set<number>(GROUP_ERROR_CODES);\n\nexport function isWhatsAppErrorCode(code: number): code is WhatsAppErrorCode {\n if (isApiPermissionErrorCode(code)) return true;\n return WHATSAPP_ERROR_CODE_SET.has(code);\n}\n\nexport function isApiPermissionErrorCode(code: number): code is ApiPermissionErrorCode {\n return code >= 200 && code < 300;\n}\n\nexport function isAuthorizationErrorCode(\n code: number,\n): code is ApiPermissionErrorCode | (typeof AUTHORIZATION_ERROR_CODES)[number] {\n return isApiPermissionErrorCode(code) || AUTHORIZATION_ERROR_CODE_SET.has(code);\n}\n\nexport function isThrottlingErrorCode(code: number): code is (typeof THROTTLING_ERROR_CODES)[number] {\n return THROTTLING_ERROR_CODE_SET.has(code);\n}\n\nexport function isIntegrityErrorCode(code: number): code is (typeof INTEGRITY_ERROR_CODES)[number] {\n return INTEGRITY_ERROR_CODE_SET.has(code);\n}\n\nexport function isSendMessageErrorCode(code: number): code is (typeof SEND_MESSAGE_ERROR_CODES)[number] {\n return SEND_MESSAGE_ERROR_CODE_SET.has(code);\n}\n\nexport function isFlowErrorCode(code: number): code is (typeof FLOW_ERROR_CODES)[number] {\n return FLOW_ERROR_CODE_SET.has(code);\n}\n\nexport function isBlockUserErrorCode(code: number): code is (typeof BLOCK_USER_ERROR_CODES)[number] {\n return BLOCK_USER_ERROR_CODE_SET.has(code);\n}\n\nexport function isCallingErrorCode(code: number): code is (typeof CALLING_ERROR_CODES)[number] {\n return CALLING_ERROR_CODE_SET.has(code);\n}\n\nexport function isGroupErrorCode(code: number): code is (typeof GROUP_ERROR_CODES)[number] {\n return GROUP_ERROR_CODE_SET.has(code);\n}\n\nexport class WhatsAppError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'WhatsAppError';\n }\n}\n\nexport class WhatsAppApiError extends WhatsAppError {\n readonly error: MetaErrorData;\n readonly statusCode?: number;\n /**\n * Rate limit headers of the failed response, when it carried any. Set by the SDK's requester;\n * use `rateLimit.retryDelayMs` to reschedule a throttled call.\n */\n rateLimit?: RateLimitInfo;\n\n constructor(message: string, error: MetaErrorData, statusCode?: number) {\n super(message);\n this.name = 'WhatsAppApiError';\n this.error = error;\n this.statusCode = statusCode;\n }\n}\n\nexport class WhatsAppAuthorizationError extends WhatsAppApiError {\n constructor(message: string, error: MetaErrorData, statusCode?: number) {\n super(message, error, statusCode);\n this.name = 'WhatsAppAuthorizationError';\n }\n}\n\nexport class WhatsAppThrottlingError extends WhatsAppApiError {\n constructor(message: string, error: MetaErrorData, statusCode?: number) {\n super(message, error, statusCode);\n this.name = 'WhatsAppThrottlingError';\n }\n}\n\nexport class WhatsAppIntegrityError extends WhatsAppApiError {\n constructor(message: string, error: MetaErrorData, statusCode?: number) {\n super(message, error, statusCode);\n this.name = 'WhatsAppIntegrityError';\n }\n}\n\nexport class WhatsAppSendMessageError extends WhatsAppApiError {\n constructor(message: string, error: MetaErrorData, statusCode?: number) {\n super(message, error, statusCode);\n this.name = 'WhatsAppSendMessageError';\n }\n}\n\nexport class WhatsAppFlowError extends WhatsAppApiError {\n constructor(message: string, error: MetaErrorData, statusCode?: number) {\n super(message, error, statusCode);\n this.name = 'WhatsAppFlowError';\n }\n}\n\nexport class WhatsAppBlockUserError extends WhatsAppApiError {\n constructor(message: string, error: MetaErrorData, statusCode?: number) {\n super(message, error, statusCode);\n this.name = 'WhatsAppBlockUserError';\n }\n}\n\nexport class WhatsAppCallingError extends WhatsAppApiError {\n constructor(message: string, error: MetaErrorData, statusCode?: number) {\n super(message, error, statusCode);\n this.name = 'WhatsAppCallingError';\n }\n}\n\nexport class WhatsAppGroupError extends WhatsAppApiError {\n constructor(message: string, error: MetaErrorData, statusCode?: number) {\n super(message, error, statusCode);\n this.name = 'WhatsAppGroupError';\n }\n}\n\nexport function createWhatsAppApiError(error: MetaErrorData, statusCode?: number): WhatsAppApiError {\n const code = error.code;\n\n if (isAuthorizationErrorCode(code)) {\n return new WhatsAppAuthorizationError(error.message, error, statusCode);\n }\n if (isThrottlingErrorCode(code)) {\n return new WhatsAppThrottlingError(error.message, error, statusCode);\n }\n if (isIntegrityErrorCode(code)) {\n return new WhatsAppIntegrityError(error.message, error, statusCode);\n }\n if (isSendMessageErrorCode(code)) {\n return new WhatsAppSendMessageError(error.message, error, statusCode);\n }\n if (isFlowErrorCode(code)) {\n return new WhatsAppFlowError(error.message, error, statusCode);\n }\n if (isBlockUserErrorCode(code)) {\n return new WhatsAppBlockUserError(error.message, error, statusCode);\n }\n if (isCallingErrorCode(code)) {\n return new WhatsAppCallingError(error.message, error, statusCode);\n }\n if (isGroupErrorCode(code)) {\n return new WhatsAppGroupError(error.message, error, statusCode);\n }\n\n return new WhatsAppApiError(error.message, error, statusCode);\n}\n\nexport class WhatsAppNetworkError extends WhatsAppError {\n readonly cause?: unknown;\n\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = 'WhatsAppNetworkError';\n this.cause = cause;\n }\n}\n\nexport class WhatsAppUnknownError extends WhatsAppError {\n readonly cause?: unknown;\n\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = 'WhatsAppUnknownError';\n this.cause = cause;\n }\n}\n\n/**\n * Thrown when an API method receives invalid input (e.g., malformed phone number,\n * empty required array). This error is thrown client-side before any API call is made.\n */\nexport class WhatsAppValidationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'WhatsAppValidationError';\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 if (error == null || typeof error !== 'object') return false;\n if (!('error' in error) || typeof error.error !== 'object' || error.error == null) return false;\n\n const metaError = error.error as Record<string, unknown>;\n\n if (typeof metaError.message !== 'string') return false;\n if (typeof metaError.type !== 'string') return false;\n if (typeof metaError.code !== 'number') return false;\n if (typeof metaError.fbtrace_id !== 'string') return false;\n\n if ('error_data' in metaError && metaError.error_data != null) {\n if (typeof metaError.error_data !== 'object') return false;\n const errorData = metaError.error_data as Record<string, unknown>;\n if ('messaging_product' in errorData && errorData.messaging_product !== 'whatsapp') return false;\n if ('details' in errorData && typeof errorData.details !== 'string') return false;\n }\n\n if ('error_subcode' in metaError && typeof metaError.error_subcode !== 'number') return false;\n\n return true;\n}\n\nexport function isWhatsAppApiErrorResponse(error: any): error is MetaError & { error: { code: WhatsAppErrorCode } } {\n return isMetaError(error) && isWhatsAppErrorCode(error.error.code);\n}\n\nexport function isWhatsAppAuthorizationError(error: unknown): error is WhatsAppAuthorizationError {\n return error instanceof WhatsAppAuthorizationError;\n}\n\nexport function isWhatsAppThrottlingError(error: unknown): error is WhatsAppThrottlingError {\n return error instanceof WhatsAppThrottlingError;\n}\n\nexport function isWhatsAppIntegrityError(error: unknown): error is WhatsAppIntegrityError {\n return error instanceof WhatsAppIntegrityError;\n}\n\nexport function isWhatsAppSendMessageError(error: unknown): error is WhatsAppSendMessageError {\n return error instanceof WhatsAppSendMessageError;\n}\n\nexport function isWhatsAppFlowError(error: unknown): error is WhatsAppFlowError {\n return error instanceof WhatsAppFlowError;\n}\n\nexport function isWhatsAppBlockUserError(error: unknown): error is WhatsAppBlockUserError {\n return error instanceof WhatsAppBlockUserError;\n}\n\nexport function isWhatsAppCallingError(error: unknown): error is WhatsAppCallingError {\n return error instanceof WhatsAppCallingError;\n}\n\nexport function isWhatsAppGroupError(error: unknown): error is WhatsAppGroupError {\n return error instanceof WhatsAppGroupError;\n}\n\nexport function normalizeMetaError(errorData: unknown, statusCode?: number): MetaError {\n if (isMetaError(errorData)) return errorData;\n\n let message = 'Unknown error occurred';\n if (errorData && typeof errorData === 'object' && 'message' in errorData) {\n const candidate = (errorData as { message?: unknown }).message;\n if (typeof candidate === 'string') message = candidate;\n }\n\n return {\n name: 'MetaError',\n message,\n error: {\n message,\n type: 'UnknownError',\n code: typeof statusCode === 'number' ? statusCode : 500,\n fbtrace_id: '',\n },\n };\n}\n","import { WhatsAppValidationError } from './isMetaError';\n\n/**\n * Asserts that a phone number is in valid E.164 format.\n * Accepts numbers with or without leading '+'.\n * Must be 10-15 digits (not counting the '+').\n *\n * @throws WhatsAppValidationError if the phone number is invalid\n *\n * @example\n * assertPhoneNumber('+14155552671'); // ok\n * assertPhoneNumber('14155552671'); // ok\n * assertPhoneNumber('123'); // throws\n */\nexport function assertPhoneNumber(phone: string): void {\n if (!/^\\+?\\d{10,15}$/.test(phone)) {\n throw new WhatsAppValidationError(\n `Invalid phone number: \"${phone}\". Expected E.164 format (e.g. +14155552671 or 14155552671).`,\n );\n }\n}\n\n/**\n * Asserts that an array is non-empty.\n * Also guards against null/undefined to preserve backward compatibility\n * with callers that may pass untyped values.\n *\n * @throws WhatsAppValidationError if the array is null, undefined, or empty\n *\n * @example\n * assertNonEmpty(['user1'], 'users'); // ok\n * assertNonEmpty([], 'users'); // throws\n */\nexport function assertNonEmpty<T>(arr: T[] | null | undefined, name: string): void {\n if (!arr || arr.length === 0) {\n throw new WhatsAppValidationError(`\"${name}\" must contain at least one item.`);\n }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/block-users/\n\n// Endpoints:\n// - POST /{PHONE_NUMBER_ID}/block_users\n// - DELETE /{PHONE_NUMBER_ID}/block_users\n// - GET /{PHONE_NUMBER_ID}/block_users?limit&after&before\n\nimport { WHATSAPP_MESSAGING_PRODUCT } from '../../config/defaults';\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\nimport { assertNonEmpty } from '../../utils/validate';\nimport type * as blockUsers from './types/blockUsers';\n\n/**\n * API for blocking and unblocking WhatsApp users.\n *\n * Provides methods to block, unblock, and list blocked users for your\n * WhatsApp Business phone number.\n *\n * Limitations:\n * - Can only block users that have messaged your business in the last 24 hours\n * - 64k blocklist limit\n *\n * Endpoints covered:\n * - `POST /{PHONE_NUMBER_ID}/block_users` - Block one or more users\n * - `DELETE /{PHONE_NUMBER_ID}/block_users` - Unblock one or more users\n * - `GET /{PHONE_NUMBER_ID}/block_users` - List blocked users with pagination\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/block-users/\n */\nexport default class BlockUsersApi extends BaseAPI implements blockUsers.BlockUsersClass {\n private readonly endpoint = 'block_users';\n\n /**\n * Build the request body for block/unblock operations.\n *\n * @param users - Array of phone numbers or WhatsApp IDs.\n * @returns The formatted request body.\n */\n private buildBlockUsersBody(users: string[]): blockUsers.BlockUsersRequest {\n return {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n block_users: users.map((user) => ({ user })),\n };\n }\n\n /**\n * Block one or more WhatsApp users\n * @param users - Array of phone numbers or WhatsApp IDs to block\n * @returns Response with successfully blocked and failed users\n * @throws Error if users have not messaged in last 24 hours\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/block-users/\n *\n * @example\n * ```typescript\n * // Block single user\n * const result = await client.blockUsers.block(['1234567890']);\n *\n * // Block multiple users\n * const result = await client.blockUsers.block(['1234567890', '0987654321']);\n *\n * // Check results\n * console.log('Blocked:', result.block_users.added_users);\n * console.log('Failed:', result.block_users.failed_users);\n * ```\n */\n async block(users: string[]): Promise<blockUsers.BlockUsersResponse> {\n assertNonEmpty(users, 'users');\n\n const body = this.buildBlockUsersBody(users);\n\n return await this.sendJson<blockUsers.BlockUsersResponse>(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Unblock one or more WhatsApp users\n * @param users - Array of phone numbers or WhatsApp IDs to unblock\n * @returns Response with successfully unblocked and failed users\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/block-users/\n *\n * @example\n * ```typescript\n * // Unblock single user\n * const result = await client.blockUsers.unblock(['1234567890']);\n *\n * // Unblock multiple users\n * const result = await client.blockUsers.unblock(['1234567890', '0987654321']);\n *\n * // Check results\n * console.log('Unblocked:', result.block_users.added_users);\n * console.log('Failed:', result.block_users.failed_users);\n * ```\n */\n async unblock(users: string[]): Promise<blockUsers.BlockUsersResponse> {\n assertNonEmpty(users, 'users');\n\n const body = this.buildBlockUsersBody(users);\n\n return await this.sendJson<blockUsers.BlockUsersResponse>(\n HttpMethodsEnum.Delete,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Get list of blocked WhatsApp users with pagination\n * @param params - Optional pagination parameters\n * @returns List of blocked users with pagination info\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/block-users/\n *\n * @example\n * ```typescript\n * // Get first 10 blocked users\n * const result = await client.blockUsers.listBlockedUsers({ limit: 10 });\n *\n * // Pagination with cursor\n * const nextPage = await client.blockUsers.listBlockedUsers({\n * limit: 10,\n * after: result.paging?.cursors?.after\n * });\n *\n * // Get all blocked users\n * const allBlocked = await client.blockUsers.listBlockedUsers();\n * ```\n */\n async listBlockedUsers(params?: blockUsers.ListBlockedUsersParams): Promise<blockUsers.ListBlockedUsersResponse> {\n let endpoint = `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`;\n\n // Add query parameters if provided\n if (params) {\n const queryString = objectToQueryString(params);\n if (queryString) {\n endpoint += queryString;\n }\n }\n\n return await this.sendJson<blockUsers.ListBlockedUsersResponse>(\n HttpMethodsEnum.Get,\n endpoint,\n this.config[WabaConfigEnum.RequestTimeout],\n );\n }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/overview/\n\n// Endpoints:\n// - GET /{APPLICATION_ID}/connected_client_businesses\n// - POST /{BUSINESS_ID}/add_phone_numbers\n// - GET /{BUSINESS_ID}\n// - GET /{BUSINESS_ID}/preverified_numbers\n// - GET /{BUSINESS_ID}/client_whatsapp_business_accounts\n// - POST /{BUSINESS_ID}/onboard_partners_to_mm_lite\n// - GET /{BUSINESS_ID}/owned_whatsapp_business_accounts\n// - POST /{BUSINESS_ID}/share_preverified_numbers\n// - GET /{BUSINESS_ID}/extendedcredits\n// - GET /{USER_ID}/assigned_whatsapp_business_accounts\n// - GET /{WHATSAPP_ACCOUNT_NUMBER_ID}\n// - GET /{PRE_VERIFIED_PHONE_NUMBER_ID}\n// - DELETE /{PRE_VERIFIED_PHONE_NUMBER_ID}\n// - GET /{PRE_VERIFIED_PHONE_NUMBER_ID}/partners\n// - POST /{PRE_VERIFIED_PHONE_NUMBER_ID}/request_code\n// - POST /{PRE_VERIFIED_PHONE_NUMBER_ID}/verify_code\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { ResponseSuccess } from '../../types/request';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\n\nimport type * as business from './types';\n\nexport default class BusinessApi extends BaseAPI implements business.BusinessClass {\n private toQuery(params?: business.BusinessListParams): string {\n if (!params) return '';\n\n const fields = Array.isArray(params.fields) ? params.fields.join(',') : params.fields;\n const filtering = Array.isArray(params.filtering) ? JSON.stringify(params.filtering) : params.filtering;\n\n return objectToQueryString({\n fields,\n filtering,\n sort: params.sort,\n limit: params.limit,\n after: params.after,\n before: params.before,\n });\n }\n\n private fieldsQuery(fields?: business.BusinessFieldsParam): string {\n const fieldsValue = Array.isArray(fields) ? fields.join(',') : fields;\n return fieldsValue ? objectToQueryString({ fields: fieldsValue }) : '';\n }\n\n async getConnectedClientBusinesses(\n applicationId: string = this.config[WabaConfigEnum.AppId],\n params?: business.BusinessListParams,\n ): Promise<business.BusinessGraphListResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${applicationId}/connected_client_businesses${this.toQuery(params)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async addPhoneNumbers(businessId: string, request: business.AddPhoneNumbersRequest): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${businessId}/add_phone_numbers`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n async getBusinessPortfolio(\n businessId: string,\n fields?: business.BusinessFieldsParam,\n ): Promise<business.BusinessGraphObject> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${businessId}${this.fieldsQuery(fields)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async getPreVerifiedPhoneNumbers(\n businessId: string,\n params?: business.BusinessListParams,\n ): Promise<business.BusinessGraphListResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${businessId}/preverified_numbers${this.toQuery(params)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async getClientWhatsAppBusinessAccounts(\n businessId: string,\n params?: business.BusinessListParams,\n ): Promise<business.BusinessGraphListResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${businessId}/client_whatsapp_business_accounts${this.toQuery(params)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async onboardPartnersToMMLite(\n businessId: string,\n request: business.OnboardPartnersToMMLiteRequest,\n ): Promise<business.BusinessGraphObject> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${businessId}/onboard_partners_to_mm_lite`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n async getOwnedWhatsAppBusinessAccounts(\n businessId: string,\n params?: business.BusinessListParams,\n ): Promise<business.BusinessGraphListResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${businessId}/owned_whatsapp_business_accounts${this.toQuery(params)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async sharePreVerifiedPhoneNumber(\n businessId: string,\n request: business.SharePreVerifiedPhoneNumberRequest,\n ): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${businessId}/share_preverified_numbers`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n async getCreditLines(businessId: string): Promise<business.BusinessGraphListResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${businessId}/extendedcredits`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async getAssignedWhatsAppBusinessAccounts(\n userId: string,\n params?: business.BusinessListParams,\n ): Promise<business.BusinessGraphListResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${userId}/assigned_whatsapp_business_accounts${this.toQuery(params)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async getWhatsAppAccountNumberDetails(\n accountNumberId: string,\n fields?: business.BusinessFieldsParam,\n ): Promise<business.BusinessGraphObject> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${accountNumberId}${this.fieldsQuery(fields)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async getPreVerifiedPhoneNumberDetails(\n preVerifiedPhoneNumberId: string,\n fields?: business.BusinessFieldsParam,\n ): Promise<business.BusinessGraphObject> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${preVerifiedPhoneNumberId}${this.fieldsQuery(fields)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async deletePreVerifiedPhoneNumber(preVerifiedPhoneNumberId: string): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Delete,\n preVerifiedPhoneNumberId,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async getPreVerifiedPhoneNumberPartners(\n preVerifiedPhoneNumberId: string,\n params?: business.BusinessListParams,\n ): Promise<business.BusinessGraphListResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${preVerifiedPhoneNumberId}/partners${this.toQuery(params)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async requestPreVerifiedPhoneNumberCode(\n preVerifiedPhoneNumberId: string,\n request: business.RequestPreVerifiedPhoneNumberCodeRequest,\n ): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${preVerifiedPhoneNumberId}/request_code`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n async verifyPreVerifiedPhoneNumberCode(\n preVerifiedPhoneNumberId: string,\n request: business.VerifyPreVerifiedPhoneNumberCodeRequest,\n ): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${preVerifiedPhoneNumberId}/verify_code`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/reference/\n\n// Endpoints:\n// - POST /{PHONE_NUMBER_ID}/settings\n// - GET /{PHONE_NUMBER_ID}/settings?fields&include_sip_credentials\n// - GET /{PHONE_NUMBER_ID}/call_permissions?user_wa_id\n// - POST /{PHONE_NUMBER_ID}/calls\n\nimport { WHATSAPP_MESSAGING_PRODUCT } from '../../config/defaults';\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { ResponseSuccess } from '../../types/request';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\n\nimport type * as calling from './types';\n\n/**\n * API for WhatsApp Calling features.\n *\n * Provides methods to manage calling settings, permissions, and call lifecycle\n * (initiate, pre-accept, accept, reject, terminate).\n *\n * Endpoints covered:\n * - `POST /{PHONE_NUMBER_ID}/settings` - Update calling settings\n * - `GET /{PHONE_NUMBER_ID}/settings` - Get calling settings\n * - `GET /{PHONE_NUMBER_ID}/call_permissions` - Get call permissions for a user\n * - `POST /{PHONE_NUMBER_ID}/calls` - Initiate, pre-accept, accept, reject, or terminate a call\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/reference/\n */\nexport default class CallingApi extends BaseAPI implements calling.CallingClass {\n private readonly endpoint = 'calls';\n\n /**\n * Update calling settings for the phone number, such as enabling/disabling calling\n * or configuring SIP credentials.\n *\n * @param params - The calling settings to update.\n * @returns A success response confirming the settings were updated.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/reference/\n */\n async updateCallingSettings(params: calling.UpdateCallingSettingsRequest): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/settings`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(params),\n );\n }\n\n /**\n * Retrieve the current calling settings for the phone number.\n *\n * @param params - Optional query parameters to filter the response.\n * @param params.fields - Specific fields to include in the response.\n * @param params.include_sip_credentials - Whether to include SIP credentials in the response.\n * @returns The current calling settings configuration.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/reference/\n */\n async getCallingSettings(params?: {\n fields?: string[] | string;\n include_sip_credentials?: boolean;\n }): Promise<calling.CallingSettingsResponse> {\n const fieldsValue = Array.isArray(params?.fields) ? params?.fields.join(',') : params?.fields;\n const queryParams = objectToQueryString({\n ...(fieldsValue ? { fields: fieldsValue } : {}),\n ...(params?.include_sip_credentials !== undefined\n ? { include_sip_credentials: params.include_sip_credentials }\n : {}),\n });\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/settings${queryParams}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Get calling permissions for a specific WhatsApp user.\n *\n * @param params - The request parameters.\n * @param params.userWaId - The WhatsApp ID of the user to check permissions for.\n * @returns The call permissions for the specified user.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/reference/\n */\n async getCallPermissions(params: { userWaId: string }): Promise<calling.CallPermissionsResponse> {\n const queryParams = objectToQueryString({ user_wa_id: params.userWaId });\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/call_permissions${queryParams}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Initiate an outbound call to a WhatsApp user.\n *\n * @param params - The call initiation parameters.\n * @param params.to - The recipient's WhatsApp phone number.\n * @param params.session - The call session configuration.\n * @param params.biz_opaque_callback_data - Optional opaque data passed back in webhooks.\n * @param params.recording - Optional per-call recording configuration.\n * @param params.transcription - Optional per-call transcription configuration.\n * @returns The initiated call response with call ID and status.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/reference/\n */\n async initiateCall(params: calling.InitiateCallRequest): Promise<calling.InitiateCallResponse> {\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n to: params.to,\n action: 'connect',\n session: params.session,\n } as {\n messaging_product: 'whatsapp';\n to: string;\n action: calling.CallAction;\n session: calling.CallSession;\n biz_opaque_callback_data?: string;\n recording?: calling.CallRecordingConfig;\n transcription?: calling.CallTranscriptionConfig;\n };\n\n if (params.biz_opaque_callback_data) {\n body.biz_opaque_callback_data = params.biz_opaque_callback_data;\n }\n if (params.recording) body.recording = params.recording;\n if (params.transcription) body.transcription = params.transcription;\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Pre-accept an incoming call, signaling readiness to connect before full acceptance.\n *\n * @param params - The pre-accept request parameters.\n * @param params.call_id - The ID of the call to pre-accept.\n * @param params.session - Optional session configuration for the call.\n * @returns The call action response confirming the pre-accept.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/reference/\n */\n async preAcceptCall(params: calling.PreAcceptCallRequest): Promise<calling.CallActionResponse> {\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n call_id: params.call_id,\n action: 'pre_accept',\n } as {\n messaging_product: 'whatsapp';\n call_id: string;\n action: calling.CallAction;\n session?: calling.CallSession;\n };\n\n if (params.session) body.session = params.session;\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Accept an incoming call and establish the connection.\n *\n * @param params - The accept request parameters.\n * @param params.call_id - The ID of the call to accept.\n * @param params.session - Optional session configuration for the call.\n * @param params.biz_opaque_callback_data - Optional opaque data passed back in webhooks.\n * @param params.recording - Optional per-call recording configuration.\n * @param params.transcription - Optional per-call transcription configuration.\n * @returns The call action response confirming acceptance.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/reference/\n */\n async acceptCall(params: calling.AcceptCallRequest): Promise<calling.CallActionResponse> {\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n call_id: params.call_id,\n action: 'accept',\n } as {\n messaging_product: 'whatsapp';\n call_id: string;\n action: calling.CallAction;\n session?: calling.CallSession;\n biz_opaque_callback_data?: string;\n recording?: calling.CallRecordingConfig;\n transcription?: calling.CallTranscriptionConfig;\n };\n\n if (params.session) body.session = params.session;\n if (params.biz_opaque_callback_data) {\n body.biz_opaque_callback_data = params.biz_opaque_callback_data;\n }\n if (params.recording) body.recording = params.recording;\n if (params.transcription) body.transcription = params.transcription;\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Reject an incoming call.\n *\n * @param params - The reject request parameters.\n * @param params.call_id - The ID of the call to reject.\n * @returns The call action response confirming rejection.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/reference/\n */\n async rejectCall(params: calling.RejectCallRequest): Promise<calling.CallActionResponse> {\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n call_id: params.call_id,\n action: 'reject',\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Terminate an active call.\n *\n * @param params - The terminate request parameters.\n * @param params.call_id - The ID of the call to terminate.\n * @returns The call action response confirming termination.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/reference/\n */\n async terminateCall(params: calling.TerminateCallRequest): Promise<calling.CallActionResponse> {\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n call_id: params.call_id,\n action: 'terminate',\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/catalogs/sell-products-and-services/set-commerce-settings/\n\n// Endpoints:\n// - GET /{PHONE_NUMBER_ID}/whatsapp_commerce_settings\n// - POST /{PHONE_NUMBER_ID}/whatsapp_commerce_settings?is_cart_enabled&is_catalog_visible\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { ResponseSuccess } from '../../types/request';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\n\nimport type * as commerce from './types';\n\n/**\n * API for WhatsApp Commerce Settings.\n *\n * Provides methods to retrieve and update commerce settings such as cart\n * and catalog visibility for your WhatsApp Business phone number.\n *\n * Endpoints covered:\n * - `GET /{PHONE_NUMBER_ID}/whatsapp_commerce_settings` - Get commerce settings\n * - `POST /{PHONE_NUMBER_ID}/whatsapp_commerce_settings` - Update commerce settings\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/catalogs/sell-products-and-services/set-commerce-settings/\n */\nexport default class CommerceApi extends BaseAPI implements commerce.CommerceClass {\n private readonly endpoint = 'whatsapp_commerce_settings';\n\n /**\n * Retrieve the current commerce settings for the phone number.\n *\n * @returns The current commerce settings including cart and catalog visibility state.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/catalogs/sell-products-and-services/set-commerce-settings/\n */\n async getCommerceSettings(): Promise<commerce.CommerceSettingsResponse> {\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 * Update commerce settings for the phone number (e.g., enable/disable cart or catalog).\n *\n * @param params - The commerce settings to update (e.g., is_cart_enabled, is_catalog_visible).\n * @returns A success response confirming the settings were updated.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/catalogs/sell-products-and-services/set-commerce-settings/\n */\n async updateCommerceSettings(params: commerce.UpdateCommerceSettingsRequest): Promise<ResponseSuccess> {\n const queryParams = objectToQueryString(params);\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}${queryParams}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/business-scoped-user-ids/\n\n// Endpoints:\n// - DELETE /{PHONE_NUMBER_ID}/contact_book?messaging_product=whatsapp&bsuid={BSUID}\n\nimport { WHATSAPP_MESSAGING_PRODUCT } from '../../config/defaults';\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport { WhatsAppValidationError } from '../../utils/isMetaError';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\n\nimport type * as contactBook from './types/contactBook';\n\n/**\n * API for the Meta-hosted contact book.\n *\n * The contact book pairs a WhatsApp user's phone number with their\n * business-scoped user ID (BSUID). Meta populates it automatically: any message\n * or call between a business phone number in your portfolio and a user stores\n * that pairing, which is why webhooks keep including the phone number even after\n * the user adopts a username. It is scoped to the business portfolio, not to a\n * single phone number, and only captures interactions from early April 2026\n * onward — there is no historical backfill.\n *\n * Endpoints covered:\n * - `DELETE /{PHONE_NUMBER_ID}/contact_book` - Delete a user's contact book entry\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/business-scoped-user-ids/\n */\nexport default class ContactBookApi extends BaseAPI implements contactBook.ContactBookClass {\n private readonly endpoint = 'contact_book';\n\n /**\n * Delete a user's entry from your contact book.\n *\n * Once deleted, the user's phone number and BSUID are no longer included in\n * webhook payloads for any business phone number in the portfolio — unless\n * the number is still in the 30-day cache, or a new interaction recreates the\n * entry.\n *\n * Unknown, malformed, and other-portfolio BSUIDs no longer raise an API error\n * (changed August 25, 2026): the request resolves with `deleted: false`, so\n * check that flag instead of relying on a thrown error to detect a miss.\n *\n * @param params - Delete parameters.\n * @param params.bsuid - BSUID of the entry to delete (e.g. \"US.13491208655302741918\").\n * @returns Response reporting whether the entry was deleted (`deleted: false` when no entry matched).\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/business-scoped-user-ids/\n *\n * @example\n * ```typescript\n * const result = await client.contactBook.deleteEntry({ bsuid: 'US.13491208655302741918' });\n * // true when an entry was removed, false when the BSUID had no entry in the portfolio\n * console.log(result.deleted);\n * ```\n */\n async deleteEntry(\n params: contactBook.DeleteContactBookEntryParams,\n ): Promise<contactBook.DeleteContactBookEntryResponse> {\n if (!params?.bsuid) {\n throw new WhatsAppValidationError('\"bsuid\" is required to delete a contact book entry.');\n }\n\n const query = objectToQueryString({\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n bsuid: params.bsuid,\n });\n\n return await this.sendJson<contactBook.DeleteContactBookEntryResponse>(\n HttpMethodsEnum.Delete,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}${query}`,\n this.config[WabaConfigEnum.RequestTimeout],\n );\n }\n}\n","// Docs: https://developers.facebook.com/docs/whatsapp/cloud-api/reference/whatsapp-business-encryption/\n\n// Endpoints:\n// - GET /{PHONE_NUMBER_ID}/whatsapp_business_encryption\n// - POST /{PHONE_NUMBER_ID}/whatsapp_business_encryption\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { ResponseSuccess } from '../../types/request';\nimport type { EncryptionClass, EncryptionPublicKeyResponse } from './types';\n\n/**\n * API for managing WhatsApp Business Encryption keys.\n *\n * Provides methods to get and set the public encryption key used for\n * end-to-end encrypted messaging with WhatsApp Business.\n *\n * Endpoints covered:\n * - `GET /{PHONE_NUMBER_ID}/whatsapp_business_encryption` - Get the current public encryption key\n * - `POST /{PHONE_NUMBER_ID}/whatsapp_business_encryption` - Set a new public encryption key\n *\n * @see https://developers.facebook.com/docs/whatsapp/cloud-api/reference/whatsapp-business-encryption/\n */\nexport default class EncryptionApi extends BaseAPI implements EncryptionClass {\n private readonly endpoint = 'whatsapp_business_encryption';\n\n /**\n * Retrieve the current public encryption key for the phone number.\n *\n * @returns The current public encryption key.\n * @see https://developers.facebook.com/docs/whatsapp/cloud-api/reference/whatsapp-business-encryption/\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 /**\n * Set a new public encryption key for the phone number.\n *\n * @param businessPublicKey - The PEM-encoded public key string to set.\n * @returns A success response confirming the key was set.\n * @see https://developers.facebook.com/docs/whatsapp/cloud-api/reference/whatsapp-business-encryption/\n */\n async setEncryptionPublicKey(businessPublicKey: string): Promise<ResponseSuccess> {\n const formData = new FormData();\n formData.append('business_public_key', businessPublicKey);\n\n return this.sendFormData(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n formData,\n );\n }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/flows/\n\n// Endpoints:\n// - GET /{WABA_ID}/flows\n// - POST /{WABA_ID}/flows\n// - GET /{FLOW_ID}?fields&date_format\n// - POST /{FLOW_ID}\n// - DELETE /{FLOW_ID}\n// - GET /{FLOW_ID}/assets\n// - POST /{FLOW_ID}/assets\n// - POST /{FLOW_ID}/publish\n// - POST /{FLOW_ID}/deprecate\n// - POST /{DESTINATION_WABA_ID}/migrate_flows\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { ResponseSuccess } from '../../types/request';\n\nimport type * as flow from './types';\n\n/**\n * API for managing WhatsApp Flows.\n *\n * WhatsApp Flows allow businesses to build structured, interactive experiences\n * within WhatsApp conversations. Flows can be used for appointment booking,\n * lead generation, customer support, surveys, and more.\n *\n * This API allows you to:\n * - List flows for a WhatsApp Business Account (`GET /{WABA_ID}/flows`)\n * - Create new flows (`POST /{WABA_ID}/flows`)\n * - Get flow details and previews (`GET /{FLOW_ID}`)\n * - Update flow metadata (`POST /{FLOW_ID}`)\n * - Delete draft flows (`DELETE /{FLOW_ID}`)\n * - List flow assets / download Flow JSON (`GET /{FLOW_ID}/assets`)\n * - Upload or update Flow JSON (`POST /{FLOW_ID}/assets`)\n * - Publish flows (`POST /{FLOW_ID}/publish`)\n * - Deprecate flows (`POST /{FLOW_ID}/deprecate`)\n * - Migrate flows between WABAs (`POST /{DESTINATION_WABA_ID}/migrate_flows`)\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi | Flows API Reference}\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/flows/ | WhatsApp Flows Documentation}\n */\nexport default class FlowApi extends BaseAPI implements flow.FlowClass {\n private appendFormValue(\n formData: FormData,\n key: string,\n value?: string | boolean | string[] | flow.FlowCategoryEnum[],\n ) {\n if (value === undefined) return;\n formData.append(key, Array.isArray(value) ? JSON.stringify(value) : String(value));\n }\n\n /**\n * List all flows belonging to a WhatsApp Business Account.\n *\n * Retrieves a paginated list of all flows associated with the given WABA ID,\n * including their IDs, names, statuses, and categories.\n *\n * @param wabaId - The WhatsApp Business Account ID to list flows for.\n * @returns A promise that resolves with the list of flows and pagination info.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#list | List Flows}\n *\n * @example\n * ```ts\n * const response = await whatsappClient.flow.listFlows('WABA_ID');\n * for (const flow of response.data) {\n * console.log(flow.id, flow.name, flow.status);\n * }\n * ```\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 a new flow for a WhatsApp Business Account.\n *\n * Creates a new flow in DRAFT status. You can optionally clone an existing flow,\n * provide initial Flow JSON, and even publish the flow immediately upon creation.\n *\n * @param wabaId - The WhatsApp Business Account ID to create the flow under.\n * @param data - The flow creation parameters.\n * @param data.name - The name of the flow.\n * @param data.categories - Optional array of flow categories (e.g., LEAD_GENERATION, APPOINTMENT_BOOKING).\n * @param data.endpoint_uri - Optional URI for the flow endpoint that will receive flow action payloads.\n * @param data.clone_flow_id - Optional ID of an existing flow to clone.\n * @param data.flow_json - Optional Flow JSON definition as a string.\n * @param data.publish - Optional flag to publish the flow immediately after creation.\n * @returns A promise that resolves with the created flow ID and any validation errors.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#create | Create Flow}\n *\n * @example\n * ```ts\n * const result = await whatsappClient.flow.createFlow('WABA_ID', {\n * name: 'Appointment Booking',\n * categories: ['APPOINTMENT_BOOKING'],\n * endpoint_uri: 'https://example.com/flow-endpoint',\n * });\n * console.log(result.id); // New flow ID\n * ```\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 const formData = new FormData();\n this.appendFormValue(formData, 'name', data.name);\n this.appendFormValue(formData, 'categories', data.categories);\n this.appendFormValue(formData, 'endpoint_uri', data.endpoint_uri);\n this.appendFormValue(formData, 'clone_flow_id', data.clone_flow_id);\n this.appendFormValue(formData, 'flow_json', data.flow_json);\n this.appendFormValue(formData, 'publish', data.publish);\n\n return this.sendFormData(\n HttpMethodsEnum.Post,\n `/${wabaId}/flows`,\n this.config[WabaConfigEnum.RequestTimeout],\n formData,\n );\n }\n\n /**\n * Get details of a specific flow.\n *\n * Retrieves flow information such as name, status, categories, JSON validation errors,\n * and optionally a preview URL. Use the `fields` parameter to request specific fields\n * or the preview endpoint.\n *\n * @param flowId - The ID of the flow to retrieve.\n * @param fields - Optional comma-separated list of fields to return (e.g., `'name,status,preview.invalidate(false)'`).\n * @param dateFormat - Optional date format string for date fields in the response.\n * @returns A promise that resolves with the flow details or preview response.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#details | Get Flow Details}\n *\n * @example\n * ```ts\n * // Get all flow details\n * const flow = await whatsappClient.flow.getFlow('FLOW_ID');\n * console.log(flow.name, flow.status);\n *\n * // Get specific fields only\n * const flow = await whatsappClient.flow.getFlow('FLOW_ID', 'name,status,categories');\n * ```\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 a preview URL for a flow.\n *\n * Generates a shareable preview URL that allows viewing the flow without publishing it.\n * The preview can optionally be invalidated to force generation of a fresh URL.\n *\n * @param flowId - The ID of the flow to preview.\n * @param invalidate - If `true`, invalidates the existing preview and generates a new one. Defaults to `false`.\n * @returns A promise that resolves with the flow preview details including the preview URL.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#details | Get Flow Preview}\n *\n * @example\n * ```ts\n * // Get existing preview URL\n * const preview = await whatsappClient.flow.getFlowPreview('FLOW_ID');\n * console.log(preview.preview.preview_url);\n *\n * // Force a new preview URL\n * const freshPreview = await whatsappClient.flow.getFlowPreview('FLOW_ID', true);\n * ```\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 the metadata of an existing flow.\n *\n * Allows updating a flow's name, categories, endpoint URI, or associated application ID.\n * The flow must be in DRAFT status to update certain fields.\n *\n * @param flowId - The ID of the flow to update.\n * @param data - The metadata fields to update.\n * @param data.name - Optional new name for the flow.\n * @param data.categories - Optional new categories for the flow.\n * @param data.endpoint_uri - Optional new endpoint URI for flow action payloads.\n * @param data.application_id - Optional application ID to associate with the flow.\n * @returns A promise that resolves with a success indicator.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#update | Update Flow}\n *\n * @example\n * ```ts\n * await whatsappClient.flow.updateFlowMetadata('FLOW_ID', {\n * name: 'Updated Flow Name',\n * endpoint_uri: 'https://example.com/new-endpoint',\n * });\n * ```\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 const formData = new FormData();\n this.appendFormValue(formData, 'name', data.name);\n this.appendFormValue(formData, 'categories', data.categories);\n this.appendFormValue(formData, 'endpoint_uri', data.endpoint_uri);\n this.appendFormValue(formData, 'application_id', data.application_id);\n\n return this.sendFormData(\n HttpMethodsEnum.Post,\n `/${flowId}`,\n this.config[WabaConfigEnum.RequestTimeout],\n formData,\n );\n }\n\n /**\n * Delete a flow.\n *\n * Permanently deletes a flow. Only flows in DRAFT status can be deleted.\n * Published or deprecated flows cannot be deleted.\n *\n * @param flowId - The ID of the flow to delete.\n * @returns A promise that resolves with a success indicator.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#delete | Delete Flow}\n *\n * @example\n * ```ts\n * await whatsappClient.flow.deleteFlow('FLOW_ID');\n * ```\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 associated with a flow.\n *\n * Retrieves the list of assets (e.g., Flow JSON) associated with the flow.\n * The response includes download URLs for each asset.\n *\n * @param flowId - The ID of the flow to list assets for.\n * @returns A promise that resolves with the list of assets including download URLs.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#asset-list | List Flow Assets}\n *\n * @example\n * ```ts\n * const assets = await whatsappClient.flow.listAssets('FLOW_ID');\n * for (const asset of assets.data) {\n * console.log(asset.name, asset.download_url);\n * }\n * ```\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 * Upload or update the Flow JSON for a flow.\n *\n * Uploads a Flow JSON definition to the flow's assets. The JSON defines the screens,\n * layout, and logic of the flow. Accepts a Buffer, plain JSON object, or Blob.\n *\n * @param flowId - The ID of the flow to update.\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 A promise that resolves with the upload status and any validation errors.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#asset-upload | Upload Flow JSON}\n *\n * @example\n * ```ts\n * // Upload from a JSON object\n * const result = await whatsappClient.flow.updateFlowJson('FLOW_ID', {\n * file: {\n * version: '5.0',\n * screens: [{ id: 'WELCOME', layout: { type: 'SingleColumnLayout', children: [] } }],\n * },\n * });\n *\n * // Upload from a Buffer\n * const jsonBuffer = Buffer.from(JSON.stringify(flowDefinition));\n * await whatsappClient.flow.updateFlowJson('FLOW_ID', { file: jsonBuffer });\n * ```\n */\n async updateFlowJson(\n flowId: string,\n data: {\n file: Blob | Uint8Array | 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 Uint8Array) {\n // Buffer or Uint8Array - convert to Uint8Array for BlobPart compatibility\n fileContent = new globalThis.Blob([new Uint8Array(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 without publishing.\n *\n * This is a convenience method that uploads the Flow JSON and checks for validation\n * errors. The API does not have a dedicated validation endpoint, so this method\n * performs an update and inspects the response for errors.\n *\n * @param flowId - The ID of the flow to validate against (must exist, can be in DRAFT status).\n * @param flowJsonData - The Flow JSON content as a Buffer, JSON object, or Blob.\n * @returns A promise that resolves with validation results, including a `valid` boolean\n * and any `validation_errors` found.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#asset-upload | Upload Flow JSON (validation)}\n *\n * @example\n * ```ts\n * const result = await whatsappClient.flow.validateFlowJson('FLOW_ID', {\n * version: '5.0',\n * screens: [{ id: 'WELCOME', layout: { type: 'SingleColumnLayout', children: [] } }],\n * });\n * if (result.valid) {\n * console.log('Flow JSON is valid');\n * } else {\n * console.error('Validation errors:', result.validation_errors);\n * }\n * ```\n */\n async validateFlowJson(\n flowId: string,\n flowJsonData: Blob | Uint8Array | object,\n ): Promise<flow.ValidateFlowJsonResponse> {\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 }\n\n /**\n * Publish a flow.\n *\n * Transitions a flow from DRAFT status to PUBLISHED. Once published, the flow\n * can be sent to users in WhatsApp messages. A published flow's JSON can no longer\n * be updated.\n *\n * @param flowId - The ID of the flow to publish.\n * @returns A promise that resolves with a success indicator.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#publish | Publish Flow}\n *\n * @example\n * ```ts\n * await whatsappClient.flow.publishFlow('FLOW_ID');\n * ```\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 a flow.\n *\n * Transitions a flow from PUBLISHED status to DEPRECATED. A deprecated flow\n * can no longer be sent to users but existing sessions will continue to work.\n * This action cannot be undone.\n *\n * @param flowId - The ID of the flow to deprecate.\n * @returns A promise that resolves with a success indicator.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#deprecate | Deprecate Flow}\n *\n * @example\n * ```ts\n * await whatsappClient.flow.deprecateFlow('FLOW_ID');\n * ```\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 WhatsApp Business Accounts.\n *\n * Copies flows from a source WABA to a destination WABA. You can optionally\n * specify which flows to migrate by name. Migrated flows are created in DRAFT\n * status in the destination WABA.\n *\n * @param destinationWabaId - The ID of the destination WhatsApp Business Account.\n * @param data - The migration parameters.\n * @param data.source_waba_id - The ID of the source WhatsApp Business Account to migrate flows from.\n * @param data.source_flow_names - Optional array of flow names to migrate. If omitted, all flows are migrated.\n * @returns A promise that resolves with migration results including successes and failures.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi#migrate | Migrate Flows}\n *\n * @example\n * ```ts\n * // Migrate all flows from one WABA to another\n * const result = await whatsappClient.flow.migrateFlows('DEST_WABA_ID', {\n * source_waba_id: 'SOURCE_WABA_ID',\n * });\n *\n * // Migrate specific flows by name\n * const result = await whatsappClient.flow.migrateFlows('DEST_WABA_ID', {\n * source_waba_id: 'SOURCE_WABA_ID',\n * source_flow_names: ['Appointment Booking', 'Lead Gen Form'],\n * });\n * console.log(result.migrated_flows, result.failed_flows);\n * ```\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 const formData = new FormData();\n this.appendFormValue(formData, 'source_waba_id', data.source_waba_id);\n this.appendFormValue(formData, 'source_flow_names', data.source_flow_names);\n\n return this.sendFormData(\n HttpMethodsEnum.Post,\n `/${destinationWabaId}/migrate_flows`,\n this.config[WabaConfigEnum.RequestTimeout],\n formData,\n );\n }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/flows/\n\nimport type { IncomingHttpHeaders, IncomingMessage } from 'node:http';\nimport type { ResponseSuccess } from '../../../types';\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 | Uint8Array | 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 | Uint8Array | 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","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n\n// Endpoints:\n// - POST /{PHONE_NUMBER_ID}/groups\n// - DELETE /{GROUP_ID}\n// - GET /{GROUP_ID}?fields\n// - GET /{PHONE_NUMBER_ID}/groups?limit&after&before\n// - GET /{GROUP_ID}/invite_link\n// - POST /{GROUP_ID}/invite_link\n// - DELETE /{GROUP_ID}/invite_link\n// - GET /{GROUP_ID}/join_requests\n// - POST /{GROUP_ID}/join_requests\n// - DELETE /{GROUP_ID}/join_requests\n// - POST /{GROUP_ID}/participants\n// - DELETE /{GROUP_ID}/participants\n// - POST /{GROUP_ID}\n\nimport { WHATSAPP_MESSAGING_PRODUCT } from '../../config/defaults';\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { ResponseSuccess } from '../../types/request';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\nimport { assertNonEmpty } from '../../utils/validate';\n\nimport type * as groups from './types';\n\n/**\n * API for managing WhatsApp Groups.\n *\n * This API allows you to:\n * - Create and delete groups\n * - Approve/reject join requests\n * - Manage group invite links\n * - Remove participants\n * - Update group settings\n * - Fetch group metadata and active groups\n *\n * Endpoints covered:\n * - `POST /{PHONE_NUMBER_ID}/groups` - Create a new group\n * - `DELETE /{GROUP_ID}` - Delete a group\n * - `GET /{GROUP_ID}` - Get group info\n * - `GET /{PHONE_NUMBER_ID}/groups` - List active groups\n * - `GET /{GROUP_ID}/invite_link` - Get group invite link\n * - `POST /{GROUP_ID}/invite_link` - Reset group invite link\n * - `GET /{GROUP_ID}/join_requests` - Get pending join requests\n * - `POST /{GROUP_ID}/join_requests` - Approve join requests\n * - `DELETE /{GROUP_ID}/join_requests` - Reject join requests\n * - `DELETE /{GROUP_ID}/participants` - Remove participants\n * - `POST /{GROUP_ID}` - Update group settings\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\nexport default class GroupsApi extends BaseAPI implements groups.GroupsClass {\n /**\n * Create a new WhatsApp group.\n *\n * @param params - The group creation parameters.\n * @param params.subject - The name/subject of the group.\n * @param params.description - Optional description for the group.\n * @param params.join_approval_mode - Optional join approval mode setting.\n * @returns The created group response with group ID.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n async createGroup(params: groups.GroupCreateRequest): Promise<groups.GroupCreateResponse> {\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n subject: params.subject,\n } as { messaging_product: 'whatsapp'; subject: string; description?: string; join_approval_mode?: string };\n\n if (params.description) body.description = params.description;\n if (params.join_approval_mode) body.join_approval_mode = params.join_approval_mode;\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/groups`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Delete a WhatsApp group.\n *\n * @param groupId - The ID of the group to delete.\n * @returns A success response confirming deletion.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n async deleteGroup(groupId: string): Promise<ResponseSuccess> {\n return this.sendJson(HttpMethodsEnum.Delete, groupId, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n /**\n * Retrieve metadata and information about a specific group.\n *\n * @param groupId - The ID of the group to retrieve.\n * @param fields - Optional fields to include in the response (e.g., subject, description, participants).\n * @returns The group information including metadata and requested fields.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n async getGroupInfo(groupId: string, fields?: groups.GroupInfoFieldsParam): Promise<groups.GroupInfoResponse> {\n const fieldValue = Array.isArray(fields) ? fields.join(',') : fields;\n const queryParams = fieldValue ? objectToQueryString({ fields: fieldValue }) : '';\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${groupId}${queryParams}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * List all active groups for the phone number with optional pagination.\n *\n * @param params - Optional pagination parameters.\n * @param params.limit - Maximum number of groups to return.\n * @param params.after - Cursor for forward pagination.\n * @param params.before - Cursor for backward pagination.\n * @returns A paginated list of active groups.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n async getActiveGroups(params?: groups.GroupListParams): Promise<groups.GroupListResponse> {\n const queryParams = params ? objectToQueryString(params) : '';\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/groups${queryParams}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Get the current invite link for a group.\n *\n * @param groupId - The ID of the group.\n * @returns The group invite link.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n async getGroupInviteLink(groupId: string): Promise<groups.GroupInviteLinkResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${groupId}/invite_link`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Create a group invite link.\n *\n * @param groupId - The ID of the group.\n * @returns The group invite link.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n async createGroupInviteLink(groupId: string): Promise<groups.GroupInviteLinkResponse> {\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n };\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${groupId}/invite_link`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Reset and regenerate the invite link for a group, invalidating the previous link.\n *\n * @param groupId - The ID of the group.\n * @returns The new group invite link.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n async resetGroupInviteLink(groupId: string): Promise<groups.GroupInviteLinkResponse> {\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n };\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${groupId}/invite_link`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Delete the current invite link for a group.\n *\n * @param groupId - The ID of the group.\n * @returns A success response confirming deletion.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n async deleteGroupInviteLink(groupId: string): Promise<ResponseSuccess> {\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n };\n return this.sendJson(\n HttpMethodsEnum.Delete,\n `${groupId}/invite_link`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Get pending join requests for a group.\n *\n * @param groupId - The ID of the group.\n * @returns A list of pending join requests.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n async getJoinRequests(groupId: string): Promise<groups.GroupJoinRequestsResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${groupId}/join_requests`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Approve one or more pending join requests for a group.\n *\n * @param groupId - The ID of the group.\n * @param joinRequestIds - Array of join request IDs to approve.\n * @returns The result of the approval action.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n async approveJoinRequests(\n groupId: string,\n joinRequestIds: string[],\n ): Promise<groups.GroupJoinRequestsActionResponse> {\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n join_requests: joinRequestIds,\n };\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${groupId}/join_requests`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Reject one or more pending join requests for a group.\n *\n * @param groupId - The ID of the group.\n * @param joinRequestIds - Array of join request IDs to reject.\n * @returns The result of the rejection action.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n async rejectJoinRequests(\n groupId: string,\n joinRequestIds: string[],\n ): Promise<groups.GroupJoinRequestsActionResponse> {\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n join_requests: joinRequestIds,\n };\n return this.sendJson(\n HttpMethodsEnum.Delete,\n `${groupId}/join_requests`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Add one or more participants to a group.\n *\n * @param groupId - The ID of the group.\n * @param participants - Array of user WhatsApp IDs to add to the group.\n * @returns A success response confirming the addition.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n async addParticipants(groupId: string, participants: string[]): Promise<ResponseSuccess> {\n assertNonEmpty(participants, 'participants');\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n participants: participants.map((user) => ({ user })),\n };\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${groupId}/participants`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Remove one or more participants from a group.\n *\n * @param groupId - The ID of the group.\n * @param participants - Array of user WhatsApp IDs to remove from the group.\n * @returns A success response confirming removal.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n async removeParticipants(groupId: string, participants: string[]): Promise<ResponseSuccess> {\n assertNonEmpty(participants, 'participants');\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n participants: participants.map((user) => ({ user })),\n };\n return this.sendJson(\n HttpMethodsEnum.Delete,\n `${groupId}/participants`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n\n /**\n * Update group settings such as subject, description, or profile picture.\n *\n * @param groupId - The ID of the group to update.\n * @param params - The settings to update.\n * @param params.subject - Optional new group subject/name.\n * @param params.description - Optional new group description.\n * @param params.profilePictureFile - Optional profile picture as a Buffer or Blob.\n * @returns The updated group settings response.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n async updateGroupSettings(\n groupId: string,\n params: groups.UpdateGroupSettingsRequest,\n ): Promise<groups.GroupSettingsResponse> {\n if (params.profilePictureFile) {\n const formData = new FormData();\n formData.append('messaging_product', WHATSAPP_MESSAGING_PRODUCT);\n if (params.subject) formData.append('subject', params.subject);\n if (params.description) formData.append('description', params.description);\n\n if (params.profilePictureFile instanceof Uint8Array) {\n const fileBlob = new globalThis.Blob([new Uint8Array(params.profilePictureFile)], {\n type: 'image/jpeg',\n });\n formData.append('file', fileBlob as unknown as Blob);\n } else if (params.profilePictureFile instanceof Blob) {\n formData.append('file', params.profilePictureFile);\n } else {\n throw new Error('Invalid profile picture file type. Use a Buffer or Blob.');\n }\n\n return this.sendFormData(\n HttpMethodsEnum.Post,\n groupId,\n this.config[WabaConfigEnum.RequestTimeout],\n formData,\n );\n }\n\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n } as { messaging_product: 'whatsapp'; subject?: string; description?: string };\n\n if (params.subject) body.subject = params.subject;\n if (params.description) body.description = params.description;\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n groupId,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/marketing-messages/send-marketing-messages/\n\n// Endpoints:\n// - POST /{PHONE_NUMBER_ID}/marketing_messages\n\nimport { WHATSAPP_MESSAGING_PRODUCT } from '../../config/defaults';\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport { WhatsAppValidationError } from '../../utils/isMetaError';\n\nimport type { MessagesResponse } from '../messages/types';\nimport type * as marketing from './types';\n\n/**\n * API for WhatsApp Marketing Messages.\n *\n * Provides methods to send marketing template messages to WhatsApp users,\n * with support for message activity sharing opt-in.\n *\n * Endpoints covered:\n * - `POST /{PHONE_NUMBER_ID}/marketing_messages` - Send a marketing template message\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/marketing-messages/send-marketing-messages/\n */\nexport default class MarketingMessagesApi extends BaseAPI implements marketing.MarketingMessagesClass {\n private readonly endpoint = 'marketing_messages';\n\n /**\n * Send a marketing template message to a WhatsApp user.\n *\n * Address the user either by phone number (`to`) or by business-scoped user ID\n * (`recipient`). Exactly one of the two is required.\n *\n * @param params - The marketing message request parameters.\n * @param params.to - The recipient's WhatsApp phone number.\n * @param params.recipient - The recipient's BSUID or parent BSUID, used instead of `to`.\n * @param params.template - The template configuration (name, language, components).\n * @param params.message_activity_sharing - Optional flag to enable message activity sharing.\n * @param params.product_policy - Optional product policy for marketing messages.\n * @param params.bid_spec - Optional send-time multiplier applied to the template's max price.\n * @returns The messages response with message ID and status.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/marketing-messages/send-marketing-messages/\n */\n async sendTemplateMessage(params: marketing.MarketingMessageRequest): Promise<MessagesResponse> {\n if (!params.to === !params.recipient) {\n throw new WhatsAppValidationError('Provide exactly one of \"to\" (phone number) or \"recipient\" (BSUID).');\n }\n\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n recipient_type: 'individual',\n type: 'template',\n template: params.template,\n } as {\n messaging_product: 'whatsapp';\n recipient_type: 'individual';\n to?: string;\n recipient?: string;\n type: 'template';\n template: marketing.MarketingMessageRequest['template'];\n message_activity_sharing?: boolean;\n product_policy?: marketing.MarketingMessageRequest['product_policy'];\n bid_spec?: marketing.MarketingMessageRequest['bid_spec'];\n };\n\n if (params.to !== undefined) {\n body.to = params.to;\n }\n\n if (params.recipient !== undefined) {\n body.recipient = params.recipient;\n }\n\n if (params.message_activity_sharing !== undefined) {\n body.message_activity_sharing = params.message_activity_sharing;\n }\n\n if (params.product_policy !== undefined) {\n body.product_policy = params.product_policy;\n }\n\n if (params.bid_spec !== undefined) {\n body.bid_spec = params.bid_spec;\n }\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/media/\n\n// Endpoints:\n// - GET /{MEDIA_ID}\n// - POST /{PHONE_NUMBER_ID}/media\n// - DELETE /{MEDIA_ID}\n// - GET {MEDIA_URL}\n\nimport { WHATSAPP_MESSAGING_PRODUCT } from '../../config/defaults';\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { ResponseSuccess } from '../../types/request';\nimport { WhatsAppValidationError } from '../../utils/isMetaError';\n\nimport type * as media from './types';\n\n/**\n * WhatsApp Media API client for uploading, retrieving, downloading, and deleting media.\n *\n * Media uploaded to the WhatsApp API can be used in messages (images, audio, video,\n * documents, stickers). Each media object is identified by a unique media ID.\n *\n * **Covered endpoints:**\n * - `GET /{MEDIA_ID}` - Retrieve media info ({@link MediaApi.getMediaById})\n * - `POST /{PHONE_NUMBER_ID}/media` - Upload media ({@link MediaApi.uploadMedia})\n * - `DELETE /{MEDIA_ID}` - Delete media ({@link MediaApi.deleteMedia})\n * - `GET {MEDIA_URL}` - Download media content ({@link MediaApi.downloadMedia})\n *\n * **Supported media types and size limits:**\n * | Type | MIME Types | Max Size |\n * |------|-----------|----------|\n * | Audio | audio/aac, audio/mp4, audio/mpeg, audio/amr, audio/ogg | 16 MB |\n * | Document | Various (PDF, DOC, DOCX, PPT, XLS, etc.) | 100 MB |\n * | Image | image/jpeg, image/png | 5 MB |\n * | Sticker | image/webp | 100 KB (animated), 500 KB (static) |\n * | Video | video/mp4, video/3gp | 16 MB |\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/media | WhatsApp Media API Reference}\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/media/ | WhatsApp Media Documentation}\n *\n * @example\n * ```ts\n * const client = new WhatsApp({ accessToken: '...', phoneNumberId: '...' });\n *\n * // Upload, send, then clean up\n * const { id } = await client.media.uploadMedia(file);\n * await client.messages.image({ body: { id }, to: '1234567890' });\n * await client.media.deleteMedia(id);\n * ```\n */\nexport default class MediaApi extends BaseAPI implements media.MediaClass {\n private readonly endpoint = 'media';\n\n /**\n * Retrieves media information by media ID.\n *\n * Returns metadata about the media object including its URL, MIME type, file size,\n * and SHA-256 hash. The returned URL can be used with {@link MediaApi.downloadMedia}\n * to fetch the actual media content.\n *\n * **Endpoint:** `GET /{MEDIA_ID}`\n *\n * @param mediaId - The unique identifier of the media to retrieve\n * @returns A promise resolving to the media metadata including `url`, `mime_type`, `sha256`, and `file_size`\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/media#get-media-id | Get Media ID Reference}\n *\n * @example\n * ```ts\n * const mediaInfo = await client.media.getMediaById('media_id_123');\n * console.log(mediaInfo.url); // URL to download the media\n * console.log(mediaInfo.mime_type); // e.g., \"image/jpeg\"\n * console.log(mediaInfo.file_size); // size in bytes\n * ```\n */\n async getMediaById(mediaId: string): Promise<media.MediaResponse> {\n return this.sendJson(HttpMethodsEnum.Get, `${mediaId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n /**\n * Uploads a media file to the WhatsApp Cloud API.\n *\n * The uploaded media is assigned a unique media ID that can be used to send\n * messages containing that media. Media is automatically encrypted and stored\n * on Meta's servers.\n *\n * **Endpoint:** `POST /{PHONE_NUMBER_ID}/media` (`multipart/form-data` with `file`, `type` and\n * `messaging_product`)\n *\n * Accepts a `File`, `Blob`, `Uint8Array` (including a Node.js `Buffer`), `ArrayBuffer` or web\n * `ReadableStream<Uint8Array>` on every runtime. Pass the MIME type in `options.type` unless the\n * input is a `Blob`/`File` that already has one.\n *\n * **Memory:** a `ReadableStream` is read fully into a `Blob` before the request is sent. Meta\n * requires a multipart body and `fetch` only accepts `Blob` parts in `FormData`, so the upload is\n * not streamed end to end. Peak memory can exceed the file size (Meta caps media at 100 MB for\n * documents, 16 MB for audio/video, 5 MB for images). Buffering once also lets a throttled upload\n * be retried. Blob construction snapshots byte inputs; allow room for these copies.\n *\n * @param file - The content to upload\n * @param optionsOrMessagingProduct - Upload options, or the messaging product string (legacy form,\n * defaults to `'whatsapp'`)\n * @returns A promise resolving to the upload response containing the assigned `id` (media ID)\n * @throws WhatsAppValidationError when no MIME type is available or the input type is unsupported\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/media#upload-media | Upload Media Reference}\n *\n * @example\n * ```ts\n * const file = new File([buffer], 'image.jpg', { type: 'image/jpeg' });\n * const { id } = await client.media.uploadMedia(file);\n *\n * // Bytes or a web stream (e.g. a fetch() body) need a MIME type\n * const res = await fetch('https://example.com/report.pdf');\n * await client.media.uploadMedia(res.body!, { type: 'application/pdf', filename: 'report.pdf' });\n * ```\n */\n async uploadMedia(file: File, messagingProduct?: string): Promise<media.UploadMediaResponse>;\n async uploadMedia(\n file: media.UploadMediaInput,\n options?: media.UploadMediaOptions,\n ): Promise<media.UploadMediaResponse>;\n async uploadMedia(\n file: media.UploadMediaInput,\n optionsOrMessagingProduct?: media.UploadMediaOptions | string,\n ): Promise<media.UploadMediaResponse> {\n const options: media.UploadMediaOptions =\n typeof optionsOrMessagingProduct === 'string'\n ? { messagingProduct: optionsOrMessagingProduct }\n : (optionsOrMessagingProduct ?? {});\n const messagingProduct = options.messagingProduct ?? WHATSAPP_MESSAGING_PRODUCT;\n\n const mimeType = options.type || (file instanceof Blob ? file.type : '');\n if (!mimeType) {\n throw new WhatsAppValidationError(\n 'uploadMedia needs a MIME type: pass options.type (e.g. \"image/jpeg\") or a Blob/File with a type',\n );\n }\n\n const blob = await toUploadBlob(file, options.type);\n const formData = new FormData();\n if (blob === file && !options.type && !options.filename) {\n // Unchanged legacy path: append the caller's File/Blob as is.\n formData.append('file', blob);\n } else {\n formData.append('file', blob, options.filename ?? fileNameOf(file) ?? 'file');\n }\n formData.append('messaging_product', messagingProduct);\n formData.append('type', mimeType);\n\n return this.sendFormData(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n formData,\n );\n }\n\n /**\n * Deletes a media file from WhatsApp servers.\n *\n * Once deleted, the media ID can no longer be used in messages. Any messages\n * already sent with this media will continue to display the media.\n *\n * **Endpoint:** `DELETE /{MEDIA_ID}`\n *\n * @param mediaId - The unique identifier of the media to delete\n * @returns A promise resolving to a success response (`{ success: true }`)\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/media#delete-media | Delete Media Reference}\n *\n * @example\n * ```ts\n * const result = await client.media.deleteMedia('media_id_123');\n * console.log(result.success); // true\n * ```\n */\n async deleteMedia(mediaId: string): Promise<ResponseSuccess> {\n return this.sendJson(HttpMethodsEnum.Delete, `${mediaId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n /**\n * Downloads media content from a WhatsApp media URL.\n *\n * Use {@link MediaApi.getMediaById} first to obtain the media URL, then pass it\n * to this method to download the actual file content. The returned URL from\n * `getMediaById` is only valid for a limited time.\n *\n * **Endpoint:** `GET {MEDIA_URL}`\n *\n * @param mediaUrl - The media download URL obtained from {@link MediaApi.getMediaById}\n * @returns A promise resolving to a `Blob` containing the raw media data\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/media#download-media | Download Media Reference}\n *\n * @example\n * ```ts\n * // First get the media URL, then download it\n * const mediaInfo = await client.media.getMediaById('media_id_123');\n * const blob = await client.media.downloadMedia(mediaInfo.url);\n * ```\n */\n async downloadMedia(mediaUrl: string): Promise<Blob> {\n // The media URL returns the file bytes, not JSON, so read the body as a Blob.\n const response = await this.sendRaw(HttpMethodsEnum.Get, mediaUrl, this.config[WabaConfigEnum.RequestTimeout]);\n return response.blob();\n }\n}\n\nfunction fileNameOf(input: unknown): string | undefined {\n const name = (input as { name?: unknown } | null)?.name;\n return typeof name === 'string' && name !== '' ? name : undefined;\n}\n\nfunction isReadableStream(input: unknown): input is ReadableStream<Uint8Array> {\n return (\n typeof ReadableStream !== 'undefined' &&\n (input instanceof ReadableStream || typeof (input as ReadableStream | null)?.getReader === 'function')\n );\n}\n\nasync function toUploadBlob(input: media.UploadMediaInput, type: string | undefined): Promise<Blob> {\n if (input instanceof Blob) {\n // Re-label only when the caller overrides the MIME type; slice() does not copy the bytes.\n return type && type !== input.type ? input.slice(0, input.size, type) : input;\n }\n const blobOptions = type ? { type } : undefined;\n if (input instanceof ArrayBuffer) {\n return new Blob([input], blobOptions);\n }\n if (input instanceof Uint8Array) {\n // Blob parts must be backed by an ArrayBuffer; copy only SharedArrayBuffer-backed views.\n const bytes = input.buffer instanceof ArrayBuffer ? (input as Uint8Array<ArrayBuffer>) : new Uint8Array(input);\n return new Blob([bytes], blobOptions);\n }\n if (isReadableStream(input)) {\n const collected = await new Response(input).blob();\n return type ? collected.slice(0, collected.size, type) : collected;\n }\n throw new WhatsAppValidationError(\n 'uploadMedia accepts a File, Blob, Uint8Array, ArrayBuffer or ReadableStream<Uint8Array>',\n );\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/overview/\n\n// Endpoints:\n// - GET /{PHONE_NUMBER_ID}/message_history\n// - GET /{MESSAGE_HISTORY_ID}/events\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\n\nimport type * as messageHistory from './types';\n\nexport default class MessageHistoryApi extends BaseAPI implements messageHistory.MessageHistoryClass {\n private resolveFields(fields?: messageHistory.MessageHistoryFieldsParam): string | undefined {\n return Array.isArray(fields) ? fields.join(',') : fields;\n }\n\n async getMessageHistory(\n params?: messageHistory.MessageHistoryListParams,\n ): Promise<messageHistory.MessageHistoryResponse> {\n const query = params\n ? objectToQueryString({\n fields: this.resolveFields(params.fields),\n message_id: params.message_id,\n start_time: params.start_time,\n end_time: params.end_time,\n limit: params.limit,\n after: params.after,\n before: params.before,\n })\n : '';\n\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/message_history${query}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async getMessageHistoryEvents(\n messageHistoryId: string,\n params?: messageHistory.MessageHistoryEventListParams,\n ): Promise<messageHistory.MessageHistoryResponse> {\n const query = params\n ? objectToQueryString({\n fields: this.resolveFields(params.fields),\n status_filter: params.status_filter,\n limit: params.limit,\n after: params.after,\n before: params.before,\n })\n : '';\n\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${messageHistoryId}/events${query}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/messages/\n\n// Endpoints:\n// - POST /{PHONE_NUMBER_ID}/messages\n// - POST /{PHONE_NUMBER_ID}/messages_encrypted\n\nimport { WHATSAPP_MESSAGING_PRODUCT } from '../../config/defaults';\nimport { BaseAPI } from '../../types/base';\nimport {\n type ComponentTypesEnum,\n HttpMethodsEnum,\n type InteractiveTypesEnum,\n MessageCategoryEnum,\n MessageTypesEnum,\n WabaConfigEnum,\n} from '../../types/enums';\nimport { assertPhoneNumber } from '../../utils/validate';\nimport type * as m from './types';\n\n/**\n * Maps each message type to its appropriate payload type.\n *\n * This conditional type resolves the correct payload interface based on the {@link MessageTypesEnum} value,\n * ensuring type-safe message construction at compile time.\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\n/**\n * WhatsApp Messages API client for sending various message types.\n *\n * Provides methods to send text, media, interactive, template, location, contact,\n * reaction, and status messages through the WhatsApp Cloud API.\n *\n * **Endpoint:** `POST /{PHONE_NUMBER_ID}/messages`\n *\n * **Covered operations:**\n * - {@link MessagesApi.text | text} - Send plain text messages\n * - {@link MessagesApi.audio | audio} - Send audio messages\n * - {@link MessagesApi.image | image} - Send image messages\n * - {@link MessagesApi.video | video} - Send video messages\n * - {@link MessagesApi.document | document} - Send document messages\n * - {@link MessagesApi.sticker | sticker} - Send sticker messages\n * - {@link MessagesApi.location | location} - Send location messages\n * - {@link MessagesApi.contacts | contacts} - Send contact card(s)\n * - {@link MessagesApi.template | template} - Send template messages\n * - {@link MessagesApi.interactive | interactive} - Send interactive messages (generic)\n * - {@link MessagesApi.interactiveList | interactiveList} - Send list interactive messages\n * - {@link MessagesApi.interactiveCtaUrl | interactiveCtaUrl} - Send CTA URL interactive messages\n * - {@link MessagesApi.interactiveVoiceCall | interactiveVoiceCall} - Send \"Call on WhatsApp\" voice call button messages\n * - {@link MessagesApi.interactiveLocationRequest | interactiveLocationRequest} - Send location request messages\n * - {@link MessagesApi.interactiveAddressMessage | interactiveAddressMessage} - Send address message interactive messages\n * - {@link MessagesApi.interactiveReplyButtons | interactiveReplyButtons} - Send reply button interactive messages\n * - {@link MessagesApi.interactiveFlow | interactiveFlow} - Send flow interactive messages\n * - {@link MessagesApi.interactiveCarousel | interactiveCarousel} - Send carousel interactive messages\n * - {@link MessagesApi.reaction | reaction} - Send reaction emoji to a message\n * - {@link MessagesApi.status | status} - Update message status (read, typing)\n * - {@link MessagesApi.markAsRead | markAsRead} - Mark a message as read\n * - {@link MessagesApi.showTypingIndicator | showTypingIndicator} - Show typing indicator\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages | WhatsApp Messages API Reference}\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/messages/ | WhatsApp Messages Documentation}\n *\n * @example\n * ```ts\n * const client = new WhatsApp({ accessToken: '...', phoneNumberId: '...' });\n *\n * // Send a text message\n * await client.messages.text({ body: 'Hello!', to: '1234567890' });\n *\n * // Send an image\n * await client.messages.image({ body: { link: 'https://example.com/image.jpg' }, to: '1234567890' });\n * ```\n */\nexport default class MessagesApi extends BaseAPI implements m.MessagesClass {\n private readonly commonMethod = HttpMethodsEnum.Post;\n private readonly commonEndpoint = 'messages';\n\n /**\n * Builds the request body for WhatsApp API messages.\n *\n * Constructs a properly formatted message payload including the messaging product,\n * recipient type, recipient phone number, message type, and optional reply context.\n *\n * @param type - The type of message to send (e.g., text, image, template)\n * @param payload - The message payload object matching the specified type\n * @param to - The recipient's phone number in international format (e.g., \"1234567890\")\n * @param replyMessageId - Optional message ID to reply to, setting the message context\n * @param recipientType - Whether `to` addresses an individual or a group\n * @param directSend - Optional Direct Send options (`category` and `directSendConfig`)\n * @returns The formatted request body ready to be serialized and sent\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages | Messages API Reference}\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/direct-send/ | Direct Send}\n *\n * @example\n * ```ts\n * const body = messagesApi.bodyBuilder(\n * MessageTypesEnum.Text,\n * { body: 'Hello!' },\n * '1234567890',\n * );\n * ```\n */\n bodyBuilder<T extends MessageTypesEnum>(\n type: T,\n payload: MessagePayloadType<T>,\n to: string,\n replyMessageId?: string,\n recipientType: m.MessageRecipientType = 'individual',\n directSend?: m.DirectSendOptions,\n ) {\n if (recipientType === 'individual') assertPhoneNumber(to);\n const body: m.MessageRequestBody<T> = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n recipient_type: recipientType,\n to,\n type,\n [type]: payload,\n };\n\n if (replyMessageId) body.context = { message_id: replyMessageId };\n if (directSend?.category) body.category = directSend.category;\n if (directSend?.directSendConfig) body.direct_send_config = directSend.directSendConfig;\n\n return body;\n }\n\n /**\n * Sends a request to the WhatsApp Cloud API messages endpoint.\n *\n * Internal method that dispatches the serialized JSON body to\n * `POST /{PHONE_NUMBER_ID}/messages`.\n *\n * @param body - The serialized JSON request body to send\n * @returns A promise resolving to the WhatsApp messages API response containing the message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages | Messages API Reference}\n */\n private send<T = m.MessagesResponse>(body: BodyInit | null): Promise<T> {\n return this.sendJson<T>(\n this.commonMethod,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.commonEndpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n body,\n );\n }\n\n private sendEncrypted<T = m.EncryptedMessagesResponse>(body: BodyInit | null): Promise<T> {\n return this.sendJson<T>(\n this.commonMethod,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/messages_encrypted`,\n this.config[WabaConfigEnum.RequestTimeout],\n body,\n );\n }\n\n /**\n * Sends an audio message via the WhatsApp Cloud API.\n *\n * The audio can be specified by a media ID (previously uploaded) or a public URL link.\n * Supported formats: audio/aac, audio/mp4, audio/mpeg, audio/amr, audio/ogg (with opus codec).\n * Maximum file size: 16 MB.\n *\n * @param params - The audio message parameters\n * @param params.body - Audio media object containing either `id` (media ID) or `link` (URL)\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#audio-object | Audio Object Reference}\n *\n * @example\n * ```ts\n * // Send audio by URL\n * await client.messages.audio({\n * body: { link: 'https://example.com/audio.mp3' },\n * to: '1234567890',\n * });\n *\n * // Send audio by media ID\n * await client.messages.audio({\n * body: { id: 'media_id_123' },\n * to: '1234567890',\n * });\n * ```\n */\n async audio(params: m.MessageRequestParams<m.AudioMediaObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId, recipientType, category, directSendConfig } = params;\n return this.send(\n JSON.stringify(\n this.bodyBuilder(MessageTypesEnum.Audio, body, to, replyMessageId, recipientType, {\n category,\n directSendConfig,\n }),\n ),\n );\n }\n\n /**\n * Sends one or more contact cards via the WhatsApp Cloud API.\n *\n * Contact messages allow sharing structured contact information including names,\n * phone numbers, email addresses, and more.\n *\n * @param params - The contact message parameters\n * @param params.body - Array of {@link m.ContactObject} containing contact details (name, phones, emails, etc.)\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#contacts-object | Contacts Object Reference}\n *\n * @example\n * ```ts\n * await client.messages.contacts({\n * body: [{\n * name: { formatted_name: 'John Doe', first_name: 'John', last_name: 'Doe' },\n * phones: [{ phone: '+1234567890', type: 'MOBILE' }],\n * }],\n * to: '1234567890',\n * });\n * ```\n */\n async contacts(params: m.MessageRequestParams<m.ContactObject[]>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId, recipientType, category, directSendConfig } = params;\n return this.send(\n JSON.stringify(\n this.bodyBuilder(MessageTypesEnum.Contacts, body, to, replyMessageId, recipientType, {\n category,\n directSendConfig,\n }),\n ),\n );\n }\n\n /**\n * Sends a document message via the WhatsApp Cloud API.\n *\n * Documents can be specified by media ID or public URL. Supports various formats\n * including PDF, DOC, DOCX, PPT, PPTX, XLS, XLSX, and more.\n * Maximum file size: 100 MB.\n *\n * @param params - The document message parameters\n * @param params.body - Document media object containing `id` or `link`, and optional `caption` and `filename`\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#document-object | Document Object Reference}\n *\n * @example\n * ```ts\n * await client.messages.document({\n * body: {\n * link: 'https://example.com/report.pdf',\n * caption: 'Monthly Report',\n * filename: 'report.pdf',\n * },\n * to: '1234567890',\n * });\n * ```\n */\n async document(params: m.MessageRequestParams<m.DocumentMediaObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId, recipientType, category, directSendConfig } = params;\n return this.send(\n JSON.stringify(\n this.bodyBuilder(MessageTypesEnum.Document, body, to, replyMessageId, recipientType, {\n category,\n directSendConfig,\n }),\n ),\n );\n }\n\n /**\n * Sends an image message via the WhatsApp Cloud API.\n *\n * Images can be specified by media ID or public URL.\n * Supported formats: image/jpeg, image/png. Maximum file size: 5 MB.\n *\n * @param params - The image message parameters\n * @param params.body - Image media object containing `id` or `link`, and optional `caption`\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#image-object | Image Object Reference}\n *\n * @example\n * ```ts\n * await client.messages.image({\n * body: { link: 'https://example.com/photo.jpg', caption: 'Check this out!' },\n * to: '1234567890',\n * });\n * ```\n */\n async image(params: m.MessageRequestParams<m.ImageMediaObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId, recipientType, category, directSendConfig } = params;\n return this.send(\n JSON.stringify(\n this.bodyBuilder(MessageTypesEnum.Image, body, to, replyMessageId, recipientType, {\n category,\n directSendConfig,\n }),\n ),\n );\n }\n\n /**\n * Sends an interactive message via the WhatsApp Cloud API.\n *\n * Interactive messages allow rich user interactions such as lists, buttons, CTAs,\n * flows, location requests, address messages, and carousels. For type-specific\n * convenience methods, see {@link MessagesApi.interactiveList}, {@link MessagesApi.interactiveReplyButtons}, etc.\n *\n * @param params - The interactive message parameters\n * @param params.body - Interactive object containing the `type` and type-specific action/body/header/footer\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#interactive-object | Interactive Object Reference}\n *\n * @example\n * ```ts\n * await client.messages.interactive({\n * body: {\n * type: 'button',\n * body: { text: 'Choose an option' },\n * action: {\n * buttons: [\n * { type: 'reply', reply: { id: 'btn1', title: 'Option 1' } },\n * { type: 'reply', reply: { id: 'btn2', title: 'Option 2' } },\n * ],\n * },\n * },\n * to: '1234567890',\n * });\n * ```\n */\n async interactive(params: m.MessageRequestParams<m.InteractiveObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId, recipientType, category, directSendConfig } = params;\n return this.send(\n JSON.stringify(\n this.bodyBuilder(MessageTypesEnum.Interactive, body, to, replyMessageId, recipientType, {\n category,\n directSendConfig,\n }),\n ),\n );\n }\n\n /**\n * Sends a location message via the WhatsApp Cloud API.\n *\n * Shares a geographic location with the recipient, displayed as a map pin.\n *\n * @param params - The location message parameters\n * @param params.body - Location object containing `latitude`, `longitude`, and optional `name` and `address`\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#location-object | Location Object Reference}\n *\n * @example\n * ```ts\n * await client.messages.location({\n * body: {\n * latitude: 37.4220936,\n * longitude: -122.083922,\n * name: 'Googleplex',\n * address: '1600 Amphitheatre Parkway, Mountain View, CA',\n * },\n * to: '1234567890',\n * });\n * ```\n */\n async location(params: m.MessageRequestParams<m.LocationObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId, recipientType, category, directSendConfig } = params;\n return this.send(\n JSON.stringify(\n this.bodyBuilder(MessageTypesEnum.Location, body, to, replyMessageId, recipientType, {\n category,\n directSendConfig,\n }),\n ),\n );\n }\n\n /**\n * Sends a sticker message via the WhatsApp Cloud API.\n *\n * Stickers can be specified by media ID or public URL.\n * Supported format: image/webp. Maximum file size: 100 KB (animated), 500 KB (static).\n *\n * @param params - The sticker message parameters\n * @param params.body - Sticker media object containing `id` or `link`\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#sticker-object | Sticker Object Reference}\n *\n * @example\n * ```ts\n * await client.messages.sticker({\n * body: { link: 'https://example.com/sticker.webp' },\n * to: '1234567890',\n * });\n * ```\n */\n async sticker(params: m.MessageRequestParams<m.StickerMediaObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId, recipientType, category, directSendConfig } = params;\n return this.send(\n JSON.stringify(\n this.bodyBuilder(MessageTypesEnum.Sticker, body, to, replyMessageId, recipientType, {\n category,\n directSendConfig,\n }),\n ),\n );\n }\n\n /**\n * Sends a template message via the WhatsApp Cloud API.\n *\n * Template messages use pre-approved message templates and can include header,\n * body, and button components with dynamic parameters. Templates must be\n * approved before use.\n *\n * @param params - The template message parameters\n * @param params.body - Template object containing `name`, `language`, and optional `components`\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#template-object | Template Object Reference}\n *\n * @example\n * ```ts\n * await client.messages.template({\n * body: {\n * name: 'hello_world',\n * language: { code: 'en_US' },\n * components: [\n * { type: 'body', parameters: [{ type: 'text', text: 'John' }] },\n * ],\n * },\n * to: '1234567890',\n * });\n * ```\n */\n async template(\n params: m.MessageRequestParams<m.MessageTemplateObject<ComponentTypesEnum>>,\n ): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId, recipientType, category, directSendConfig } = params;\n return this.send(\n JSON.stringify(\n this.bodyBuilder(MessageTypesEnum.Template, body, to, replyMessageId, recipientType, {\n category,\n directSendConfig,\n }),\n ),\n );\n }\n\n /**\n * Sends a text message via the WhatsApp Cloud API.\n *\n * Sends a plain text message. The `body` can be a string or a {@link m.TextObject}.\n * URL preview is enabled by default.\n *\n * @param params - The text message parameters\n * @param params.body - Message text as a string, or a {@link m.TextObject} with `body` and optional `preview_url`\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @param params.previewUrl - Whether to show a URL preview (defaults to `true`)\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#text-object | Text Object Reference}\n *\n * @example\n * ```ts\n * // Simple text\n * await client.messages.text({ body: 'Hello, World!', to: '1234567890' });\n *\n * // With URL preview disabled\n * await client.messages.text({\n * body: { body: 'Visit https://example.com', preview_url: false },\n * to: '1234567890',\n * });\n * ```\n */\n async text(params: m.TextMessageParams): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId, previewUrl, recipientType, category, directSendConfig } = 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(\n JSON.stringify(\n this.bodyBuilder(MessageTypesEnum.Text, textPayload, to, replyMessageId, recipientType, {\n category,\n directSendConfig,\n }),\n ),\n );\n }\n\n /**\n * Sends a video message via the WhatsApp Cloud API.\n *\n * Videos can be specified by media ID or public URL.\n * Supported formats: video/mp4, video/3gp. Maximum file size: 16 MB.\n * Only H.264 video codec and AAC audio codec are supported.\n *\n * @param params - The video message parameters\n * @param params.body - Video media object containing `id` or `link`, and optional `caption`\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#video-object | Video Object Reference}\n *\n * @example\n * ```ts\n * await client.messages.video({\n * body: { link: 'https://example.com/video.mp4', caption: 'Watch this!' },\n * to: '1234567890',\n * });\n * ```\n */\n async video(params: m.MessageRequestParams<m.VideoMediaObject>): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId, recipientType, category, directSendConfig } = params;\n return this.send(\n JSON.stringify(\n this.bodyBuilder(MessageTypesEnum.Video, body, to, replyMessageId, recipientType, {\n category,\n directSendConfig,\n }),\n ),\n );\n }\n\n /**\n * Updates the status of a message (e.g., mark as read or show typing indicator).\n *\n * This is the low-level status method. For convenience, use {@link MessagesApi.markAsRead}\n * or {@link MessagesApi.showTypingIndicator} instead.\n *\n * @param params - The status update parameters\n * @param params.status - The status to set (e.g., `'read'`, `'typing'`)\n * @param params.messageId - The ID of the message to update\n * @param params.typingIndicator - Optional typing indicator configuration\n * @returns A promise resolving to the API response\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#status-object | Status Object Reference}\n *\n * @example\n * ```ts\n * await client.messages.status({\n * status: 'read',\n * messageId: 'wamid.ABC123',\n * });\n * ```\n */\n async status(params: m.StatusParams): Promise<m.StatusResponse> {\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n status: params.status,\n message_id: params.messageId,\n ...(params.typingIndicator && { typing_indicator: params.typingIndicator }),\n };\n\n return this.send<m.StatusResponse>(JSON.stringify(body));\n }\n\n /**\n * Marks a message as read, sending a read receipt to the sender.\n *\n * This is a convenience wrapper around {@link MessagesApi.status} that sets the status to `'read'`.\n * When a message is marked as read, all previous messages in the conversation are also marked as read.\n *\n * @param params - The parameters\n * @param params.messageId - The ID of the incoming message to mark as read (the `wamid` value)\n * @returns A promise resolving to the API response\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#status-object | Status Object Reference}\n *\n * @example\n * ```ts\n * await client.messages.markAsRead({ messageId: 'wamid.ABC123' });\n * ```\n */\n async markAsRead(params: { messageId: string }): Promise<m.StatusResponse> {\n return this.status({\n status: 'read',\n messageId: params.messageId,\n });\n }\n\n /**\n * Shows a typing indicator to the user, indicating that a response is being composed.\n *\n * The typing indicator is displayed for approximately 25 seconds or until a message\n * is sent, whichever comes first.\n *\n * @param params - The parameters\n * @param params.messageId - The ID of the incoming message to associate the typing indicator with\n * @returns A promise resolving to the API response\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#status-object | Status Object Reference}\n *\n * @example\n * ```ts\n * await client.messages.showTypingIndicator({ messageId: 'wamid.ABC123' });\n * ```\n */\n async showTypingIndicator(params: { messageId: string }): Promise<m.StatusResponse> {\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n status: 'typing',\n message_id: params.messageId,\n typing_indicator: { type: 'text' },\n };\n\n return this.send<m.StatusResponse>(JSON.stringify(body));\n }\n\n /**\n * Sends a list interactive message via the WhatsApp Cloud API.\n *\n * List messages present up to 10 selectable options in a menu-style list.\n * Each section can have a title and multiple rows with title, description, and ID.\n *\n * @param params - The list interactive message parameters\n * @param params.body - Interactive object with `type: 'list'` and action containing sections\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#list-messages | List Messages Reference}\n *\n * @example\n * ```ts\n * await client.messages.interactiveList({\n * body: {\n * type: 'list',\n * body: { text: 'Choose an option' },\n * action: {\n * button: 'View Options',\n * sections: [{ title: 'Section 1', rows: [{ id: '1', title: 'Option 1' }] }],\n * },\n * },\n * to: '1234567890',\n * });\n * ```\n */\n async interactiveList(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.List | 'list' }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive(params);\n }\n\n /**\n * Sends a Call-to-Action (CTA) URL button interactive message via the WhatsApp Cloud API.\n *\n * CTA URL messages display a button that opens a URL when tapped.\n *\n * @param params - The CTA URL interactive message parameters\n * @param params.body - Interactive object with `type: 'cta_url'` and action containing the URL and display text\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#interactive-object | Interactive Object Reference}\n *\n * @example\n * ```ts\n * await client.messages.interactiveCtaUrl({\n * body: {\n * type: 'cta_url',\n * body: { text: 'Visit our website' },\n * action: { name: 'cta_url', parameters: { display_text: 'Open', url: 'https://example.com' } },\n * },\n * to: '1234567890',\n * });\n * ```\n */\n async interactiveCtaUrl(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.CtaUrl | 'cta_url' }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive(params);\n }\n\n /**\n * Sends a \"Call on WhatsApp\" voice call button message via Direct Send.\n *\n * The button lets the recipient tap to start a WhatsApp voice call to your business\n * phone number. It is a Direct Send interactive type, so the request is always sent\n * with `category: 'utility'`; the button must be sent on its own and cannot be\n * combined with CTA URL or reply buttons, and footers are not supported.\n *\n * Calling must be enabled on the business phone number first\n * (`POST /{PHONE_NUMBER_ID}/settings` with `{ calling: { status: 'ENABLED' } }`) and the\n * app must be subscribed to the `calls` webhook field, otherwise the send fails with\n * error `138000`.\n *\n * @param params - The voice call interactive message parameters\n * @param params.body - Interactive object with `type: 'voice_call'` and a `voice_call` action\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @param params.directSendConfig - Optional Direct Send template attribution config\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/direct-send/supported-message-types | Direct Send supported message types}\n *\n * @example\n * ```ts\n * await client.messages.interactiveVoiceCall({\n * body: {\n * type: 'voice_call',\n * body: { text: 'Call our support team for help with your order.' },\n * action: { name: 'voice_call', parameters: { display_text: 'Call Support', ttl_minutes: 1440 } },\n * },\n * to: '1234567890',\n * });\n * ```\n */\n async interactiveVoiceCall(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.VoiceCall | 'voice_call' }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive({ ...params, category: params.category ?? MessageCategoryEnum.Utility });\n }\n\n /**\n * Sends a location request interactive message via the WhatsApp Cloud API.\n *\n * Prompts the recipient to share their current location.\n *\n * @param params - The location request interactive message parameters\n * @param params.body - Interactive object with `type: 'location_request_message'`\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#interactive-object | Interactive Object Reference}\n *\n * @example\n * ```ts\n * await client.messages.interactiveLocationRequest({\n * body: {\n * type: 'location_request_message',\n * body: { text: 'Please share your location' },\n * action: { name: 'send_location' },\n * },\n * to: '1234567890',\n * });\n * ```\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 via the WhatsApp Cloud API.\n *\n * Prompts the recipient to provide or confirm a shipping/delivery address.\n *\n * @param params - The address message interactive message parameters\n * @param params.body - Interactive object with `type: 'address_message'`\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#interactive-object | Interactive Object Reference}\n *\n * @example\n * ```ts\n * await client.messages.interactiveAddressMessage({\n * body: {\n * type: 'address_message',\n * body: { text: 'Please confirm your delivery address' },\n * action: { name: 'address_message', parameters: { country: 'US' } },\n * },\n * to: '1234567890',\n * });\n * ```\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 via the WhatsApp Cloud API.\n *\n * Reply button messages display up to 3 quick-reply buttons. Each button has\n * a unique ID and title (up to 20 characters).\n *\n * @param params - The reply buttons interactive message parameters\n * @param params.body - Interactive object with `type: 'button'` and action containing up to 3 reply buttons\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#reply-button | Reply Button Reference}\n *\n * @example\n * ```ts\n * await client.messages.interactiveReplyButtons({\n * body: {\n * type: 'button',\n * body: { text: 'Do you agree?' },\n * action: {\n * buttons: [\n * { type: 'reply', reply: { id: 'yes', title: 'Yes' } },\n * { type: 'reply', reply: { id: 'no', title: 'No' } },\n * ],\n * },\n * },\n * to: '1234567890',\n * });\n * ```\n */\n async interactiveReplyButtons(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.Button | 'button' }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive(params);\n }\n\n /**\n * Sends a flow interactive message via the WhatsApp Cloud API.\n *\n * Flow messages launch a WhatsApp Flow, which provides structured multi-step interactions\n * (forms, surveys, appointment booking, etc.) within the chat.\n *\n * @param params - The flow interactive message parameters\n * @param params.body - Interactive object with `type: 'flow'` and action containing the flow token and configuration\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#interactive-object | Interactive Object Reference}\n * @see {@link https://developers.facebook.com/docs/whatsapp/flows | WhatsApp Flows Documentation}\n *\n * @example\n * ```ts\n * await client.messages.interactiveFlow({\n * body: {\n * type: 'flow',\n * body: { text: 'Book an appointment' },\n * action: {\n * name: 'flow',\n * parameters: { flow_message_version: '3', flow_id: '123456', flow_cta: 'Book Now' },\n * },\n * },\n * to: '1234567890',\n * });\n * ```\n */\n async interactiveFlow(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.Flow | 'flow' }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive(params);\n }\n\n /**\n * Sends a carousel interactive message via the WhatsApp Cloud API.\n *\n * Carousel messages display a horizontally scrollable set of cards, each with\n * an image, body text, and up to 2 quick-reply buttons.\n *\n * @param params - The carousel interactive message parameters\n * @param params.body - Interactive object with `type: 'carousel'` and action containing carousel cards\n * @param params.to - Recipient phone number in international format\n * @param params.replyMessageId - Optional message ID to reply to\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#interactive-object | Interactive Object Reference}\n *\n * @example\n * ```ts\n * await client.messages.interactiveCarousel({\n * body: {\n * type: 'carousel',\n * body: { text: 'Browse our products' },\n * action: {\n * cards: [\n * {\n * header: { type: 'image', image: { link: 'https://example.com/product1.jpg' } },\n * body: { text: 'Product 1 - $10' },\n * buttons: [{ type: 'reply', reply: { id: 'buy_1', title: 'Buy' } }],\n * },\n * ],\n * },\n * },\n * to: '1234567890',\n * });\n * ```\n */\n async interactiveCarousel(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.Carousel }>,\n ): Promise<m.MessagesResponse> {\n return this.interactive(params);\n }\n\n /**\n * Sends a reaction emoji to an existing message via the WhatsApp Cloud API.\n *\n * Reactions allow users to respond to messages with a single emoji.\n * To remove a reaction, send an empty string as the emoji.\n *\n * @param params - The reaction parameters\n * @param params.messageId - The ID of the message to react to\n * @param params.emoji - The emoji character to react with (e.g., \"\\uD83D\\uDC4D\"), or empty string to remove reaction\n * @param params.to - Recipient phone number in international format\n * @returns A promise resolving to the message response with the sent message ID\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#reaction-object | Reaction Object Reference}\n *\n * @example\n * ```ts\n * // Add a reaction\n * await client.messages.reaction({\n * messageId: 'wamid.ABC123',\n * emoji: '\\uD83D\\uDC4D',\n * to: '1234567890',\n * });\n *\n * // Remove a reaction\n * await client.messages.reaction({\n * messageId: 'wamid.ABC123',\n * emoji: '',\n * to: '1234567890',\n * });\n * ```\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(\n JSON.stringify(\n this.bodyBuilder(\n MessageTypesEnum.Reaction,\n reactionPayload,\n params.to,\n undefined,\n params.recipientType,\n ),\n ),\n );\n }\n\n /**\n * Send a message through the encrypted messages endpoint.\n *\n * The encrypted endpoint payload varies by encryption setup, so this method accepts\n * the Graph API payload shape directly while preserving the endpoint and response type.\n */\n async encrypted(params: m.EncryptedMessageRequest): Promise<m.EncryptedMessagesResponse> {\n return this.sendEncrypted(JSON.stringify(params));\n }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/payments/payments-in/onboarding-apis/\n\n// Endpoints:\n// - GET /{WABA_ID}/payment_configurations\n// - GET /{WABA_ID}/payment_configuration/{CONFIGURATION_NAME}\n// - POST /{WABA_ID}/payment_configuration\n// - POST /{WABA_ID}/payment_configuration/{CONFIGURATION_NAME}\n// - POST /{WABA_ID}/generate_payment_configuration_oauth_link\n// - DELETE /{WABA_ID}/payment_configuration\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { ResponseSuccess } from '../../types/request';\n\nimport type * as payments from './types';\n\n/**\n * API for WhatsApp Payments (India payment configuration).\n *\n * Provides methods to manage payment configurations for WhatsApp Business Accounts,\n * including creating, reading, updating, and deleting payment configurations,\n * as well as generating OAuth links for payment onboarding.\n *\n * Endpoints covered:\n * - `GET /{WABA_ID}/payment_configurations` - List all payment configurations\n * - `GET /{WABA_ID}/payment_configuration/{CONFIGURATION_NAME}` - Get a specific payment configuration\n * - `POST /{WABA_ID}/payment_configuration` - Create a new payment configuration\n * - `POST /{WABA_ID}/payment_configuration/{CONFIGURATION_NAME}` - Update a payment configuration\n * - `POST /{WABA_ID}/generate_payment_configuration_oauth_link` - Generate an OAuth link\n * - `DELETE /{WABA_ID}/payment_configuration` - Delete a payment configuration\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/payments/payments-in/onboarding-apis/\n */\nexport default class PaymentsApi extends BaseAPI implements payments.PaymentsClass {\n /**\n * List all payment configurations for a WhatsApp Business Account.\n *\n * @param wabaId - The WhatsApp Business Account ID.\n * @returns A list of all payment configurations.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/payments/payments-in/onboarding-apis/\n */\n async listPaymentConfigurations(wabaId: string): Promise<payments.PaymentConfigurationsResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `/${wabaId}/payment_configurations`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Get a specific payment configuration by name.\n *\n * @param wabaId - The WhatsApp Business Account ID.\n * @param configurationName - The name of the payment configuration to retrieve.\n * @returns The payment configuration details.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/payments/payments-in/onboarding-apis/\n */\n async getPaymentConfiguration(\n wabaId: string,\n configurationName: string,\n ): Promise<payments.PaymentConfigurationsResponse> {\n const encodedName = encodeURIComponent(configurationName);\n return this.sendJson(\n HttpMethodsEnum.Get,\n `/${wabaId}/payment_configuration/${encodedName}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Create a new payment configuration for a WhatsApp Business Account.\n *\n * @param wabaId - The WhatsApp Business Account ID.\n * @param params - The payment configuration details to create.\n * @returns The created payment configuration response.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/payments/payments-in/onboarding-apis/\n */\n async createPaymentConfiguration(\n wabaId: string,\n params: payments.PaymentConfigurationCreateRequest,\n ): Promise<payments.PaymentConfigurationCreateResponse> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${wabaId}/payment_configuration`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(params),\n );\n }\n\n /**\n * Update an existing payment configuration.\n *\n * @param wabaId - The WhatsApp Business Account ID.\n * @param configurationName - The name of the payment configuration to update.\n * @param params - The payment configuration fields to update.\n * @returns The updated payment configuration response.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/payments/payments-in/onboarding-apis/\n */\n async updatePaymentConfiguration(\n wabaId: string,\n configurationName: string,\n params: payments.PaymentConfigurationUpdateRequest,\n ): Promise<payments.PaymentConfigurationUpdateResponse> {\n const encodedName = encodeURIComponent(configurationName);\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${wabaId}/payment_configuration/${encodedName}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(params),\n );\n }\n\n /**\n * Generate an OAuth link for payment configuration onboarding.\n *\n * @param wabaId - The WhatsApp Business Account ID.\n * @param params - The OAuth link generation parameters.\n * @returns The generated OAuth link response.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/payments/payments-in/onboarding-apis/\n */\n async generatePaymentConfigurationOauthLink(\n wabaId: string,\n params: payments.PaymentConfigurationOauthLinkRequest,\n ): Promise<payments.PaymentConfigurationOauthLinkResponse> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${wabaId}/generate_payment_configuration_oauth_link`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(params),\n );\n }\n\n /**\n * Delete a payment configuration from a WhatsApp Business Account.\n *\n * @param wabaId - The WhatsApp Business Account ID.\n * @param params - The payment configuration deletion parameters (includes configuration name).\n * @returns A success response confirming deletion.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/payments/payments-in/onboarding-apis/\n */\n async deletePaymentConfiguration(\n wabaId: string,\n params: payments.PaymentConfigurationDeleteRequest,\n ): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Delete,\n `/${wabaId}/payment_configuration`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(params),\n );\n }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/phone-numbers/\n\n// Endpoints:\n// - GET /{PHONE_NUMBER_ID}?fields\n// - POST /{PHONE_NUMBER_ID}\n// - GET /{WABA_ID}/phone_numbers\n// - POST /{WABA_ID}/phone_numbers\n// - POST /{PHONE_NUMBER_ID}/request_code\n// - POST /{PHONE_NUMBER_ID}/verify_code\n// - GET /{PHONE_NUMBER_ID}/settings\n// - POST /{PHONE_NUMBER_ID}/settings\n// - POST /{PHONE_NUMBER_ID}/conversational_automation\n// - GET /{PHONE_NUMBER_ID}?fields=conversational_automation\n// - GET /{PHONE_NUMBER_ID}?fields=throughput\n// - GET /{PHONE_NUMBER_ID}/official_business_account\n// - POST /{PHONE_NUMBER_ID}/official_business_account\n// - GET /{PHONE_NUMBER_ID}/business_compliance_info\n// - POST /{PHONE_NUMBER_ID}/business_compliance_info\n// - GET /{PHONE_NUMBER_ID}/username\n// - POST /{PHONE_NUMBER_ID}/username\n// - DELETE /{PHONE_NUMBER_ID}/username\n// - GET /{PHONE_NUMBER_ID}/username_suggestions\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { ResponseSuccess } from '../../types/request';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\n\nimport type * as phoneNumber from './types';\n\n/**\n * API for managing WhatsApp Business phone numbers.\n *\n * This API provides methods for phone number management, verification,\n * and conversational automation configuration within the WhatsApp Business Platform.\n *\n * Covered endpoints:\n * - Get phone number info by ID (`GET /{PHONE_NUMBER_ID}`)\n * - List all phone numbers for a WABA (`GET /{WABA_ID}/phone_numbers`)\n * - Request a verification code (`POST /{PHONE_NUMBER_ID}/request_code`)\n * - Verify a phone number with a code (`POST /{PHONE_NUMBER_ID}/verify_code`)\n * - Set conversational automation config (`POST /{PHONE_NUMBER_ID}/conversational_automation`)\n * - Get conversational automation config (`GET /{PHONE_NUMBER_ID}?fields=conversational_automation`)\n * - Get throughput info (`GET /{PHONE_NUMBER_ID}?fields=throughput`)\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/phone-numbers | Phone Numbers API Reference}\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/phone-numbers/ | Phone Numbers Documentation}\n */\nexport default class PhoneNumberApi extends BaseAPI implements phoneNumber.PhoneNumberClass {\n private readonly endpoint = 'phone_numbers';\n\n /**\n * Get phone number information by ID.\n *\n * Retrieves details about the configured phone number, including display phone number,\n * verified name, quality rating, platform type, and more. Use the `fields` parameter\n * to request only specific fields.\n *\n * @param fields - Optional fields to include in the response. Can be a comma-separated\n * string (e.g., `'display_phone_number,verified_name'`) or an array of field names.\n * @returns A promise that resolves with the phone number information.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/phone-numbers#get-single | Get Phone Number}\n *\n * @example\n * ```ts\n * // Get all available fields\n * const phoneNumber = await whatsappClient.phoneNumber.getPhoneNumberById();\n *\n * // Get specific fields as a comma-separated string\n * const phoneNumber = await whatsappClient.phoneNumber.getPhoneNumberById(\n * 'display_phone_number,verified_name,quality_rating'\n * );\n *\n * // Get specific fields as an array\n * const phoneNumber = await whatsappClient.phoneNumber.getPhoneNumberById(\n * ['display_phone_number', 'verified_name']\n * );\n * ```\n */\n async getPhoneNumberById(fields?: phoneNumber.PhoneNumberFieldsParam): Promise<phoneNumber.PhoneNumberResponse> {\n const fieldValue = Array.isArray(fields) ? fields.join(',') : fields;\n const queryParams = fieldValue ? objectToQueryString({ fields: fieldValue }) : '';\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 associated with the WhatsApp Business Account.\n *\n * Returns a list of all phone numbers registered under the configured WABA,\n * including their verification status, quality rating, and display information.\n *\n * @param params - Optional list query parameters such as fields, filtering, sort, and paging.\n * @returns A promise that resolves with the list of phone numbers.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/phone-numbers#get-all | List Phone Numbers}\n *\n * @example\n * ```ts\n * const response = await whatsappClient.phoneNumber.getPhoneNumbers();\n * for (const number of response.data) {\n * console.log(number.display_phone_number, number.verified_name);\n * }\n * ```\n */\n async getPhoneNumbers(params?: phoneNumber.PhoneNumbersListParams): Promise<phoneNumber.PhoneNumbersResponse> {\n const fields = Array.isArray(params?.fields) ? params.fields.join(',') : params?.fields;\n const filtering = Array.isArray(params?.filtering) ? JSON.stringify(params.filtering) : params?.filtering;\n const queryParams = objectToQueryString({\n fields,\n filtering,\n sort: params?.sort,\n limit: params?.limit,\n after: params?.after,\n before: params?.before,\n });\n\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.BusinessAcctId]}/${this.endpoint}${queryParams}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Create a phone number under a WABA.\n *\n * @param request - Phone number creation payload from the Graph API.\n * @param wabaId - Optional WABA ID. Defaults to the configured business account ID.\n */\n async createPhoneNumber(\n request: phoneNumber.CreatePhoneNumberRequest,\n wabaId: string = this.config[WabaConfigEnum.BusinessAcctId],\n ): Promise<phoneNumber.CreatePhoneNumberResponse> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${wabaId}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n /**\n * Update phone number status or configuration on the phone number node.\n */\n async updatePhoneNumberStatus(request: phoneNumber.UpdatePhoneNumberStatusRequest): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n /**\n * Request a verification code for the phone number.\n *\n * Sends a verification code to the configured phone number via SMS or voice call.\n * This is the first step of the phone number verification process.\n *\n * @param request - The verification code request parameters.\n * @param request.code_method - The delivery method for the code: `'SMS'` or `'VOICE'`.\n * @param request.language - The language code for the verification message (e.g., `'en_US'`).\n * @returns A promise that resolves with a success indicator.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/phone-numbers#request-verification-code | Request Verification Code}\n *\n * @example\n * ```ts\n * await whatsappClient.phoneNumber.requestVerificationCode({\n * code_method: 'SMS',\n * language: 'en_US',\n * });\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 a received verification code.\n *\n * Completes the phone number verification process by submitting the code\n * received via SMS or voice call from {@link requestVerificationCode}.\n *\n * @param request - The verification request parameters.\n * @param request.code - The 6-digit verification code received via SMS or voice call.\n * @returns A promise that resolves with a success indicator.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/phone-numbers#verify-code | Verify Code}\n *\n * @example\n * ```ts\n * await whatsappClient.phoneNumber.verifyCode({\n * code: '123456',\n * });\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 /**\n * Get general phone number settings.\n *\n * Calling-specific settings can also be accessed through `calling.getCallingSettings()`.\n */\n async getPhoneNumberSettings(\n params?: phoneNumber.PhoneNumberSettingsParams,\n ): Promise<phoneNumber.PhoneNumberSettingsResponse> {\n const fieldsValue = Array.isArray(params?.fields) ? params.fields.join(',') : params?.fields;\n const queryParams = objectToQueryString({\n ...(fieldsValue ? { fields: fieldsValue } : {}),\n ...(params?.include_sip_credentials !== undefined\n ? { include_sip_credentials: params.include_sip_credentials }\n : {}),\n });\n\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/settings${queryParams}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Update general phone number settings.\n */\n async updatePhoneNumberSettings(params: phoneNumber.UpdatePhoneNumberSettingsRequest): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/settings`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(params),\n );\n }\n\n /**\n * Configure conversational automation features for the phone number.\n *\n * Sets up welcome messages, ice breakers (prompts), and commands that users\n * see when they open a conversation with the business phone number.\n *\n * @param request - The conversational automation configuration.\n * @param request.enable_welcome_message - Optional. Enable or disable the welcome message.\n * @param request.commands - Optional. Array of command objects with `command_name` and `command_description`.\n * @param request.prompts - Optional. Array of ice breaker prompt strings shown to users.\n * @returns A promise that resolves with a success indicator.\n *\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/phone-numbers/ | Conversational Automation}\n *\n * @example\n * ```ts\n * // Enable welcome message\n * await whatsappClient.phoneNumber.setConversationalAutomation({\n * enable_welcome_message: true,\n * });\n *\n * // Configure commands and ice breakers\n * await whatsappClient.phoneNumber.setConversationalAutomation({\n * enable_welcome_message: true,\n * commands: [\n * { command_name: 'tickets', command_description: 'Book flight tickets' },\n * { command_name: 'hotel', command_description: 'Book a hotel room' },\n * ],\n * prompts: ['Book a flight', 'Plan a vacation'],\n * });\n * ```\n */\n async setConversationalAutomation(request: phoneNumber.ConversationalAutomationRequest): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/conversational_automation`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n /**\n * Get the current conversational automation configuration for the phone number.\n *\n * Retrieves the current settings for welcome messages, ice breakers (prompts),\n * and commands configured on the phone number.\n *\n * @returns A promise that resolves with the current conversational automation settings,\n * including welcome message status, commands, and prompts.\n *\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/phone-numbers/ | Conversational Automation}\n *\n * @example\n * ```ts\n * const config = await whatsappClient.phoneNumber.getConversationalAutomation();\n * console.log(config.enable_welcome_message); // true or false\n * console.log(config.commands); // Array of command objects\n * console.log(config.prompts); // Array of ice breaker strings\n * ```\n */\n async getConversationalAutomation(): Promise<phoneNumber.ConversationalAutomationResponse> {\n const queryParams = objectToQueryString({ fields: 'conversational_automation' });\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 the current throughput level for the phone number.\n *\n * Throughput represents the maximum messages per second (MPS) that can be\n * sent or received on this phone number.\n *\n * Throughput levels:\n * - **STANDARD**: 80 MPS (default for most numbers)\n * - **HIGH**: 1,000 MPS (automatic upgrade for eligible numbers)\n * - **NOT_APPLICABLE**: Fixed at 5 MPS (WhatsApp Business app coexistence numbers)\n *\n * @returns A promise that resolves with the current throughput information,\n * including the throughput level.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/phone-numbers | Phone Numbers - Throughput}\n *\n * @example\n * ```ts\n * const throughput = await whatsappClient.phoneNumber.getThroughput();\n * console.log(throughput.throughput.level); // 'STANDARD' | 'HIGH' | 'NOT_APPLICABLE'\n * ```\n */\n async getThroughput(): Promise<phoneNumber.ThroughputResponse> {\n const queryParams = objectToQueryString({ fields: 'throughput' });\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}${queryParams}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async getOfficialBusinessAccountStatus(): Promise<phoneNumber.OfficialBusinessAccountStatusResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/official_business_account`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async updateOfficialBusinessAccountStatus(\n params: phoneNumber.UpdateOfficialBusinessAccountStatusRequest,\n ): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/official_business_account`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(params),\n );\n }\n\n async getBusinessComplianceInfo(): Promise<phoneNumber.BusinessComplianceInfoResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/business_compliance_info`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async updateBusinessComplianceInfo(\n params: phoneNumber.UpdateBusinessComplianceInfoRequest,\n ): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/business_compliance_info`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(params),\n );\n }\n\n /**\n * Get the username currently associated with the business phone number.\n *\n * @returns A promise that resolves with the username and its status\n * (`'approved'` or `'reserved'`).\n *\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/usernames/ | Usernames}\n */\n async getUsername(): Promise<phoneNumber.UsernameResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/username`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Adopt or change the username for the business phone number.\n *\n * If the desired username is already in use by another phone number in your\n * portfolio, the API responds with error code `147005`; retry with\n * `transfer_action: 'force_transfer'` to move the username to this number.\n *\n * @param params - The username request.\n * @param params.username - The desired username.\n * @param params.transfer_action - Optional. `'none'` (default) or `'force_transfer'`.\n * @returns A promise that resolves with a success indicator.\n *\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/usernames/ | Usernames}\n *\n * @example\n * ```ts\n * await whatsappClient.phoneNumbers.updateUsername({\n * username: 'jaspersmarket',\n * transfer_action: 'force_transfer',\n * });\n * ```\n */\n async updateUsername(params: phoneNumber.UpdateUsernameRequest): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/username`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(params),\n );\n }\n\n /**\n * Delete the username associated with the business phone number.\n *\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/usernames/ | Usernames}\n */\n async deleteUsername(): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Delete,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/username`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Get username suggestions for the business phone number.\n *\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/usernames/ | Usernames}\n */\n async getUsernameSuggestions(): Promise<phoneNumber.UsernameSuggestionsResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/username_suggestions`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\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","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/business-profiles/\n\n// Endpoints:\n// - GET /{PHONE_NUMBER_ID}/whatsapp_business_profile?fields\n// - POST /{PHONE_NUMBER_ID}/whatsapp_business_profile\n// - POST /app/uploads?file_length&file_type&file_name\n// - POST /{UPLOAD_ID}\n// - GET /{UPLOAD_ID}\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { 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 * Business profiles let customers see relevant information about your business,\n * such as a description, email, address, website, and profile picture.\n *\n * Covered endpoints:\n * - Get business profile (`GET /{PHONE_NUMBER_ID}/whatsapp_business_profile`)\n * - Update business profile (`POST /{PHONE_NUMBER_ID}/whatsapp_business_profile`)\n * - Create an upload session for profile pictures (`POST /app/uploads`)\n * - Upload file binary data (`POST /{UPLOAD_ID}`)\n * - Get upload handle (`GET /{UPLOAD_ID}`)\n *\n * Profile picture upload follows a three-step process:\n * 1. Create an upload session ({@link createUploadSession})\n * 2. Upload the image binary data ({@link uploadMedia})\n * 3. Get the upload handle ({@link getUploadHandle}) and pass it to {@link updateBusinessProfile}\n *\n * Available business profile fields: `about`, `address`, `description`, `email`,\n * `profile_picture_url`, `websites`, `vertical`, `messaging_product`.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/business-profiles | Business Profiles API Reference}\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/business-profiles/ | Business Profiles Documentation}\n */\nexport default class BusinessProfileApi extends BaseAPI implements bp.BusinessProfileClass {\n private readonly endpoint = 'whatsapp_business_profile';\n\n /**\n * Get your WhatsApp Business profile information.\n *\n * Retrieves the business profile details for the configured phone number.\n * You can request all fields or specify a subset using the `fields` parameter.\n *\n * @param fields - Optional fields to return. Can be a comma-separated string\n * (e.g., `'about,address,email'`) or an array of field names. If omitted,\n * all fields are returned. Available fields: `about`, `address`, `description`,\n * `email`, `profile_picture_url`, `websites`, `vertical`.\n * @returns A promise that resolves with the business profile information.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/business-profiles#get-business-profile | Get Business Profile}\n *\n * @example\n * ```ts\n * // Get all business profile fields\n * const profile = await whatsappClient.businessProfile.getBusinessProfile();\n *\n * // Get specific fields as a string\n * const profile = await whatsappClient.businessProfile.getBusinessProfile('about,address,email');\n *\n * // Get specific fields as an array\n * const profile = await whatsappClient.businessProfile.getBusinessProfile(['about', 'address', 'email']);\n * ```\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 WhatsApp Business profile.\n *\n * Updates one or more fields of the business profile for the configured phone number.\n * Only the fields included in the request body are updated; omitted fields remain unchanged.\n *\n * @param updateRequest - The profile fields to update.\n * @param updateRequest.messaging_product - Required. Must be set to `'whatsapp'`.\n * @param updateRequest.about - Optional. Business About text (1-139 characters).\n * @param updateRequest.address - Optional. Business address (max 256 characters).\n * @param updateRequest.description - Optional. Business description (max 512 characters).\n * @param updateRequest.vertical - Optional. Business industry/category.\n * @param updateRequest.email - Optional. Contact email address (max 128 characters).\n * @param updateRequest.websites - Optional. Up to 2 website URLs (max 256 characters each).\n * @param updateRequest.profile_picture_handle - Optional. Handle obtained from the upload process.\n * @returns A promise that resolves with a success indicator.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/business-profiles#update-business-profile | Update Business Profile}\n *\n * @example\n * ```ts\n * await whatsappClient.businessProfile.updateBusinessProfile({\n * messaging_product: 'whatsapp',\n * about: 'We provide excellent service',\n * description: 'Your trusted partner for quality products',\n * email: 'contact@example.com',\n * websites: ['https://example.com'],\n * });\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 **step 1** of the three-step profile picture upload process.\n * It initializes a resumable upload session on the server and returns a session ID\n * to use in subsequent upload calls.\n *\n * @param fileLength - The size of the file in bytes.\n * @param fileType - The MIME type of the file (e.g., `'image/jpeg'`, `'image/png'`).\n * @param fileName - The file name with extension (e.g., `'profile.jpg'`).\n * @returns A promise that resolves with the upload session ID.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/business-profiles | Business Profiles - Upload}\n *\n * @example\n * ```ts\n * const session = await whatsappClient.businessProfile.createUploadSession(\n * fileBuffer.length,\n * 'image/jpeg',\n * 'profile.jpg',\n * );\n * console.log(session.upload_session_id);\n * ```\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 binary data to an upload session.\n *\n * This is **step 2** of the three-step profile picture upload process.\n * Uploads the raw binary content of the image to the previously created upload session.\n *\n * @param uploadId - The upload session ID returned from {@link createUploadSession}.\n * @param file - The binary data of the file as a Buffer.\n * @returns A promise that resolves with the upload response.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/business-profiles | Business Profiles - Upload}\n *\n * @example\n * ```ts\n * const fileBuffer = fs.readFileSync('profile.jpg');\n * await whatsappClient.businessProfile.uploadMedia(\n * session.upload_session_id,\n * fileBuffer,\n * );\n * ```\n */\n async uploadMedia(uploadId: string, file: Uint8Array): Promise<bp.UploadBusinessProfileResponse> {\n return this.sendJson(HttpMethodsEnum.Post, `${uploadId}`, this.config[WabaConfigEnum.RequestTimeout], file);\n }\n\n /**\n * Get the upload handle for a completed upload.\n *\n * This is **step 3** of the three-step profile picture upload process.\n * After uploading the file binary, retrieve the handle to use when updating\n * the business profile's `profile_picture_handle` field.\n *\n * @param uploadId - The upload session ID returned from {@link createUploadSession}.\n * @returns A promise that resolves with the upload handle information.\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/business-profiles | Business Profiles - Upload}\n *\n * @example\n * ```ts\n * // Complete three-step profile picture upload\n * const session = await whatsappClient.businessProfile.createUploadSession(\n * fileBuffer.length, 'image/jpeg', 'profile.jpg',\n * );\n * await whatsappClient.businessProfile.uploadMedia(session.upload_session_id, fileBuffer);\n * const handleInfo = await whatsappClient.businessProfile.getUploadHandle(session.upload_session_id);\n *\n * // Use the handle to update the profile picture\n * await whatsappClient.businessProfile.updateBusinessProfile({\n * messaging_product: 'whatsapp',\n * profile_picture_handle: handleInfo.handle,\n * });\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","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/qr-codes/\n\n// Endpoints:\n// - POST /{PHONE_NUMBER_ID}/message_qrdls\n// - GET /{PHONE_NUMBER_ID}/message_qrdls\n// - GET /{PHONE_NUMBER_ID}/message_qrdls/{QR_CODE_ID}\n// - POST /{PHONE_NUMBER_ID}/message_qrdls\n// - DELETE /{PHONE_NUMBER_ID}/message_qrdls/{QR_CODE_ID}\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { 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 *\n * Endpoints covered:\n * - `POST /{PHONE_NUMBER_ID}/message_qrdls` - Create a new QR code\n * - `GET /{PHONE_NUMBER_ID}/message_qrdls` - Get all QR codes\n * - `GET /{PHONE_NUMBER_ID}/message_qrdls/{QR_CODE_ID}` - Get a specific QR code\n * - `POST /{PHONE_NUMBER_ID}/message_qrdls/{QR_CODE_ID}` - Update a QR code\n * - `DELETE /{PHONE_NUMBER_ID}/message_qrdls/{QR_CODE_ID}` - Delete a QR code\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/qr-codes/\n */\nexport default class QrCodeApi extends BaseAPI implements qrCode.QrCodeClass {\n private readonly endpoint = 'message_qrdls';\n\n /**\n * Create a new QR code with a prefilled message.\n *\n * @param request - The QR code creation request containing the prefilled message and optional image format.\n * @returns QR code information including code, deep link URL, and optional image URL.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/qr-codes/\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 * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/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 * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/qr-codes/\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 * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/qr-codes/\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 * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/qr-codes/\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","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/registration/\n\n// Endpoints:\n// - POST /{PHONE_NUMBER_ID}/register\n// - POST /{PHONE_NUMBER_ID}/deregister\n\nimport { WHATSAPP_MESSAGING_PRODUCT } from '../../config/defaults';\nimport { BaseAPI } from '../../types/base';\nimport { type DataLocalizationRegionEnum, HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { 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 *\n * Endpoints covered:\n * - `POST /{PHONE_NUMBER_ID}/register` - Register a phone number\n * - `POST /{PHONE_NUMBER_ID}/deregister` - Deregister a phone number\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/registration/\n */\nexport default class RegistrationApi extends BaseAPI implements registration.RegistrationClass {\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 for storage compliance.\n * @returns Response indicating success or failure.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/registration/\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_MESSAGING_PRODUCT,\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 * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/registration/\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","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/whatsapp-business-accounts/\n\n// Endpoints:\n// - POST /{APPLICATION_ID}/whatsapp_business_solution\n// - GET /{APPLICATION_ID}/whatsapp_business_solutions\n// - GET /{SOLUTION_ID}/access_token\n// - POST /{SOLUTION_ID}/accept_deactivation_request\n// - POST /{SOLUTION_ID}/accept\n// - GET /{SOLUTION_ID}\n// - POST /{SOLUTION_ID}/reject_deactivation_request\n// - POST /{SOLUTION_ID}/reject\n// - POST /{SOLUTION_ID}/send_deactivation_request\n// - GET /{MIGRATION_INTENT_ID}\n// - GET /{WABA_ID}/solutions\n// - POST /{WABA_ID}/set_solution_migration_intent\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { ResponseSuccess } from '../../types/request';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\n\nimport type * as solutions from './types';\n\nexport default class SolutionsApi extends BaseAPI implements solutions.SolutionsClass {\n private toQuery(params?: solutions.SolutionListParams): string {\n if (!params) return '';\n\n const fields = Array.isArray(params.fields) ? params.fields.join(',') : params.fields;\n return objectToQueryString({\n fields,\n role: params.role,\n status: params.status,\n limit: params.limit,\n after: params.after,\n before: params.before,\n });\n }\n\n private fieldsQuery(fields?: solutions.SolutionFieldsParam): string {\n const fieldsValue = Array.isArray(fields) ? fields.join(',') : fields;\n return fieldsValue ? objectToQueryString({ fields: fieldsValue }) : '';\n }\n\n async createWhatsAppBusinessSolution(\n applicationId: string,\n request: solutions.CreateWhatsAppBusinessSolutionRequest,\n ): Promise<solutions.SolutionGraphObject> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${applicationId}/whatsapp_business_solution`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n async getApplicationWhatsAppBusinessSolutions(\n applicationId: string,\n params?: solutions.SolutionListParams,\n ): Promise<solutions.SolutionListResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${applicationId}/whatsapp_business_solutions${this.toQuery(params)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async getSolutionAccessToken(\n solutionId: string,\n fields?: solutions.SolutionFieldsParam,\n ): Promise<solutions.SolutionGraphObject> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${solutionId}/access_token${this.fieldsQuery(fields)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async acceptSolutionDeactivationRequest(\n solutionId: string,\n request: solutions.SolutionDeactivationRequest = {},\n ): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${solutionId}/accept_deactivation_request`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n async acceptSolution(solutionId: string, request: solutions.AcceptSolutionRequest = {}): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${solutionId}/accept`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n async getSolutionDetails(\n solutionId: string,\n fields?: solutions.SolutionFieldsParam,\n ): Promise<solutions.SolutionGraphObject> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${solutionId}${this.fieldsQuery(fields)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async rejectSolutionDeactivationRequest(\n solutionId: string,\n request: solutions.SolutionDeactivationRequest = {},\n ): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${solutionId}/reject_deactivation_request`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n async rejectSolutionRequest(\n solutionId: string,\n request: solutions.RejectSolutionRequest = {},\n ): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${solutionId}/reject`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n async sendSolutionDeactivationRequest(\n solutionId: string,\n request: solutions.SolutionDeactivationRequest = {},\n ): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${solutionId}/send_deactivation_request`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n\n async getMigrationIntentDetails(\n migrationIntentId: string,\n fields?: solutions.SolutionFieldsParam,\n ): Promise<solutions.SolutionGraphObject> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${migrationIntentId}${this.fieldsQuery(fields)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async listWabaSolutions(\n wabaId: string = this.config[WabaConfigEnum.BusinessAcctId],\n params?: solutions.SolutionListParams,\n ): Promise<solutions.SolutionListResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${wabaId}/solutions${this.toQuery(params)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async setSolutionMigrationIntent(\n wabaId: string,\n request: solutions.SetSolutionMigrationIntentRequest,\n ): Promise<solutions.SolutionGraphObject> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${wabaId}/set_solution_migration_intent`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(request),\n );\n }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/\n\nimport { CategoryEnum } from '../../../types/enums';\nimport type {\n AuthenticationTemplateOptions,\n BodyOptions,\n ButtonOptions,\n CatalogTemplateOptions,\n ComponentTypes,\n CouponTemplateOptions,\n FooterOptions,\n HeaderOptions,\n LimitedTimeOfferTemplateOptions,\n MediaCardCarouselTemplateOptions,\n MediaCarouselCard,\n MPMTemplateOptions,\n OTPTemplateOptions,\n ProductCardCarouselTemplateOptions,\n ProductCarouselCard,\n SPMTemplateOptions,\n TemplateBody,\n TemplateButton,\n TemplateButtons,\n TemplateFooter,\n TemplateHeader,\n TemplateOptions,\n TemplateParameter,\n TemplateRequestBody,\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","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/\n\n// Endpoints:\n// - GET /{TEMPLATE_ID}\n// - POST /{TEMPLATE_ID}\n// - GET /{WABA_ID}/message_templates?...\n// - POST /{WABA_ID}/message_templates\n// - DELETE /{WABA_ID}/message_templates?...\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { 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\n/**\n * WhatsApp Message Templates API client for managing message templates.\n *\n * Message templates are pre-approved message formats that businesses can use to\n * send notifications and customer care messages. Templates must be approved by\n * Meta before they can be used to send messages.\n *\n * **Covered endpoints:**\n * - `GET /{TEMPLATE_ID}` - Get a single template ({@link TemplateApi.getTemplate})\n * - `POST /{TEMPLATE_ID}` - Update an existing template ({@link TemplateApi.updateTemplate})\n * - `GET /{WABA_ID}/message_templates` - List all templates ({@link TemplateApi.getTemplates})\n * - `POST /{WABA_ID}/message_templates` - Create a new template ({@link TemplateApi.createTemplate})\n * - `DELETE /{WABA_ID}/message_templates` - Delete a template ({@link TemplateApi.deleteTemplate})\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/message-templates | Message Templates API Reference}\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/ | WhatsApp Templates Documentation}\n *\n * @example\n * ```ts\n * const client = new WhatsApp({ accessToken: '...', phoneNumberId: '...', businessAcctId: '...' });\n *\n * // Create a template\n * const template = await client.template.createTemplate({\n * name: 'hello_world',\n * language: 'en_US',\n * category: 'MARKETING',\n * components: [{ type: 'BODY', text: 'Hello {{1}}!' }],\n * });\n *\n * // List all templates\n * const templates = await client.template.getTemplates();\n * ```\n */\nexport default class TemplateApi extends BaseAPI implements TemplateClass {\n private readonly endpoint = 'message_templates';\n\n /**\n * Retrieves a single message template by its ID.\n *\n * Returns the full template definition including name, language, status,\n * category, and components.\n *\n * **Endpoint:** `GET /{TEMPLATE_ID}`\n *\n * @param templateId - The unique identifier of the template to retrieve\n * @returns A promise resolving to the template details\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/message-templates | Message Templates Reference}\n *\n * @example\n * ```ts\n * const template = await client.template.getTemplate('template_id_123');\n * console.log(template.name); // e.g., \"hello_world\"\n * console.log(template.status); // e.g., \"APPROVED\"\n * ```\n */\n async getTemplate(templateId: string): Promise<TemplateResponse> {\n return this.sendJson(HttpMethodsEnum.Get, `${templateId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n /**\n * Updates an existing message template.\n *\n * Allows modifying template components and other properties. Note that editing\n * an approved template will resubmit it for review, changing its status back\n * to `PENDING`.\n *\n * Marketing templates also accept `optimization_spec` here. As of\n * August 31, 2026, an eligible template can be switched between standard rate\n * card pricing and max price without creating a new template, and an existing\n * max price can be updated in place. Approved templates allow up to 100 edits\n * per hour and 2,400 per day.\n *\n * **Endpoint:** `POST /{TEMPLATE_ID}`\n *\n * @param templateId - The unique identifier of the template to update\n * @param template - Partial template body containing only the fields to update\n * @returns A promise resolving to a success response (`{ success: true }`)\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/message-templates | Message Templates Reference}\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/marketing-messages/pricing | Max price for marketing messages}\n *\n * @example\n * ```ts\n * await client.template.updateTemplate('template_id_123', {\n * components: [{ type: 'BODY', text: 'Updated greeting: Hello {{1}}!' }],\n * });\n *\n * // Switch an eligible marketing template onto max price (or change the cap).\n * await client.template.updateTemplate('template_id_123', {\n * optimization_spec: { bid_strategy: 'LOWEST_COST_WITH_BID_CAP', bid_amount: 25000 },\n * });\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 /**\n * Lists message templates for the WhatsApp Business Account.\n *\n * Returns a paginated list of templates, optionally filtered by query parameters\n * such as category, language, name, status, or quality score.\n *\n * **Endpoint:** `GET /{WABA_ID}/message_templates`\n *\n * @param params - Optional query parameters to filter results\n * @param params.category - Filter by template category (e.g., `'MARKETING'`, `'UTILITY'`)\n * @param params.content - Filter by template content\n * @param params.language - Filter by language code (e.g., `'en_US'`)\n * @param params.name - Filter by exact template name\n * @param params.name_or_content - Filter by name or content (search)\n * @param params.quality_score - Filter by quality score\n * @param params.status - Filter by template status (e.g., `'APPROVED'`, `'PENDING'`, `'REJECTED'`)\n * @returns A promise resolving to a paginated response containing an array of templates\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/message-templates | Message Templates Reference}\n *\n * @example\n * ```ts\n * // List all templates\n * const allTemplates = await client.template.getTemplates();\n *\n * // Filter by category and status\n * const approved = await client.template.getTemplates({\n * category: 'MARKETING',\n * status: 'APPROVED',\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 /**\n * Creates a new message template for the WhatsApp Business Account.\n *\n * The template will be submitted for review. Once approved, it can be used\n * to send template messages via {@link MessagesApi.template}.\n *\n * **Endpoint:** `POST /{WABA_ID}/message_templates`\n *\n * @param template - The template definition\n * @param template.name - Template name (lowercase alphanumeric and underscores only)\n * @param template.language - Language code (e.g., `'en_US'`)\n * @param template.category - Template category (`'MARKETING'`, `'UTILITY'`, or `'AUTHENTICATION'`)\n * @param template.components - Array of template components (header, body, footer, buttons)\n * @param template.allow_category_change - Whether Meta can auto-assign a different category\n * @param template.parameter_format - Parameter format (`'POSITIONAL'` or `'NAMED'`)\n * @param template.sub_category - Optional sub-category for the template\n * @param template.message_send_ttl_seconds - Optional TTL in seconds for message delivery attempts\n * @returns A promise resolving to the created template response with its assigned `id` and `status`\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/message-templates | Message Templates Reference}\n *\n * @example\n * ```ts\n * const template = await client.template.createTemplate({\n * name: 'order_confirmation',\n * language: 'en_US',\n * category: 'UTILITY',\n * components: [\n * { type: 'BODY', text: 'Your order {{1}} has been confirmed.' },\n * ],\n * });\n * console.log(template.id); // Template ID\n * console.log(template.status); // \"PENDING\"\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 /**\n * Deletes a message template from the WhatsApp Business Account.\n *\n * Deleting a template removes all language variations of that template.\n * To delete a specific language version, provide the `hsm_id` parameter.\n *\n * **Endpoint:** `DELETE /{WABA_ID}/message_templates`\n *\n * @param params - The delete parameters\n * @param params.name - The name of the template to delete (required)\n * @param params.hsm_id - Optional template ID to delete a specific language version\n * @returns A promise resolving to a success response (`{ success: true }`)\n *\n * @see {@link https://developers.facebook.com/docs/whatsapp/cloud-api/reference/message-templates | Message Templates Reference}\n *\n * @example\n * ```ts\n * // Delete all language versions of a template\n * await client.template.deleteTemplate({ name: 'old_template' });\n *\n * // Delete a specific language version\n * await client.template.deleteTemplate({ name: 'old_template', hsm_id: '123456' });\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","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/conversation-routing/thread-control/\n\n// Endpoints:\n// - POST /{PHONE_NUMBER_ID}/thread_control\n\nimport { WHATSAPP_MESSAGING_PRODUCT } from '../../config/defaults';\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport { WhatsAppValidationError } from '../../utils/isMetaError';\n\nimport type * as threadControl from './types/threadControl';\n\nconst METADATA_MAX_LENGTH = 2000;\n\ntype ThreadControlAction = 'pass' | 'release' | 'take';\n\n/**\n * API for Conversation Routing thread control.\n *\n * When more than one responder shares a WhatsApp account, Conversation Routing\n * gives each thread exactly one owner. Thread control lets a responder pass\n * ownership to another role, release the thread back to idle, or (escalation\n * partner only) take it. Routing itself is configured by the business in Meta\n * Business Suite, not through the API, and the account must be enrolled for\n * thread control before this endpoint accepts requests.\n *\n * There is no endpoint that reports the current owner: track ownership locally\n * from inbound messages, `messaging_handovers` events (`processor.onMessagingHandovers`),\n * and standby events, and reconcile after 24 hours of user inactivity, when the\n * thread returns to idle on its own.\n *\n * Endpoints covered:\n * - `POST /{PHONE_NUMBER_ID}/thread_control` - Pass, release, or take a thread\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/conversation-routing/thread-control/\n */\nexport default class ThreadControlApi extends BaseAPI implements threadControl.ThreadControlClass {\n private readonly endpoint = 'thread_control';\n\n /**\n * Pass thread ownership from you (the current owner) to another responder.\n *\n * Without `control_pass`, control goes to the account's escalation partner.\n * With `control_pass.target_role`, control goes to that role. Meta rejects the\n * request if the thread is idle, you do not own it, the target is not enabled,\n * or the target already owns the thread. The new owner receives a\n * `control_passed` `messaging_handovers` event.\n *\n * @param params - The WhatsApp user (`to` or `recipient`), optional `metadata`, and optional `control_pass`.\n * @returns `{ messaging_product, request_id }`.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/conversation-routing/thread-control/#pass\n *\n * @example\n * ```typescript\n * const { request_id } = await client.threadControl.pass({\n * recipient: 'US.13491208655302741918',\n * metadata: 'WhatsApp user requested human agent',\n * control_pass: { target_role: 'customer_service' },\n * });\n * ```\n */\n async pass(params: threadControl.PassThreadControlParams): Promise<threadControl.ThreadControlResponse> {\n return this.send('pass', params);\n }\n\n /**\n * Release the thread back to idle. The WhatsApp user's next message is\n * re-routed by entry point. Releasing an idle thread succeeds; releasing a\n * thread you do not own is rejected (the escalation partner must take it first).\n * No `messaging_handovers` event fires for a release.\n *\n * @param params - The WhatsApp user (`to` or `recipient`) and optional `metadata`.\n * @returns `{ messaging_product, request_id }`.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/conversation-routing/thread-control/#release\n */\n async release(params: threadControl.ReleaseThreadControlParams): Promise<threadControl.ThreadControlResponse> {\n return this.send('release', params);\n }\n\n /**\n * Take thread ownership. Only the account's designated escalation partner can\n * take a thread, regardless of who owns it; the previous owner receives a\n * `control_taken` `messaging_handovers` event. Sending a Service message as the\n * escalation partner takes the thread implicitly, without this call.\n *\n * @param params - The WhatsApp user (`to` or `recipient`) and optional `metadata`.\n * @returns `{ messaging_product, request_id }`.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/conversation-routing/thread-control/#take\n */\n async take(params: threadControl.TakeThreadControlParams): Promise<threadControl.ThreadControlResponse> {\n return this.send('take', params);\n }\n\n private async send(\n action: ThreadControlAction,\n params: threadControl.PassThreadControlParams,\n ): Promise<threadControl.ThreadControlResponse> {\n const hasTo = Boolean(params?.to);\n const hasRecipient = Boolean(params?.recipient);\n if (hasTo === hasRecipient) {\n throw new WhatsAppValidationError('Exactly one of \"to\" or \"recipient\" is required for thread control.');\n }\n if (params.metadata && params.metadata.length > METADATA_MAX_LENGTH) {\n throw new WhatsAppValidationError(\n `\"metadata\" must be at most ${METADATA_MAX_LENGTH} characters for thread control.`,\n );\n }\n if (action !== 'pass' && params.control_pass) {\n throw new WhatsAppValidationError('\"control_pass\" is only supported for the pass action.');\n }\n\n const body = {\n messaging_product: WHATSAPP_MESSAGING_PRODUCT,\n ...(hasTo ? { to: params.to } : { recipient: params.recipient }),\n action,\n ...(params.metadata !== undefined && { metadata: params.metadata }),\n ...(params.control_pass && { control_pass: params.control_pass }),\n };\n\n return await this.sendJson<threadControl.ThreadControlResponse>(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/${this.endpoint}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(body),\n );\n }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/two-step-verification/\n\n// Endpoints:\n// - POST /{PHONE_NUMBER_ID}\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { 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 *\n * Endpoints covered:\n * - `POST /{PHONE_NUMBER_ID}` - Set two-step verification PIN\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/two-step-verification/\n */\nexport default class TwoStepVerificationApi extends BaseAPI implements twoStepVerification.TwoStepVerificationClass {\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 * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/two-step-verification/\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","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/whatsapp-business-accounts/\n\n// Endpoints:\n// - GET /{WABA_ID}?fields\n// - POST /{WABA_ID}\n// - GET /{WABA_ID}/activities\n// - GET /{WABA_ID}/subscribed_apps\n// - POST /{WABA_ID}/subscribed_apps\n// - DELETE /{WABA_ID}/subscribed_apps\n// - GET /{WABA_ID}/assigned_users\n// - POST /{WABA_ID}/assigned_users\n// - DELETE /{WABA_ID}/assigned_users\n// - GET /{WABA_ID}/in_progress_onbehalf_request\n// - GET /{OBO_MOBILITY_INTENT_ID}\n// - POST /{WABA_ID}/obo_mobility_intent\n// - POST /{WABA_ID}/set_obo_mobility_intent\n// - GET /{WABA_ID}/schedules\n// - POST /{WABA_ID}/schedules\n// - GET /{WABA_BOT_ID}\n// - GET /{WHATSAPP_BUSINESS_PROFILE_ID}\n// - POST /{WHATSAPP_BUSINESS_PROFILE_ID}\n\nimport { BaseAPI } from '../../types/base';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../../types/enums';\nimport type { ResponseSuccess } from '../../types/request';\nimport { buildFieldsQueryString } from '../../utils/buildFieldsQueryString';\nimport { objectToQueryString } from '../../utils/objectToQueryString';\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 *\n * Endpoints covered:\n * - `GET /{WABA_ID}` - Get WABA account information\n * - `GET /{WABA_ID}/subscribed_apps` - Get all WABA subscriptions\n * - `POST /{WABA_ID}/subscribed_apps` - Update/create a WABA subscription\n * - `DELETE /{WABA_ID}/subscribed_apps` - Unsubscribe from WABA webhooks\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/whatsapp-business-accounts/\n */\nexport default class WabaApi extends BaseAPI implements waba.WABAClass {\n private toQuery(params?: waba.WabaListParams): string {\n if (!params) return '';\n\n const fields = Array.isArray(params.fields) ? params.fields.join(',') : params.fields;\n const filtering = Array.isArray(params.filtering) ? JSON.stringify(params.filtering) : params.filtering;\n\n return objectToQueryString({\n fields,\n filtering,\n sort: params.sort,\n limit: params.limit,\n after: params.after,\n before: params.before,\n });\n }\n\n private fieldsQuery(fields?: waba.WabaFieldsParam): string {\n const fieldsValue = Array.isArray(fields) ? fields.join(',') : fields;\n return fieldsValue ? objectToQueryString({ fields: fieldsValue }) : '';\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 * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/whatsapp-business-accounts/\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 * Update WABA account fields such as name or timezone.\n */\n async updateWabaAccount(params: waba.UpdateWabaAccountRequest): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.BusinessAcctId]}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(params),\n );\n }\n\n /**\n * Get account activity events for a WABA.\n */\n async getWabaActivities(params?: waba.WabaListParams): Promise<waba.WabaListResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${this.config[WabaConfigEnum.BusinessAcctId]}/activities${this.toQuery(params)}`,\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 * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/whatsapp-business-accounts/\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 * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/whatsapp-business-accounts/\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 * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/whatsapp-business-accounts/\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 async getAssignedUsers(\n params: waba.AssignedUsersListParams,\n wabaId: string = this.config[WabaConfigEnum.BusinessAcctId],\n ): Promise<waba.WabaListResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${wabaId}/assigned_users${this.toQuery(params)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async addAssignedUser(\n params: waba.AssignedUserRequest,\n wabaId: string = this.config[WabaConfigEnum.BusinessAcctId],\n ): Promise<ResponseSuccess> {\n const body = {\n user: params.user,\n tasks: params.tasks,\n };\n\n return this.sendUrlEncodedForm(\n HttpMethodsEnum.Post,\n `${wabaId}/assigned_users`,\n this.config[WabaConfigEnum.RequestTimeout],\n body,\n );\n }\n\n async removeAssignedUser(\n params: waba.RemoveAssignedUserRequest,\n wabaId: string = this.config[WabaConfigEnum.BusinessAcctId],\n ): Promise<ResponseSuccess> {\n return this.sendUrlEncodedForm(\n HttpMethodsEnum.Delete,\n `${wabaId}/assigned_users`,\n this.config[WabaConfigEnum.RequestTimeout],\n { user: params.user },\n );\n }\n\n async getInProgressOnBehalfRequests(\n params?: waba.WabaListParams,\n wabaId: string = this.config[WabaConfigEnum.BusinessAcctId],\n ): Promise<waba.WabaListResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${wabaId}/in_progress_onbehalf_request${this.toQuery(params)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async getOBOMobilityIntent(\n oboMobilityIntentId: string,\n fields?: waba.WabaFieldsParam,\n ): Promise<waba.WabaGraphObject> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${oboMobilityIntentId}${this.fieldsQuery(fields)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async createOBOMobilityIntent(\n params: waba.CreateOBOMobilityIntentRequest,\n wabaId: string = this.config[WabaConfigEnum.BusinessAcctId],\n ): Promise<waba.WabaGraphObject> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${wabaId}/obo_mobility_intent`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(params),\n );\n }\n\n async setOBOMobilityIntent(\n params: waba.SetOBOMobilityIntentRequest,\n wabaId: string = this.config[WabaConfigEnum.BusinessAcctId],\n ): Promise<waba.WabaGraphObject> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${wabaId}/set_obo_mobility_intent`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(params),\n );\n }\n\n async getWabaSchedules(\n params?: waba.WabaListParams,\n wabaId: string = this.config[WabaConfigEnum.BusinessAcctId],\n ): Promise<waba.WabaListResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${wabaId}/schedules${this.toQuery(params)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async createWabaSchedule(\n params: waba.CreateScheduleRequest,\n wabaId: string = this.config[WabaConfigEnum.BusinessAcctId],\n ): Promise<waba.WabaGraphObject> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${wabaId}/schedules`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(params),\n );\n }\n\n async getWhatsAppBusinessBotDetails(botId: string, fields?: waba.WabaFieldsParam): Promise<waba.WabaGraphObject> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${botId}${this.fieldsQuery(fields)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async getWhatsAppBusinessProfileDetails(\n profileId: string,\n fields?: waba.WabaFieldsParam,\n ): Promise<waba.WabaGraphObject> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `${profileId}${this.fieldsQuery(fields)}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n async updateWhatsAppBusinessProfile(\n profileId: string,\n params: waba.UpdateWhatsAppBusinessProfileRequest,\n ): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n profileId,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(params),\n );\n }\n}\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/whatsapp-business-accounts/\n\nimport type { Paging, ResponseSuccess } from '../../../types/request';\n\n/**\n * WhatsApp Business Account subscription configuration\n */\nexport type WabaSubscription = {\n whatsapp_business_api_data: {\n id: string;\n link: string;\n name: string;\n category: string;\n };\n override_callback_uri?: string;\n};\n\n/**\n * Parameters for updating WABA subscription\n */\nexport interface UpdateWabaSubscription {\n override_callback_uri: string;\n verify_token: string;\n}\n\n/**\n * Response containing all WABA subscriptions\n */\nexport interface WabaSubscriptions {\n data: Array<WabaSubscription>;\n}\n\n/**\n * WABA account review status enumeration\n */\nexport enum WabaAccountReviewStatus {\n Approved = 'APPROVED',\n Active = 'ACTIVE',\n Inactive = 'INACTIVE',\n Disabled = 'DISABLED',\n}\n\n/**\n * WABA health status for message sending capability\n */\nexport enum WabaHealthStatusCanSendMessage {\n Blocked = 'BLOCKED',\n Limited = 'LIMITED',\n Available = 'AVAILABLE',\n}\n\n/**\n * WABA account status enumeration\n */\nexport enum WabaAccountStatus {\n Approved = 'APPROVED',\n Active = 'ACTIVE',\n Inactive = 'INACTIVE',\n Disabled = 'DISABLED',\n}\n\n/**\n * Business verification status enumeration\n */\nexport enum WabaBusinessVerificationStatus {\n Verified = 'verified',\n PendingSubmission = 'pending_submission',\n Unverified = 'unverified',\n Rejected = 'rejected',\n}\n\n/**\n * WABA health status error details\n */\nexport interface WabaHealthStatusError {\n error_code?: number;\n error_description?: string;\n possible_solution?: string;\n}\n\n/**\n * WABA health status entity information\n */\nexport interface WabaHealthStatusEntity {\n entity_type?: string;\n id?: string;\n can_send_message?: string;\n errors?: WabaHealthStatusError[];\n}\n\n/**\n * Overall WABA health status\n */\nexport interface WabaHealthStatus {\n can_send_message?: WabaHealthStatusCanSendMessage;\n entities?: WabaHealthStatusEntity[];\n}\n\n/**\n * WhatsApp Business Account information\n */\nexport interface WabaAccount {\n account_review_status?: WabaAccountReviewStatus;\n id?: string;\n health_status?: WabaHealthStatus;\n status?: WabaAccountStatus;\n business_verification_status?: WabaBusinessVerificationStatus;\n message_template_namespace?: string;\n name?: string;\n ownership_type?: string;\n timezone_id?: string;\n primary_business_location?: Record<string, unknown> | string;\n currency?: string;\n country?: string;\n analytics?: Record<string, unknown>;\n is_enabled_for_insights?: boolean;\n is_shared_with_partners?: boolean;\n marketing_messages_lite_api_status?: string;\n marketing_messages_onboarding_status?: string;\n on_behalf_of_business_info?: Record<string, unknown>;\n primary_funding_id?: string;\n purchase_order_number?: string;\n whatsapp_business_manager_messaging_limit?: string;\n}\n\n/**\n * Available fields for WABA account queries\n */\nexport type WabaAccountFields =\n | 'id'\n | 'name'\n | 'timezone_id'\n | 'account_review_status'\n | 'auth_international_rate_eligibility'\n | 'business_verification_status'\n | 'country'\n | 'currency'\n | 'health_status'\n | 'status'\n | 'ownership_type'\n | 'message_template_namespace'\n | 'primary_business_location'\n | 'analytics'\n | 'is_enabled_for_insights'\n | 'is_shared_with_partners'\n | 'marketing_messages_lite_api_status'\n | 'marketing_messages_onboarding_status'\n | 'on_behalf_of_business_info'\n | 'primary_funding_id'\n | 'purchase_order_number'\n | 'whatsapp_business_manager_messaging_limit';\n\n/**\n * Parameter type for specifying which WABA account fields to retrieve\n */\nexport type WabaAccountFieldsParam = WabaAccountFields[];\n\nexport type WabaGraphObject = Record<string, unknown>;\n\nexport type WabaFieldsParam = string[] | string;\n\nexport type WabaListParams = {\n fields?: WabaFieldsParam;\n filtering?: WabaGraphObject[] | string;\n sort?: string;\n limit?: number;\n after?: string;\n before?: string;\n};\n\nexport type WabaListResponse<T = WabaGraphObject> = {\n data: T[];\n paging?: Paging;\n summary?: WabaGraphObject;\n};\n\nexport type UpdateWabaAccountRequest = {\n name?: string;\n timezone_id?: string;\n [key: string]: unknown;\n};\n\nexport type AssignedUsersListParams = WabaListParams & {\n business: string;\n};\n\nexport type AssignedUserRequest = {\n user: string;\n tasks: string[];\n};\n\nexport type RemoveAssignedUserRequest = {\n user: string;\n [key: string]: unknown;\n};\n\nexport type CreateOBOMobilityIntentRequest = {\n intent?: string;\n [key: string]: unknown;\n};\n\nexport type SetOBOMobilityIntentRequest = {\n [key: string]: unknown;\n};\n\nexport type CreateScheduleRequest = {\n name?: string;\n schedule_type?: string;\n [key: string]: unknown;\n};\n\nexport type UpdateWhatsAppBusinessProfileRequest = {\n [key: string]: unknown;\n};\n\n/**\n * Interface defining all WABA API methods\n */\nexport interface WABAClass {\n getWabaAccount(fields?: WabaAccountFieldsParam): Promise<WabaAccount>;\n updateWabaAccount(params: UpdateWabaAccountRequest): Promise<ResponseSuccess>;\n getWabaActivities(params?: WabaListParams): Promise<WabaListResponse>;\n getAllWabaSubscriptions(): Promise<WabaSubscriptions>;\n updateWabaSubscription(params: UpdateWabaSubscription): Promise<ResponseSuccess>;\n unsubscribeFromWaba(): Promise<ResponseSuccess>;\n getAssignedUsers(params: AssignedUsersListParams, wabaId?: string): Promise<WabaListResponse>;\n addAssignedUser(params: AssignedUserRequest, wabaId?: string): Promise<ResponseSuccess>;\n removeAssignedUser(params: RemoveAssignedUserRequest, wabaId?: string): Promise<ResponseSuccess>;\n getInProgressOnBehalfRequests(params?: WabaListParams, wabaId?: string): Promise<WabaListResponse>;\n getOBOMobilityIntent(oboMobilityIntentId: string, fields?: WabaFieldsParam): Promise<WabaGraphObject>;\n createOBOMobilityIntent(params: CreateOBOMobilityIntentRequest, wabaId?: string): Promise<WabaGraphObject>;\n setOBOMobilityIntent(params: SetOBOMobilityIntentRequest, wabaId?: string): Promise<WabaGraphObject>;\n getWabaSchedules(params?: WabaListParams, wabaId?: string): Promise<WabaListResponse>;\n createWabaSchedule(params: CreateScheduleRequest, wabaId?: string): Promise<WabaGraphObject>;\n getWhatsAppBusinessBotDetails(botId: string, fields?: WabaFieldsParam): Promise<WabaGraphObject>;\n getWhatsAppBusinessProfileDetails(profileId: string, fields?: WabaFieldsParam): Promise<WabaGraphObject>;\n updateWhatsAppBusinessProfile(\n profileId: string,\n params: UpdateWhatsAppBusinessProfileRequest,\n ): Promise<ResponseSuccess>;\n}\n","import type { LoggerInterface } from '../types/logger';\n\nexport default class Logger implements LoggerInterface {\n private name: string;\n private debugEnabled: boolean;\n\n constructor(name: string, debug: boolean = false) {\n this.name = name;\n this.debugEnabled = debug;\n }\n\n private formatData(data: any[]): string {\n return data.map((item) => (typeof item === 'object' && item !== null ? stringify(item) : item)).join(' ');\n }\n\n log(...data: any[]) {\n if (this.debugEnabled) {\n let prefix = `[ ${Date.now()} ]`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.log(prefix, ': ', this.formatData(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(prefix, ': ', this.formatData(data));\n }\n\n warn(...data: any[]) {\n if (this.debugEnabled) {\n let prefix = `[ ${Date.now()} ] - WARN`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.warn(prefix, ': ', this.formatData(data));\n }\n }\n\n info(...data: any[]) {\n if (this.debugEnabled) {\n let prefix = `[ ${Date.now()} ] - INFO`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.info(prefix, ': ', this.formatData(data));\n }\n }\n\n debug(...data: any[]) {\n if (this.debugEnabled) {\n let prefix = `[ ${Date.now()} ] - DEBUG`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.debug(prefix, ': ', this.formatData(data));\n }\n }\n}\n\n/**\n * Serialize log data without `node:util` so logging works on every runtime.\n * Errors keep their message and stack; circular references are marked.\n */\nfunction stringify(value: object): string {\n if (value instanceof Error) {\n return value.stack || `${value.name}: ${value.message}`;\n }\n const seen = new WeakSet<object>();\n try {\n return JSON.stringify(\n value,\n (_key, val) => {\n if (val instanceof Error) {\n return { name: val.name, message: val.message, stack: val.stack };\n }\n if (typeof val === 'bigint') return val.toString();\n if (typeof val === 'object' && val !== null) {\n if (seen.has(val)) return '[Circular]';\n seen.add(val);\n }\n return val;\n },\n 2,\n );\n } catch {\n return String(value);\n }\n}\n","// Selected only by the Node conditional package entry during the build.\nimport * as crypto from 'node:crypto';\n\nexport const nodeCrypto = crypto;\n","import { nodeCrypto } from './runtimeCrypto';\n\n/**\n * Runtime helpers that keep the SDK free of static `node:*` imports, so the\n * universal bundle loads on Bun, Deno, Cloudflare Workers and Vercel Edge.\n * Node conditional entries inject crypto for versions lacking getBuiltinModule.\n */\n\ntype NodeCrypto = typeof import('node:crypto');\n\ntype ProcessLike = {\n env?: Record<string, string | undefined>;\n version?: string;\n versions?: Record<string, string | undefined>;\n getBuiltinModule?: (id: string) => unknown;\n};\n\nfunction getProcess(): ProcessLike | undefined {\n const proc = (globalThis as { process?: ProcessLike }).process;\n return typeof proc === 'object' && proc !== null ? proc : undefined;\n}\n\n/**\n * Read an environment variable. Returns undefined on runtimes without\n * `process.env` (e.g. Cloudflare Workers without `nodejs_compat`).\n */\nexport function readEnv(name: string): string | undefined {\n return getProcess()?.env?.[name];\n}\n\n/** True when the `DEBUG` environment variable is `'true'`. */\nexport function isDebugEnv(): boolean {\n return readEnv('DEBUG') === 'true';\n}\n\n/**\n * Load `node:crypto` synchronously without a static import, via\n * `process.getBuiltinModule` (Node.js >= 20.16, Bun, Deno, workerd with\n * `nodejs_compat`), or the Node entry module. Returns undefined\n * when it is not available.\n */\nexport function getNodeCrypto(): NodeCrypto | undefined {\n const getBuiltinModule = getProcess()?.getBuiltinModule;\n if (typeof getBuiltinModule !== 'function') return getProcess() ? nodeCrypto : undefined;\n try {\n return getBuiltinModule('node:crypto') as NodeCrypto;\n } catch {\n return undefined;\n }\n}\n\n/** Like {@link getNodeCrypto} but throws a descriptive error when missing. */\nexport function requireNodeCrypto(feature: string): NodeCrypto {\n const crypto = getNodeCrypto();\n if (!crypto) {\n throw new Error(\n `${feature} needs the node:crypto module, which is not available in this runtime. ` +\n 'Use the async Web Crypto variant instead, or run on Node.js >= 20.12, Bun or Deno.',\n );\n }\n return crypto;\n}\n\n/** Web Crypto `SubtleCrypto`, available on every supported runtime. */\nexport function getSubtle(): SubtleCrypto {\n const subtle = globalThis.crypto?.subtle;\n if (!subtle) {\n throw new Error('Web Crypto (globalThis.crypto.subtle) is not available in this runtime.');\n }\n return subtle;\n}\n\n/** Human-readable runtime name for the User-Agent header. */\nexport function describeRuntime(): string {\n const g = globalThis as {\n Bun?: { version?: string };\n Deno?: { version?: { deno?: string } };\n EdgeRuntime?: string;\n navigator?: { userAgent?: string };\n };\n if (g.Bun?.version) return `Bun ${g.Bun.version}`;\n if (g.Deno?.version?.deno) return `Deno ${g.Deno.version.deno}`;\n if (typeof g.EdgeRuntime === 'string') return `Edge Runtime ${g.EdgeRuntime}`;\n if (g.navigator?.userAgent === 'Cloudflare-Workers') return 'Cloudflare Workers';\n const version = getProcess()?.version;\n if (version) return `Node.js ${version}`;\n return 'unknown runtime';\n}\n\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\nexport function utf8Encode(value: string): Uint8Array<ArrayBuffer> {\n return textEncoder.encode(value) as Uint8Array<ArrayBuffer>;\n}\n\nexport function utf8Decode(value: Uint8Array): string {\n return textDecoder.decode(value);\n}\n\nexport function base64ToBytes(value: string): Uint8Array<ArrayBuffer> {\n const binary = atob(value);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n\nexport function bytesToBase64(bytes: Uint8Array): string {\n let binary = '';\n const chunk = 0x8000;\n for (let i = 0; i < bytes.length; i += chunk) {\n binary += String.fromCharCode(...bytes.subarray(i, i + chunk));\n }\n return btoa(binary);\n}\n\nexport function bytesToHex(bytes: Uint8Array): string {\n let hex = '';\n for (const byte of bytes) {\n hex += byte.toString(16).padStart(2, '0');\n }\n return hex;\n}\n\n/** Constant-time string comparison (length is not secret). */\nexport function timingSafeEqualString(a: string, b: string): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) {\n diff |= a.charCodeAt(i) ^ b.charCodeAt(i);\n }\n return diff === 0;\n}\n\n/** HMAC-SHA256 hex digest using Web Crypto. */\nexport async function hmacSha256Hex(key: string, data: string): Promise<string> {\n const subtle = getSubtle();\n const cryptoKey = await subtle.importKey('raw', utf8Encode(key), { name: 'HMAC', hash: 'SHA-256' }, false, [\n 'sign',\n ]);\n const signature = await subtle.sign('HMAC', cryptoKey, utf8Encode(data));\n return bytesToHex(new Uint8Array(signature));\n}\n","import type { WabaConfigType, WhatsAppConfig } from '../types/config';\nimport { WabaConfigEnum } from '../types/enums';\nimport Logger from '../utils/logger';\nimport { isDebugEnv, readEnv } from '../utils/runtime';\nimport {\n DEFAULT_CLOUD_API_VERSION,\n DEFAULT_LISTENER_PORT,\n DEFAULT_MAX_RETRIES_AFTER_WAIT,\n DEFAULT_REQUEST_TIMEOUT,\n} from './defaults';\n\nconst LIB_NAME = 'UTILS';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, isDebugEnv() || LOG_LOCAL);\n\nconst emptyConfigChecker = (config: WhatsAppConfig | undefined) => {\n if (!readEnv(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 || readEnv('M4D_APP_ID') || '',\n [WabaConfigEnum.AppSecret]: inputConfig?.appSecret || readEnv('M4D_APP_SECRET') || '',\n [WabaConfigEnum.PhoneNumberId]:\n inputConfig?.phoneNumberId || (readEnv('WA_PHONE_NUMBER_ID') ? Number(readEnv('WA_PHONE_NUMBER_ID')) : 0),\n [WabaConfigEnum.BusinessAcctId]: inputConfig?.businessAcctId || readEnv('WA_BUSINESS_ACCOUNT_ID') || '',\n [WabaConfigEnum.APIVersion]:\n inputConfig?.apiVersion || readEnv('CLOUD_API_VERSION') || DEFAULT_CLOUD_API_VERSION,\n [WabaConfigEnum.AccessToken]: inputConfig?.accessToken || readEnv('CLOUD_API_ACCESS_TOKEN') || '',\n [WabaConfigEnum.WebhookEndpoint]: inputConfig?.webhookEndpoint || readEnv('WEBHOOK_ENDPOINT') || '',\n [WabaConfigEnum.WebhookVerificationToken]:\n inputConfig?.webhookVerificationToken || readEnv('WEBHOOK_VERIFICATION_TOKEN') || '',\n [WabaConfigEnum.ListenerPort]:\n inputConfig?.listenerPort || parseInt(readEnv('LISTENER_PORT') || '', 10) || DEFAULT_LISTENER_PORT,\n [WabaConfigEnum.MaxRetriesAfterWait]:\n inputConfig?.maxRetriesAfterWait ||\n parseInt(readEnv('MAX_RETRIES_AFTER_WAIT') || '', 10) ||\n DEFAULT_MAX_RETRIES_AFTER_WAIT,\n [WabaConfigEnum.RequestTimeout]:\n inputConfig?.requestTimeout || parseInt(readEnv('REQUEST_TIMEOUT') || '', 10) || DEFAULT_REQUEST_TIMEOUT,\n [WabaConfigEnum.Debug]: inputConfig?.debug || isDebugEnv(),\n [WabaConfigEnum.PrivatePem]: inputConfig?.privatePem || readEnv('FLOW_API_PRIVATE_PEM') || '',\n [WabaConfigEnum.Passphrase]: inputConfig?.passphrase || readEnv('FLOW_API_PASSPHRASE') || '',\n retry: inputConfig?.retry,\n onRateLimitInfo: inputConfig?.onRateLimitInfo,\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","/**\n * WhatsApp Flow Encryption/Decryption Utilities\n * Handles encryption and decryption of WhatsApp Flow requests and responses\n * @see https://developers.facebook.com/docs/whatsapp/cloud-api/reference/whatsapp-business-encryption/\n */\n\nimport type { KeyObject } from 'node:crypto';\n\nimport type { FlowEndpointRequest } from '../api/flow';\nimport type { WabaConfigType } from '../types/config';\nimport Logger from './logger';\nimport {\n base64ToBytes,\n bytesToBase64,\n getNodeCrypto,\n getSubtle,\n isDebugEnv,\n readEnv,\n requireNodeCrypto,\n utf8Decode,\n utf8Encode,\n} from './runtime';\n\nconst LIB_NAME = 'FLOW_ENCRYPTION_UTILS';\nconst LOGGER = new Logger(LIB_NAME, isDebugEnv());\n\n/**\n * Environment model for encryption keys\n */\nexport type EncryptionKeyPair = {\n passphrase: string;\n privateKey: string;\n publicKey: string;\n};\n\n/**\n * Validates that the code is running in a Node.js environment\n * @throws {Error} If not running in Node.js environment\n */\nfunction validateNodeEnvironment(): typeof import('node:crypto') {\n const crypto = getNodeCrypto();\n // Check if crypto module exists and has required methods\n if (!crypto || typeof crypto.generateKeyPairSync !== 'function') {\n const error = new Error(\n 'This utility requires Node.js environment with crypto module. ' +\n 'It cannot be used in browser or edge runtime environments.',\n );\n LOGGER.error('Environment validation failed:', error);\n throw error;\n }\n\n // Check if running in browser\n if (typeof window !== 'undefined') {\n const error = new Error(\n 'This utility cannot run in a browser environment. ' +\n 'Please use it in a Node.js server environment only.',\n );\n LOGGER.error('Browser environment detected:', error);\n throw error;\n }\n\n // Check Node.js version (crypto.generateKeyPairSync requires Node.js 10.12.0+)\n const nodeVersionString = (globalThis as { process?: { versions?: { node?: string } } }).process?.versions?.node;\n if (nodeVersionString) {\n const nodeVersion = nodeVersionString.split('.').map(Number);\n const major = nodeVersion[0] ?? 0;\n const minor = nodeVersion[1] ?? 0;\n\n if (major < 10 || (major === 10 && minor < 12)) {\n const error = new Error(\n `Node.js version ${nodeVersionString} is not supported. ` +\n 'Please upgrade to Node.js 10.12.0 or higher.',\n );\n LOGGER.error('Node.js version check failed:', error);\n throw error;\n }\n }\n\n return crypto;\n}\n\n/**\n * Generates RSA key pair for WhatsApp Business Flow API encryption\n *\n * This function generates a 2048-bit RSA key pair with:\n * - Public key in SPKI format (PEM)\n * - Private key in PKCS#8 format (PEM) encrypted with AES-256-CBC\n *\n * @param passphrase - Passphrase to encrypt the private key. If not provided, uses FLOW_API_PASSPHRASE from environment\n * @returns Object containing passphrase, privateKey, and publicKey\n * @throws {Error} If passphrase is empty or key generation fails\n * @throws {Error} If not running in Node.js environment\n *\n * @example\n * ```typescript\n * import { WhatsApp } from 'meta-cloud-api';\n *\n * const wa = new WhatsApp();\n *\n * try {\n * // Uses FLOW_API_PASSPHRASE from environment\n * const keys = wa.generateEncryption();\n * console.log('Public Key:', keys.publicKey);\n * console.log('Private Key:', keys.privateKey);\n *\n * // Or provide custom passphrase\n * const customKeys = wa.generateEncryption('my-secret-passphrase');\n * } catch (error) {\n * console.error('Failed to generate keys:', error.message);\n * }\n * ```\n */\nexport function generateEncryption(passphrase?: string): EncryptionKeyPair {\n LOGGER.info('[generateEncryption] Starting key pair generation');\n\n // Validate environment first\n const crypto = validateNodeEnvironment();\n\n // Get passphrase from parameter or environment variable\n const effectivePassphrase = passphrase || readEnv('FLOW_API_PASSPHRASE');\n\n // Validate passphrase\n if (!effectivePassphrase || effectivePassphrase.trim().length === 0) {\n const error = new Error(\n 'Passphrase is empty. Please provide a passphrase as parameter or set FLOW_API_PASSPHRASE environment variable.',\n );\n LOGGER.error('[generateEncryption] Passphrase validation failed:', error);\n throw error;\n }\n\n // Warn if passphrase is too short\n if (effectivePassphrase.length < 8) {\n LOGGER.warn(\n '[generateEncryption] Passphrase is shorter than 8 characters. Consider using a longer passphrase for better security.',\n );\n }\n\n try {\n LOGGER.info('[generateEncryption] Generating 2048-bit RSA key pair');\n\n // Generate RSA key pair\n const keyPair = crypto.generateKeyPairSync('rsa', {\n modulusLength: 2048,\n publicKeyEncoding: {\n type: 'spki',\n format: 'pem',\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'pem',\n cipher: 'aes-256-cbc',\n passphrase: effectivePassphrase,\n },\n });\n\n LOGGER.info('[generateEncryption] Key pair generated successfully');\n\n return {\n passphrase: effectivePassphrase,\n privateKey: keyPair.privateKey,\n publicKey: keyPair.publicKey,\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n const generationError = new Error(`Failed to generate key pair: ${errorMessage}`);\n LOGGER.error('[generateEncryption] Key generation failed:', generationError);\n throw generationError;\n }\n}\n\n/**\n * Decrypt a WhatsApp Flow request (Node.js only; see {@link decryptFlowRequestAsync} for every runtime)\n * @param body - Encrypted request body containing encrypted_aes_key, encrypted_flow_data, and initial_vector\n * @param config - WABA configuration containing FLOW_API_PRIVATE_PEM and FLOW_API_PASSPHRASE\n * @returns Decrypted flow request body, AES key buffer, and initial vector buffer\n * @throws {Error} If required encryption properties are missing or decryption fails\n */\nexport function decryptFlowRequest(\n body: any,\n config: WabaConfigType,\n): {\n decryptedBody: FlowEndpointRequest;\n aesKeyBuffer: Buffer;\n initialVectorBuffer: Buffer;\n} {\n LOGGER.info('[decryptFlowRequest] Starting Flow request decryption');\n\n const crypto = requireNodeCrypto('decryptFlowRequest');\n\n // Validate required environment variables\n if (!config.FLOW_API_PRIVATE_PEM || config.FLOW_API_PRIVATE_PEM.trim() === '') {\n const error = new Error(\n 'Missing FLOW_API_PRIVATE_PEM. Please set the FLOW_API_PRIVATE_PEM environment variable or pass privatePem via config.',\n );\n LOGGER.error('[decryptFlowRequest] Configuration error:', error);\n throw error;\n }\n\n if (!config.FLOW_API_PASSPHRASE || config.FLOW_API_PASSPHRASE.trim() === '') {\n const error = new Error(\n 'Missing FLOW_API_PASSPHRASE. Please set the FLOW_API_PASSPHRASE environment variable or pass passphrase via config.',\n );\n LOGGER.error('[decryptFlowRequest] Configuration error:', error);\n throw error;\n }\n\n LOGGER.info('[decryptFlowRequest] Configuration validated');\n\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('[decryptFlowRequest] Missing required encryption properties in request body');\n throw new Error('Missing required encryption properties');\n }\n\n LOGGER.info('[decryptFlowRequest] Request body validated');\n\n // Handle both escaped and unescaped newlines\n let privatePem = config.FLOW_API_PRIVATE_PEM;\n if (privatePem.includes('\\\\n')) {\n privatePem = privatePem.replace(/\\\\n/g, '\\n');\n }\n\n const passphrase = config.FLOW_API_PASSPHRASE;\n\n const isPKCS1 = privatePem.includes('-----BEGIN RSA PRIVATE KEY-----');\n const isPKCS8 =\n privatePem.includes('-----BEGIN PRIVATE KEY-----') ||\n privatePem.includes('-----BEGIN ENCRYPTED PRIVATE KEY-----');\n\n LOGGER.info('[decryptFlowRequest] Loading private key', {\n format: isPKCS8 ? 'PKCS#8' : isPKCS1 ? 'PKCS#1' : 'Unknown',\n });\n\n let privateKey: KeyObject;\n try {\n // Try to create private key with passphrase\n if (passphrase) {\n privateKey = crypto.createPrivateKey({\n key: privatePem,\n format: 'pem',\n passphrase,\n });\n } else {\n privateKey = crypto.createPrivateKey(privatePem);\n }\n LOGGER.info('[decryptFlowRequest] Private key loaded successfully');\n } catch (error) {\n LOGGER.error('[decryptFlowRequest] Failed to load private key (first attempt):', {\n error: error instanceof Error ? error.message : error,\n hasPassphrase: !!passphrase,\n format: isPKCS8 ? 'PKCS#8' : isPKCS1 ? 'PKCS#1' : 'Unknown',\n });\n\n // If PKCS#1 key failed, try to convert it to PKCS#8 format automatically\n if (isPKCS1 && passphrase) {\n try {\n LOGGER.info('[decryptFlowRequest] Attempting to convert PKCS#1 to PKCS#8 format');\n\n // First, load the PKCS#1 key with passphrase\n const pkcs1Key = crypto.createPrivateKey({\n key: privatePem,\n format: 'pem',\n passphrase,\n });\n\n // Export it as PKCS#8 with the same passphrase\n const pkcs8Pem = pkcs1Key.export({\n type: 'pkcs8',\n format: 'pem',\n cipher: 'aes-256-cbc',\n passphrase,\n });\n\n // Now create the private key from PKCS#8 format\n privateKey = crypto.createPrivateKey({\n key: pkcs8Pem as string,\n format: 'pem',\n passphrase,\n });\n\n LOGGER.info('[decryptFlowRequest] Successfully converted PKCS#1 to PKCS#8 and loaded private key');\n } catch (conversionError) {\n LOGGER.error('[decryptFlowRequest] Failed to convert PKCS#1 to PKCS#8:', {\n error: conversionError instanceof Error ? conversionError.message : conversionError,\n });\n\n // Provide helpful error message\n let errorMessage = `Failed to parse private key. Error: ${error instanceof Error ? error.message : error}`;\n errorMessage += '\\n\\nYour key is in PKCS#1 format with unsupported encryption (DES-EDE3-CBC).';\n errorMessage += '\\nPlease convert it to PKCS#8 format using:';\n errorMessage += '\\n openssl pkcs8 -topk8 -inform PEM -outform PEM -in old_key.pem -out new_key.pem';\n\n throw new Error(errorMessage);\n }\n } else {\n // Provide helpful error message\n let errorMessage = `Failed to parse private key. Error: ${error instanceof Error ? error.message : error}`;\n\n if (isPKCS1) {\n errorMessage += '\\n\\nYour key is in PKCS#1 format (-----BEGIN RSA PRIVATE KEY-----).';\n errorMessage += '\\nPlease convert it to PKCS#8 format using:';\n errorMessage += '\\n openssl pkcs8 -topk8 -inform PEM -outform PEM -in old_key.pem -out new_key.pem';\n } else if (!isPKCS8) {\n errorMessage += '\\n\\nYour key format is not recognized. Please ensure it is in PKCS#8 format.';\n }\n\n throw new Error(errorMessage);\n }\n }\n\n let decryptedAesKey: Buffer;\n\n try {\n LOGGER.info('[decryptFlowRequest] Decrypting AES key with RSA private 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 LOGGER.info('[decryptFlowRequest] AES key decrypted successfully');\n } catch (error) {\n LOGGER.error('[decryptFlowRequest] 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('[decryptFlowRequest] Decrypting flow data with AES-128-GCM');\n\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('[decryptFlowRequest] Flow request decrypted successfully');\n\n return {\n decryptedBody: JSON.parse(decryptedJSONString),\n aesKeyBuffer: decryptedAesKey,\n initialVectorBuffer,\n };\n}\n\n/**\n * Encrypt a WhatsApp Flow response (Node.js only; see {@link encryptFlowResponseAsync} for every runtime)\n * @param response - Response object to encrypt\n * @param aesKeyBuffer - AES key buffer from the decrypted request\n * @param initialVectorBuffer - Initial vector buffer from the decrypted request\n * @returns Base64-encoded encrypted response\n * @throws {Error} If encryption fails\n */\nexport function encryptFlowResponse(response: any, aesKeyBuffer: Buffer, initialVectorBuffer: Buffer): string {\n LOGGER.info('[encryptFlowResponse] Starting Flow response encryption');\n\n const crypto = requireNodeCrypto('encryptFlowResponse');\n\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 LOGGER.info('[encryptFlowResponse] Encrypting response with AES-128-GCM');\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('[encryptFlowResponse] Flow response encrypted successfully');\n\n return encryptedResponse;\n } catch (error) {\n LOGGER.error('[encryptFlowResponse] Response encryption failed:', error);\n throw new Error('Failed to encrypt response. Internal server error.');\n }\n}\n\n/**\n * Result of {@link decryptFlowRequestAsync}. Pass `aesKeyBuffer` and\n * `initialVectorBuffer` to {@link encryptFlowResponseAsync}.\n */\nexport type DecryptedFlowRequest = {\n decryptedBody: FlowEndpointRequest;\n aesKeyBuffer: Uint8Array<ArrayBuffer>;\n initialVectorBuffer: Uint8Array<ArrayBuffer>;\n};\n\nconst PEM_PATTERN = /-----BEGIN ([A-Z ]+)-----([\\s\\S]*?)-----END \\1-----/;\n\nlet cachedPrivateKey: { pem: string; passphrase: string; key: Promise<CryptoKey> } | undefined;\n\n/**\n * Turn a PEM private key into PKCS#8 DER bytes that Web Crypto can import.\n * Unencrypted PKCS#8 (`BEGIN PRIVATE KEY`) works everywhere. Encrypted PKCS#8\n * and PKCS#1 keys need `node:crypto` to unwrap, because Web Crypto has no\n * passphrase support; on runtimes without it a descriptive error is thrown.\n */\nfunction privatePemToPkcs8Der(privatePem: string, passphrase: string): Uint8Array<ArrayBuffer> {\n const match = PEM_PATTERN.exec(privatePem);\n if (!match) {\n throw new Error('Failed to parse private key. Expected a PEM encoded PKCS#8 private key.');\n }\n const label = match[1];\n if (label === 'PRIVATE KEY') {\n return base64ToBytes((match[2] ?? '').replace(/\\s+/g, ''));\n }\n\n const crypto = getNodeCrypto();\n if (!crypto) {\n throw new Error(\n `Failed to parse private key. \"${label}\" keys need node:crypto, which this runtime lacks. ` +\n 'Convert the key to an unencrypted PKCS#8 key and keep it in a secret store:' +\n '\\n openssl pkcs8 -topk8 -nocrypt -in private.pem -out private-pkcs8.pem',\n );\n }\n try {\n const keyObject = crypto.createPrivateKey({\n key: privatePem,\n format: 'pem',\n passphrase: passphrase || undefined,\n });\n const der = keyObject.export({ type: 'pkcs8', format: 'der' });\n return new Uint8Array(der);\n } catch (error) {\n throw new Error(`Failed to parse private key. Error: ${error instanceof Error ? error.message : error}`);\n }\n}\n\nfunction importFlowPrivateKey(privatePem: string, passphrase: string): Promise<CryptoKey> {\n if (cachedPrivateKey && cachedPrivateKey.pem === privatePem && cachedPrivateKey.passphrase === passphrase) {\n return cachedPrivateKey.key;\n }\n const key = (async () =>\n getSubtle().importKey(\n 'pkcs8',\n privatePemToPkcs8Der(privatePem, passphrase),\n { name: 'RSA-OAEP', hash: 'SHA-256' },\n false,\n ['decrypt'],\n ))();\n cachedPrivateKey = { pem: privatePem, passphrase, key };\n // Do not keep a rejected promise around; a corrected config should retry.\n key.catch(() => {\n if (cachedPrivateKey?.key === key) cachedPrivateKey = undefined;\n });\n return key;\n}\n\n/**\n * Decrypt a WhatsApp Flow request with Web Crypto. Works on Node.js, Bun, Deno,\n * Cloudflare Workers and Vercel Edge.\n *\n * On runtimes without `node:crypto` the private key must be an unencrypted\n * PKCS#8 PEM (`-----BEGIN PRIVATE KEY-----`); the passphrase is then ignored.\n *\n * @param body - Encrypted request body containing encrypted_aes_key, encrypted_flow_data, and initial_vector\n * @param config - WABA configuration containing FLOW_API_PRIVATE_PEM and (for encrypted keys) FLOW_API_PASSPHRASE\n * @throws {Error} If required encryption properties are missing or decryption fails\n */\nexport async function decryptFlowRequestAsync(body: any, config: WabaConfigType): Promise<DecryptedFlowRequest> {\n if (!config.FLOW_API_PRIVATE_PEM || config.FLOW_API_PRIVATE_PEM.trim() === '') {\n throw new Error(\n 'Missing FLOW_API_PRIVATE_PEM. Please set the FLOW_API_PRIVATE_PEM environment variable or pass privatePem via config.',\n );\n }\n\n const { encrypted_aes_key, encrypted_flow_data, initial_vector } = body ?? {};\n if (!encrypted_aes_key || !encrypted_flow_data || !initial_vector) {\n throw new Error('Missing required encryption properties');\n }\n\n let privatePem = config.FLOW_API_PRIVATE_PEM;\n if (privatePem.includes('\\\\n')) {\n privatePem = privatePem.replace(/\\\\n/g, '\\n');\n }\n\n const subtle = getSubtle();\n const privateKey = await importFlowPrivateKey(privatePem, config.FLOW_API_PASSPHRASE || '');\n\n let aesKeyBuffer: Uint8Array<ArrayBuffer>;\n try {\n aesKeyBuffer = new Uint8Array(\n await subtle.decrypt({ name: 'RSA-OAEP' }, privateKey, base64ToBytes(encrypted_aes_key)),\n );\n } catch (error) {\n LOGGER.error('[decryptFlowRequestAsync] Failed to decrypt AES key:', error);\n throw new Error('Failed to decrypt the request. Please verify your private key.');\n }\n\n const initialVectorBuffer = base64ToBytes(initial_vector);\n const aesKey = await subtle.importKey('raw', aesKeyBuffer, { name: 'AES-GCM' }, false, ['decrypt']);\n // Meta sends ciphertext || 16-byte tag, which is exactly what Web Crypto expects.\n const decrypted = await subtle.decrypt(\n { name: 'AES-GCM', iv: initialVectorBuffer, tagLength: 128 },\n aesKey,\n base64ToBytes(encrypted_flow_data),\n );\n\n return {\n decryptedBody: JSON.parse(utf8Decode(new Uint8Array(decrypted))),\n aesKeyBuffer,\n initialVectorBuffer,\n };\n}\n\n/**\n * Encrypt a WhatsApp Flow response with Web Crypto. Works on every runtime.\n * @param response - Response object to encrypt\n * @param aesKeyBuffer - AES key from {@link decryptFlowRequestAsync} (a Node.js Buffer also works)\n * @param initialVectorBuffer - Initial vector from {@link decryptFlowRequestAsync} (a Node.js Buffer also works)\n * @returns Base64-encoded encrypted response\n */\nexport async function encryptFlowResponseAsync(\n response: any,\n aesKeyBuffer: Uint8Array,\n initialVectorBuffer: Uint8Array,\n): Promise<string> {\n const flippedIv = new Uint8Array(initialVectorBuffer.length);\n for (let i = 0; i < initialVectorBuffer.length; i++) {\n flippedIv[i] = ~(initialVectorBuffer[i] ?? 0) & 0xff;\n }\n\n try {\n const subtle = getSubtle();\n const aesKey = await subtle.importKey('raw', new Uint8Array(aesKeyBuffer), { name: 'AES-GCM' }, false, [\n 'encrypt',\n ]);\n const encrypted = await subtle.encrypt(\n { name: 'AES-GCM', iv: flippedIv, tagLength: 128 },\n aesKey,\n utf8Encode(JSON.stringify(response || {})),\n );\n return bytesToBase64(new Uint8Array(encrypted));\n } catch (error) {\n LOGGER.error('[encryptFlowResponseAsync] Response encryption failed:', error);\n throw new Error('Failed to encrypt response. Internal server error.');\n }\n}\n","// Docs: https://developers.facebook.com/docs/graph-api/overview/rate-limiting/\n\n/**\n * Usage percentages reported by Meta. Each value is the share (0-100+) of the allowance used in the\n * current rolling window.\n */\nexport interface RateLimitUsage {\n /** Percentage of calls made (`call_count`). */\n callCount?: number;\n /** Percentage of total CPU time used (`total_cputime`). */\n totalCputime?: number;\n /** Percentage of total time used (`total_time`). */\n totalTime?: number;\n}\n\n/** One entry of the `X-Business-Use-Case-Usage` header. */\nexport interface BusinessUseCaseUsage extends RateLimitUsage {\n /** The business object the entry belongs to (for WhatsApp, usually the WABA or phone number ID). */\n businessId: string;\n /** Rate limit type, e.g. `whatsapp_business_management` or `whatsapp`. */\n type?: string;\n /**\n * `estimated_time_to_regain_access`: \"Time, in minutes, until calls will no longer be throttled.\"\n * `0` when not throttled.\n */\n estimatedTimeToRegainAccessMinutes?: number;\n /** `ads_api_access_tier`, only sent for Marketing API use cases. */\n adsApiAccessTier?: string;\n}\n\n/**\n * Rate limit information parsed from a Graph API response.\n *\n * WhatsApp Cloud API responses carry `x-business-use-case-usage` (types\n * `whatsapp_business_management` and `whatsapp`) and `x-app-usage`; throttled responses may add\n * `Retry-After` (seconds).\n */\nexport interface RateLimitInfo {\n /** Parsed `X-App-Usage` header (platform rate limits). */\n appUsage?: RateLimitUsage;\n /** Parsed `X-Business-Use-Case-Usage` header, flattened across business IDs. Empty when absent. */\n businessUseCaseUsage: BusinessUseCaseUsage[];\n /** Parsed `Retry-After` header in milliseconds (seconds or HTTP-date form). */\n retryAfterMs?: number;\n /**\n * Highest usage percentage across every parsed metric, handy for alerting before Meta starts\n * throttling (it throttles at 100).\n */\n maxUsagePercent?: number;\n /**\n * How long Meta asks you to wait, in milliseconds: the larger of `retryAfterMs` and the largest\n * `estimatedTimeToRegainAccessMinutes`. Undefined when Meta gave no wait time.\n */\n retryDelayMs?: number;\n}\n\n/** Headers accepted by {@link parseRateLimitHeaders}. */\nexport type RateLimitHeadersInput =\n | Headers\n | Record<string, string | string[] | undefined>\n | { get(name: string): string | null };\n\nfunction readHeader(headers: RateLimitHeadersInput, name: string): string | undefined {\n if (typeof (headers as { get?: unknown }).get === 'function') {\n const value = (headers as { get(name: string): string | null }).get(name);\n return value ?? undefined;\n }\n const record = headers as Record<string, string | string[] | undefined>;\n const key = Object.keys(record).find((k) => k.toLowerCase() === name);\n if (key === undefined) return undefined;\n const value = record[key];\n return Array.isArray(value) ? value[0] : value;\n}\n\nfunction parseJson(value: string | undefined): unknown {\n if (value === undefined || value.trim() === '') return undefined;\n try {\n return JSON.parse(value);\n } catch {\n return undefined;\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction num(value: unknown): number | undefined {\n if (typeof value === 'number' && Number.isFinite(value)) return value;\n if (typeof value === 'string' && value.trim() !== '' && Number.isFinite(Number(value))) return Number(value);\n return undefined;\n}\n\nfunction str(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction parseUsage(value: Record<string, unknown>): RateLimitUsage {\n const usage: RateLimitUsage = {};\n const callCount = num(value.call_count);\n const totalCputime = num(value.total_cputime);\n const totalTime = num(value.total_time);\n if (callCount !== undefined) usage.callCount = callCount;\n if (totalCputime !== undefined) usage.totalCputime = totalCputime;\n if (totalTime !== undefined) usage.totalTime = totalTime;\n return usage;\n}\n\nfunction parseBusinessUseCaseUsage(value: unknown): BusinessUseCaseUsage[] {\n if (!isRecord(value)) return [];\n const entries: BusinessUseCaseUsage[] = [];\n for (const [businessId, list] of Object.entries(value)) {\n if (!Array.isArray(list)) continue;\n for (const item of list) {\n if (!isRecord(item)) continue;\n const entry: BusinessUseCaseUsage = { businessId, ...parseUsage(item) };\n const type = str(item.type);\n const regain = num(item.estimated_time_to_regain_access);\n const tier = str(item.ads_api_access_tier);\n if (type !== undefined) entry.type = type;\n if (regain !== undefined) entry.estimatedTimeToRegainAccessMinutes = regain;\n if (tier !== undefined) entry.adsApiAccessTier = tier;\n entries.push(entry);\n }\n }\n return entries;\n}\n\n/**\n * Parses a `Retry-After` value (delta-seconds or HTTP-date) into milliseconds.\n * Returns undefined for missing or malformed values.\n */\nexport function parseRetryAfter(value: string | null | undefined, now: number = Date.now()): number | undefined {\n if (value === null || value === undefined) return undefined;\n const trimmed = value.trim();\n if (trimmed === '') return undefined;\n if (/^\\d+(\\.\\d+)?$/.test(trimmed)) return Math.round(Number(trimmed) * 1000);\n // An HTTP-date always names a weekday/month; this rejects values such as \"-1\" that Date.parse accepts.\n if (!/[a-z]/i.test(trimmed)) return undefined;\n const date = Date.parse(trimmed);\n if (!Number.isFinite(date)) return undefined;\n return Math.max(0, date - now);\n}\n\n/**\n * Parses Meta's rate limit headers (`X-App-Usage`, `X-Business-Use-Case-Usage`, `Retry-After`).\n * Header names are matched case-insensitively. Malformed JSON or values are ignored, never thrown.\n *\n * Returns undefined when none of the headers are present.\n *\n * @see {@link https://developers.facebook.com/docs/graph-api/overview/rate-limiting/ | Graph API rate limiting}\n *\n * @example\n * ```ts\n * const info = parseRateLimitHeaders(response.headers);\n * if ((info?.maxUsagePercent ?? 0) > 80) slowDown();\n * ```\n */\nexport function parseRateLimitHeaders(headers: RateLimitHeadersInput | null | undefined): RateLimitInfo | undefined {\n if (!headers) return undefined;\n\n const appRaw = readHeader(headers, 'x-app-usage');\n const bucRaw = readHeader(headers, 'x-business-use-case-usage');\n const retryAfterRaw = readHeader(headers, 'retry-after');\n if (appRaw === undefined && bucRaw === undefined && retryAfterRaw === undefined) return undefined;\n\n const info: RateLimitInfo = { businessUseCaseUsage: [] };\n\n const appJson = parseJson(appRaw);\n if (isRecord(appJson)) info.appUsage = parseUsage(appJson);\n\n info.businessUseCaseUsage = parseBusinessUseCaseUsage(parseJson(bucRaw));\n\n const retryAfterMs = parseRetryAfter(retryAfterRaw);\n if (retryAfterMs !== undefined) info.retryAfterMs = retryAfterMs;\n\n const usages: RateLimitUsage[] = [...(info.appUsage ? [info.appUsage] : []), ...info.businessUseCaseUsage];\n const percents = usages.flatMap((u) =>\n [u.callCount, u.totalCputime, u.totalTime].filter((v): v is number => v !== undefined),\n );\n if (percents.length > 0) info.maxUsagePercent = Math.max(...percents);\n\n const waits = [\n ...(retryAfterMs !== undefined ? [retryAfterMs] : []),\n ...info.businessUseCaseUsage\n .map((u) => u.estimatedTimeToRegainAccessMinutes)\n .filter((m): m is number => m !== undefined && m > 0)\n .map((m) => m * 60_000),\n ];\n if (waits.length > 0) info.retryDelayMs = Math.max(...waits);\n\n return info;\n}\n","import type { HttpMethodsEnum } from '../../types/enums';\nimport type {\n HttpsClientClass,\n HttpsClientResponseClass,\n ResponseHeaders,\n ResponseJSONBody,\n} from '../../types/httpsClient';\nimport Logger from '../logger';\nimport { isDebugEnv } from '../runtime';\n\nconst LIB_NAME = 'HttpsClient';\nconst LOGGER = new Logger(LIB_NAME, isDebugEnv());\n\nexport default class HttpsClient implements HttpsClientClass {\n /**\n * Kept for backwards compatibility. Requests go through the global `fetch`,\n * which manages its own connection pool, so there is nothing to clear.\n */\n clearSockets(): boolean {\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 const error = new Error(`Failed to parse response body to JSON: ${(err as Error).message}`);\n error.cause = err;\n throw error;\n }\n }\n}\n","import {\n DEFAULT_CLOUD_API_VERSION,\n DEFAULT_RETRY_BACKOFF,\n DEFAULT_RETRY_INITIAL_DELAY_MS,\n DEFAULT_RETRY_MAX_ATTEMPTS,\n DEFAULT_RETRY_MAX_SERVER_DELAY_MS,\n GRAPH_API_HOST,\n GRAPH_API_PROTOCOL,\n} from '../../config/defaults';\nimport type { RateLimitInfoListener, RetryConfig } from '../../types/config';\nimport type { HttpMethodsEnum } from '../../types/enums';\nimport type { RequesterClass, UrlEncodedFormBody } from '../../types/request';\nimport {\n createWhatsAppApiError,\n isMetaError,\n normalizeMetaError,\n WhatsAppError,\n WhatsAppNetworkError,\n WhatsAppThrottlingError,\n} from '../isMetaError';\nimport Logger from '../logger';\nimport { parseRateLimitHeaders, type RateLimitInfo } from '../rateLimit';\nimport { isDebugEnv } from '../runtime';\nimport HttpsClient from './httpsClient';\n\nconst LIB_NAME = 'REQUESTER';\nconst LOGGER = new Logger(LIB_NAME, isDebugEnv());\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\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> = GRAPH_API_PROTOCOL;\n private retryConfig: RetryConfig | undefined;\n private onRateLimitInfo: RateLimitInfoListener | undefined;\n private lastRateLimitInfo: RateLimitInfo | undefined;\n\n constructor(\n apiVersion: string,\n phoneNumberId: number,\n accessToken: string,\n businessAcctId: string,\n userAgent: string,\n retryConfig?: RetryConfig,\n onRateLimitInfo?: RateLimitInfoListener,\n ) {\n this.client = new HttpsClient();\n this.host = GRAPH_API_HOST;\n this.apiVersion = this.normalizeApiVersion(apiVersion);\n this.phoneNumberId = phoneNumberId;\n this.accessToken = accessToken;\n this.businessAcctId = businessAcctId;\n this.userAgent = userAgent;\n this.retryConfig = retryConfig;\n this.onRateLimitInfo = onRateLimitInfo;\n }\n\n /**\n * Rate limit headers of the most recent response that carried any, or undefined.\n * With concurrent requests this is whichever response finished last; use the\n * `onRateLimitInfo` config callback to see every response.\n */\n getLastRateLimitInfo(): RateLimitInfo | undefined {\n return this.lastRateLimitInfo;\n }\n\n private captureRateLimitInfo(\n response: { headers?: () => unknown; statusCode?: () => number },\n method: string,\n endpoint: string,\n ): RateLimitInfo | undefined {\n if (typeof response.headers !== 'function') return undefined;\n const info = parseRateLimitHeaders(response.headers() as Parameters<typeof parseRateLimitHeaders>[0]);\n if (!info) return undefined;\n\n this.lastRateLimitInfo = info;\n if (this.onRateLimitInfo) {\n try {\n const statusCode = typeof response.statusCode === 'function' ? response.statusCode() : 0;\n // Observe asynchronous failures too, without delaying the API response on telemetry.\n void Promise.resolve(this.onRateLimitInfo(info, { method, endpoint, statusCode })).catch(\n (error: unknown) => {\n LOGGER.log(`onRateLimitInfo listener threw: ${error instanceof Error ? error.message : error}`);\n },\n );\n } catch (error) {\n LOGGER.log(`onRateLimitInfo listener threw: ${error instanceof Error ? error.message : error}`);\n }\n }\n return info;\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 `${this.apiVersion}/${endpoint}`;\n }\n\n private normalizeApiVersion(apiVersion?: string): string {\n if (!apiVersion) return DEFAULT_CLOUD_API_VERSION;\n\n const trimmed = apiVersion.trim();\n if (/^v\\d+\\.\\d+$/.test(trimmed)) return trimmed;\n if (/^\\d+\\.\\d+$/.test(trimmed)) return `v${trimmed}`;\n if (/^v\\d+$/.test(trimmed)) return `${trimmed}.0`;\n if (/^\\d+$/.test(trimmed)) return `v${trimmed}.0`;\n\n return trimmed;\n }\n\n private buildRequestTarget(endpoint: string): { host: string; path: string; displayUrl: string } {\n if (/^https?:\\/\\//.test(endpoint)) {\n const url = new URL(endpoint);\n const path = `${url.pathname}${url.search}`.replace(/^\\//, '');\n return {\n host: url.host,\n path,\n displayUrl: url.toString(),\n };\n }\n\n const path = this.buildCAPIPath(endpoint.replace(/^\\//, ''));\n return {\n host: this.host,\n path,\n displayUrl: `${this.protocol.toLowerCase()}//${this.host}/${path}`,\n };\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 const maxAttempts = this.retryConfig?.maxAttempts ?? DEFAULT_RETRY_MAX_ATTEMPTS;\n const initialDelayMs = this.retryConfig?.initialDelayMs ?? DEFAULT_RETRY_INITIAL_DELAY_MS;\n const backoff = this.retryConfig?.backoff ?? DEFAULT_RETRY_BACKOFF;\n const respectServerDelay = this.retryConfig?.respectServerDelay ?? true;\n const maxServerDelayMs = this.retryConfig?.maxServerDelayMs ?? DEFAULT_RETRY_MAX_SERVER_DELAY_MS;\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 requestTarget = this.buildRequestTarget(endpoint);\n LOGGER.log(`${method} : ${requestTarget.displayUrl} (${effectiveContentType})`);\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n const shouldSendBody = method === 'POST' || method === 'PUT' || method === 'DELETE';\n\n const response = await this.client.sendRequest(\n requestTarget.host,\n requestTarget.path,\n method,\n this.buildHeader(effectiveContentType, additionalHeaders),\n timeout,\n shouldSendBody ? body : undefined,\n );\n\n const rateLimit = this.captureRateLimitInfo(response, method, endpoint);\n\n if (!response.rawResponse().ok) {\n let errorData: unknown = null;\n try {\n errorData = await response.json();\n } catch {\n errorData = null;\n }\n\n const metaError = normalizeMetaError(errorData, response.statusCode());\n const apiError = createWhatsAppApiError(metaError.error, response.statusCode());\n if (rateLimit) apiError.rateLimit = rateLimit;\n throw apiError;\n }\n\n return response;\n } catch (error) {\n if (error instanceof WhatsAppThrottlingError && attempt < maxAttempts) {\n const backoffDelay =\n backoff === 'exponential' ? initialDelayMs * 2 ** (attempt - 1) : initialDelayMs;\n const serverDelay = respectServerDelay ? error.rateLimit?.retryDelayMs : undefined;\n const delay =\n serverDelay !== undefined\n ? Math.max(backoffDelay, Math.min(serverDelay, Math.max(0, maxServerDelayMs)))\n : backoffDelay;\n LOGGER.log(`Throttled (attempt ${attempt}/${maxAttempts}). Retrying in ${delay}ms...`);\n await sleep(delay);\n continue;\n }\n\n if (error instanceof WhatsAppError) {\n throw error;\n }\n if (isMetaError(error)) {\n throw createWhatsAppApiError(error.error);\n }\n\n const message = error instanceof Error ? error.message : 'Network error occurred';\n throw new WhatsAppNetworkError(message, error);\n }\n }\n\n // Unreachable in practice — loop always returns or throws.\n // Required for TypeScript return type inference.\n throw new WhatsAppThrottlingError(\n 'Max retry attempts exceeded',\n { message: 'Max retry attempts exceeded', type: 'ThrottlingError', code: 130429, fbtrace_id: '' },\n 429,\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 updateTimeout(timeout: number): void {\n LOGGER.log(`Timeout updated to ${timeout}ms`);\n }\n\n updateAccessToken(accessToken: string): void {\n (this as { accessToken: string }).accessToken = accessToken;\n LOGGER.log('Access token updated');\n }\n\n async sendUrlEncodedForm<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n formData: UrlEncodedFormBody,\n additionalHeaders?: Record<string, string>,\n ): Promise<T> {\n const urlParams = new URLSearchParams();\n for (const [key, value] of Object.entries(formData)) {\n if (Array.isArray(value)) {\n for (const item of value) {\n urlParams.append(key, item);\n }\n } else {\n urlParams.append(key, value);\n }\n }\n\n const urlEncodedBody = urlParams.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 { readEnv } from './runtime';\n\nexport function printLogo() {\n // Skip logo output in test environment\n if (\n readEnv('NODE_ENV') === 'test' ||\n readEnv('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 { describeRuntime } from './runtime';\n\n/**\n * SDK version, replaced with the package.json version at build time\n * (see `define` in tsdown.config.ts and vitest.config.ts).\n */\ndeclare const __SDK_VERSION__: string;\n\n/**\n * Get SDK version from package.json\n */\nexport function getVersion(): string {\n return typeof __SDK_VERSION__ === 'string' ? __SDK_VERSION__ : 'unknown';\n}\n\n/**\n * Generate User-Agent string following official SDK pattern\n */\nexport function getUserAgent(): string {\n return `WhatsApp-Nodejs-SDK/${getVersion()} (${describeRuntime()})`;\n}\n","import {\n BlockUsersApi,\n BusinessApi,\n BusinessProfileApi,\n CallingApi,\n CommerceApi,\n ContactBookApi,\n EncryptionApi,\n FlowApi,\n GroupsApi,\n MarketingMessagesApi,\n MediaApi,\n MessageApi,\n MessageHistoryApi,\n PaymentsApi,\n PhoneNumberApi,\n QrCodeApi,\n RegistrationApi,\n SolutionsApi,\n TemplateApi,\n ThreadControlApi,\n TwoStepVerificationApi,\n WabaApi,\n} from '../../api';\nimport { importConfig } from '../../config/importConfig';\nimport type { WabaConfigType, WhatsAppConfig } from '../../types/config';\nimport * as SDKEnums from '../../types/enums';\nimport { formatConfigTable } from '../../utils/configTable';\nimport { type EncryptionKeyPair, generateEncryption } from '../../utils/flowEncryptionUtils';\nimport Requester from '../../utils/http/request';\nimport Logger from '../../utils/logger';\nimport { printLogo } from '../../utils/logoConsole';\nimport type { RateLimitInfo } from '../../utils/rateLimit';\nimport { isDebugEnv } from '../../utils/runtime';\nimport { getUserAgent, getVersion } from '../../utils/version';\n\nconst LIB_NAME = 'WHATSAPP';\nconst LOGGER = new Logger(LIB_NAME, isDebugEnv());\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 blockUsers: BlockUsersApi;\n business: BusinessApi;\n calling: CallingApi;\n commerce: CommerceApi;\n contactBook: ContactBookApi;\n groups: GroupsApi;\n marketingMessages: MarketingMessagesApi;\n messageHistory: MessageHistoryApi;\n messages: MessageApi;\n media: MediaApi;\n payments: PaymentsApi;\n phoneNumbers: PhoneNumberApi;\n solutions: SolutionsApi;\n threadControl: ThreadControlApi;\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 this.config.retry,\n this.config.onRateLimitInfo,\n );\n\n this.blockUsers = new BlockUsersApi(this.config, this.requester);\n this.business = new BusinessApi(this.config, this.requester);\n this.calling = new CallingApi(this.config, this.requester);\n this.commerce = new CommerceApi(this.config, this.requester);\n this.contactBook = new ContactBookApi(this.config, this.requester);\n this.groups = new GroupsApi(this.config, this.requester);\n this.marketingMessages = new MarketingMessagesApi(this.config, this.requester);\n this.messageHistory = new MessageHistoryApi(this.config, this.requester);\n this.messages = new MessageApi(this.config, this.requester);\n this.media = new MediaApi(this.config, this.requester);\n this.payments = new PaymentsApi(this.config, this.requester);\n this.phoneNumbers = new PhoneNumberApi(this.config, this.requester);\n this.solutions = new SolutionsApi(this.config, this.requester);\n this.threadControl = new ThreadControlApi(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 this.requester.updateTimeout(timeout);\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 this.requester.updateAccessToken(accessToken);\n LOGGER.log('Access token updated');\n }\n\n /**\n * Rate limit headers (`X-App-Usage`, `X-Business-Use-Case-Usage`, `Retry-After`) of the most\n * recent response that carried any, or undefined before the first such response. With\n * concurrent requests this reflects whichever finished last; pass `onRateLimitInfo` in the\n * config to observe every response.\n */\n getLastRateLimitInfo(): RateLimitInfo | undefined {\n return this.requester.getLastRateLimitInfo();\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 /**\n * Generate RSA encryption key pair for WhatsApp Business Flow API\n *\n * This method generates a 2048-bit RSA key pair with:\n * - Public key in SPKI format (PEM)\n * - Private key in PKCS#8 format (PEM) encrypted with AES-256-CBC\n *\n * @param passphrase - Optional passphrase to encrypt the private key. If not provided, uses FLOW_API_PASSPHRASE from config\n * @returns Object containing passphrase, privateKey, and publicKey\n * @throws {Error} If passphrase is empty or key generation fails\n * @throws {Error} If not running in Node.js environment\n *\n * @see https://developers.facebook.com/docs/whatsapp/cloud-api/reference/whatsapp-business-encryption/\n *\n * @example\n * ```typescript\n * const wa = new WhatsApp();\n *\n * // Uses FLOW_API_PASSPHRASE from environment/config\n * const keys = wa.generateEncryption();\n *\n * // Or provide custom passphrase\n * const customKeys = wa.generateEncryption('my-secret-passphrase');\n *\n * console.log('Public Key:', keys.publicKey);\n * console.log('Private Key:', keys.privateKey);\n * ```\n */\n generateEncryption(passphrase?: string): EncryptionKeyPair {\n // If no passphrase provided, try to use from config\n const effectivePassphrase = passphrase || this.config[SDKEnums.WabaConfigEnum.Passphrase];\n return generateEncryption(effectivePassphrase);\n }\n}\n","import type { DedupeStore, WebhookDedupeConfig } from '../../types/config';\n\n/** Default time a dedupe key is remembered: 24 hours. */\nexport const DEFAULT_DEDUPE_TTL_SECONDS = 86_400;\n\n/** Default number of keys kept by {@link MemoryDedupeStore}. */\nexport const DEFAULT_MEMORY_DEDUPE_MAX_ENTRIES = 10_000;\n\nexport interface MemoryDedupeStoreOptions {\n /** Most keys kept at once; the least recently seen key is dropped first. Defaults to 10,000. */\n maxEntries?: number;\n}\n\n/**\n * Bounded in-memory {@link DedupeStore} with per-key TTL and least recently\n * seen eviction. This is the default store for `dedupe`.\n *\n * Single instance only: it lives in this process's memory, so it does not see\n * deliveries handled by other instances and forgets everything on restart (and\n * on each cold start of a serverless function). Use a shared store such as\n * Redis when you run more than one instance.\n */\nexport class MemoryDedupeStore implements DedupeStore {\n private readonly maxEntries: number;\n /** key -> expiry time in ms. Map order doubles as recency order (oldest first). */\n private readonly entries = new Map<string, number>();\n\n constructor(options: MemoryDedupeStoreOptions = {}) {\n const maxEntries = options.maxEntries ?? DEFAULT_MEMORY_DEDUPE_MAX_ENTRIES;\n if (!Number.isInteger(maxEntries) || maxEntries < 1) {\n throw new Error(`MemoryDedupeStore maxEntries must be a positive integer, got ${maxEntries}`);\n }\n this.maxEntries = maxEntries;\n }\n\n async has(key: string): Promise<boolean> {\n return this.lookup(key, Date.now()) !== undefined;\n }\n\n async setIfAbsent(key: string, ttlSeconds: number): Promise<boolean> {\n const now = Date.now();\n const expiresAt = this.lookup(key, now);\n if (expiresAt !== undefined) {\n // Mark as recently seen without extending the TTL.\n this.entries.delete(key);\n this.entries.set(key, expiresAt);\n return false;\n }\n this.entries.set(key, now + ttlSeconds * 1000);\n this.evict(now);\n return true;\n }\n\n /** Number of keys currently held (expired keys may still be counted until evicted). */\n get size(): number {\n return this.entries.size;\n }\n\n /** Forget every key. */\n clear(): void {\n this.entries.clear();\n }\n\n private lookup(key: string, now: number): number | undefined {\n const expiresAt = this.entries.get(key);\n if (expiresAt === undefined) return undefined;\n if (expiresAt <= now) {\n this.entries.delete(key);\n return undefined;\n }\n return expiresAt;\n }\n\n private evict(now: number): void {\n // Recency changes on duplicate deliveries without extending TTL, so\n // expiry order can differ from Map order. Reclaim expired keys first.\n for (const [key, expiresAt] of this.entries) {\n if (expiresAt <= now) this.entries.delete(key);\n }\n for (const key of this.entries.keys()) {\n if (this.entries.size <= this.maxEntries) break;\n this.entries.delete(key);\n }\n }\n}\n\n/** Dedupe settings after defaults are applied. */\nexport type ResolvedDedupe = {\n store: DedupeStore;\n ttlSeconds: number;\n};\n\n/** Apply defaults to the `dedupe` config option. Returns undefined when dedupe is off. */\nexport function resolveDedupe(config: boolean | WebhookDedupeConfig | undefined): ResolvedDedupe | undefined {\n if (!config) return undefined;\n const options = config === true ? {} : config;\n const ttlSeconds = options.ttlSeconds ?? DEFAULT_DEDUPE_TTL_SECONDS;\n if (!Number.isFinite(ttlSeconds) || ttlSeconds <= 0) {\n throw new Error(`dedupe.ttlSeconds must be a positive number, got ${ttlSeconds}`);\n }\n return { store: options.store ?? new MemoryDedupeStore(), ttlSeconds };\n}\n","import {\n FlowActionEnum,\n type FlowDataExchangeRequest,\n type FlowEndpointRequest,\n type FlowErrorNotificationRequest,\n type 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 type { FlowEndpointRequest } from '../../../api/flow';\nimport { FlowTypeEnum } from '../../../api/flow/types';\nimport type { DedupeStore, WabaConfigType } from '../../../types/config';\nimport { MessageTypesEnum, WabaConfigEnum } from '../../../types/enums';\nimport { decryptFlowRequestAsync, encryptFlowResponseAsync } from '../../../utils/flowEncryptionUtils';\nimport { isFlowDataExchangeRequest, isFlowErrorRequest, isFlowPingRequest } from '../../../utils/flowTypeGuards';\nimport Logger from '../../../utils/logger';\nimport { hmacSha256Hex, isDebugEnv, requireNodeCrypto, timingSafeEqualString } from '../../../utils/runtime';\nimport type WhatsApp from '../../whatsapp/WhatsApp';\nimport { DEFAULT_DEDUPE_TTL_SECONDS } from '../dedupe';\nimport type {\n ConversationContext,\n MessageWebhookValue,\n NonMessageWebhookField,\n StatusWebhook,\n StatusWebhookValue,\n UserAction,\n UserActionsWebhookValue,\n WebhookFieldType,\n WebhookFieldValueMap,\n WebhookPayload,\n WebhookValue,\n WhatsAppMessage,\n} from '../types';\n\nconst LIB_NAME = 'WEBHOOK_UTILS';\nconst LOGGER = new Logger(LIB_NAME, isDebugEnv());\n\n/**\n * Processed message with metadata for handlers\n */\nexport type ProcessedMessage = {\n wabaId: string;\n phoneNumberId: string;\n displayPhoneNumber: string;\n profileName: string;\n message: WhatsAppMessage;\n /**\n * The message ID extracted from the appropriate location based on message type.\n * For most messages, this comes from message.id\n * For certain types like nfm_reply, this comes from message.context.id\n */\n messageId: string;\n /**\n * AI-generated conversation summary from `value.conversation_context`, present\n * under Conversation Routing when a thread is assigned to you without standby\n * history. Optional; never parse `summary.text`.\n */\n conversationContext?: ConversationContext;\n};\n\n/**\n * Processed status with metadata for handlers\n */\nexport type ProcessedStatus = {\n wabaId: string;\n phoneNumberId: string;\n displayPhoneNumber: string;\n status: StatusWebhook;\n};\n\n/**\n * Processed marketing message user action (link click or landing page view)\n * delivered as `user_actions` on the `messages` field. Marketing Messages API\n * for WhatsApp only. Branch on `action.action_type` and ignore unknown values.\n */\nexport type ProcessedUserAction = {\n wabaId: string;\n phoneNumberId: string;\n displayPhoneNumber: string;\n action: UserAction;\n};\n\n/**\n * What a handler for a non-`messages` webhook field receives: the WhatsApp\n * Business Account id and the change's `value`, typed by field name.\n */\nexport type ProcessedWebhookField<F extends NonMessageWebhookField> = {\n wabaId: string;\n value: WebhookFieldValueMap[F];\n};\n\n/**\n * Processed webhook field types for specialized handlers\n */\nexport type ProcessedAccountUpdate = ProcessedWebhookField<'account_update'>;\nexport type ProcessedAccountReviewUpdate = ProcessedWebhookField<'account_review_update'>;\nexport type ProcessedAccountAlerts = ProcessedWebhookField<'account_alerts'>;\nexport type ProcessedBusinessCapabilityUpdate = ProcessedWebhookField<'business_capability_update'>;\nexport type ProcessedPhoneNumberNameUpdate = ProcessedWebhookField<'phone_number_name_update'>;\nexport type ProcessedPhoneNumberQualityUpdate = ProcessedWebhookField<'phone_number_quality_update'>;\nexport type ProcessedMessageTemplateStatusUpdate = ProcessedWebhookField<'message_template_status_update'>;\nexport type ProcessedTemplateCategoryUpdate = ProcessedWebhookField<'template_category_update'>;\nexport type ProcessedMessageTemplateQualityUpdate = ProcessedWebhookField<'message_template_quality_update'>;\nexport type ProcessedFlows = ProcessedWebhookField<'flows'>;\nexport type ProcessedSecurity = ProcessedWebhookField<'security'>;\nexport type ProcessedHistory = ProcessedWebhookField<'history'>;\nexport type ProcessedSmbMessageEchoes = ProcessedWebhookField<'smb_message_echoes'>;\nexport type ProcessedSmbAppStateSync = ProcessedWebhookField<'smb_app_state_sync'>;\nexport type ProcessedAccountSettingsUpdate = ProcessedWebhookField<'account_settings_update'>;\nexport type ProcessedAutomaticEvents = ProcessedWebhookField<'automatic_events'>;\nexport type ProcessedBusinessStatusUpdate = ProcessedWebhookField<'business_status_update'>;\nexport type ProcessedBusinessUsernameUpdates = ProcessedWebhookField<'business_username_updates'>;\nexport type ProcessedCalls = ProcessedWebhookField<'calls'>;\nexport type ProcessedGroupLifecycleUpdate = ProcessedWebhookField<'group_lifecycle_update'>;\nexport type ProcessedGroupParticipantsUpdate = ProcessedWebhookField<'group_participants_update'>;\nexport type ProcessedGroupSettingsUpdate = ProcessedWebhookField<'group_settings_update'>;\nexport type ProcessedGroupStatusUpdate = ProcessedWebhookField<'group_status_update'>;\nexport type ProcessedMessageEchoes = ProcessedWebhookField<'message_echoes'>;\nexport type ProcessedMessageTemplateComponentsUpdate = ProcessedWebhookField<'message_template_components_update'>;\nexport type ProcessedMessagingHandovers = ProcessedWebhookField<'messaging_handovers'>;\nexport type ProcessedPartnerSolutions = ProcessedWebhookField<'partner_solutions'>;\nexport type ProcessedPaymentConfigurationUpdate = ProcessedWebhookField<'payment_configuration_update'>;\nexport type ProcessedStandby = ProcessedWebhookField<'standby'>;\nexport type ProcessedTemplateCorrectCategoryDetection = ProcessedWebhookField<'template_correct_category_detection'>;\nexport type ProcessedTrackingEvents = ProcessedWebhookField<'tracking_events'>;\nexport type ProcessedUserPreferences = ProcessedWebhookField<'user_preferences'>;\n\n// Type-specific processed messages for specialized handlers\nexport type TextProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Text }>;\n};\n\nexport type ImageProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Image }>;\n};\n\nexport type VideoProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Video }>;\n};\n\nexport type AudioProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Audio }>;\n};\n\nexport type DocumentProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Document }>;\n};\n\nexport type StickerProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Sticker }>;\n};\n\nexport type InteractiveProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Interactive }>;\n};\n\nexport type ButtonProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Button }>;\n};\n\nexport type LocationProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Location }>;\n};\n\nexport type ContactsProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Contacts }>;\n};\n\nexport type ReactionProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Reaction }>;\n};\n\nexport type OrderProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.Order }>;\n};\n\nexport type SystemProcessedMessage = ProcessedMessage & {\n message: Extract<WhatsAppMessage, { type: MessageTypesEnum.System }>;\n};\n\n/**\n * Original HTTP request context for WhatsApp webhook handlers.\n *\n * The `rawBody` and `headers` values preserve the incoming webhook request so\n * callers can forward or verify the request according to Meta's request syntax.\n *\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/create-webhook-endpoint/#request-syntax-1\n */\nexport type WebhookHandlerContext = {\n /** Original request headers from the incoming webhook request. */\n headers: Headers;\n /** Original request body string before JSON parsing or field filtering. */\n rawBody: string;\n /** Original request method. */\n method: string;\n /** Original request URL. */\n url: string;\n};\n\ntype WebhookHandler<TProcessed, TReturn = void> = (\n whatsapp: WhatsApp,\n processed: TProcessed,\n context: WebhookHandlerContext,\n) => TReturn | Promise<TReturn>;\n\nexport type MessageHandler = WebhookHandler<ProcessedMessage>;\nexport type StatusHandler = WebhookHandler<ProcessedStatus>;\nexport type UserActionHandler = WebhookHandler<ProcessedUserAction>;\nexport type FlowHandler = WebhookHandler<FlowEndpointRequest, any>;\nexport type RawWebhookHandler = WebhookHandler<WebhookPayload>;\n\n/** Handler for a non-`messages` webhook field; `processed.value` is typed by the field name. */\nexport type WebhookFieldHandler<F extends NonMessageWebhookField> = WebhookHandler<ProcessedWebhookField<F>>;\n\n/** Registered field handlers keyed by field name, as kept by `WebhookProcessor`. */\nexport type WebhookFieldHandlerMap = ReadonlyMap<NonMessageWebhookField, AnyWebhookFieldHandler>;\n\n/**\n * Field handler with the field type erased, for storage in a map. `on()`\n * guarantees each stored handler matches its key.\n */\n// biome-ignore lint/suspicious/noExplicitAny: the value type depends on the map key\ntype AnyWebhookFieldHandler = WebhookHandler<{ wabaId: string; value: any }>;\n\n// Webhook field handlers\nexport type AccountUpdateHandler = WebhookFieldHandler<'account_update'>;\nexport type AccountReviewUpdateHandler = WebhookFieldHandler<'account_review_update'>;\nexport type AccountAlertsHandler = WebhookFieldHandler<'account_alerts'>;\nexport type BusinessCapabilityUpdateHandler = WebhookFieldHandler<'business_capability_update'>;\nexport type PhoneNumberNameUpdateHandler = WebhookFieldHandler<'phone_number_name_update'>;\nexport type PhoneNumberQualityUpdateHandler = WebhookFieldHandler<'phone_number_quality_update'>;\nexport type MessageTemplateStatusUpdateHandler = WebhookFieldHandler<'message_template_status_update'>;\nexport type TemplateCategoryUpdateHandler = WebhookFieldHandler<'template_category_update'>;\nexport type MessageTemplateQualityUpdateHandler = WebhookFieldHandler<'message_template_quality_update'>;\nexport type FlowsHandler = WebhookFieldHandler<'flows'>;\nexport type SecurityHandler = WebhookFieldHandler<'security'>;\nexport type HistoryHandler = WebhookFieldHandler<'history'>;\nexport type SmbMessageEchoesHandler = WebhookFieldHandler<'smb_message_echoes'>;\nexport type SmbAppStateSyncHandler = WebhookFieldHandler<'smb_app_state_sync'>;\nexport type AccountSettingsUpdateHandler = WebhookFieldHandler<'account_settings_update'>;\nexport type AutomaticEventsHandler = WebhookFieldHandler<'automatic_events'>;\nexport type BusinessStatusUpdateHandler = WebhookFieldHandler<'business_status_update'>;\nexport type BusinessUsernameUpdatesHandler = WebhookFieldHandler<'business_username_updates'>;\nexport type CallsHandler = WebhookFieldHandler<'calls'>;\nexport type GroupLifecycleUpdateHandler = WebhookFieldHandler<'group_lifecycle_update'>;\nexport type GroupParticipantsUpdateHandler = WebhookFieldHandler<'group_participants_update'>;\nexport type GroupSettingsUpdateHandler = WebhookFieldHandler<'group_settings_update'>;\nexport type GroupStatusUpdateHandler = WebhookFieldHandler<'group_status_update'>;\nexport type MessageEchoesHandler = WebhookFieldHandler<'message_echoes'>;\nexport type MessageTemplateComponentsUpdateHandler = WebhookFieldHandler<'message_template_components_update'>;\nexport type MessagingHandoversHandler = WebhookFieldHandler<'messaging_handovers'>;\nexport type PartnerSolutionsHandler = WebhookFieldHandler<'partner_solutions'>;\nexport type PaymentConfigurationUpdateHandler = WebhookFieldHandler<'payment_configuration_update'>;\nexport type StandbyHandler = WebhookFieldHandler<'standby'>;\nexport type TemplateCorrectCategoryDetectionHandler = WebhookFieldHandler<'template_correct_category_detection'>;\nexport type TrackingEventsHandler = WebhookFieldHandler<'tracking_events'>;\nexport type UserPreferencesHandler = WebhookFieldHandler<'user_preferences'>;\n\n// Type-specific handlers for specialized methods\nexport type TextMessageHandler = WebhookHandler<TextProcessedMessage>;\nexport type ImageMessageHandler = WebhookHandler<ImageProcessedMessage>;\nexport type VideoMessageHandler = WebhookHandler<VideoProcessedMessage>;\nexport type AudioMessageHandler = WebhookHandler<AudioProcessedMessage>;\nexport type DocumentMessageHandler = WebhookHandler<DocumentProcessedMessage>;\nexport type StickerMessageHandler = WebhookHandler<StickerProcessedMessage>;\nexport type InteractiveMessageHandler = WebhookHandler<InteractiveProcessedMessage>;\nexport type ButtonMessageHandler = WebhookHandler<ButtonProcessedMessage>;\nexport type LocationMessageHandler = WebhookHandler<LocationProcessedMessage>;\nexport type ContactsMessageHandler = WebhookHandler<ContactsProcessedMessage>;\nexport type ReactionMessageHandler = WebhookHandler<ReactionProcessedMessage>;\nexport type OrderMessageHandler = WebhookHandler<OrderProcessedMessage>;\nexport type SystemMessageHandler = WebhookHandler<SystemProcessedMessage>;\n\n/**\n * Named handler options accepted by {@link processWebhookMessages}, one per\n * webhook field except `messages`. Kept for backward compatibility; new code\n * can pass `fieldHandlers` instead.\n */\nexport type WebhookFieldHandlerOptions = {\n accountUpdateHandler?: AccountUpdateHandler;\n accountReviewUpdateHandler?: AccountReviewUpdateHandler;\n accountAlertsHandler?: AccountAlertsHandler;\n businessCapabilityUpdateHandler?: BusinessCapabilityUpdateHandler;\n phoneNumberNameUpdateHandler?: PhoneNumberNameUpdateHandler;\n phoneNumberQualityUpdateHandler?: PhoneNumberQualityUpdateHandler;\n messageTemplateStatusUpdateHandler?: MessageTemplateStatusUpdateHandler;\n templateCategoryUpdateHandler?: TemplateCategoryUpdateHandler;\n messageTemplateQualityUpdateHandler?: MessageTemplateQualityUpdateHandler;\n flowsHandler?: FlowsHandler;\n securityHandler?: SecurityHandler;\n historyHandler?: HistoryHandler;\n smbMessageEchoesHandler?: SmbMessageEchoesHandler;\n smbAppStateSyncHandler?: SmbAppStateSyncHandler;\n accountSettingsUpdateHandler?: AccountSettingsUpdateHandler;\n automaticEventsHandler?: AutomaticEventsHandler;\n businessStatusUpdateHandler?: BusinessStatusUpdateHandler;\n businessUsernameUpdatesHandler?: BusinessUsernameUpdatesHandler;\n callsHandler?: CallsHandler;\n groupLifecycleUpdateHandler?: GroupLifecycleUpdateHandler;\n groupParticipantsUpdateHandler?: GroupParticipantsUpdateHandler;\n groupSettingsUpdateHandler?: GroupSettingsUpdateHandler;\n groupStatusUpdateHandler?: GroupStatusUpdateHandler;\n messageEchoesHandler?: MessageEchoesHandler;\n messageTemplateComponentsUpdateHandler?: MessageTemplateComponentsUpdateHandler;\n messagingHandoversHandler?: MessagingHandoversHandler;\n partnerSolutionsHandler?: PartnerSolutionsHandler;\n paymentConfigurationUpdateHandler?: PaymentConfigurationUpdateHandler;\n standbyHandler?: StandbyHandler;\n templateCorrectCategoryDetectionHandler?: TemplateCorrectCategoryDetectionHandler;\n trackingEventsHandler?: TrackingEventsHandler;\n userPreferencesHandler?: UserPreferencesHandler;\n};\n\n/** The {@link WebhookFieldHandlerOptions} key whose handler type matches field `F`. */\ntype HandlerOptionKeyFor<F extends NonMessageWebhookField> = {\n [K in keyof WebhookFieldHandlerOptions]-?: NonNullable<WebhookFieldHandlerOptions[K]> extends WebhookFieldHandler<F>\n ? K\n : never;\n}[keyof WebhookFieldHandlerOptions];\n\n/**\n * Registry of every webhook field except `messages`, mapping each field to its\n * named handler option. Dispatch is driven by this table: a field listed here\n * is routed to its handler, anything else is logged as unhandled. Adding a\n * field to `WebhookFieldValueMap` without an entry here fails type checking.\n */\nexport const WEBHOOK_FIELD_REGISTRY = {\n account_update: 'accountUpdateHandler',\n account_review_update: 'accountReviewUpdateHandler',\n account_alerts: 'accountAlertsHandler',\n account_settings_update: 'accountSettingsUpdateHandler',\n automatic_events: 'automaticEventsHandler',\n business_capability_update: 'businessCapabilityUpdateHandler',\n business_status_update: 'businessStatusUpdateHandler',\n business_username_updates: 'businessUsernameUpdatesHandler',\n calls: 'callsHandler',\n flows: 'flowsHandler',\n group_lifecycle_update: 'groupLifecycleUpdateHandler',\n group_participants_update: 'groupParticipantsUpdateHandler',\n group_settings_update: 'groupSettingsUpdateHandler',\n group_status_update: 'groupStatusUpdateHandler',\n history: 'historyHandler',\n message_echoes: 'messageEchoesHandler',\n message_template_components_update: 'messageTemplateComponentsUpdateHandler',\n message_template_quality_update: 'messageTemplateQualityUpdateHandler',\n message_template_status_update: 'messageTemplateStatusUpdateHandler',\n messaging_handovers: 'messagingHandoversHandler',\n partner_solutions: 'partnerSolutionsHandler',\n payment_configuration_update: 'paymentConfigurationUpdateHandler',\n phone_number_name_update: 'phoneNumberNameUpdateHandler',\n phone_number_quality_update: 'phoneNumberQualityUpdateHandler',\n security: 'securityHandler',\n smb_app_state_sync: 'smbAppStateSyncHandler',\n smb_message_echoes: 'smbMessageEchoesHandler',\n standby: 'standbyHandler',\n template_category_update: 'templateCategoryUpdateHandler',\n template_correct_category_detection: 'templateCorrectCategoryDetectionHandler',\n tracking_events: 'trackingEventsHandler',\n user_preferences: 'userPreferencesHandler',\n} as const satisfies { [F in NonMessageWebhookField]: HandlerOptionKeyFor<F> };\n\n/** True when `field` is a webhook field other than `messages` that the SDK knows. */\nexport function isNonMessageWebhookField(field: string): field is NonMessageWebhookField {\n return Object.hasOwn(WEBHOOK_FIELD_REGISTRY, field);\n}\n\n/**\n * Dedupe keys for non-`messages` fields that carry a natural id. Fields not\n * listed here are never deduped. A change is a duplicate only when its whole\n * set of ids was seen before.\n */\nconst FIELD_DEDUPE_KEYS: { [F in NonMessageWebhookField]?: (value: WebhookFieldValueMap[F]) => string | undefined } = {\n calls: (value) =>\n joinDedupeIds(\n 'calls',\n mapArray(value?.calls, (call) =>\n call?.id ? `${call.id}:${call.event}${call.call_status ? `:${call.call_status}` : ''}` : undefined,\n ),\n ),\n smb_message_echoes: (value) =>\n joinDedupeIds(\n 'smb_message_echoes',\n mapArray(value?.message_echoes, (echo) => echo?.id),\n ),\n message_echoes: (value) =>\n joinDedupeIds(\n 'message_echoes',\n mapArray(value?.messaging, (entry) => entry?.message?.mid),\n ),\n};\n\nfunction mapArray<T>(\n items: T[] | undefined,\n fn: (item: T) => string | undefined,\n): Array<string | undefined> | undefined {\n return Array.isArray(items) ? items.map(fn) : undefined;\n}\n\nfunction joinDedupeIds(prefix: string, ids: Array<string | undefined> | undefined): string | undefined {\n if (!ids || ids.length === 0 || ids.some((id) => !id)) return undefined;\n return `${prefix}:${ids.join(',')}`;\n}\n\n/** Dedupe key for one change of a non-`messages` field, or undefined when it has no natural id. */\nexport function getWebhookFieldDedupeKey<F extends NonMessageWebhookField>(\n field: F,\n value: WebhookFieldValueMap[F],\n): string | undefined {\n const keyFn = FIELD_DEDUPE_KEYS[field] as ((value: WebhookFieldValueMap[F]) => string | undefined) | undefined;\n return keyFn?.(value);\n}\n\n/** Dedupe settings for {@link processWebhookMessages}. */\nexport type WebhookDedupeOptions = {\n store: DedupeStore;\n /** Defaults to 86400 (24 hours). */\n ttlSeconds?: number;\n};\n\n/** Options for {@link processWebhookMessages}. */\nexport type ProcessWebhookOptions = WebhookSignatureOptions & {\n /** Skip handlers for deliveries already seen. Duplicates still get a 200 response. */\n dedupe?: WebhookDedupeOptions;\n};\n\ntype ResolvedDedupeOptions = { store: DedupeStore; ttlSeconds: number };\n\n/**\n * Claim a dedupe key. Resolves true when the delivery was already seen.\n * Store errors fail open: the delivery is processed and the error is logged.\n */\nasync function isDuplicateDelivery(\n dedupe: ResolvedDedupeOptions | undefined,\n key: string | undefined,\n): Promise<boolean> {\n if (!dedupe || !key) return false;\n try {\n const stored = await dedupe.store.setIfAbsent(key, dedupe.ttlSeconds);\n if (!stored) {\n LOGGER.log(`Skipping duplicate webhook delivery: ${key}`);\n return true;\n }\n return false;\n } catch (error) {\n LOGGER.error('Dedupe store failed; processing the webhook anyway:', { key, error });\n return false;\n }\n}\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 statusHandler?: StatusHandler;\n userActionHandler?: UserActionHandler;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n rawHandler?: RawWebhookHandler;\n rawHandlerFields?: WebhookFieldType[];\n /**\n * Handlers for non-`messages` fields keyed by field name. Takes\n * precedence over the named `xxxHandler` option for the same field.\n */\n fieldHandlers?: WebhookFieldHandlerMap;\n } & WebhookFieldHandlerOptions,\n options: ProcessWebhookOptions = {},\n): Promise<Response> {\n try {\n const rawBody = await request.text();\n\n if (options.verifySignature) {\n if (!options.appSecret) {\n LOGGER.error('verifyWebhookSignature is on but appSecret is not configured; rejecting webhook');\n return new Response(JSON.stringify({ error: 'Webhook signature verification misconfigured' }), {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n if (\n !(await verifyWebhookSignature(rawBody, request.headers.get('x-hub-signature-256'), options.appSecret))\n ) {\n LOGGER.warn('Rejected webhook with missing or invalid X-Hub-Signature-256');\n return new Response(JSON.stringify({ error: 'Invalid signature' }), {\n status: 401,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n }\n\n const body = JSON.parse(rawBody);\n const context: WebhookHandlerContext = {\n headers: request.headers,\n rawBody,\n method: request.method,\n url: request.url,\n };\n const dedupe: ResolvedDedupeOptions | undefined = options.dedupe\n ? { store: options.dedupe.store, ttlSeconds: options.dedupe.ttlSeconds ?? DEFAULT_DEDUPE_TTL_SECONDS }\n : undefined;\n\n if (handlers.rawHandler) {\n const { rawHandler, rawHandlerFields } = handlers;\n let payload = body as WebhookPayload;\n if (rawHandlerFields && rawHandlerFields.length > 0) {\n const filtered: WebhookPayload = {\n ...payload,\n entry: payload.entry\n .map((entry) => ({\n ...entry,\n changes: entry.changes.filter((change) =>\n rawHandlerFields.includes(change.field as WebhookFieldType),\n ),\n }))\n .filter((entry) => entry.changes.length > 0),\n };\n if (filtered.entry.length === 0) {\n payload = null as any;\n } else {\n payload = filtered;\n }\n }\n if (payload) {\n await rawHandler(whatsapp, payload, context);\n }\n }\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);\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 const changes = entry.changes;\n for (const change of changes) {\n const field: string = change.field;\n if (field === 'messages') {\n await processMessages(entry.id, change.value, whatsapp, handlers, context, dedupe);\n } else if (isNonMessageWebhookField(field)) {\n const handler =\n handlers.fieldHandlers?.get(field) ??\n (handlers[WEBHOOK_FIELD_REGISTRY[field]] as AnyWebhookFieldHandler | undefined);\n await processWebhookField(\n entry.id,\n { field, value: change.value },\n handler,\n whatsapp,\n context,\n dedupe,\n );\n } else {\n LOGGER.warn(`Unhandled webhook field: ${change.field}`);\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 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 * Create a standard ping response for WhatsApp Flow health checks\n * @returns Flow ping response object\n */\nexport function createFlowPingResponse() {\n return {\n version: '3.0',\n data: { status: 'active' },\n };\n}\n\n/**\n * Create a standard error response for WhatsApp Flow error notifications\n * @returns Acknowledgement response for error notification\n */\nexport function createFlowErrorResponse() {\n return {\n data: {\n acknowledged: true,\n },\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 const body = await request.text();\n const context: WebhookHandlerContext = {\n headers: request.headers,\n rawBody: body,\n method: request.method,\n url: request.url,\n };\n const signature = request.headers.get('x-hub-signature-256');\n\n // Meta signs Flow requests with the App Secret. Older versions of this SDK\n // keyed the HMAC with the webhook verification token, which never matches\n // a real Meta request; that key is kept only as a fallback when no App\n // Secret is configured.\n const signingKey = config[WabaConfigEnum.AppSecret] || config.WEBHOOK_VERIFICATION_TOKEN || '';\n if (!config[WabaConfigEnum.AppSecret]) {\n LOGGER.warn('appSecret not configured; verifying Flow signature with the webhook verification token');\n }\n if (!(await verifyWebhookSignature(body, signature, signingKey))) {\n LOGGER.warn('Invalid request signature');\n return new Response(JSON.stringify({ error: 'Unauthorized' }), { status: 401 });\n }\n\n const data = JSON.parse(body);\n\n // Decrypt the request and get decrypted AES key and IV\n const { decryptedBody, aesKeyBuffer, initialVectorBuffer } = await decryptFlowRequestAsync(data, config);\n\n // Determine flow type\n const isPing = isFlowPingRequest(decryptedBody);\n const isError = isFlowErrorRequest(decryptedBody);\n const isDataExchange = isFlowDataExchangeRequest(decryptedBody);\n\n let flowType: FlowTypeEnum;\n if (isPing) {\n flowType = FlowTypeEnum.Ping;\n } else if (isError) {\n flowType = FlowTypeEnum.Error;\n } else if (isDataExchange) {\n flowType = FlowTypeEnum.Change;\n } else {\n flowType = FlowTypeEnum.All;\n }\n\n // Get the flow handler based on type\n let handler = flowHandlers.get(flowType);\n\n // For Ping and Error, use default handlers if not registered\n if (!handler) {\n if (flowType === FlowTypeEnum.Ping) {\n handler = () => createFlowPingResponse();\n } else if (flowType === FlowTypeEnum.Error) {\n handler = () => createFlowErrorResponse();\n } else {\n // For Change and other types, try All handler as fallback\n handler = flowHandlers.get(FlowTypeEnum.All);\n if (!handler) {\n LOGGER.warn('No handler registered for flow type:', { flowType, action: decryptedBody.action });\n return new Response(JSON.stringify({ error: 'Handler not found' }), { status: 404 });\n }\n }\n }\n\n // Call the user's handler for the flow type\n const result = await handler(whatsapp, decryptedBody, context);\n\n // Return response based on flow type\n if (isError) {\n LOGGER.warn('Flow error notification received', { error: decryptedBody.data });\n\n // If user handler didn't return a response, use default acknowledgement\n const errorResponse = result || createFlowErrorResponse();\n\n return new Response(JSON.stringify(errorResponse), {\n status: 200,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n // Both ping and data_exchange responses need to be encrypted\n if (isPing || isDataExchange) {\n // Encrypt the response using decrypted AES key and IV\n const encryptedResponse = await encryptFlowResponseAsync(result, aesKeyBuffer, initialVectorBuffer);\n\n // Meta expects the encrypted response as a plain base64 string (not wrapped in JSON)\n return new Response(encryptedResponse, {\n status: 200,\n headers: { 'Content-Type': 'text/plain' },\n });\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\nexport type WebhookSignatureOptions = {\n /** Meta App Secret used as the HMAC key. */\n appSecret?: string;\n /** When true, reject requests without a valid `X-Hub-Signature-256`. */\n verifySignature?: boolean;\n};\n\n/**\n * Check an `X-Hub-Signature-256` header (`sha256=<hex>`) against the raw\n * request body using Web Crypto, so it works on every runtime. Constant-time;\n * resolves to false instead of throwing on malformed or wrong-length input.\n */\nexport async function verifyWebhookSignature(\n rawBody: string,\n signatureHeader: string | null,\n appSecret: string,\n): Promise<boolean> {\n if (!signatureHeader || !appSecret) return false;\n const provided = signatureHeader.startsWith('sha256=') ? signatureHeader.slice(7) : signatureHeader;\n const expected = await hmacSha256Hex(appSecret, rawBody);\n return timingSafeEqualString(provided.toLowerCase(), expected);\n}\n\n/**\n * Synchronous variant of {@link verifyWebhookSignature}. Needs `node:crypto`\n * (Node.js >= 20.12, Bun, Deno); prefer the async variant on edge runtimes.\n */\nexport function isValidWebhookSignature(rawBody: string, signatureHeader: string | null, appSecret: string): boolean {\n if (!signatureHeader || !appSecret) return false;\n const crypto = requireNodeCrypto('isValidWebhookSignature');\n const provided = signatureHeader.startsWith('sha256=') ? signatureHeader.slice(7) : signatureHeader;\n const expected = crypto.createHmac('sha256', appSecret).update(rawBody, 'utf8').digest('hex');\n return timingSafeEqualString(provided.toLowerCase(), expected);\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 * Extract message ID based on message type\n * Some message types (like nfm_reply) have ID in context instead of root level\n */\nfunction extractMessageId(message: WhatsAppMessage): string {\n // If message has id at root level, use it\n if (message.id) {\n return message.id;\n }\n\n // For interactive and button messages, check context.id\n if (message.type === MessageTypesEnum.Interactive || message.type === MessageTypesEnum.Button) {\n if ('context' in message && message.context?.id) {\n return message.context.id;\n }\n }\n\n // Fallback to empty string if no ID found\n return '';\n}\n\n/**\n * Private helper functions\n */\nasync function processMessages(\n waba_id: string,\n value: WebhookValue,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n statusHandler?: StatusHandler;\n userActionHandler?: UserActionHandler;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n context: WebhookHandlerContext,\n dedupe?: ResolvedDedupeOptions,\n): Promise<void> {\n const metadata = value.metadata;\n const wabaId = waba_id;\n const displayPhoneNumber = metadata.display_phone_number;\n const phoneNumberId = metadata.phone_number_id;\n\n // Handle marketing message user actions (link clicks, landing page views)\n if ('user_actions' in value && value.user_actions) {\n const userActionsValue = value as UserActionsWebhookValue;\n for (const action of userActionsValue.user_actions) {\n const processed: ProcessedUserAction = {\n wabaId,\n phoneNumberId,\n displayPhoneNumber,\n action,\n };\n\n await executeUserActionHandler(handlers.userActionHandler, whatsapp, processed, context);\n }\n return;\n }\n\n // Handle status webhooks\n if ('statuses' in value && value.statuses) {\n const statusValue = value as StatusWebhookValue;\n for (const status of statusValue.statuses) {\n if (!handlers.statusHandler) continue;\n if (await isDuplicateDelivery(dedupe, status.id ? `status:${status.id}:${status.status}` : undefined)) {\n continue;\n }\n const processed: ProcessedStatus = {\n wabaId,\n phoneNumberId,\n displayPhoneNumber,\n status,\n };\n\n await executeStatusHandler(handlers.statusHandler, whatsapp, processed, context);\n }\n return;\n }\n\n // Handle message webhooks\n if ('messages' in value && value.messages) {\n const messageValue = value as MessageWebhookValue;\n const profileName = messageValue.contacts?.[0]?.profile?.name || '';\n\n for (const message of messageValue.messages) {\n const processed: ProcessedMessage = {\n wabaId,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n message,\n messageId: extractMessageId(message),\n ...(messageValue.conversation_context && { conversationContext: messageValue.conversation_context }),\n };\n\n const messageType = message.type;\n const messageHandler = handlers.messageHandlers.get(messageType);\n if (!handlers.preProcessHandler && !messageHandler && !handlers.postProcessHandler) continue;\n if (await isDuplicateDelivery(dedupe, processed.messageId ? `message:${processed.messageId}` : undefined)) {\n continue;\n }\n\n // Execute handlers in sequence\n await executeMessageHandler(handlers.preProcessHandler, whatsapp, processed, context, 'pre-process');\n await executeMessageHandler(messageHandler, whatsapp, processed, context, messageType);\n await executeMessageHandler(handlers.postProcessHandler, whatsapp, processed, context, 'post-process');\n }\n }\n}\n\nasync function executeMessageHandler(\n handler: MessageHandler | undefined,\n whatsapp: WhatsApp,\n processed: ProcessedMessage,\n context: WebhookHandlerContext,\n handlerType: string,\n): Promise<void> {\n if (handler) {\n try {\n await handler(whatsapp, processed, context);\n } catch (error) {\n LOGGER.error(`Error in ${handlerType} handler:`, { error, messageId: processed.messageId });\n }\n }\n}\n\nasync function executeStatusHandler(\n handler: StatusHandler | undefined,\n whatsapp: WhatsApp,\n processed: ProcessedStatus,\n context: WebhookHandlerContext,\n): Promise<void> {\n if (handler) {\n try {\n await handler(whatsapp, processed, context);\n } catch (error) {\n LOGGER.error('Error in status handler:', { error, statusId: processed.status.id });\n }\n }\n}\n\nasync function executeUserActionHandler(\n handler: UserActionHandler | undefined,\n whatsapp: WhatsApp,\n processed: ProcessedUserAction,\n context: WebhookHandlerContext,\n): Promise<void> {\n if (handler) {\n try {\n await handler(whatsapp, processed, context);\n } catch (error) {\n LOGGER.error('Error in user action handler:', { error, actionType: processed.action.action_type });\n }\n }\n}\n\n/**\n * Generic webhook field processor\n * Processes webhook fields other than 'messages'\n */\nasync function processWebhookField<F extends NonMessageWebhookField>(\n wabaId: string,\n webhookValue: { field: F; value: WebhookFieldValueMap[F] },\n handler: WebhookFieldHandler<F> | AnyWebhookFieldHandler | undefined,\n whatsapp: WhatsApp,\n context: WebhookHandlerContext,\n dedupe?: ResolvedDedupeOptions,\n): Promise<void> {\n if (!handler) return;\n if (await isDuplicateDelivery(dedupe, getWebhookFieldDedupeKey(webhookValue.field, webhookValue.value))) return;\n try {\n await handler(\n whatsapp,\n {\n wabaId,\n value: webhookValue.value,\n },\n context,\n );\n } catch (error) {\n LOGGER.error(`Error in ${webhookValue.field} handler:`, { error, wabaId });\n }\n}\n","import type { FlowTypeEnum } from '../../api/flow/types';\nimport { importConfig } from '../../config/importConfig';\nimport type { WabaConfigType, WhatsAppConfig } from '../../types/config';\nimport { MessageTypesEnum, WabaConfigEnum } from '../../types/enums';\nimport Logger from '../../utils/logger';\nimport { isDebugEnv } from '../../utils/runtime';\nimport { WhatsApp } from '../whatsapp';\nimport { type ResolvedDedupe, resolveDedupe } from './dedupe';\nimport type { NonMessageWebhookField, WebhookFieldType } from './types';\nimport {\n type AccountAlertsHandler,\n type AccountReviewUpdateHandler,\n type AccountSettingsUpdateHandler,\n type AccountUpdateHandler,\n type AudioMessageHandler,\n type AutomaticEventsHandler,\n type BusinessCapabilityUpdateHandler,\n type BusinessStatusUpdateHandler,\n type BusinessUsernameUpdatesHandler,\n type ButtonMessageHandler,\n type CallsHandler,\n type ContactsMessageHandler,\n type DocumentMessageHandler,\n type FlowHandler,\n type FlowsHandler,\n type GroupLifecycleUpdateHandler,\n type GroupParticipantsUpdateHandler,\n type GroupSettingsUpdateHandler,\n type GroupStatusUpdateHandler,\n type HistoryHandler,\n type ImageMessageHandler,\n type InteractiveMessageHandler,\n isNonMessageWebhookField,\n type LocationMessageHandler,\n type MessageEchoesHandler,\n type MessageHandler,\n type MessageTemplateComponentsUpdateHandler,\n type MessageTemplateQualityUpdateHandler,\n type MessageTemplateStatusUpdateHandler,\n type MessagingHandoversHandler,\n type OrderMessageHandler,\n type PartnerSolutionsHandler,\n type PaymentConfigurationUpdateHandler,\n type PhoneNumberNameUpdateHandler,\n type PhoneNumberQualityUpdateHandler,\n processFlowRequest,\n processWebhookMessages,\n type RawWebhookHandler,\n type ReactionMessageHandler,\n type SecurityHandler,\n type SmbAppStateSyncHandler,\n type SmbMessageEchoesHandler,\n type StandbyHandler,\n type StatusHandler,\n type StickerMessageHandler,\n type SystemMessageHandler,\n type TemplateCategoryUpdateHandler,\n type TemplateCorrectCategoryDetectionHandler,\n type TextMessageHandler,\n type TrackingEventsHandler,\n type UserActionHandler,\n type UserPreferencesHandler,\n type VideoMessageHandler,\n type WebhookFieldHandler,\n} from './utils/webhookUtils';\n\nconst LOGGER = new Logger('WEBHOOK_PROCESSOR', isDebugEnv());\n\nfunction assertNonMessageField(field: string, method: 'on' | 'off'): void {\n if (field === 'messages') {\n throw new Error(\n `${method}('messages') is not supported. Use onMessage/onText/... for messages, ` +\n 'onStatus for statuses and onUserAction for marketing user actions.',\n );\n }\n if (!isNonMessageWebhookField(field)) {\n throw new Error(`${method}('${field}'): unknown webhook field`);\n }\n}\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 statusHandler: StatusHandler | undefined = undefined;\n private userActionHandler: UserActionHandler | undefined = undefined;\n private preProcessHandler: MessageHandler | undefined = undefined;\n private postProcessHandler: MessageHandler | undefined = undefined;\n private rawHandler: { handler: RawWebhookHandler; fields?: WebhookFieldType[] } | undefined = undefined;\n private flowHandlers: Map<FlowTypeEnum, FlowHandler> = new Map();\n\n /** Handlers for every webhook field except `messages`, keyed by field name. */\n private fieldHandlers: Map<NonMessageWebhookField, WebhookFieldHandler<NonMessageWebhookField>> = new Map();\n\n private verifySignature: boolean;\n private dedupe: ResolvedDedupe | undefined;\n\n constructor(config: WhatsAppConfig) {\n this.config = importConfig(config);\n this.verifySignature = config.verifyWebhookSignature === true;\n this.dedupe = resolveDedupe(config.dedupe);\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(\n request,\n this.client,\n {\n messageHandlers: this.messageHandlers,\n statusHandler: this.statusHandler,\n userActionHandler: this.userActionHandler,\n preProcessHandler: this.preProcessHandler,\n postProcessHandler: this.postProcessHandler,\n rawHandler: this.rawHandler?.handler,\n rawHandlerFields: this.rawHandler?.fields,\n fieldHandlers: this.fieldHandlers,\n },\n {\n appSecret: this.config[WabaConfigEnum.AppSecret],\n verifySignature: this.verifySignature,\n dedupe: this.dedupe,\n },\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') || 'text/plain';\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 | string, handler: MessageHandler): void {\n if (type === ('statuses' as MessageTypesEnum)) {\n throw new Error(\n 'MessageTypesEnum.Statuses is deprecated. Use onStatus(handler) instead of onMessage(MessageTypesEnum.Statuses, handler)',\n );\n }\n this.messageHandlers.set(type as MessageTypesEnum, handler);\n LOGGER.log(`Registered message handler for ${type}`);\n }\n\n onStatus(handler: StatusHandler): void {\n this.statusHandler = handler;\n LOGGER.log('Registered status handler');\n }\n\n /**\n * Register a handler for marketing message user actions delivered as\n * `user_actions` on the `messages` webhook field (Marketing Messages API\n * for WhatsApp only): `marketing_messages_link_click` and\n * `landing_page_view`. `action_type` is an open enum — ignore unknown values.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/marketing-messages/track-landing-page-views\n */\n onUserAction(handler: UserActionHandler): void {\n this.userActionHandler = handler;\n LOGGER.log('Registered user action handler');\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 onRaw(handler: RawWebhookHandler, fields?: WebhookFieldType[]): void {\n this.rawHandler = { handler, fields };\n LOGGER.log(`Registered raw webhook handler${fields ? ` for fields: ${fields.join(', ')}` : ''}`);\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 /**\n * Register a handler for any webhook field except `messages`. The type of\n * `processed.value` follows from the field name. Replaces any handler\n * already registered for that field, including one set with the matching\n * `onXxx` method (for example `onCalls` is `on('calls', handler)`).\n *\n * `messages` is not accepted: use `onMessage`, the typed message methods\n * (`onText`, ...), `onStatus` or `onUserAction`, which split that field\n * into messages, statuses and user actions.\n *\n * @example\n * ```typescript\n * processor.on('calls', async (whatsapp, { value }) => {\n * for (const call of value.calls) console.log(call.id, call.event);\n * });\n * ```\n */\n on<F extends NonMessageWebhookField>(field: F, handler: WebhookFieldHandler<F>): void {\n assertNonMessageField(field, 'on');\n this.fieldHandlers.set(field, handler as unknown as WebhookFieldHandler<NonMessageWebhookField>);\n LOGGER.log(`Registered ${field} handler`);\n }\n\n /**\n * Remove the handler for a webhook field registered with `on()` or the\n * matching `onXxx` method. `messages` is not accepted (see {@link on}).\n */\n off(field: NonMessageWebhookField): void {\n assertNonMessageField(field, 'off');\n this.fieldHandlers.delete(field);\n LOGGER.log(`Removed ${field} handler`);\n }\n\n // ============================================================================\n // Specialized type-safe message handlers\n // ============================================================================\n\n /**\n * Register a handler for text messages\n * @param handler Type-safe handler that receives text messages with guaranteed text field\n */\n onText(handler: TextMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Text, handler as MessageHandler);\n LOGGER.log('Registered text message handler');\n }\n\n /**\n * Register a handler for image messages\n * @param handler Type-safe handler that receives image messages with guaranteed image field\n */\n onImage(handler: ImageMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Image, handler as MessageHandler);\n LOGGER.log('Registered image message handler');\n }\n\n /**\n * Register a handler for video messages\n * @param handler Type-safe handler that receives video messages with guaranteed video field\n */\n onVideo(handler: VideoMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Video, handler as MessageHandler);\n LOGGER.log('Registered video message handler');\n }\n\n /**\n * Register a handler for audio messages\n * @param handler Type-safe handler that receives audio messages with guaranteed audio field\n */\n onAudio(handler: AudioMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Audio, handler as MessageHandler);\n LOGGER.log('Registered audio message handler');\n }\n\n /**\n * Register a handler for document messages\n * @param handler Type-safe handler that receives document messages with guaranteed document field\n */\n onDocument(handler: DocumentMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Document, handler as MessageHandler);\n LOGGER.log('Registered document message handler');\n }\n\n /**\n * Register a handler for sticker messages\n * @param handler Type-safe handler that receives sticker messages with guaranteed sticker field\n */\n onSticker(handler: StickerMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Sticker, handler as MessageHandler);\n LOGGER.log('Registered sticker message handler');\n }\n\n /**\n * Register a handler for interactive messages (buttons, lists, flows)\n * @param handler Type-safe handler that receives interactive messages with guaranteed interactive field\n */\n onInteractive(handler: InteractiveMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Interactive, handler as MessageHandler);\n LOGGER.log('Registered interactive message handler');\n }\n\n /**\n * Register a handler for button messages\n * @param handler Type-safe handler that receives button messages with guaranteed button field\n */\n onButton(handler: ButtonMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Button, handler as MessageHandler);\n LOGGER.log('Registered button message handler');\n }\n\n /**\n * Register a handler for location messages\n * @param handler Type-safe handler that receives location messages with guaranteed location field\n */\n onLocation(handler: LocationMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Location, handler as MessageHandler);\n LOGGER.log('Registered location message handler');\n }\n\n /**\n * Register a handler for contact messages\n * @param handler Type-safe handler that receives contact messages with guaranteed contacts field\n */\n onContacts(handler: ContactsMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Contacts, handler as MessageHandler);\n LOGGER.log('Registered contacts message handler');\n }\n\n /**\n * Register a handler for reaction messages\n * @param handler Type-safe handler that receives reaction messages with guaranteed reaction field\n */\n onReaction(handler: ReactionMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Reaction, handler as MessageHandler);\n LOGGER.log('Registered reaction message handler');\n }\n\n /**\n * Register a handler for order messages\n * @param handler Type-safe handler that receives order messages with guaranteed order field\n */\n onOrder(handler: OrderMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.Order, handler as MessageHandler);\n LOGGER.log('Registered order message handler');\n }\n\n /**\n * Register a handler for system messages\n * @param handler Type-safe handler that receives system messages with guaranteed system field\n */\n onSystem(handler: SystemMessageHandler): void {\n this.messageHandlers.set(MessageTypesEnum.System, handler as MessageHandler);\n LOGGER.log('Registered system message handler');\n }\n\n // ============================================================================\n // Webhook field handlers\n // @see https://developers.facebook.com/docs/graph-api/webhooks/reference/whatsapp-business-account\n // ============================================================================\n\n /**\n * Register a handler for account_update webhook field\n * @see https://developers.facebook.com/docs/whatsapp/business-management-api/webhooks/components#account_update\n */\n onAccountUpdate(handler: AccountUpdateHandler): void {\n this.on('account_update', handler);\n }\n\n /**\n * Register a handler for account_review_update webhook field\n * @see https://developers.facebook.com/docs/whatsapp/business-management-api/webhooks/components#account_review_update\n */\n onAccountReviewUpdate(handler: AccountReviewUpdateHandler): void {\n this.on('account_review_update', handler);\n }\n\n /**\n * Register a handler for account_alerts webhook field\n * @see https://developers.facebook.com/docs/whatsapp/business-management-api/webhooks/components#account_alerts\n */\n onAccountAlerts(handler: AccountAlertsHandler): void {\n this.on('account_alerts', handler);\n }\n\n /**\n * Register a handler for business_capability_update webhook field\n * @see https://developers.facebook.com/docs/whatsapp/business-management-api/webhooks/components#business_capability_update\n */\n onBusinessCapabilityUpdate(handler: BusinessCapabilityUpdateHandler): void {\n this.on('business_capability_update', handler);\n }\n\n /**\n * Register a handler for phone_number_name_update webhook field\n * @see https://developers.facebook.com/docs/whatsapp/business-management-api/webhooks/components#phone_number_name_update\n */\n onPhoneNumberNameUpdate(handler: PhoneNumberNameUpdateHandler): void {\n this.on('phone_number_name_update', handler);\n }\n\n /**\n * Register a handler for phone_number_quality_update webhook field\n * @see https://developers.facebook.com/docs/whatsapp/business-management-api/webhooks/components#phone_number_quality_update\n */\n onPhoneNumberQualityUpdate(handler: PhoneNumberQualityUpdateHandler): void {\n this.on('phone_number_quality_update', handler);\n }\n\n /**\n * Register a handler for message_template_status_update webhook field\n * @see https://developers.facebook.com/docs/whatsapp/business-management-api/webhooks/components#message_template_status_update\n */\n onMessageTemplateStatusUpdate(handler: MessageTemplateStatusUpdateHandler): void {\n this.on('message_template_status_update', handler);\n }\n\n /**\n * Register a handler for template_category_update webhook field\n * @see https://developers.facebook.com/docs/whatsapp/business-management-api/webhooks/components#template_category_update\n */\n onTemplateCategoryUpdate(handler: TemplateCategoryUpdateHandler): void {\n this.on('template_category_update', handler);\n }\n\n /**\n * Register a handler for message_template_quality_update webhook field\n * @see https://developers.facebook.com/docs/whatsapp/business-management-api/webhooks/components#message_template_quality_update\n */\n onMessageTemplateQualityUpdate(handler: MessageTemplateQualityUpdateHandler): void {\n this.on('message_template_quality_update', handler);\n }\n\n /**\n * Register a handler for flows webhook field\n * @see https://developers.facebook.com/docs/whatsapp/flows/guides/implementingyourflowendpoint#webhooks\n */\n onFlows(handler: FlowsHandler): void {\n this.on('flows', handler);\n }\n\n /**\n * Register a handler for security webhook field\n * @see https://developers.facebook.com/docs/whatsapp/business-management-api/webhooks/components#security\n */\n onSecurity(handler: SecurityHandler): void {\n this.on('security', handler);\n }\n\n /**\n * Register a handler for history webhook field\n * @see https://developers.facebook.com/docs/graph-api/webhooks/reference/whatsapp-business-account#history\n */\n onHistory(handler: HistoryHandler): void {\n this.on('history', handler);\n }\n\n /**\n * Register a handler for smb_message_echoes webhook field\n * @see https://developers.facebook.com/docs/graph-api/webhooks/reference/whatsapp-business-account#smb_message_echoes\n */\n onSmbMessageEchoes(handler: SmbMessageEchoesHandler): void {\n this.on('smb_message_echoes', handler);\n }\n\n /**\n * Register a handler for smb_app_state_sync webhook field\n * @see https://developers.facebook.com/docs/graph-api/webhooks/reference/whatsapp-business-account#smb_app_state_sync\n */\n onSmbAppStateSync(handler: SmbAppStateSyncHandler): void {\n this.on('smb_app_state_sync', handler);\n }\n\n /**\n * Register a handler for account_settings_update webhook field\n */\n onAccountSettingsUpdate(handler: AccountSettingsUpdateHandler): void {\n this.on('account_settings_update', handler);\n }\n\n /**\n * Register a handler for automatic_events webhook field\n */\n onAutomaticEvents(handler: AutomaticEventsHandler): void {\n this.on('automatic_events', handler);\n }\n\n /**\n * Register a handler for business_status_update webhook field\n */\n onBusinessStatusUpdate(handler: BusinessStatusUpdateHandler): void {\n this.on('business_status_update', handler);\n }\n\n /**\n * Register a handler for business_username_updates webhook field.\n * Check `value.context === 'revoked'` to tell a Meta revocation from a change the business made.\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/business-scoped-user-ids#business_username_updates-webhook\n */\n onBusinessUsernameUpdates(handler: BusinessUsernameUpdatesHandler): void {\n this.on('business_username_updates', handler);\n }\n\n /**\n * Register a handler for calls webhook field\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/reference/\n */\n onCalls(handler: CallsHandler): void {\n this.on('calls', handler);\n }\n\n /**\n * Register a handler for group_lifecycle_update webhook field\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n onGroupLifecycleUpdate(handler: GroupLifecycleUpdateHandler): void {\n this.on('group_lifecycle_update', handler);\n }\n\n /**\n * Register a handler for group_participants_update webhook field\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n onGroupParticipantsUpdate(handler: GroupParticipantsUpdateHandler): void {\n this.on('group_participants_update', handler);\n }\n\n /**\n * Register a handler for group_settings_update webhook field\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n onGroupSettingsUpdate(handler: GroupSettingsUpdateHandler): void {\n this.on('group_settings_update', handler);\n }\n\n /**\n * Register a handler for group_status_update webhook field\n * @see https://developers.facebook.com/documentation/business-messaging/whatsapp/groups/reference/\n */\n onGroupStatusUpdate(handler: GroupStatusUpdateHandler): void {\n this.on('group_status_update', handler);\n }\n\n /**\n * Register a handler for message_echoes webhook field\n * @see https://developers.facebook.com/docs/graph-api/webhooks/reference/whatsapp-business-account#message_echoes\n */\n onMessageEchoes(handler: MessageEchoesHandler): void {\n this.on('message_echoes', handler);\n }\n\n /**\n * Register a handler for message_template_components_update webhook field\n */\n onMessageTemplateComponentsUpdate(handler: MessageTemplateComponentsUpdateHandler): void {\n this.on('message_template_components_update', handler);\n }\n\n /**\n * Register a handler for messaging_handovers webhook field\n */\n onMessagingHandovers(handler: MessagingHandoversHandler): void {\n this.on('messaging_handovers', handler);\n }\n\n /**\n * Register a handler for partner_solutions webhook field\n */\n onPartnerSolutions(handler: PartnerSolutionsHandler): void {\n this.on('partner_solutions', handler);\n }\n\n /**\n * Register a handler for payment_configuration_update webhook field\n */\n onPaymentConfigurationUpdate(handler: PaymentConfigurationUpdateHandler): void {\n this.on('payment_configuration_update', handler);\n }\n\n /**\n * Register a handler for standby webhook field\n */\n onStandby(handler: StandbyHandler): void {\n this.on('standby', handler);\n }\n\n /**\n * Register a handler for template_correct_category_detection webhook field\n */\n onTemplateCorrectCategoryDetection(handler: TemplateCorrectCategoryDetectionHandler): void {\n this.on('template_correct_category_detection', handler);\n }\n\n /**\n * Register a handler for tracking_events webhook field\n */\n onTrackingEvents(handler: TrackingEventsHandler): void {\n this.on('tracking_events', handler);\n }\n\n /**\n * Register a handler for user_preferences webhook field\n */\n onUserPreferences(handler: UserPreferencesHandler): void {\n this.on('user_preferences', handler);\n }\n\n // ============================================================================\n // Handler removal methods\n // ============================================================================\n\n /**\n * Remove a registered message handler by type\n */\n offMessage(type: MessageTypesEnum | string): void {\n this.messageHandlers.delete(type as MessageTypesEnum);\n LOGGER.log(`Removed message handler for ${type}`);\n }\n\n /**\n * Remove the pre-process handler\n */\n offMessagePreProcess(): void {\n this.preProcessHandler = undefined;\n LOGGER.log('Removed pre-process handler');\n }\n\n /**\n * Remove the post-process handler\n */\n offMessagePostProcess(): void {\n this.postProcessHandler = undefined;\n LOGGER.log('Removed post-process handler');\n }\n\n /**\n * Remove the status handler\n */\n offStatus(): void {\n this.statusHandler = undefined;\n LOGGER.log('Removed status handler');\n }\n\n /**\n * Remove the user action handler\n */\n offUserAction(): void {\n this.userActionHandler = undefined;\n LOGGER.log('Removed user action handler');\n }\n\n /**\n * Remove the raw webhook handler\n */\n offRaw(): void {\n this.rawHandler = undefined;\n LOGGER.log('Removed raw webhook handler');\n }\n\n /**\n * Remove a registered flow handler by type\n */\n offFlow(type: FlowTypeEnum): void {\n this.flowHandlers.delete(type);\n LOGGER.log(`Removed flow handler for ${type}`);\n }\n\n /**\n * Remove all registered handlers\n */\n removeAllHandlers(): void {\n this.messageHandlers.clear();\n this.statusHandler = undefined;\n this.userActionHandler = undefined;\n this.preProcessHandler = undefined;\n this.postProcessHandler = undefined;\n this.rawHandler = undefined;\n this.flowHandlers.clear();\n\n this.fieldHandlers.clear();\n\n LOGGER.log('Removed all handlers');\n }\n\n getClient(): WhatsApp {\n return this.client;\n }\n\n getConfig(): WabaConfigType {\n return this.config;\n }\n}\n","import type { WhatsAppConfig } from '../../../types/config';\nimport { constructFullUrl } from '../utils/webhookUtils';\nimport { WebhookProcessor } from '../WebhookProcessor';\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 | undefined;\n send?(data?: any): T | undefined;\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 type { WebhookResponse } from '../../WebhookProcessor';\nimport { type BaseRequest, type BaseResponse, type 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 type NextFunction = (error?: any) => void;\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 protected async handleGet(req: ExpressRequest, res: ExpressResponse, next: NextFunction): Promise<WebhookResponse> {\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 res.status(result.status).send(result.body);\n return result;\n } catch (error) {\n next(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 protected async handlePost(\n req: ExpressRequest,\n res: ExpressResponse,\n next: NextFunction,\n ): Promise<WebhookResponse> {\n try {\n const fullUrl = this.constructFullUrl(req.headers, req.url);\n const bodyContent = req.rawBody ?? (req.method === 'POST' ? JSON.stringify(req.body) : undefined);\n const webRequest = new globalThis.Request(fullUrl, {\n method: req.method,\n headers: req.headers as HeadersInit,\n body: bodyContent,\n });\n\n const result = await this.processWebhook(webRequest);\n this.applyHeaders(result, res);\n res.status(result.status).send(result.body);\n return result;\n } catch (error) {\n next(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 protected async handleFlow(\n req: ExpressRequest,\n res: ExpressResponse,\n next: NextFunction,\n ): Promise<WebhookResponse> {\n try {\n const fullUrl = this.constructFullUrl(req.headers, req.url);\n\n // Use raw body if available (for signature verification), otherwise stringify parsed body\n const bodyContent = req.rawBody ?? (req.method === 'POST' ? JSON.stringify(req.body) : undefined);\n\n const webRequest = new globalThis.Request(fullUrl, {\n method: req.method,\n headers: req.headers as HeadersInit,\n body: bodyContent,\n });\n\n const result = await this.processFlow(webRequest);\n this.applyHeaders(result, res);\n res.status(result.status).send(result.body);\n return result;\n } catch (error) {\n next(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 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\n// Singleton cache keyed by phoneNumberId\nconst handlerCache = new Map<string, ReturnType<ExpressWebhookHandler['getHandlers']> & { destroy: () => void }>();\n\nfunction getCacheKey(config: ExpressWebhookConfig): string {\n return `express:${config.phoneNumberId ?? 'default'}`;\n}\n\nexport function expressWebhookHandler(config: ExpressWebhookConfig) {\n const key = getCacheKey(config);\n const cached = handlerCache.get(key);\n if (cached) return cached;\n\n const handler = new ExpressWebhookHandler(config);\n const handlers = {\n ...handler.getHandlers(),\n /**\n * Destroy this handler instance: removes all registered handlers\n * and clears it from the singleton cache so the next call creates a fresh instance.\n */\n destroy: () => {\n handler.webhookProcessor.removeAllHandlers();\n handlerCache.delete(key);\n },\n };\n\n handlerCache.set(key, handlers);\n return handlers;\n}\n","// Docs: https://fastify.dev/docs/latest/Reference/ContentTypeParser/\nimport type { WhatsAppConfig } from '../../../../types/config';\nimport { constructFullUrl } from '../../utils/webhookUtils';\nimport { WebhookProcessor, type WebhookResponse } from '../../WebhookProcessor';\n\n// Fastify-like interfaces to avoid a direct Fastify dependency\nexport interface FastifyWebhookRequest {\n method: string;\n url: string;\n headers: Record<string, string | string[] | undefined>;\n body?: unknown;\n query?: unknown;\n /**\n * The unparsed request body. Fastify does not keep it by default: set it in\n * a content-type parser or with the `fastify-raw-body` plugin. Required for\n * `verifyWebhookSignature: true`, because re-serializing the parsed body\n * does not reproduce the bytes Meta signed.\n */\n rawBody?: string | Uint8Array;\n}\n\nexport interface FastifyWebhookReply {\n code(statusCode: number): FastifyWebhookReply;\n header(name: string, value: string): FastifyWebhookReply;\n send(payload?: any): FastifyWebhookReply;\n}\n\nexport interface FastifyWebhookConfig extends WhatsAppConfig {\n // Fastify specific config (currently none, but interface reserved for future use)\n}\n\n/** The object returned by {@link fastifyWebhookHandler}. */\nexport type FastifyWebhookHandlers = ReturnType<typeof createHandlers>;\n\n// Singleton cache keyed by phoneNumberId\nconst handlerCache = new Map<string, FastifyWebhookHandlers>();\n\nfunction getCacheKey(config: FastifyWebhookConfig): string {\n return `fastify:${config.phoneNumberId ?? 'default'}`;\n}\n\nfunction sendResult(reply: FastifyWebhookReply, result: WebhookResponse): FastifyWebhookReply {\n reply.code(result.status);\n for (const [name, value] of Object.entries(result.headers)) {\n reply.header(name, value);\n }\n return reply.send(result.body);\n}\n\nfunction sendInternalError(reply: FastifyWebhookReply): FastifyWebhookReply {\n return reply\n .code(500)\n .header('Content-Type', 'application/json')\n .send(JSON.stringify({ error: 'Internal Server Error' }));\n}\n\nfunction getQueryParam(query: unknown, name: string): string | null {\n if (typeof query !== 'object' || query === null) return null;\n const value = (query as Record<string, unknown>)[name];\n if (Array.isArray(value)) return typeof value[0] === 'string' ? value[0] : null;\n return typeof value === 'string' ? value : null;\n}\n\nfunction toHeaders(headers: FastifyWebhookRequest['headers']): Headers {\n const result = new Headers();\n for (const [name, value] of Object.entries(headers)) {\n if (value === undefined) continue;\n // The body is re-sent from memory, so the original framing headers no longer apply.\n if (name === 'content-length' || name === 'transfer-encoding') continue;\n result.set(name, Array.isArray(value) ? value.join(', ') : value);\n }\n return result;\n}\n\nfunction getBody(request: FastifyWebhookRequest): string | Uint8Array | undefined {\n if (request.rawBody !== undefined) return request.rawBody;\n if (request.body === undefined || request.body === null) return undefined;\n // Fallback: re-serialize the parsed body. Signature verification only\n // passes if this reproduces Meta's bytes exactly, so provide `rawBody`.\n return typeof request.body === 'string' ? request.body : JSON.stringify(request.body);\n}\n\nfunction toWebRequest(request: FastifyWebhookRequest): Request {\n const body = request.method === 'GET' || request.method === 'HEAD' ? undefined : getBody(request);\n return new Request(constructFullUrl(request.headers, request.url), {\n method: request.method,\n headers: toHeaders(request.headers),\n body: body as BodyInit | undefined,\n });\n}\n\n/**\n * Fastify webhook handler.\n *\n * @example\n * const wa = fastifyWebhookHandler(config);\n * wa.processor.onText(async (whatsapp, { message }) => { ... });\n * app.get('/webhook', wa.GET);\n * app.post('/webhook', wa.POST);\n * app.post('/flow', wa.flow);\n */\nexport function fastifyWebhookHandler(config: FastifyWebhookConfig): FastifyWebhookHandlers {\n const key = getCacheKey(config);\n const cached = handlerCache.get(key);\n if (cached) return cached;\n\n const handlers = createHandlers(config, key);\n handlerCache.set(key, handlers);\n return handlers;\n}\n\nfunction createHandlers(config: FastifyWebhookConfig, key: string) {\n const processor = new WebhookProcessor(config);\n\n const GET = async (request: FastifyWebhookRequest, reply: FastifyWebhookReply): Promise<FastifyWebhookReply> => {\n try {\n const result = await processor.processVerification(\n getQueryParam(request.query, 'hub.mode'),\n getQueryParam(request.query, 'hub.verify_token'),\n getQueryParam(request.query, 'hub.challenge'),\n );\n return sendResult(reply, result);\n } catch (error) {\n console.error('Webhook verification error:', error);\n return sendInternalError(reply);\n }\n };\n\n const POST = async (request: FastifyWebhookRequest, reply: FastifyWebhookReply): Promise<FastifyWebhookReply> => {\n try {\n return sendResult(reply, await processor.processWebhook(toWebRequest(request)));\n } catch (error) {\n console.error('Webhook processing error:', error);\n return sendInternalError(reply);\n }\n };\n\n const handlers = {\n GET,\n POST,\n\n // Auto-routing webhook handler (`app.route({ method: ['GET', 'POST'], url, handler: wa.webhook })`)\n webhook: async (request: FastifyWebhookRequest, reply: FastifyWebhookReply): Promise<FastifyWebhookReply> => {\n switch (request.method.toUpperCase()) {\n case 'GET':\n return GET(request, reply);\n case 'POST':\n return POST(request, reply);\n default:\n return reply\n .code(405)\n .header('Content-Type', 'application/json')\n .header('Allow', 'GET, POST')\n .send(JSON.stringify({ error: 'Method Not Allowed' }));\n }\n },\n\n // Flow handler\n flow: async (request: FastifyWebhookRequest, reply: FastifyWebhookReply): Promise<FastifyWebhookReply> => {\n try {\n return sendResult(reply, await processor.processFlow(toWebRequest(request)));\n } catch (error) {\n console.error('Flow processing error:', error);\n return sendInternalError(reply);\n }\n },\n\n // Expose processor for handler registration\n processor,\n\n /**\n * Destroy this handler instance: removes all registered handlers\n * and clears it from the singleton cache so the next call creates a fresh instance.\n */\n destroy: () => {\n processor.removeAllHandlers();\n handlerCache.delete(key);\n },\n };\n\n return handlers;\n}\n","// Docs: https://hono.dev/docs/api/context\nimport type { WhatsAppConfig } from '../../../../types/config';\nimport { WebhookProcessor, type WebhookResponse } from '../../WebhookProcessor';\n\n/**\n * The part of Hono's `Context` this adapter uses, typed locally so `hono` is\n * not a dependency. Any Hono `Context` satisfies it: `c.req.raw` is the\n * underlying web `Request`.\n */\nexport interface HonoWebhookContext {\n req: {\n raw: Request;\n /** Hono's cached body reader, used when middleware already consumed `raw`. */\n text?: () => Promise<string>;\n };\n}\n\nexport interface HonoWebhookConfig extends WhatsAppConfig {\n // Hono specific config (currently none, but interface reserved for future use)\n}\n\n/** The object returned by {@link honoWebhookHandler}. */\nexport type HonoWebhookHandlers = ReturnType<typeof createHandlers>;\n\n// Singleton cache keyed by phoneNumberId\nconst handlerCache = new Map<string, HonoWebhookHandlers>();\n\nfunction getCacheKey(config: HonoWebhookConfig): string {\n return `hono:${config.phoneNumberId ?? 'default'}`;\n}\n\nfunction toResponse(result: WebhookResponse): Response {\n return new Response(result.body, { status: result.status, headers: result.headers });\n}\n\nfunction internalError(): Response {\n return new Response(JSON.stringify({ error: 'Internal Server Error' }), {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n });\n}\n\n/**\n * Return the web Request for this context. If middleware already read the body\n * (e.g. `await c.req.json()`), rebuild the request from Hono's body cache.\n */\nasync function getRequest(c: HonoWebhookContext): Promise<Request> {\n const raw = c.req.raw;\n if (!raw.bodyUsed || !c.req.text) return raw;\n return new Request(raw.url, { method: raw.method, headers: raw.headers, body: await c.req.text() });\n}\n\n/**\n * Hono webhook handler. Works on every runtime Hono runs on (Node.js, Bun,\n * Deno, Cloudflare Workers, Vercel Edge).\n *\n * @example\n * const wa = honoWebhookHandler(config);\n * wa.processor.onText(async (whatsapp, { message }) => { ... });\n * app.get('/webhook', wa.GET);\n * app.post('/webhook', wa.POST);\n * app.post('/flow', wa.flow);\n */\nexport function honoWebhookHandler(config: HonoWebhookConfig): HonoWebhookHandlers {\n const key = getCacheKey(config);\n const cached = handlerCache.get(key);\n if (cached) return cached;\n\n const handlers = createHandlers(config, key);\n handlerCache.set(key, handlers);\n return handlers;\n}\n\nfunction createHandlers(config: HonoWebhookConfig, key: string) {\n const processor = new WebhookProcessor(config);\n\n const GET = async (c: HonoWebhookContext): Promise<Response> => {\n try {\n const { searchParams } = new URL(c.req.raw.url);\n const result = await processor.processVerification(\n searchParams.get('hub.mode'),\n searchParams.get('hub.verify_token'),\n searchParams.get('hub.challenge'),\n );\n return toResponse(result);\n } catch (error) {\n console.error('Webhook verification error:', error);\n return internalError();\n }\n };\n\n const POST = async (c: HonoWebhookContext): Promise<Response> => {\n try {\n return toResponse(await processor.processWebhook(await getRequest(c)));\n } catch (error) {\n console.error('Webhook processing error:', error);\n return internalError();\n }\n };\n\n const handlers = {\n GET,\n POST,\n\n // Auto-routing webhook handler (`app.all('/webhook', wa.webhook)`)\n webhook: async (c: HonoWebhookContext): Promise<Response> => {\n switch (c.req.raw.method.toUpperCase()) {\n case 'GET':\n return GET(c);\n case 'POST':\n return POST(c);\n default:\n return new Response(JSON.stringify({ error: 'Method Not Allowed' }), {\n status: 405,\n headers: { 'Content-Type': 'application/json', Allow: 'GET, POST' },\n });\n }\n },\n\n // Flow handler\n flow: async (c: HonoWebhookContext): Promise<Response> => {\n try {\n return toResponse(await processor.processFlow(await getRequest(c)));\n } catch (error) {\n console.error('Flow processing error:', error);\n return internalError();\n }\n },\n\n // Expose processor for handler registration\n processor,\n\n /**\n * Destroy this handler instance: removes all registered handlers\n * and clears it from the singleton cache so the next call creates a fresh instance.\n */\n destroy: () => {\n processor.removeAllHandlers();\n handlerCache.delete(key);\n },\n };\n\n return handlers;\n}\n","import type { 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\n// Singleton cache keyed by phoneNumberId\nconst handlerCache = new Map<string, NextJsAppWebhookHandlers>();\n\nfunction getCacheKey(config: NextJsAppWebhookConfig): string {\n return `nextjs-app:${config.phoneNumberId ?? 'default'}`;\n}\n\n/** The object returned by {@link nextjsAppWebhookHandler}. */\nexport type NextJsAppWebhookHandlers = ReturnType<typeof createHandlers>;\n\n// Next.js App Router webhook handler\nexport function nextjsAppWebhookHandler(config: NextJsAppWebhookConfig): NextJsAppWebhookHandlers {\n const key = getCacheKey(config);\n const cached = handlerCache.get(key);\n if (cached) return cached;\n\n const handlers = createHandlers(config, key);\n handlerCache.set(key, handlers);\n return handlers;\n}\n\nfunction createHandlers(config: NextJsAppWebhookConfig, key: string) {\n const processor = new WebhookProcessor(config);\n\n const handlers = {\n // Clean GET/POST handlers following whatsapp-api-js methodology\n GET: async (request: Request) => {\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: Request) => {\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: Request) => {\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: Request) => {\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: Request) => {\n try {\n const result = await processor.processFlow(request);\n\n // result.body is already a JSON string, don't double-encode it\n return new Response(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(JSON.stringify({ error: 'Internal Server Error' }), {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n },\n\n POST: async (request: Request) => {\n try {\n const result = await processor.processFlow(request);\n\n // result.body is already a JSON string, don't double-encode it\n return new Response(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(JSON.stringify({ error: 'Internal Server Error' }), {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n },\n },\n\n // Expose processor for handler registration\n processor,\n\n /**\n * Destroy this handler instance: removes all registered handlers\n * and clears it from the singleton cache so the next call creates a fresh instance.\n */\n destroy: () => {\n processor.removeAllHandlers();\n handlerCache.delete(key);\n },\n };\n\n return handlers;\n}\n","import type { WebhookResponse } from '../../WebhookProcessor';\nimport { type BaseRequest, type BaseResponse, type 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): undefined | any;\n send(data?: any): undefined | 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 // Helper function to parse request body for POST requests\n private async parseRequestBody(req: TRequest, preserveRaw: boolean = false): 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 // Store raw body if requested (for signature verification)\n if (preserveRaw) {\n req.rawBody = body;\n }\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<WebhookResponse> {\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 res.status(result.status).send(result.body);\n return result;\n } catch (error) {\n console.error('Webhook verification error:', error);\n res.status(500).json({ error: 'Internal Server 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 protected async handlePost(req: TRequest, res: TResponse): Promise<WebhookResponse> {\n try {\n // Auto-parse body if needed\n await this.parseRequestBody(req, true);\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 res.status(400).json({ error: 'Invalid JSON' });\n return {\n status: 400,\n body: JSON.stringify({ error: 'Invalid JSON' }),\n headers: { 'Content-Type': 'application/json' },\n };\n }\n\n res.status(500).json({ error: 'Internal Server Error' });\n return {\n status: 500,\n body: JSON.stringify({ error: 'Internal Server Error' }),\n headers: { 'Content-Type': 'application/json' },\n };\n }\n\n try {\n const fullUrl = this.constructFullUrl(req.headers, req.url);\n const bodyContent = req.rawBody ?? (req.method === 'POST' ? JSON.stringify(req.body) : undefined);\n\n const webRequest = new Request(fullUrl, {\n method: 'POST',\n headers: req.headers as HeadersInit,\n body: bodyContent,\n });\n\n const result = await this.processWebhook(webRequest);\n this.applyHeaders(result, res);\n res.status(result.status).send(result.body);\n return result;\n } catch (error) {\n console.error('Webhook processing error:', error);\n res.status(500).json({ error: 'Internal Server 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 protected async handleFlow(req: TRequest, res: TResponse): Promise<WebhookResponse> {\n try {\n // Parse body and preserve raw body for signature verification\n await this.parseRequestBody(req, true);\n } catch (error) {\n console.error('Flow body parsing error:', error);\n\n // Handle JSON parsing errors specifically\n if (error instanceof Error && error.message === 'Invalid JSON in request body') {\n res.status(400).json({ error: 'Invalid JSON' });\n return {\n status: 400,\n body: JSON.stringify({ error: 'Invalid JSON' }),\n headers: { 'Content-Type': 'application/json' },\n };\n }\n\n res.status(500).json({ error: 'Internal Server Error' });\n return {\n status: 500,\n body: JSON.stringify({ error: 'Internal Server Error' }),\n headers: { 'Content-Type': 'application/json' },\n };\n }\n\n try {\n const fullUrl = this.constructFullUrl(req.headers, req.url);\n\n // Use raw body if available (for signature verification), otherwise stringify parsed body\n const bodyContent = req.rawBody ?? (req.method === 'POST' ? JSON.stringify(req.body) : undefined);\n\n const webRequest = new Request(fullUrl, {\n method: req.method,\n headers: req.headers as HeadersInit,\n body: bodyContent,\n });\n\n const result = await this.processFlow(webRequest);\n this.applyHeaders(result, res);\n res.status(result.status).send(result.body);\n\n // Return result for user's custom handling\n return result;\n } catch (error) {\n console.error('Flow error:', error);\n res.status(500).json({ error: 'Internal Server 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 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// Singleton cache keyed by phoneNumberId\nconst handlerCache = new Map<\n string,\n ReturnType<NextJsWebhookHandler<any, any>['getHandlers']> & { destroy: () => void }\n>();\n\nfunction getCacheKey(config: NextJsWebhookConfig): string {\n return `nextjs-page:${config.phoneNumberId ?? 'default'}`;\n}\n\n// Next.js Pages Router webhook handler\nexport function nextjsPagesWebhookHandler<TRequest extends BaseApiRequest, TResponse extends BaseApiResponse>(\n config: NextJsWebhookConfig,\n) {\n const key = getCacheKey(config);\n const cached = handlerCache.get(key);\n if (cached) return cached;\n\n const handler = new NextJsWebhookHandler<TRequest, TResponse>(config);\n const handlers = {\n ...handler.getHandlers(),\n /**\n * Destroy this handler instance: removes all registered handlers\n * and clears it from the singleton cache so the next call creates a fresh instance.\n */\n destroy: () => {\n handler.webhookProcessor.removeAllHandlers();\n handlerCache.delete(key);\n },\n };\n\n handlerCache.set(key, handlers);\n return handlers;\n}\n","import { MessageTypesEnum } from '../../../types/enums';\nimport type { WhatsAppMessage } from '../types/message';\n\n/**\n * Extracts a human-readable display text from any incoming WhatsApp message.\n *\n * Useful for logging, notifications, chat previews, and storing message summaries.\n *\n * @param message - The incoming WhatsApp message from a webhook handler\n * @returns A display-friendly string representing the message content\n *\n * @example\n * ```ts\n * handler.processor.onText(async (whatsapp, processed) => {\n * const text = extractMessageText(processed.message);\n * console.log(`Message from ${processed.message.from}: ${text}`);\n * });\n * ```\n */\nexport function extractMessageText(message: WhatsAppMessage): string {\n switch (message.type) {\n case MessageTypesEnum.Text:\n return message.text.body;\n\n case MessageTypesEnum.Image:\n return message.image.caption || '[Image]';\n\n case MessageTypesEnum.Video:\n return message.video.caption || '[Video]';\n\n case MessageTypesEnum.Audio:\n return message.audio.voice ? '[Voice Message]' : '[Audio]';\n\n case MessageTypesEnum.Document:\n return message.document.caption || message.document.filename || '[Document]';\n\n case MessageTypesEnum.Sticker:\n return message.sticker.animated ? '[Animated Sticker]' : '[Sticker]';\n\n case MessageTypesEnum.Interactive: {\n const interactive = message.interactive;\n if (interactive.type === 'button_reply') {\n return interactive.button_reply.title;\n }\n if (interactive.type === 'list_reply') {\n return interactive.list_reply.title;\n }\n if (interactive.type === 'nfm_reply') {\n return interactive.nfm_reply.body || interactive.nfm_reply.name || '[Form Reply]';\n }\n return '[Interactive]';\n }\n\n case MessageTypesEnum.Button:\n return message.button.text;\n\n case MessageTypesEnum.Location:\n return (\n message.location.name ||\n message.location.address ||\n `📍 ${message.location.latitude}, ${message.location.longitude}`\n );\n\n case MessageTypesEnum.Contacts: {\n const names = message.contacts.map((c) => c.name.formatted_name);\n return names.length === 1 ? `👤 ${names[0]}` : `👤 ${names.length} contacts`;\n }\n\n case MessageTypesEnum.Reaction:\n return message.reaction.emoji || '[Reaction removed]';\n\n case MessageTypesEnum.Order: {\n const count = message.order.product_items.length;\n return `🛒 Order: ${count} item${count > 1 ? 's' : ''}`;\n }\n\n case MessageTypesEnum.System:\n return message.system.body;\n\n case MessageTypesEnum.Unsupported:\n return '[Unsupported message]';\n\n default:\n return `[${(message as any).type}]`;\n }\n}\n","import { hmacSha256Hex, requireNodeCrypto } from '../../../utils/runtime';\n\n/**\n * Compute the hex HMAC-SHA256 that Meta sends in `X-Hub-Signature-256`\n * (without the `sha256=` prefix). Needs `node:crypto`; use\n * {@link generateXHub256SigAsync} on edge runtimes.\n */\nexport const generateXHub256Sig = (body: string, appSecret: string) => {\n return requireNodeCrypto('generateXHub256Sig').createHmac('sha256', appSecret).update(body, 'utf-8').digest('hex');\n};\n\n/** Web Crypto variant of {@link generateXHub256Sig}; works on every runtime. */\nexport const generateXHub256SigAsync = (body: string, appSecret: string): Promise<string> => {\n return hmacSha256Hex(appSecret, body);\n};\n","import { MessageTypesEnum } from '../../../types/enums';\nimport type {\n AudioMessage,\n ButtonMessage,\n ContactsMessage,\n DocumentMessage,\n ImageMessage,\n InteractiveButtonReplyMessage,\n InteractiveListReplyMessage,\n InteractiveMessage,\n InteractiveNfmReplyMessage,\n LocationMessage,\n OrderMessage,\n ReactionMessage,\n StickerMessage,\n SystemMessage,\n TextMessage,\n VideoMessage,\n WhatsAppMessage,\n} from '../types/message';\n\n// ============================================================================\n// Type Guards — narrow WhatsAppMessage to specific types\n// ============================================================================\n\nexport function isTextMessage(msg: WhatsAppMessage): msg is TextMessage {\n return msg.type === MessageTypesEnum.Text;\n}\n\nexport function isImageMessage(msg: WhatsAppMessage): msg is ImageMessage {\n return msg.type === MessageTypesEnum.Image;\n}\n\nexport function isVideoMessage(msg: WhatsAppMessage): msg is VideoMessage {\n return msg.type === MessageTypesEnum.Video;\n}\n\nexport function isAudioMessage(msg: WhatsAppMessage): msg is AudioMessage {\n return msg.type === MessageTypesEnum.Audio;\n}\n\nexport function isDocumentMessage(msg: WhatsAppMessage): msg is DocumentMessage {\n return msg.type === MessageTypesEnum.Document;\n}\n\nexport function isStickerMessage(msg: WhatsAppMessage): msg is StickerMessage {\n return msg.type === MessageTypesEnum.Sticker;\n}\n\nexport function isInteractiveMessage(msg: WhatsAppMessage): msg is InteractiveMessage {\n return msg.type === MessageTypesEnum.Interactive;\n}\n\nexport function isButtonMessage(msg: WhatsAppMessage): msg is ButtonMessage {\n return msg.type === MessageTypesEnum.Button;\n}\n\nexport function isLocationMessage(msg: WhatsAppMessage): msg is LocationMessage {\n return msg.type === MessageTypesEnum.Location;\n}\n\nexport function isContactsMessage(msg: WhatsAppMessage): msg is ContactsMessage {\n return msg.type === MessageTypesEnum.Contacts;\n}\n\nexport function isReactionMessage(msg: WhatsAppMessage): msg is ReactionMessage {\n return msg.type === MessageTypesEnum.Reaction;\n}\n\nexport function isOrderMessage(msg: WhatsAppMessage): msg is OrderMessage {\n return msg.type === MessageTypesEnum.Order;\n}\n\nexport function isSystemMessage(msg: WhatsAppMessage): msg is SystemMessage {\n return msg.type === MessageTypesEnum.System;\n}\n\n// Interactive sub-type guards\nexport function isButtonReply(msg: WhatsAppMessage): msg is InteractiveButtonReplyMessage {\n return isInteractiveMessage(msg) && msg.interactive.type === 'button_reply';\n}\n\nexport function isListReply(msg: WhatsAppMessage): msg is InteractiveListReplyMessage {\n return isInteractiveMessage(msg) && msg.interactive.type === 'list_reply';\n}\n\nexport function isNfmReply(msg: WhatsAppMessage): msg is InteractiveNfmReplyMessage {\n return isInteractiveMessage(msg) && msg.interactive.type === 'nfm_reply';\n}\n\n// ============================================================================\n// Structured data extractors — type-safe parsed data from messages\n// ============================================================================\n\nexport type MediaInfo = {\n id: string;\n mimeType: string;\n sha256: string;\n caption?: string;\n filename?: string;\n animated?: boolean;\n voice?: boolean;\n};\n\n/**\n * Extract media info from image/video/audio/document/sticker messages.\n * Returns null if the message is not a media message.\n *\n * @example\n * ```ts\n * const media = getMediaInfo(message);\n * if (media) {\n * const url = await sdk.media.get(media.id);\n * }\n * ```\n */\nexport function getMediaInfo(msg: WhatsAppMessage): MediaInfo | null {\n if (isImageMessage(msg)) {\n return {\n id: msg.image.id,\n mimeType: msg.image.mime_type,\n sha256: msg.image.sha256,\n caption: msg.image.caption,\n };\n }\n if (isVideoMessage(msg)) {\n return {\n id: msg.video.id,\n mimeType: msg.video.mime_type,\n sha256: msg.video.sha256,\n caption: msg.video.caption,\n };\n }\n if (isAudioMessage(msg)) {\n return { id: msg.audio.id, mimeType: msg.audio.mime_type, sha256: msg.audio.sha256, voice: msg.audio.voice };\n }\n if (isDocumentMessage(msg)) {\n return {\n id: msg.document.id,\n mimeType: msg.document.mime_type,\n sha256: msg.document.sha256,\n caption: msg.document.caption,\n filename: msg.document.filename,\n };\n }\n if (isStickerMessage(msg)) {\n return {\n id: msg.sticker.id,\n mimeType: msg.sticker.mime_type,\n sha256: msg.sticker.sha256,\n animated: msg.sticker.animated,\n };\n }\n return null;\n}\n\nexport type InteractiveReply = {\n type: 'button_reply' | 'list_reply' | 'nfm_reply';\n id: string;\n title: string;\n description?: string;\n responseJson?: string;\n};\n\n/**\n * Extract the user's selection from interactive messages (button reply, list reply, nfm reply).\n * Returns null if not an interactive message.\n *\n * @example\n * ```ts\n * const reply = getInteractiveReply(message);\n * if (reply) {\n * console.log(`User selected: ${reply.title} (id: ${reply.id})`);\n * }\n * ```\n */\nexport function getInteractiveReply(msg: WhatsAppMessage): InteractiveReply | null {\n if (!isInteractiveMessage(msg)) return null;\n\n if (msg.interactive.type === 'button_reply') {\n return {\n type: 'button_reply',\n id: msg.interactive.button_reply.id,\n title: msg.interactive.button_reply.title,\n };\n }\n if (msg.interactive.type === 'list_reply') {\n return {\n type: 'list_reply',\n id: msg.interactive.list_reply.id,\n title: msg.interactive.list_reply.title,\n description: msg.interactive.list_reply.description,\n };\n }\n if (msg.interactive.type === 'nfm_reply') {\n return {\n type: 'nfm_reply',\n id: msg.interactive.nfm_reply.name,\n title: msg.interactive.nfm_reply.body,\n responseJson: msg.interactive.nfm_reply.response_json,\n };\n }\n return null;\n}\n\nexport type LocationInfo = {\n latitude: number;\n longitude: number;\n name?: string;\n address?: string;\n url?: string;\n};\n\n/**\n * Extract location data from a location message.\n * Returns null if not a location message.\n */\nexport function getLocationInfo(msg: WhatsAppMessage): LocationInfo | null {\n if (!isLocationMessage(msg)) return null;\n return {\n latitude: msg.location.latitude,\n longitude: msg.location.longitude,\n name: msg.location.name,\n address: msg.location.address,\n url: msg.location.url,\n };\n}\n\nexport type ContactInfo = {\n formattedName: string;\n firstName?: string;\n lastName?: string;\n phones: string[];\n emails: string[];\n};\n\n/**\n * Extract contact info from a contacts message.\n * Returns empty array if not a contacts message.\n */\nexport function getContactsInfo(msg: WhatsAppMessage): ContactInfo[] {\n if (!isContactsMessage(msg)) return [];\n return msg.contacts.map((c) => ({\n formattedName: c.name.formatted_name,\n firstName: c.name.first_name,\n lastName: c.name.last_name,\n phones: c.phones?.map((p) => p.phone) || [],\n emails: c.emails?.map((e) => e.email) || [],\n }));\n}\n\nexport type ReactionInfo = {\n messageId: string;\n emoji: string | null; // null = reaction removed\n};\n\n/**\n * Extract reaction data from a reaction message.\n * Returns null if not a reaction message.\n */\nexport function getReactionInfo(msg: WhatsAppMessage): ReactionInfo | null {\n if (!isReactionMessage(msg)) return null;\n return {\n messageId: msg.reaction.message_id,\n emoji: msg.reaction.emoji || null,\n };\n}\n\nexport type OrderInfo = {\n catalogId: string;\n text?: string;\n items: Array<{\n productId: string;\n quantity: number;\n price: number;\n currency: string;\n }>;\n};\n\n/**\n * Extract order data from an order message.\n * Returns null if not an order message.\n */\nexport function getOrderInfo(msg: WhatsAppMessage): OrderInfo | null {\n if (!isOrderMessage(msg)) return null;\n return {\n catalogId: msg.order.catalog_id,\n text: msg.order.text,\n items: msg.order.product_items.map((item) => ({\n productId: item.product_retailer_id,\n quantity: item.quantity,\n price: item.item_price,\n currency: item.currency,\n })),\n };\n}\n","/**\n * As-const alternatives to enums.\n *\n * Every enum in enums.ts gets a matching `as const` object and a union type here.\n * Use whichever style you prefer:\n * - Enum: CategoryEnum.Marketing\n * - Const: Category.Marketing (value: 'MARKETING')\n * - Type: CategoryType (union: 'AUTHENTICATION' | 'MARKETING' | 'UTILITY')\n */\n\n// ---- Category ----\nexport const Category = {\n Authentication: 'AUTHENTICATION',\n Marketing: 'MARKETING',\n Utility: 'UTILITY',\n} as const;\nexport type CategoryType = (typeof Category)[keyof typeof Category];\n\n// ---- MessageCategory (Direct Send) ----\nexport const MessageCategory = {\n Authentication: 'authentication',\n Service: 'service',\n Utility: 'utility',\n} as const;\nexport type MessageCategoryType = (typeof MessageCategory)[keyof typeof MessageCategory];\n\n// ---- TemplateStatus ----\nexport const TemplateStatus = {\n Approved: 'APPROVED',\n Pending: 'PENDING',\n Rejected: 'REJECTED',\n} as const;\nexport type TemplateStatusType = (typeof TemplateStatus)[keyof typeof TemplateStatus];\n\n// ---- HttpMethods ----\nexport const HttpMethods = {\n Get: 'GET',\n Post: 'POST',\n Put: 'PUT',\n Delete: 'DELETE',\n} as const;\nexport type HttpMethodsType = (typeof HttpMethods)[keyof typeof HttpMethods];\n\n// ---- MessageTypes ----\nexport const MessageTypes = {\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 Unsupported: 'unsupported',\n Unknown: 'unknown',\n /** @deprecated Use WebhookProcessor.onStatus() instead */\n Statuses: 'statuses',\n All: '*',\n} as const;\nexport type MessageTypesType = (typeof MessageTypes)[keyof typeof MessageTypes];\n\n// ---- ParametersTypes ----\nexport const ParametersTypes = {\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} as const;\nexport type ParametersTypesType = (typeof ParametersTypes)[keyof typeof ParametersTypes];\n\n// ---- InteractiveTypes ----\nexport const InteractiveTypes = {\n Button: 'button',\n List: 'list',\n Product: 'product',\n ProductList: 'product_list',\n CtaUrl: 'cta_url',\n Carousel: 'carousel',\n LocationRequest: 'location_request_message',\n AddressMessage: 'address_message',\n Flow: 'flow',\n VoiceCall: 'voice_call',\n} as const;\nexport type InteractiveTypesType = (typeof InteractiveTypes)[keyof typeof InteractiveTypes];\n\n// ---- ButtonPosition ----\nexport const ButtonPosition = {\n First: 1,\n Second: 2,\n Third: 3,\n Fourth: 4,\n Fifth: 5,\n} as const;\nexport type ButtonPositionType = (typeof ButtonPosition)[keyof typeof ButtonPosition];\n\n// ---- SubType ----\nexport const SubType = {\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} as const;\nexport type SubTypeType = (typeof SubType)[keyof typeof SubType];\n\n// ---- ComponentTypes (template) ----\nexport const ComponentType = {\n Header: 'HEADER',\n Body: 'BODY',\n Button: 'BUTTON',\n Footer: 'FOOTER',\n} as const;\nexport type ComponentTypeType = (typeof ComponentType)[keyof typeof ComponentType];\n\n// ---- ConversationTypes ----\nexport const ConversationTypes = {\n BusinessInitiated: 'business_initiated',\n CustomerInitiated: 'customer_initiated',\n ReferralConversion: 'referral_conversion',\n} as const;\nexport type ConversationTypesType = (typeof ConversationTypes)[keyof typeof ConversationTypes];\n\n// ---- Status ----\nexport const Status = {\n Delivered: 'delivered',\n Read: 'read',\n Sent: 'sent',\n} as const;\nexport type StatusType = (typeof Status)[keyof typeof Status];\n\n// ---- VideoMediaTypes ----\nexport const VideoMediaTypes = {\n Mp4: 'video/mp4',\n Threegp: 'video/3gp',\n} as const;\nexport type VideoMediaTypesType = (typeof VideoMediaTypes)[keyof typeof VideoMediaTypes];\n\n// ---- StickerMediaTypes ----\nexport const StickerMediaTypes = {\n Webp: 'image/webp',\n} as const;\nexport type StickerMediaTypesType = (typeof StickerMediaTypes)[keyof typeof StickerMediaTypes];\n\n// ---- ImageMediaTypes ----\nexport const ImageMediaTypes = {\n Jpeg: 'image/jpeg',\n Png: 'image/png',\n} as const;\nexport type ImageMediaTypesType = (typeof ImageMediaTypes)[keyof typeof ImageMediaTypes];\n\n// ---- DocumentMediaTypes ----\nexport const DocumentMediaTypes = {\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} as const;\nexport type DocumentMediaTypesType = (typeof DocumentMediaTypes)[keyof typeof DocumentMediaTypes];\n\n// ---- AudioMediaTypes ----\nexport const AudioMediaTypes = {\n Aac: 'audio/aac',\n Mp4: 'audio/mp4',\n Mpeg: 'audio/mpeg',\n Amr: 'audio/amr',\n Ogg: 'audio/ogg',\n} as const;\nexport type AudioMediaTypesType = (typeof AudioMediaTypes)[keyof typeof AudioMediaTypes];\n\n// ---- WebhookTypes ----\nexport const WebhookTypes = {\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} as const;\nexport type WebhookTypesType = (typeof WebhookTypes)[keyof typeof WebhookTypes];\n\n// ---- SystemChangeTypes ----\nexport const SystemChangeTypes = {\n /** @deprecated Meta renamed this to `user_changed_number`. Use `UserChangedNumber`. */\n CustomerChangedNumber: 'customer_changed_number',\n /** @deprecated Meta renamed this to `user_identity_changed`. Use `UserIdentityChanged`. */\n CustomerIdentityChanged: 'customer_identity_changed',\n UserChangedNumber: 'user_changed_number',\n UserIdentityChanged: 'user_identity_changed',\n /** The user's business-scoped user ID (BSUID) changed. */\n UserChangedUserId: 'user_changed_user_id',\n} as const;\nexport type SystemChangeTypesType = (typeof SystemChangeTypes)[keyof typeof SystemChangeTypes];\n\n// ---- ReferralSourceTypes ----\nexport const ReferralSourceTypes = {\n Ad: 'ad',\n Post: 'post',\n} as const;\nexport type ReferralSourceTypesType = (typeof ReferralSourceTypes)[keyof typeof ReferralSourceTypes];\n\n// ---- RequestCodeMethods ----\nexport const RequestCodeMethods = {\n Sms: 'SMS',\n Voice: 'VOICE',\n} as const;\nexport type RequestCodeMethodsType = (typeof RequestCodeMethods)[keyof typeof RequestCodeMethods];\n\n// ---- Languages ----\nexport const Languages = {\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} as const;\nexport type LanguagesType = (typeof Languages)[keyof typeof Languages];\n\n// ---- DataLocalizationRegion ----\nexport const DataLocalizationRegion = {\n AU: 'AU',\n ID: 'ID',\n IN: 'IN',\n JP: 'JP',\n SG: 'SG',\n KR: 'KR',\n DE: 'DE',\n CH: 'CH',\n GB: 'GB',\n BR: 'BR',\n BH: 'BH',\n ZA: 'ZA',\n AE: 'AE',\n CA: 'CA',\n} as const;\nexport type DataLocalizationRegionType = (typeof DataLocalizationRegion)[keyof typeof DataLocalizationRegion];\n","// Docs: https://developers.facebook.com/documentation/business-messaging/whatsapp/messages/send-messages/\n\nimport { WhatsAppValidationError } from './isMetaError';\n\nconst HOUR_MS = 60 * 60 * 1000;\n\n/**\n * Length of the customer service window: 24 hours.\n *\n * \"When a WhatsApp user messages you or calls you, a 24-hour timer called a customer service window\n * starts. If the user messages or calls you again before the timer expires, the timer resets to\n * 24 hours. [...] When the window closes, you can only send pre-approved template messages.\"\n *\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/messages/send-messages/ | Send messages: customer service windows}\n */\nexport const CUSTOMER_SERVICE_WINDOW_MS = 24 * HOUR_MS;\n\n/**\n * SDK fallback length of a free entry point (FEP) window: 72 hours.\n * Prefer the expiry supplied by Meta; this fallback does not establish billing eligibility.\n *\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/pricing/ | Pricing: free entry point windows}\n */\nexport const FREE_ENTRY_POINT_WINDOW_MS = 72 * HOUR_MS;\n\n/**\n * Longest free entry point window Meta documents: up to 7 days for conversations started from an\n * ad that clicks to WhatsApp.\n *\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/pricing/ | Pricing: free entry point windows}\n */\nexport const MAX_FREE_ENTRY_POINT_WINDOW_MS = 7 * 24 * HOUR_MS;\n\n/**\n * A point in time accepted by the window helpers:\n * - `Date`\n * - `number`: Unix epoch in milliseconds, or in seconds when below `1e11` (before the year 5138 in\n * seconds, before March 1973 in milliseconds), so both `Date.now()` and webhook timestamps work\n * - `string`: a numeric string such as the webhook `messages[].timestamp` (`\"1727856000\"`, Unix\n * seconds, same rule as numbers), or any string `Date.parse` understands (ISO 8601)\n */\nexport type WindowTimestamp = Date | number | string;\n\n/** State of a messaging window at a given instant. */\nexport interface MessagingWindow {\n /** True while the window is open (`now < expiresAt`). */\n isOpen: boolean;\n /** When the window closes, or `null` when there is no window (no inbound message yet). */\n expiresAt: Date | null;\n /** Milliseconds until the window closes, `0` once closed. Never more than the window length. */\n remainingMs: number;\n}\n\nexport interface CustomerServiceWindowOptions {\n /** The instant to evaluate. Defaults to `Date.now()`. */\n now?: WindowTimestamp;\n /**\n * Treat the window as closing this many milliseconds early. Use it to absorb clock drift between\n * your servers and Meta and the time a send spends in flight. Defaults to `0`.\n */\n safetyMarginMs?: number;\n}\n\nexport interface FreeEntryPointWindowOptions extends CustomerServiceWindowOptions {\n /**\n * Window length. Defaults to {@link FREE_ENTRY_POINT_WINDOW_MS} (72 hours). Meta may keep a\n * click-to-WhatsApp ad window open for up to {@link MAX_FREE_ENTRY_POINT_WINDOW_MS} (7 days)\n * without saying how long a given window lasts, so prefer `expiresAt` when you have it.\n */\n durationMs?: number;\n /**\n * Exact expiry when known, for example the status webhook's `conversation.expiration_timestamp`\n * (Unix seconds). Overrides `durationMs`.\n */\n expiresAt?: WindowTimestamp;\n}\n\nconst SECONDS_THRESHOLD = 1e11;\n\nfunction toEpochMs(value: WindowTimestamp, name: string): number {\n let ms: number;\n\n if (value instanceof Date) {\n ms = value.getTime();\n } else if (typeof value === 'number') {\n ms = Math.abs(value) < SECONDS_THRESHOLD ? value * 1000 : value;\n } else if (typeof value === 'string') {\n const trimmed = value.trim();\n if (/^\\d+(\\.\\d+)?$/.test(trimmed)) {\n const num = Number(trimmed);\n ms = num < SECONDS_THRESHOLD ? num * 1000 : num;\n } else {\n ms = trimmed === '' ? Number.NaN : Date.parse(trimmed);\n }\n } else {\n ms = Number.NaN;\n }\n\n if (!Number.isFinite(ms) || !Number.isFinite(new Date(ms).getTime())) {\n throw new WhatsAppValidationError(`${name} is not a valid timestamp: ${String(value)}`);\n }\n return ms;\n}\n\nfunction toNonNegativeMs(value: number | undefined, name: string, fallback: number): number {\n if (value === undefined) return fallback;\n if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {\n throw new WhatsAppValidationError(`${name} must be a non-negative number of milliseconds`);\n }\n return value;\n}\n\nfunction computeWindow(startMs: number, endMs: number, nowMs: number, safetyMarginMs: number): MessagingWindow {\n if (!Number.isFinite(new Date(endMs).getTime())) {\n throw new WhatsAppValidationError('Window expiry is outside the supported timestamp range');\n }\n const lengthMs = Math.max(0, endMs - startMs);\n const effectiveEndMs = endMs - safetyMarginMs;\n // A start in the future means the clocks disagree; never report more than one full window.\n const remainingMs = Math.min(Math.max(0, effectiveEndMs - nowMs), lengthMs);\n return {\n isOpen: remainingMs > 0,\n expiresAt: new Date(endMs),\n remainingMs,\n };\n}\n\nconst CLOSED: MessagingWindow = Object.freeze({ isOpen: false, expiresAt: null, remainingMs: 0 }) as MessagingWindow;\n\n/**\n * Returns the state of the 24-hour customer service window opened by the user's last inbound\n * message (or call).\n *\n * Free-form (non-template) messages can only be sent while it is open; outside it only approved\n * template messages are delivered (Meta rejects others with error `131047`). The window is exactly\n * 24 hours from the user's last message: at `lastInboundAt + 24h` it is closed.\n *\n * Pass the webhook message `timestamp` (Unix seconds string) of the latest message from the user.\n * Messages you send do not extend the window. Pass `null`/`undefined` when the user has never\n * messaged you; that returns a closed window with `expiresAt: null`.\n *\n * A free entry point window does not reopen this window: \"the customer service window is independent\n * of the FEP window, so if the customer service window closes, you will only be able to send template\n * messages.\" Use {@link getFreeEntryPointWindow} for the pricing side.\n *\n * @throws WhatsAppValidationError when a timestamp or `safetyMarginMs` is malformed.\n *\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/messages/send-messages/ | Send messages: customer service windows}\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/pricing/ | Pricing}\n *\n * @example\n * ```ts\n * const { isOpen, expiresAt } = getCustomerServiceWindow(message.timestamp);\n * if (!isOpen) await sendTemplateInstead();\n * ```\n */\nexport function getCustomerServiceWindow(\n lastInboundAt: WindowTimestamp | null | undefined,\n options: CustomerServiceWindowOptions = {},\n): MessagingWindow {\n const safetyMarginMs = toNonNegativeMs(options.safetyMarginMs, 'safetyMarginMs', 0);\n const nowMs = options.now === undefined ? Date.now() : toEpochMs(options.now, 'now');\n if (lastInboundAt === null || lastInboundAt === undefined) return { ...CLOSED };\n\n const startMs = toEpochMs(lastInboundAt, 'lastInboundAt');\n return computeWindow(startMs, startMs + CUSTOMER_SERVICE_WINDOW_MS, nowMs, safetyMarginMs);\n}\n\n/**\n * True when a free-form (non-template) message can be sent: the customer service window opened by\n * the user's last inbound message is still open. See {@link getCustomerServiceWindow}.\n *\n * @throws WhatsAppValidationError when a timestamp or `safetyMarginMs` is malformed.\n */\nexport function canSendFreeformMessage(\n lastInboundAt: WindowTimestamp | null | undefined,\n options: CustomerServiceWindowOptions = {},\n): boolean {\n return getCustomerServiceWindow(lastInboundAt, options).isOpen;\n}\n\n/**\n * Returns the state of a free entry point (FEP) window.\n *\n * For eligible click-to-WhatsApp ad traffic, replying within the customer service window opens\n * a billing window from the time of your reply. Pass that first reply time as `openedAt`.\n *\n * Meta documents windows lasting up to 7 days for ads that click to WhatsApp. This helper uses\n * a 72-hour fallback estimate. Pass `expiresAt` (the status webhook's\n * `conversation.expiration_timestamp`) when you have it, or set `durationMs`.\n *\n * This is a billing window only. It does not allow free-form messages after the customer service\n * window closes; check {@link canSendFreeformMessage} for that.\n *\n * @throws WhatsAppValidationError when a timestamp, `durationMs` or `safetyMarginMs` is malformed.\n *\n * @see {@link https://developers.facebook.com/documentation/business-messaging/whatsapp/pricing/ | Pricing: free entry point windows}\n */\nexport function getFreeEntryPointWindow(\n openedAt: WindowTimestamp | null | undefined,\n options: FreeEntryPointWindowOptions = {},\n): MessagingWindow {\n const safetyMarginMs = toNonNegativeMs(options.safetyMarginMs, 'safetyMarginMs', 0);\n const durationMs = toNonNegativeMs(options.durationMs, 'durationMs', FREE_ENTRY_POINT_WINDOW_MS);\n const nowMs = options.now === undefined ? Date.now() : toEpochMs(options.now, 'now');\n if (openedAt === null || openedAt === undefined) return { ...CLOSED };\n\n const startMs = toEpochMs(openedAt, 'openedAt');\n const endMs = options.expiresAt === undefined ? startMs +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