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