meta-cloud-api 0.2.12 → 0.2.14

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.
Files changed (297) hide show
  1. package/README.md +5 -2
  2. package/dist/api/index.d.mts +495 -27
  3. package/dist/api/index.mjs +1 -1
  4. package/dist/api/index.mjs.map +1 -1
  5. package/dist/chunk-KZQQJAPX.mjs +2 -0
  6. package/dist/chunk-KZQQJAPX.mjs.map +1 -0
  7. package/dist/chunk-N7A7DQDX.mjs +2 -0
  8. package/dist/chunk-N7A7DQDX.mjs.map +1 -0
  9. package/dist/chunk-QE4PKOSW.mjs +2 -0
  10. package/dist/chunk-QE4PKOSW.mjs.map +1 -0
  11. package/dist/chunk-R4CFE2XP.mjs +2 -0
  12. package/dist/chunk-R4CFE2XP.mjs.map +1 -0
  13. package/dist/chunk-XVYL7ZTG.mjs +2 -0
  14. package/dist/chunk-XVYL7ZTG.mjs.map +1 -0
  15. package/dist/index.d.mts +142 -43
  16. package/dist/index.mjs +2 -2
  17. package/dist/index.mjs.map +1 -1
  18. package/dist/types/index.d.mts +512 -19
  19. package/dist/types/index.mjs +1 -1
  20. package/dist/types/index.mjs.map +1 -1
  21. package/dist/utils/index.d.mts +70 -21
  22. package/dist/utils/index.mjs +1 -1
  23. package/dist/utils/index.mjs.map +1 -1
  24. package/dist/waba-RRlZTQUG.d.mts +2229 -0
  25. package/dist/{types/whatsapp.d.ts → whatsapp-BNHXjrds.d.mts} +2 -17
  26. package/package.json +52 -18
  27. package/dist/api/base.d.mts +0 -15
  28. package/dist/api/base.d.ts +0 -15
  29. package/dist/api/base.js +0 -2
  30. package/dist/api/base.js.map +0 -1
  31. package/dist/api/base.mjs +0 -2
  32. package/dist/api/base.mjs.map +0 -1
  33. package/dist/api/businessProfile.d.mts +0 -145
  34. package/dist/api/businessProfile.d.ts +0 -145
  35. package/dist/api/businessProfile.js +0 -2
  36. package/dist/api/businessProfile.js.map +0 -1
  37. package/dist/api/businessProfile.mjs +0 -2
  38. package/dist/api/businessProfile.mjs.map +0 -1
  39. package/dist/api/encryption.d.mts +0 -15
  40. package/dist/api/encryption.d.ts +0 -15
  41. package/dist/api/encryption.js +0 -2
  42. package/dist/api/encryption.js.map +0 -1
  43. package/dist/api/encryption.mjs +0 -2
  44. package/dist/api/encryption.mjs.map +0 -1
  45. package/dist/api/flow.d.mts +0 -126
  46. package/dist/api/flow.d.ts +0 -126
  47. package/dist/api/flow.js +0 -2
  48. package/dist/api/flow.js.map +0 -1
  49. package/dist/api/flow.mjs +0 -2
  50. package/dist/api/flow.mjs.map +0 -1
  51. package/dist/api/index.d.ts +0 -28
  52. package/dist/api/index.js +0 -2
  53. package/dist/api/index.js.map +0 -1
  54. package/dist/api/media.d.mts +0 -17
  55. package/dist/api/media.d.ts +0 -17
  56. package/dist/api/media.js +0 -2
  57. package/dist/api/media.js.map +0 -1
  58. package/dist/api/media.mjs +0 -2
  59. package/dist/api/media.mjs.map +0 -1
  60. package/dist/api/messages.d.mts +0 -193
  61. package/dist/api/messages.d.ts +0 -193
  62. package/dist/api/messages.js +0 -2
  63. package/dist/api/messages.js.map +0 -1
  64. package/dist/api/messages.mjs +0 -2
  65. package/dist/api/messages.mjs.map +0 -1
  66. package/dist/api/phoneNumber.d.mts +0 -17
  67. package/dist/api/phoneNumber.d.ts +0 -17
  68. package/dist/api/phoneNumber.js +0 -2
  69. package/dist/api/phoneNumber.js.map +0 -1
  70. package/dist/api/phoneNumber.mjs +0 -2
  71. package/dist/api/phoneNumber.mjs.map +0 -1
  72. package/dist/api/qrCode.d.mts +0 -18
  73. package/dist/api/qrCode.d.ts +0 -18
  74. package/dist/api/qrCode.js +0 -2
  75. package/dist/api/qrCode.js.map +0 -1
  76. package/dist/api/qrCode.mjs +0 -2
  77. package/dist/api/qrCode.mjs.map +0 -1
  78. package/dist/api/registration.d.mts +0 -14
  79. package/dist/api/registration.d.ts +0 -14
  80. package/dist/api/registration.js +0 -2
  81. package/dist/api/registration.js.map +0 -1
  82. package/dist/api/registration.mjs +0 -2
  83. package/dist/api/registration.mjs.map +0 -1
  84. package/dist/api/template.d.mts +0 -18
  85. package/dist/api/template.d.ts +0 -18
  86. package/dist/api/template.js +0 -2
  87. package/dist/api/template.js.map +0 -1
  88. package/dist/api/template.mjs +0 -2
  89. package/dist/api/template.mjs.map +0 -1
  90. package/dist/api/twoStepVerification.d.mts +0 -13
  91. package/dist/api/twoStepVerification.d.ts +0 -13
  92. package/dist/api/twoStepVerification.js +0 -2
  93. package/dist/api/twoStepVerification.js.map +0 -1
  94. package/dist/api/twoStepVerification.mjs +0 -2
  95. package/dist/api/twoStepVerification.mjs.map +0 -1
  96. package/dist/api/waba.d.mts +0 -16
  97. package/dist/api/waba.d.ts +0 -16
  98. package/dist/api/waba.js +0 -2
  99. package/dist/api/waba.js.map +0 -1
  100. package/dist/api/waba.mjs +0 -2
  101. package/dist/api/waba.mjs.map +0 -1
  102. package/dist/enums-CI7vzKhn.d.mts +0 -687
  103. package/dist/enums-CI7vzKhn.d.ts +0 -687
  104. package/dist/httpsClient.d.mts +0 -22
  105. package/dist/httpsClient.d.ts +0 -22
  106. package/dist/httpsClient.js +0 -2
  107. package/dist/httpsClient.js.map +0 -1
  108. package/dist/httpsClient.mjs +0 -2
  109. package/dist/httpsClient.mjs.map +0 -1
  110. package/dist/index.d.ts +0 -46
  111. package/dist/index.js +0 -3
  112. package/dist/index.js.map +0 -1
  113. package/dist/request.d.mts +0 -25
  114. package/dist/request.d.ts +0 -25
  115. package/dist/request.js +0 -2
  116. package/dist/request.js.map +0 -1
  117. package/dist/request.mjs +0 -2
  118. package/dist/request.mjs.map +0 -1
  119. package/dist/types/base.d.mts +0 -8
  120. package/dist/types/base.d.ts +0 -8
  121. package/dist/types/base.js +0 -2
  122. package/dist/types/base.js.map +0 -1
  123. package/dist/types/base.mjs +0 -1
  124. package/dist/types/base.mjs.map +0 -1
  125. package/dist/types/businessProfile.d.mts +0 -153
  126. package/dist/types/businessProfile.d.ts +0 -153
  127. package/dist/types/businessProfile.js +0 -2
  128. package/dist/types/businessProfile.js.map +0 -1
  129. package/dist/types/businessProfile.mjs +0 -1
  130. package/dist/types/businessProfile.mjs.map +0 -1
  131. package/dist/types/config.d.mts +0 -62
  132. package/dist/types/config.d.ts +0 -62
  133. package/dist/types/config.js +0 -2
  134. package/dist/types/config.js.map +0 -1
  135. package/dist/types/config.mjs +0 -1
  136. package/dist/types/config.mjs.map +0 -1
  137. package/dist/types/encryption.d.mts +0 -13
  138. package/dist/types/encryption.d.ts +0 -13
  139. package/dist/types/encryption.js +0 -2
  140. package/dist/types/encryption.js.map +0 -1
  141. package/dist/types/encryption.mjs +0 -1
  142. package/dist/types/encryption.mjs.map +0 -1
  143. package/dist/types/enums.d.mts +0 -1
  144. package/dist/types/enums.d.ts +0 -1
  145. package/dist/types/enums.js +0 -2
  146. package/dist/types/enums.js.map +0 -1
  147. package/dist/types/enums.mjs +0 -2
  148. package/dist/types/enums.mjs.map +0 -1
  149. package/dist/types/flow.d.mts +0 -404
  150. package/dist/types/flow.d.ts +0 -404
  151. package/dist/types/flow.js +0 -2
  152. package/dist/types/flow.js.map +0 -1
  153. package/dist/types/flow.mjs +0 -2
  154. package/dist/types/flow.mjs.map +0 -1
  155. package/dist/types/httpsClient.d.mts +0 -19
  156. package/dist/types/httpsClient.d.ts +0 -19
  157. package/dist/types/httpsClient.js +0 -2
  158. package/dist/types/httpsClient.js.map +0 -1
  159. package/dist/types/httpsClient.mjs +0 -1
  160. package/dist/types/httpsClient.mjs.map +0 -1
  161. package/dist/types/index.d.ts +0 -20
  162. package/dist/types/index.js +0 -2
  163. package/dist/types/index.js.map +0 -1
  164. package/dist/types/logger.d.mts +0 -9
  165. package/dist/types/logger.d.ts +0 -9
  166. package/dist/types/logger.js +0 -2
  167. package/dist/types/logger.js.map +0 -1
  168. package/dist/types/logger.mjs +0 -1
  169. package/dist/types/logger.mjs.map +0 -1
  170. package/dist/types/media.d.mts +0 -31
  171. package/dist/types/media.d.ts +0 -31
  172. package/dist/types/media.js +0 -2
  173. package/dist/types/media.js.map +0 -1
  174. package/dist/types/media.mjs +0 -1
  175. package/dist/types/media.mjs.map +0 -1
  176. package/dist/types/messages.d.mts +0 -558
  177. package/dist/types/messages.d.ts +0 -558
  178. package/dist/types/messages.js +0 -2
  179. package/dist/types/messages.js.map +0 -1
  180. package/dist/types/messages.mjs +0 -1
  181. package/dist/types/messages.mjs.map +0 -1
  182. package/dist/types/phoneNumber.d.mts +0 -82
  183. package/dist/types/phoneNumber.d.ts +0 -82
  184. package/dist/types/phoneNumber.js +0 -2
  185. package/dist/types/phoneNumber.js.map +0 -1
  186. package/dist/types/phoneNumber.mjs +0 -1
  187. package/dist/types/phoneNumber.mjs.map +0 -1
  188. package/dist/types/qrCode.d.mts +0 -27
  189. package/dist/types/qrCode.d.ts +0 -27
  190. package/dist/types/qrCode.js +0 -2
  191. package/dist/types/qrCode.js.map +0 -1
  192. package/dist/types/qrCode.mjs +0 -1
  193. package/dist/types/qrCode.mjs.map +0 -1
  194. package/dist/types/registration.d.mts +0 -14
  195. package/dist/types/registration.d.ts +0 -14
  196. package/dist/types/registration.js +0 -2
  197. package/dist/types/registration.js.map +0 -1
  198. package/dist/types/registration.mjs +0 -1
  199. package/dist/types/registration.mjs.map +0 -1
  200. package/dist/types/request.d.mts +0 -50
  201. package/dist/types/request.d.ts +0 -50
  202. package/dist/types/request.js +0 -2
  203. package/dist/types/request.js.map +0 -1
  204. package/dist/types/request.mjs +0 -1
  205. package/dist/types/request.mjs.map +0 -1
  206. package/dist/types/template.d.mts +0 -106
  207. package/dist/types/template.d.ts +0 -106
  208. package/dist/types/template.js +0 -2
  209. package/dist/types/template.js.map +0 -1
  210. package/dist/types/template.mjs +0 -1
  211. package/dist/types/template.mjs.map +0 -1
  212. package/dist/types/twoStepVerification.d.mts +0 -11
  213. package/dist/types/twoStepVerification.d.ts +0 -11
  214. package/dist/types/twoStepVerification.js +0 -2
  215. package/dist/types/twoStepVerification.js.map +0 -1
  216. package/dist/types/twoStepVerification.mjs +0 -1
  217. package/dist/types/twoStepVerification.mjs.map +0 -1
  218. package/dist/types/waba.d.mts +0 -78
  219. package/dist/types/waba.d.ts +0 -78
  220. package/dist/types/waba.js +0 -2
  221. package/dist/types/waba.js.map +0 -1
  222. package/dist/types/waba.mjs +0 -2
  223. package/dist/types/waba.mjs.map +0 -1
  224. package/dist/types/webhook.d.mts +0 -486
  225. package/dist/types/webhook.d.ts +0 -486
  226. package/dist/types/webhook.js +0 -2
  227. package/dist/types/webhook.js.map +0 -1
  228. package/dist/types/webhook.mjs +0 -2
  229. package/dist/types/webhook.mjs.map +0 -1
  230. package/dist/types/whatsapp.d.mts +0 -61
  231. package/dist/types/whatsapp.js +0 -2
  232. package/dist/types/whatsapp.js.map +0 -1
  233. package/dist/types/whatsapp.mjs +0 -1
  234. package/dist/types/whatsapp.mjs.map +0 -1
  235. package/dist/utils/buildFieldsQueryString.d.mts +0 -3
  236. package/dist/utils/buildFieldsQueryString.d.ts +0 -3
  237. package/dist/utils/buildFieldsQueryString.js +0 -2
  238. package/dist/utils/buildFieldsQueryString.js.map +0 -1
  239. package/dist/utils/buildFieldsQueryString.mjs +0 -2
  240. package/dist/utils/buildFieldsQueryString.mjs.map +0 -1
  241. package/dist/utils/filters.d.mts +0 -144
  242. package/dist/utils/filters.d.ts +0 -144
  243. package/dist/utils/filters.js +0 -2
  244. package/dist/utils/filters.js.map +0 -1
  245. package/dist/utils/filters.mjs +0 -2
  246. package/dist/utils/filters.mjs.map +0 -1
  247. package/dist/utils/flowTypeGuards.d.mts +0 -46
  248. package/dist/utils/flowTypeGuards.d.ts +0 -46
  249. package/dist/utils/flowTypeGuards.js +0 -2
  250. package/dist/utils/flowTypeGuards.js.map +0 -1
  251. package/dist/utils/flowTypeGuards.mjs +0 -2
  252. package/dist/utils/flowTypeGuards.mjs.map +0 -1
  253. package/dist/utils/generateXHub256Sig.d.mts +0 -3
  254. package/dist/utils/generateXHub256Sig.d.ts +0 -3
  255. package/dist/utils/generateXHub256Sig.js +0 -2
  256. package/dist/utils/generateXHub256Sig.js.map +0 -1
  257. package/dist/utils/generateXHub256Sig.mjs +0 -2
  258. package/dist/utils/generateXHub256Sig.mjs.map +0 -1
  259. package/dist/utils/importConfig.d.mts +0 -21
  260. package/dist/utils/importConfig.d.ts +0 -21
  261. package/dist/utils/importConfig.js +0 -2
  262. package/dist/utils/importConfig.js.map +0 -1
  263. package/dist/utils/importConfig.mjs +0 -2
  264. package/dist/utils/importConfig.mjs.map +0 -1
  265. package/dist/utils/index.d.ts +0 -22
  266. package/dist/utils/index.js +0 -2
  267. package/dist/utils/index.js.map +0 -1
  268. package/dist/utils/isMetaError.d.mts +0 -21
  269. package/dist/utils/isMetaError.d.ts +0 -21
  270. package/dist/utils/isMetaError.js +0 -2
  271. package/dist/utils/isMetaError.js.map +0 -1
  272. package/dist/utils/isMetaError.mjs +0 -2
  273. package/dist/utils/isMetaError.mjs.map +0 -1
  274. package/dist/utils/logger.d.mts +0 -13
  275. package/dist/utils/logger.d.ts +0 -13
  276. package/dist/utils/logger.js +0 -2
  277. package/dist/utils/logger.js.map +0 -1
  278. package/dist/utils/logger.mjs +0 -2
  279. package/dist/utils/logger.mjs.map +0 -1
  280. package/dist/utils/objectToQueryString.d.mts +0 -3
  281. package/dist/utils/objectToQueryString.d.ts +0 -3
  282. package/dist/utils/objectToQueryString.js +0 -2
  283. package/dist/utils/objectToQueryString.js.map +0 -1
  284. package/dist/utils/objectToQueryString.mjs +0 -2
  285. package/dist/utils/objectToQueryString.mjs.map +0 -1
  286. package/dist/webhook.d.mts +0 -123
  287. package/dist/webhook.d.ts +0 -123
  288. package/dist/webhook.js +0 -3
  289. package/dist/webhook.js.map +0 -1
  290. package/dist/webhook.mjs +0 -3
  291. package/dist/webhook.mjs.map +0 -1
  292. package/dist/whatsapp.d.mts +0 -58
  293. package/dist/whatsapp.d.ts +0 -58
  294. package/dist/whatsapp.js +0 -2
  295. package/dist/whatsapp.js.map +0 -1
  296. package/dist/whatsapp.mjs +0 -2
  297. package/dist/whatsapp.mjs.map +0 -1
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/index.ts","../src/types/enums.ts","../src/types/flow.ts","../src/types/waba.ts","../src/types/webhook.ts","../src/webhook.ts","../src/utils/generateXHub256Sig.ts","../src/utils/logger.ts","../src/utils/importConfig.ts","../src/utils/isMetaError.ts","../src/utils/objectToQueryString.ts","../src/utils/flowTypeGuards.ts","../src/api/base.ts","../src/utils/buildFieldsQueryString.ts","../src/api/businessProfile.ts","../src/api/encryption.ts","../src/api/flow.ts","../src/api/media.ts","../src/api/messages.ts","../src/api/phoneNumber.ts","../src/api/qrCode.ts","../src/api/registration.ts","../src/api/template.ts","../src/api/twoStepVerification.ts","../src/api/waba.ts","../src/httpsClient.ts","../src/request.ts","../src/whatsapp.ts"],"sourcesContent":["import WebhookHandler, { IRequest, IResponse } from './webhook';\nimport WhatsApp from './whatsapp';\n\nexport default WhatsApp;\nexport * from './types';\nexport * from './utils';\nexport { WebhookHandler, type IRequest, type IResponse };\n","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 '*' = '*',\n}\n\nexport enum ParametersTypesEnum {\n Currency = 'currency',\n DateTime = 'date_time',\n Document = 'document',\n Image = 'image',\n Text = 'text',\n Video = 'video',\n Payload = 'payload',\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 ButtonTypesEnum {\n QuickReply = 'quick_reply',\n URL = 'url',\n}\n\nexport enum ButtonPositionEnum {\n First,\n Second,\n Third,\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","import { IncomingHttpHeaders, IncomingMessage } from 'http';\nimport { ResponseSuccess } from './request';\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\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 asset_type: 'FLOW_JSON';\n file: Blob;\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 type { ResponseSuccess } from './request';\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\nexport interface UpdateWabaSubscription {\n override_callback_uri: string;\n verify_token: string;\n}\n\nexport interface WabaSubscriptions {\n data: Array<WabaSubscription>;\n}\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\nexport enum WabaAccountReviewStatus {\n Approved = 'APPROVED',\n Active = 'ACTIVE',\n Inactive = 'INACTIVE',\n Disabled = 'DISABLED',\n}\n\nexport enum WabaHealthStatusCanSendMessage {\n Blocked = 'BLOCKED',\n Limited = 'LIMITED',\n Available = 'AVAILABLE',\n}\n\nexport enum WabaAccountStatus {\n Approved = 'APPROVED',\n Active = 'ACTIVE',\n Inactive = 'INACTIVE',\n Disabled = 'DISABLED',\n}\n\nexport enum WabaBusinessVerificationStatus {\n Verified = 'verified',\n PendingSubmission = 'pending_submission',\n Unverified = 'unverified',\n Rejected = 'rejected',\n}\n\nexport interface WabaHealthStatusError {\n error_code?: number;\n error_description?: string;\n possible_solution?: string;\n}\n\nexport interface WabaHealthStatusEntity {\n entity_type?: string;\n id?: string;\n can_send_message?: string;\n errors?: WabaHealthStatusError[];\n}\n\nexport interface WabaHealthStatus {\n can_send_message?: WabaHealthStatusCanSendMessage;\n entities?: WabaHealthStatusEntity[];\n}\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\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\nexport type WabaAccountFieldsParam = WabaAccountFields[];\n","import { MessageTypesEnum } from './enums';\n\nexport interface WebhookContact {\n /**\n * WhatsApp ID of the contact. Business can respond to this contact using this ID.\n */\n wa_id: string;\n /**\n * Additional unique, alphanumeric identifier for a WhatsApp user\n */\n user_id?: string;\n /**\n * Profile of Whatsapp user\n */\n profile: {\n /**\n * The display name of the contact\n */\n name: string;\n };\n}\n\n/**\n * Represents a message received through the webhook\n * Based on Meta's documentation: https://developers.facebook.com/docs/whatsapp/cloud-api/webhooks/components#messages-object\n */\nexport interface WebhookMessage {\n /**\n * The message ID\n */\n id: string;\n\n /**\n * The sender's phone number\n */\n from: string;\n\n /**\n * The timestamp of the message\n */\n timestamp: string;\n\n /**\n * The type of message (text, image, etc.)\n */\n type: MessageTypesEnum;\n\n /**\n * The phone number ID that received the message\n */\n phoneNumberId: string;\n\n /**\n * The display phone number that received the message\n */\n displayPhoneNumber: string;\n\n /**\n * The profile name of the sender\n */\n profileName: string;\n\n /**\n * Text object for text messages\n */\n text?: {\n /**\n * The text content of the message\n */\n body: string;\n };\n\n /**\n * Image object for image messages\n */\n image?: {\n /**\n * The image caption (if provided)\n */\n caption?: string;\n /**\n * The SHA256 hash of the image\n */\n sha256?: string;\n /**\n * The ID for the image\n */\n id: string;\n /**\n * The MIME type of the image\n */\n mime_type: string;\n };\n\n /**\n * Video object for video messages\n */\n video?: {\n /**\n * The video caption (if provided)\n */\n caption?: string;\n /**\n * The SHA256 hash of the video\n */\n sha256?: string;\n /**\n * The ID for the video\n */\n id: string;\n /**\n * The MIME type of the video\n */\n mime_type: string;\n };\n\n /**\n * Audio object for audio messages\n */\n audio?: {\n /**\n * The ID for the audio file\n */\n id: string;\n /**\n * The MIME type of the audio file\n */\n mime_type: string;\n /**\n * Whether the audio is a voice message\n */\n voice?: boolean;\n };\n\n /**\n * Document object for document messages\n */\n document?: {\n /**\n * The document caption (if provided)\n */\n caption?: string;\n /**\n * The document filename\n */\n filename: string;\n /**\n * The SHA256 hash of the document\n */\n sha256?: string;\n /**\n * The ID for the document\n */\n id: string;\n /**\n * The MIME type of the document\n */\n mime_type: string;\n };\n\n /**\n * Sticker object for sticker messages\n */\n sticker?: {\n /**\n * The ID for the sticker\n */\n id: string;\n /**\n * Whether this is an animated sticker\n */\n animated: boolean;\n /**\n * The MIME type of the sticker\n */\n mime_type: string;\n };\n\n /**\n * Reaction object for reaction messages\n */\n reaction?: {\n /**\n * The ID of the message being reacted to\n */\n message_id: string;\n /**\n * Emoji used for the reaction\n */\n emoji: string;\n };\n\n /**\n * Contacts object for contact messages\n */\n contacts?: Array<{\n /**\n * The contact's name\n */\n name: {\n formatted_name: string;\n first_name?: string;\n last_name?: string;\n middle_name?: string;\n suffix?: string;\n prefix?: string;\n };\n /**\n * The contact's phone numbers\n */\n phones?: Array<{\n phone: string;\n type?: string;\n wa_id?: string;\n }>;\n /**\n * The contact's emails\n */\n emails?: Array<{\n email: string;\n type?: string;\n }>;\n /**\n * The contact's addresses\n */\n addresses?: Array<{\n street?: string;\n city?: string;\n state?: string;\n zip?: string;\n country?: string;\n country_code?: string;\n type?: string;\n }>;\n /**\n * The contact's organizations\n */\n org?: {\n company?: string;\n department?: string;\n title?: string;\n };\n /**\n * The contact's URLs\n */\n urls?: Array<{\n url: string;\n type?: string;\n }>;\n /**\n * The contact's birthday (YYYY-MM-DD format)\n */\n birthday?: string;\n }>;\n\n /**\n * Location object for location messages\n */\n location?: {\n /**\n * Latitude of the location\n */\n latitude: number;\n /**\n * Longitude of the location\n */\n longitude: number;\n /**\n * Name of the location\n */\n name?: string;\n /**\n * Address of the location\n */\n address?: string;\n };\n\n /**\n * Interactive object for interactive messages\n */\n interactive?: {\n /**\n * Type of the interactive message\n * Can be: button_reply, list_reply, flow, nfm_reply, etc.\n */\n type: string;\n /**\n * ID for the button that was clicked\n */\n button_reply?: {\n id: string;\n title: string;\n };\n /**\n * ID for the list item that was selected\n */\n list_reply?: {\n id: string;\n title: string;\n description?: string;\n };\n\n /**\n * NFM (No-Code Flow Message) reply data\n */\n nfm_reply?: {\n /**\n * Response data in JSON format\n */\n response_json: string;\n /**\n * Body text of the reply\n */\n body: string;\n /**\n * Name of the flow\n */\n name: string;\n };\n };\n\n /**\n * System object for system messages (like user phone number changes)\n */\n system?: {\n /**\n * The type of system update\n */\n type: string;\n /**\n * User's identity if the update is a customer identity change\n */\n identity?: string;\n /**\n * Old and new phone numbers if the update is a phone number change\n */\n customer?: {\n /**\n * The previous phone number\n */\n previous_wa_id: string;\n /**\n * The new phone number\n */\n wa_id: string;\n };\n };\n\n /**\n * Order object for order messages\n */\n order?: {\n /**\n * Catalog ID\n */\n catalog_id: string;\n /**\n * Product items in the order\n */\n product_items: Array<{\n /**\n * Product ID\n */\n product_retailer_id: string;\n /**\n * Quantity of the product\n */\n quantity: number;\n /**\n * Item price\n */\n item_price: number;\n /**\n * Currency code\n */\n currency: string;\n }>;\n /**\n * Text message included with the order\n */\n text?: string;\n };\n\n /**\n * Context object, included when a user replies or interacts\n */\n context?: {\n /**\n * ID of the message\n */\n id?: string;\n /**\n * ID of the sender\n */\n from?: string;\n /**\n * ID of the message being replied to or interacted with\n */\n message_id: string;\n /**\n * ID of the forwarded message, if applicable\n */\n forwarded?: boolean;\n /**\n * Frequently forwarded status\n */\n frequently_forwarded?: boolean;\n /**\n * Original message information if the message was referred\n */\n referred_product?: {\n /**\n * Catalog ID\n */\n catalog_id: string;\n /**\n * Product ID\n */\n product_retailer_id: string;\n };\n };\n\n /**\n * Errors array, if the message had errors\n */\n errors?: Array<{\n /**\n * Error code\n */\n code: number;\n /**\n * Error title\n */\n title: string;\n /**\n * Error message\n */\n message: string;\n /**\n * Error details object\n */\n error_data?: {\n /**\n * Describes the error details\n */\n details: string;\n };\n }>;\n\n /**\n * Button object for button messages\n */\n button?: {\n /**\n * The payload for the button\n */\n payload: string;\n /**\n * Button text\n */\n text: string;\n };\n\n /**\n * The original message data as received from the webhook\n */\n originalData: any;\n}\n\n/**\n * Represents a non-message event received through the webhook\n */\nexport interface WebhookEvent {\n /**\n * The field type of the event\n */\n field: string;\n\n /**\n * The event data\n */\n value: any;\n}\n\n/**\n * Handler function for processing messages\n */\nexport type MessageHandler = (message: WebhookMessage) => void | Promise<void>;\n\n/**\n * Handler function for processing events\n */\nexport type EventHandler = (event: WebhookEvent) => void | Promise<void>;\n\n/**\n * Statuses that can be received in status updates\n */\nexport enum MessageStatus {\n DELIVERED = 'delivered',\n READ = 'read',\n SENT = 'sent',\n}\n\n/**\n * Event fields that can be received through the webhook\n */\nexport enum EventField {\n MESSAGES = 'messages',\n STATUSES = 'statuses',\n MESSAGE_TEMPLATE_STATUS_UPDATE = 'message_template_status_update',\n PHONE_NUMBER_QUALITY_UPDATE = 'phone_number_quality_update',\n PHONE_NUMBER_NAME_UPDATE = 'phone_number_name_update',\n UNKNOWN = 'unknown',\n}\n","import { IncomingMessage } from 'http';\nimport { FlowEndpointRequest, FlowTypeEnum, MessageTypesEnum, WhatsAppConfig } from './types';\nimport { WabaConfigType } from './types/config';\n\nimport crypto from 'crypto';\nimport { EventField, WebhookEvent, WebhookMessage } from './types/webhook';\nimport { importConfig } from './utils';\nimport { isFlowDataExchangeRequest, isFlowErrorRequest, isFlowPingRequest } from './utils/flowTypeGuards';\nimport Logger from './utils/logger';\nimport WhatsApp from './whatsapp';\nconst LIB_NAME = 'WEBHOOK';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport interface IRequest extends IncomingMessage {\n body: any;\n query: Record<string, any>;\n method?: string;\n}\nexport interface IResponse {\n status: (code: number) => IResponse;\n send: (body: any) => IResponse | void;\n json: (body: any) => IResponse | void;\n end: () => void;\n}\n\n/**\n * Webhook handler for WhatsApp Cloud API\n */\nexport default class WebhookHandler {\n private config: WabaConfigType;\n private client: WhatsApp;\n private messageHandlers: Map<\n MessageTypesEnum,\n (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>\n > = new Map();\n private eventHandlers: Map<string, (event: WebhookEvent) => void | Promise<void>> = new Map();\n private preProcessHandler: ((whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>) | null = null;\n private postProcessHandler: ((whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>) | null = null;\n private flowHandlers: Map<FlowTypeEnum, (whatsapp: WhatsApp, request: FlowEndpointRequest) => any | Promise<any>> =\n new Map();\n\n /**\n * Create a new WebhookHandler\n * @param config The WhatsApp configuration\n */\n constructor(config: WhatsAppConfig) {\n const configuration = importConfig(config);\n this.config = configuration;\n this.client = new WhatsApp(config);\n LOGGER.log('WebhookHandler instantiated!');\n }\n\n /**\n * Handle a GET request for webhook verification\n */\n public handleVerificationRequest<Req extends IRequest, Res extends IResponse>(req: Req, res: Res): void {\n const mode = req.query['hub.mode'];\n const token = req.query['hub.verify_token'];\n const challenge = req.query['hub.challenge'];\n\n if (mode === 'subscribe' && token === this.config.WEBHOOK_VERIFICATION_TOKEN) {\n LOGGER.log('Webhook verified successfully');\n res.status(200).send(challenge);\n } else {\n LOGGER.log('Webhook verification failed');\n res.status(403).end();\n }\n }\n\n /**\n * Handle a POST request for webhook events\n */\n public async handleWebhookRequest<Req extends IRequest, Res extends IResponse>(req: Req, res: Res): Promise<void> {\n const body = req.body;\n\n // Check this is a WhatsApp Business Account webhook\n if (body.object !== 'whatsapp_business_account') {\n LOGGER.log('Received webhook for non-WhatsApp event');\n res.status(404).end();\n return;\n }\n\n // Process each entry\n for (const entry of body.entry) {\n try {\n const changes = entry.changes;\n for (const change of changes) {\n if (change.field === EventField.MESSAGES) {\n await this.processMessages(change.value);\n } else {\n // Handle other event types\n await this.processEvent(change.field, change.value);\n }\n }\n } catch (error) {\n LOGGER.log(`Error processing webhook: ${error}`);\n }\n }\n\n // Always respond with 200 to acknowledge receipt\n res.status(200).end();\n }\n\n /**\n * Handle webhook requests (both verification and events)\n */\n public handleRequest(req: IRequest, res: IResponse): void | Promise<void> {\n if (req.method === 'GET') {\n return this.handleVerificationRequest(req, res);\n } else if (req.method === 'POST') {\n return this.handleWebhookRequest(req, res);\n } else {\n res.status(405).end(); // Method not allowed\n }\n }\n\n /**\n * Process incoming messages\n */\n private async processMessages(value: any): Promise<void> {\n // Extract metadata\n const metadata = value.metadata;\n const displayPhoneNumber = metadata.display_phone_number;\n const phoneNumberId = metadata.phone_number_id;\n const profileName = value.contacts[0].profile.name;\n const messages = value.messages as WebhookMessage[];\n\n // Process messages if present\n if (messages && messages.length > 0) {\n for (const message of messages) {\n const messageType = message.type;\n\n // Create the base message object\n const processedMessage: WebhookMessage = {\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 // Add type-specific data based on the message type\n switch (message.type) {\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 default:\n // Unknown message type\n break;\n }\n\n // Add context if available\n if (message.context) {\n processedMessage.context = message.context;\n }\n\n // Add errors if available\n if (message.errors) {\n processedMessage.errors = message.errors;\n }\n\n // 1. Execute pre-processing handler if exists\n if (this.preProcessHandler) {\n await Promise.resolve(this.preProcessHandler(this.client, processedMessage));\n }\n\n // 2. Dispatch to appropriate message handler\n if (this.messageHandlers.has(messageType)) {\n const handler = this.messageHandlers.get(messageType);\n if (handler) {\n await Promise.resolve(handler(this.client, processedMessage));\n }\n }\n\n // Also dispatch to general message handler if exists\n if (this.messageHandlers.has(MessageTypesEnum['*'])) {\n const handler = this.messageHandlers.get(MessageTypesEnum['*']);\n if (handler) {\n await Promise.resolve(handler(this.client, processedMessage));\n }\n }\n\n // 3. Execute post-processing handler if exists\n if (this.postProcessHandler) {\n await Promise.resolve(this.postProcessHandler(this.client, processedMessage));\n }\n }\n }\n\n if (value.statuses && value.statuses.length > 0) {\n await this.processEvent(EventField.STATUSES, value);\n }\n }\n\n private async processEvent(field: string, value: any): Promise<void> {\n const event: WebhookEvent = {\n field,\n value,\n };\n\n if (this.eventHandlers.has(field)) {\n const handler = this.eventHandlers.get(field);\n if (handler) {\n await Promise.resolve(handler(event));\n }\n }\n\n if (this.eventHandlers.has('*')) {\n const handler = this.eventHandlers.get('*');\n if (handler) {\n await Promise.resolve(handler(event));\n }\n }\n }\n\n /**\n * Register a message handler for a specific message type\n * @param type Message type to handle, or '*' for all types\n * @param handler The handler function\n */\n public onMessage(\n type: MessageTypesEnum,\n handler: (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>,\n ): void {\n this.messageHandlers.set(type, handler);\n LOGGER.log(`Registered handler for message type: ${type}`);\n }\n\n /**\n * Register a general event handler\n * @param field Event field to handle, or '*' for all fields\n * @param handler The handler function\n */\n public onEvent(field: string, handler: (event: WebhookEvent) => void | Promise<void>): void {\n this.eventHandlers.set(field, handler);\n LOGGER.log(`Registered handler for event field: ${field}`);\n }\n\n /**\n * Register a pre-processing handler for all messages\n * @param handler The handler function\n */\n public onMessagePreProcess(handler: (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>): void {\n this.preProcessHandler = handler;\n LOGGER.log('Registered pre-processing handler for all messages');\n }\n\n /**\n * Register a post-processing handler for all messages\n * @param handler The handler function\n */\n public onMessagePostProcess(handler: (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>): void {\n this.postProcessHandler = handler;\n LOGGER.log('Registered post-processing handler for all messages');\n }\n\n public async handleFlowRequest<Req extends IRequest & { rawBody: string }, Res extends IResponse>(\n req: Req,\n res: Res,\n ): Promise<void> {\n if (!this.isRequestSignatureValid(req)) {\n res.status(403).end();\n return;\n }\n\n let flowRequestData: {\n decryptedBody: FlowEndpointRequest;\n aesKeyBuffer: Buffer;\n initialVectorBuffer: Buffer;\n };\n\n try {\n flowRequestData = this.decryptRequest(req.body);\n } catch (error) {\n LOGGER.error(error);\n if (error instanceof Error) {\n res.status(421).send(error.message);\n return;\n }\n\n res.status(500).send('internal server error, please check with logs');\n return;\n }\n\n const { decryptedBody, aesKeyBuffer, initialVectorBuffer } = flowRequestData;\n\n // Determine flow type\n let flowType: FlowTypeEnum | undefined = undefined;\n\n if (isFlowPingRequest(decryptedBody)) {\n flowType = FlowTypeEnum.Ping;\n } else if (isFlowDataExchangeRequest(decryptedBody)) {\n flowType = FlowTypeEnum.Change;\n } else if (isFlowErrorRequest(decryptedBody)) {\n flowType = FlowTypeEnum.Error;\n }\n\n // Create a comprehensive request object\n const processedRequest: FlowEndpointRequest = decryptedBody;\n\n // If we have a registered handler for this flow type, use it\n if (flowType && this.flowHandlers.has(flowType)) {\n const handler = this.flowHandlers.get(flowType);\n if (handler) {\n const response = await Promise.resolve(handler(this.client, processedRequest));\n const encryptedResponse = this.encryptResponse(response, aesKeyBuffer, initialVectorBuffer);\n res.status(200).send(encryptedResponse);\n return;\n }\n }\n\n // If we have a catch-all handler, use it\n if (this.flowHandlers.has(FlowTypeEnum.All)) {\n const handler = this.flowHandlers.get(FlowTypeEnum.All);\n if (handler) {\n const response = await Promise.resolve(handler(this.client, processedRequest));\n const encryptedResponse = this.encryptResponse(response, aesKeyBuffer, initialVectorBuffer);\n res.status(200).send(encryptedResponse);\n return;\n }\n }\n\n // No handler found, send an empty response\n // Add an empty response here for consistency\n LOGGER.log('No handler found, sending an empty response');\n const encryptedResponse = this.encryptResponse({}, aesKeyBuffer, initialVectorBuffer);\n res.status(200).send(encryptedResponse);\n }\n\n public isRequestSignatureValid(req: IRequest & { rawBody: string }): boolean {\n const appSecret = this.config.M4D_APP_SECRET;\n\n if (!appSecret) {\n LOGGER.warn('App Secret is not set up. Please Add M4D_APP_SECRET or configuration');\n return false;\n }\n\n const signatureHeader = req.headers['x-hub-signature-256'];\n\n if (!signatureHeader || typeof signatureHeader !== 'string') {\n LOGGER.warn('x-hub-signature-256 header is missing');\n return false;\n }\n\n const signatureBuffer = Buffer.from(signatureHeader.replace('sha256=', ''), 'utf-8');\n const hmac = crypto.createHmac('sha256', appSecret);\n\n const digestString = hmac.update(req.rawBody).digest('hex');\n const digestBuffer = Buffer.from(digestString, 'utf-8');\n\n // Note: This is corrected from the original code which had inverted logic\n if (!crypto.timingSafeEqual(digestBuffer, signatureBuffer)) {\n LOGGER.error('Error: Request Signature did not match');\n return false;\n }\n return true;\n }\n\n public decryptRequest(body: any): {\n decryptedBody: FlowEndpointRequest;\n aesKeyBuffer: Buffer;\n initialVectorBuffer: Buffer;\n } {\n const { encrypted_aes_key, encrypted_flow_data, initial_vector } = body;\n\n const privatePem = this.config.FLOW_API_PRIVATE_PEM.replace(/\\\\n/g, '\\n');\n const passphrase = this.config.FLOW_API_PASSPHRASE;\n\n const privateKey = crypto.createPrivateKey({ key: privatePem, passphrase });\n let decryptedAesKey = null;\n try {\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(error);\n /*\n Failed to decrypt. Please verify your private key.\n If you change your public key. You need to return HTTP status code 421 to refresh the public key on the client\n */\n throw new Error('Failed to decrypt the request. Please verify your private key.');\n }\n\n // decrypt flow data\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 const decipher = crypto.createDecipheriv('aes-128-gcm', decryptedAesKey, initialVectorBuffer);\n decipher.setAuthTag(encrypted_flow_data_tag);\n\n const decryptedJSONString = Buffer.concat([\n decipher.update(encrypted_flow_data_body),\n decipher.final(),\n ]).toString('utf-8');\n\n return {\n decryptedBody: JSON.parse(decryptedJSONString),\n aesKeyBuffer: decryptedAesKey,\n initialVectorBuffer,\n };\n }\n\n private encryptResponse(response: any, aesKeyBuffer: Buffer, initialVectorBuffer: Buffer) {\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 // encrypt response data\n const cipher = crypto.createCipheriv('aes-128-gcm', aesKeyBuffer, Buffer.from(flipped_iv));\n return Buffer.concat([\n cipher.update(JSON.stringify(response || {}), 'utf-8'),\n cipher.final(),\n cipher.getAuthTag(),\n ]).toString('base64');\n } catch (error) {\n LOGGER.error('Response encryption error:', error);\n throw new Error('Failed to encrypt response. Internal server error.');\n }\n }\n\n /**\n * Register a Flow action handler for a specific flow type\n * @param type The flow type to handle (ping, change, error), or '*' for all types\n * @param handler The handler function that receives the WhatsApp client and the Flow request\n */\n public onFlow(\n type: FlowTypeEnum,\n handler: (whatsapp: WhatsApp, request: FlowEndpointRequest) => any | Promise<any>,\n ): void {\n this.flowHandlers.set(type, handler);\n LOGGER.log(`Registered handler for Flow type: ${type}`);\n }\n}\n","import * as crypto from 'crypto';\n\nexport const generateXHub256Sig = (body: string, appSecret: string) => {\n return crypto.createHmac('sha256', appSecret).update(body, 'utf-8').digest('hex');\n};\n","// @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 { WhatsAppConfig } from 'src/types/whatsapp';\nimport type { WabaConfigType } from '../types/config';\nimport { WabaConfigEnum } from '../types/enums';\nimport Logger from './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 LOGGER.log(`Configuration loaded for App Id ${wabaConfig[WabaConfigEnum.AppId]}`);\n\n return wabaConfig;\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","export const objectToQueryString = (params: Record<string, any>): string => {\n if (!params || Object.keys(params).length === 0) {\n return '';\n }\n\n const searchParams = new URLSearchParams();\n\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined) {\n searchParams.append(key, String(value));\n }\n }\n\n const queryString = searchParams.toString();\n return queryString ? `?${queryString}` : '';\n};\n","import {\n FlowActionEnum,\n FlowDataExchangeRequest,\n FlowEndpointRequest,\n FlowErrorNotificationRequest,\n FlowHealthCheckRequest,\n} from 'src/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 { HttpMethodsEnum } from '../types/enums';\nimport type { BaseClass } from '../types/base';\nimport type { WabaConfigType } from '../types/config';\nimport type { RequesterClass } from '../types/request';\nimport Logger from '../utils/logger';\n\nconst LIB_NAME = 'BaseAPI';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default 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 LOGGER.log('Initialized with HTTPSClient');\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","export function buildFieldsQueryString(fields?: string[]): string {\n if (!fields) return '';\n\n let fieldParams = '';\n\n if (Array.isArray(fields)) {\n fieldParams = fields.join(',');\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 { buildFieldsQueryString } from '../utils/buildFieldsQueryString';\nimport {\n BusinessProfileClass,\n BusinessProfileFieldsParam,\n BusinessProfileResponse,\n UpdateBusinessProfileRequest,\n UploadBusinessProfileResponse,\n UploadHandle,\n UploadSessionResponse,\n} from '../types/businessProfile';\nimport type { WabaConfigType } from '../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../types/request';\nimport { objectToQueryString } from '../utils/objectToQueryString';\nimport BaseAPI from './base';\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 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?: BusinessProfileFieldsParam): Promise<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: 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(fileLength: number, fileType: string, fileName: string): Promise<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<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<UploadHandle> {\n return this.sendJson(HttpMethodsEnum.Get, `${uploadId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n}\n","import type { WabaConfigType } from '../types/config';\nimport type { EncryptionClass, EncryptionPublicKeyResponse } from '../types/encryption';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../types/enums';\nimport type { RequesterClass, RequesterResponseInterface, ResponseSuccess } from '../types/request';\nimport BaseAPI from './base';\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 { WabaConfigType } from '../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../types/enums';\nimport {\n CreateFlowResponse,\n Flow,\n FlowAssetsResponse,\n FlowCategoryEnum,\n FlowClass,\n FlowMigrationResponse,\n FlowPreviewResponse,\n FlowsListResponse,\n UpdateFlowResponse,\n ValidateFlowJsonResponse,\n} from '../types/flow';\nimport { RequesterClass, ResponseSuccess } from '../types/request';\nimport Logger from '../utils/logger';\nimport BaseAPI from './base';\n\nconst LIB_NAME = 'FlowAPI';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class FlowAPI extends BaseAPI implements FlowClass {\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n LOGGER.log('FlowAPI initialized');\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<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?: 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<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 | 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<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<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?: 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<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<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(flowId: string, flowJsonData: Blob | Buffer | object): Promise<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 LOGGER.error('Error during Flow JSON validation attempt:', 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<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 type { WabaConfigType } from '../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../types/enums';\nimport type { MediaClass, MediaResponse, UploadMediaResponse } from '../types/media';\nimport type { RequesterClass, ResponseSuccess } from '../types/request';\nimport BaseAPI from './base';\n\nexport default class MediaAPI extends BaseAPI implements MediaClass {\n private readonly endpoint = 'media';\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n async getMediaById(mediaId: string): Promise<MediaResponse> {\n return this.sendJson(HttpMethodsEnum.Get, `${mediaId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n async uploadMedia(file: File, messagingProduct: string = 'whatsapp'): Promise<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 async deleteMedia(mediaId: string): Promise<ResponseSuccess> {\n return this.sendJson(HttpMethodsEnum.Delete, `${mediaId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n async downloadMedia(mediaUrl: string): Promise<Blob> {\n return this.sendJson(HttpMethodsEnum.Get, mediaUrl, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n}\n","import type { WabaConfigType } from '../types/config';\nimport {\n type ComponentTypesEnum,\n HttpMethodsEnum,\n type InteractiveTypesEnum,\n MessageTypesEnum,\n WabaConfigEnum,\n} from '../types/enums';\n\nimport type * as m from '../types/messages';\nimport type { RequesterClass } from '../types/request';\nimport BaseAPI from './base';\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\n// Request object interface type definitions\nexport interface MessageRequestParams<T> {\n body: T;\n to: string;\n replyMessageId?: string;\n}\n\nexport interface TextMessageParams extends MessageRequestParams<m.TextObject | string> {\n previewUrl?: boolean;\n}\n\nexport interface ReactionParams {\n messageId: string;\n emoji: string;\n to: string;\n}\n\nexport interface StatusParams {\n status: string;\n messageId: string;\n typingIndicator?: {\n type: string;\n };\n}\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, previewUrl, to, replyMessageId } = params;\n\n let textObject: m.TextObject;\n if (typeof body === 'string') {\n textObject = {\n body: body,\n preview_url: previewUrl,\n };\n } else {\n textObject = body;\n }\n\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Text, textObject, to, replyMessageId)));\n }\n\n /**\n * Sends a video 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 (used for read receipts and typing indicators)\n * @param params The status update parameter object\n * @returns Promise with the response\n */\n async status(params: m.StatusParams): Promise<m.MessagesResponse> {\n const { status, messageId, typingIndicator } = params;\n\n const bodyToSend = {\n messaging_product: 'whatsapp',\n status: status,\n message_id: messageId,\n ...(typingIndicator && { typing_indicator: typingIndicator }),\n };\n\n return this.send(JSON.stringify(bodyToSend));\n }\n\n /**\n * Marks a message as read in WhatsApp\n * @param params The parameter object to mark message as read\n * @returns Promise with the 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 * Marks a message as read and shows a typing indicator in WhatsApp\n * @param params The typing indicator parameter object\n * @returns Promise with the response\n */\n async showTypingIndicator(params: { messageId: string }): Promise<m.MessagesResponse> {\n return this.status({\n status: 'read',\n messageId: params.messageId,\n typingIndicator: {\n type: 'text',\n },\n });\n }\n\n /**\n * Sends an interactive list message\n * @param params The list message parameter object\n * @returns Promise with the response\n */\n async interactiveList(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.List }>,\n ): 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 an interactive CTA URL message\n * @param params The CTA URL message parameter object\n * @returns Promise with the response\n */\n async interactiveCtaUrl(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.CtaUrl }>,\n ): 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 request message\n * @param params The location request message parameter object\n * @returns Promise with the response\n */\n async interactiveLocationRequest(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.LocationRequest }>,\n ): 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 an address message to request shipping address from the user\n * Note: This feature is only available for businesses based in India and their India customers\n * @param params The address message parameter object\n * @returns Promise with the response\n */\n async interactiveAddressMessage(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.AddressMessage }>,\n ): 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 an interactive reply buttons message\n * @param params The reply buttons message parameter object\n * @returns Promise with the response\n */\n async interactiveReplyButtons(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.Button }>,\n ): 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 an interactive Flow message\n * @param params The Flow message parameter object\n * @returns Promise with the response\n */\n async interactiveFlow(\n params: m.MessageRequestParams<m.InteractiveObject & { type: InteractiveTypesEnum.Flow }>,\n ): Promise<m.MessagesResponse> {\n const { body, to, replyMessageId } = params;\n\n // Apply default values for FlowParameters\n if (body.action.parameters.flow_message_version === undefined) {\n body.action.parameters.flow_message_version = '3';\n }\n if (body.action.parameters.mode === undefined) {\n body.action.parameters.mode = 'published';\n }\n if (body.action.parameters.flow_action === undefined) {\n body.action.parameters.flow_action = 'navigate';\n }\n\n // Only include flow_action_payload when flow_action is navigate\n if (body.action.parameters.flow_action === 'navigate') {\n if (body.action.parameters.flow_action_payload?.screen === undefined) {\n body.action.parameters.flow_action_payload = {\n ...body.action.parameters.flow_action_payload,\n screen: 'INIT',\n };\n }\n } else if (body.action.parameters.flow_action === 'data_exchange') {\n // Remove flow_action_payload when flow_action is data_exchange\n delete body.action.parameters.flow_action_payload;\n }\n\n return this.send(JSON.stringify(this.bodyBuilder(MessageTypesEnum.Interactive, body, to, replyMessageId)));\n }\n\n /**\n * Sends a reaction to a message (emoji response)\n * @param params The reaction message parameter object\n * @returns Promise with the response\n */\n async reaction(params: m.ReactionParams): Promise<m.MessagesResponse> {\n const { messageId, emoji, to } = params;\n\n const body = {\n messaging_product: 'whatsapp',\n recipient_type: 'individual',\n to: to,\n type: 'reaction',\n reaction: {\n message_id: messageId,\n emoji: emoji,\n },\n };\n\n return this.send(JSON.stringify(body));\n }\n}\n","import {\n PhoneNumberClass,\n PhoneNumberResponse,\n PhoneNumbersResponse,\n RequestVerificationCodeRequest,\n VerifyCodeRequest,\n} from '../types/phoneNumber';\nimport { objectToQueryString } from '../utils/objectToQueryString';\nimport type { WabaConfigType } from '../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../types/request';\nimport BaseAPI from './base';\n\nexport default class PhoneNumberApi extends BaseAPI implements PhoneNumberClass {\n private readonly endpoint = 'phone_numbers';\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n async getPhoneNumberById(fields?: string): Promise<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 async getPhoneNumbers(): Promise<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 async requestVerificationCode(\n requestVerificationCodeRequest: RequestVerificationCodeRequest,\n ): Promise<ResponseSuccess> {\n return this.sendJson(\n HttpMethodsEnum.Post,\n `${this.config[WabaConfigEnum.PhoneNumberId]}/request_code`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(requestVerificationCodeRequest),\n );\n }\n\n async verifyCode(verifyCodeRequest: 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(verifyCodeRequest),\n );\n }\n}\n","import type { WabaConfigType } from '../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../types/enums';\nimport {\n CreateQrCodeRequest,\n QrCodeClass,\n QrCodeResponse,\n QrCodesResponse,\n UpdateQrCodeRequest,\n} from '../types/qrCode';\nimport type { RequesterClass, ResponseSuccess } from '../types/request';\nimport BaseAPI from './base';\n\nexport default class QrCodeAPI extends BaseAPI implements QrCodeClass {\n private readonly endpoint = 'message_qrdls';\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n async createQrCode(request: CreateQrCodeRequest): Promise<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 async getQrCodes(): Promise<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 async getQrCode(qrCodeId: string): Promise<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 async updateQrCode(request: UpdateQrCodeRequest): Promise<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 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 type { WabaConfigType } from '../types/config';\nimport { DataLocalizationRegionEnum, HttpMethodsEnum, WabaConfigEnum } from '../types/enums';\nimport { RegistrationClass } from '../types/registration';\nimport type { RequesterClass, ResponseSuccess } from '../types/request';\nimport BaseAPI from './base';\n\nexport default class RegistrationAPI extends BaseAPI implements RegistrationClass {\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n async register(pin: string, dataLocalizationRegion?: DataLocalizationRegionEnum): Promise<ResponseSuccess> {\n const body = {\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 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 { objectToQueryString } from '../utils/objectToQueryString';\nimport type { WabaConfigType } from '../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../types/enums';\nimport type { RequesterClass, ResponsePagination, ResponseSuccess } from '../types/request';\nimport type {\n TemplateClass,\n TemplateDeleteParams,\n TemplateGetParams,\n TemplateRequestBody,\n TemplateResponse,\n} from '../types/template';\nimport BaseAPI from './base';\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 type { WabaConfigType } from '../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../types/request';\nimport { TwoStepVerificationClass } from '../types/twoStepVerification';\nimport BaseAPI from './base';\n\nexport default class TwoStepVerificationAPI extends BaseAPI implements TwoStepVerificationClass {\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\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 { buildFieldsQueryString } from '../utils/buildFieldsQueryString';\nimport type { WabaConfigType } from '../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../types/enums';\nimport type { RequesterClass, ResponseSuccess } from '../types/request';\nimport type {\n UpdateWabaSubscription,\n WABAClass,\n WabaAccount,\n WabaAccountFieldsParam,\n WabaSubscriptions,\n} from '../types/waba';\nimport BaseAPI from './base';\n\nexport default class WabaAPI extends BaseAPI implements WABAClass {\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n }\n\n async getWabaAccount(fields?: WabaAccountFieldsParam): Promise<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 async getAllWabaSubscriptions(): Promise<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 async updateWabaSubscription({\n override_callback_uri,\n verify_token,\n }: 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 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 { Agent } from 'https';\n\nimport Logger from './utils/logger';\nimport { HttpMethodsEnum } from './types/enums';\nimport { HttpsClientClass, HttpsClientResponseClass, ResponseHeaders, ResponseJSONBody } from './types/httpsClient';\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 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 HttpsClient from './httpsClient';\nimport type { HttpMethodsEnum } from './types/enums';\nimport type { RequesterClass } from './types/request';\nimport { isMetaError, MetaError } from './utils/isMetaError';\nimport Logger from './utils/logger';\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 { WabaConfigType } from './types/config';\nimport * as SDKEnums from './types/enums';\nimport Logger from './utils/logger';\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 Requester from './request';\nimport { WhatsAppClass, WhatsAppConfig } from './types/whatsapp';\nimport { importConfig } from './utils/importConfig';\n\nconst LIB_NAME = 'WHATSAPP';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nconst headerPrefix = 'WA_SDK';\n\nexport default class WhatsApp implements WhatsAppClass {\n config: WabaConfigType;\n\n requester: Readonly<Requester>;\n\n readonly messages: MessagesAPI;\n readonly templates: TemplateAPI;\n readonly phoneNumber: PhoneNumberAPI;\n readonly qrCode: QrCodeAPI;\n readonly encryption: EncryptionAPI;\n readonly twoStepVerification: TwoStepVerificationAPI;\n readonly registration: RegistrationAPI;\n readonly media: MediaAPI;\n readonly waba: WabaAPI;\n readonly flow: FlowAPI;\n readonly businessProfile: BusinessProfileAPI;\n static readonly Enums = SDKEnums;\n\n constructor(config?: WhatsAppConfig) {\n this.config = importConfig(config);\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.userAgent(),\n );\n\n this.messages = new MessagesAPI(this.config, this.requester);\n this.templates = new TemplateAPI(this.config, this.requester);\n this.phoneNumber = new PhoneNumberAPI(this.config, this.requester);\n this.qrCode = new QrCodeAPI(this.config, this.requester);\n this.encryption = new EncryptionAPI(this.config, this.requester);\n this.twoStepVerification = new TwoStepVerificationAPI(this.config, this.requester);\n this.registration = new RegistrationAPI(this.config, this.requester);\n this.media = new MediaAPI(this.config, this.requester);\n this.waba = new WabaAPI(this.config, this.requester);\n this.flow = new FlowAPI(this.config, this.requester);\n this.businessProfile = new BusinessProfileAPI(this.config, this.requester);\n LOGGER.log('WhatsApp Node.js SDK instantiated!');\n }\n\n private userAgent(): string {\n const userAgentString = `${headerPrefix}/${'0.0.1'} (Node.js ${process.version})`;\n return userAgentString;\n }\n\n updateTimeout(ms: number): boolean {\n this.config[SDKEnums.WabaConfigEnum.RequestTimeout] = ms;\n LOGGER.log(`Updated request timeout to ${ms}ms`);\n return true;\n }\n\n updatePhoneNumberId(phoneNumberId: number): boolean {\n this.config[SDKEnums.WabaConfigEnum.PhoneNumberId] = phoneNumberId;\n LOGGER.log(`Updated sender phone number id to ${phoneNumberId}`);\n return true;\n }\n\n updateAccessToken(accessToken: string): boolean {\n this.config[SDKEnums.WabaConfigEnum.AccessToken] = accessToken;\n LOGGER.log(`Updated access token`);\n return true;\n }\n\n updateWabaId(wabaId: string): boolean {\n this.config[SDKEnums.WabaConfigEnum.BusinessAcctId] = wabaId;\n LOGGER.log(`Updated business account id to ${wabaId}`);\n return true;\n }\n}\n"],"mappings":"0kBAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,yBAAAE,GAAA,yBAAAC,GAAA,uBAAAC,EAAA,oBAAAC,EAAA,iBAAAC,EAAA,uBAAAC,EAAA,0BAAAC,GAAA,sBAAAC,GAAA,+BAAAC,GAAA,2BAAAC,GAAA,eAAAC,GAAA,mBAAAC,GAAA,qBAAAC,GAAA,mBAAAC,GAAA,iBAAAC,GAAA,oBAAAC,EAAA,wBAAAC,GAAA,yBAAAC,EAAA,kBAAAC,GAAA,kBAAAC,GAAA,qBAAAC,EAAA,wBAAAC,EAAA,4BAAAC,GAAA,2BAAAC,GAAA,eAAAC,GAAA,0BAAAC,GAAA,0BAAAC,GAAA,uBAAAC,EAAA,wBAAAC,GAAA,4BAAAC,GAAA,sBAAAC,GAAA,mCAAAC,GAAA,mBAAAC,EAAA,mCAAAC,GAAA,mBAAAC,EAAA,qBAAAC,GAAA,YAAAC,GAAA,uBAAAC,GAAA,iBAAAC,EAAA,8BAAAC,GAAA,uBAAAC,GAAA,sBAAAC,GAAA,gBAAAC,EAAA,wBAAAC,IAAA,eAAAC,GAAA9C,ICAA,IAAA+C,GAAA,GAAAC,GAAAD,GAAA,yBAAAE,GAAA,yBAAAC,GAAA,uBAAAC,EAAA,oBAAAC,EAAA,iBAAAC,EAAA,uBAAAC,EAAA,0BAAAC,GAAA,sBAAAC,GAAA,+BAAAC,GAAA,2BAAAC,GAAA,oBAAAC,EAAA,wBAAAC,GAAA,yBAAAC,EAAA,kBAAAC,GAAA,qBAAAC,EAAA,wBAAAC,EAAA,4BAAAC,GAAA,2BAAAC,GAAA,eAAAC,GAAA,0BAAAC,GAAA,0BAAAC,GAAA,uBAAAC,EAAA,wBAAAC,GAAA,mBAAAC,EAAA,qBAAA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EAAO,IAAI,qCAAqC6B,CAAI,EAAE,CAC1D,CACJ,EL7dA,IAAOkC,GAAQC","names":["index_exports","__export","AudioMediaTypesEnum","BusinessVerticalEnum","ButtonPositionEnum","ButtonTypesEnum","CategoryEnum","ComponentTypesEnum","ConversationTypesEnum","CurrencyCodesEnum","DataLocalizationRegionEnum","DocumentMediaTypesEnum","EventField","FlowActionEnum","FlowCategoryEnum","FlowStatusEnum","FlowTypeEnum","HttpMethodsEnum","ImageMediaTypesEnum","InteractiveTypesEnum","LanguagesEnum","MessageStatus","MessageTypesEnum","ParametersTypesEnum","ReferralSourceTypesEnum","RequestCodeMethodsEnum","StatusEnum","StickerMediaTypesEnum","SystemChangeTypesEnum","TemplateStatusEnum","VideoMediaTypesEnum","WabaAccountReviewStatus","WabaAccountStatus","WabaBusinessVerificationStatus","WabaConfigEnum","WabaHealthStatusCanSendMessage","WebhookHandler","WebhookTypesEnum","index_default","generateXHub256Sig","importConfig","isFlowDataExchangeRequest","isFlowErrorRequest","isFlowPingRequest","isMetaError","objectToQueryString","__toCommonJS","enums_exports","__export","AudioMediaTypesEnum","BusinessVerticalEnum","ButtonPositionEnum","ButtonTypesEnum","CategoryEnum","ComponentTypesEnum","ConversationTypesEnum","CurrencyCodesEnum","DataLocalizationRegionEnum","DocumentMediaTypesEnum","HttpMethodsEnum","ImageMediaTypesEnum","InteractiveTypesEnum","LanguagesEnum","MessageTypesEnum","ParametersTypesEnum","ReferralSourceTypesEnum","RequestCodeMethodsEnum","StatusEnum","StickerMediaTypesEnum","SystemChangeTypesEnum","TemplateStatusEnum","VideoMediaTypesEnum","WabaConfigEnum","WebhookTypesEnum","FlowStatusEnum","FlowCategoryEnum","FlowActionEnum","FlowTypeEnum","WabaAccountReviewStatus","WabaHealthStatusCanSendMessage","WabaAccountStatus","WabaBusinessVerificationStatus","MessageStatus","EventField","import_crypto","crypto","generateXHub256Sig","body","appSecret","Logger","name","debug","data","prefix","LIB_NAME","LOG_LOCAL","LOGGER","Logger","DEFAULT_LISTENER_PORT","DEFAULT_MAX_RETRIES_AFTER_WAIT","DEFAULT_REQUEST_TIMEOUT","emptyConfigChecker","config","importConfig","inputConfig","wabaConfig","isMetaError","error","objectToQueryString","params","searchParams","key","value","queryString","isObject","value","isString","DATA_EXCHANGE_ACTIONS","ERROR_ACTIONS","isFlowDataExchangeRequest","request","action","version","screen","data","hasValidVersion","hasValidAction","hasValidScreen","hasValidData","isFlowErrorRequest","isFlowPingRequest","LIB_NAME","LOG_LOCAL","LOGGER","Logger","BaseAPI","config","client","method","endpoint","timeout","body","buildFieldsQueryString","fields","fieldParams","_","value","key","BusinessProfileAPI","BaseAPI","config","client","fields","buildFieldsQueryString","updateRequest","fileLength","fileType","fileName","queryParams","objectToQueryString","uploadId","file","EncryptionAPI","BaseAPI","config","client","businessPublicKey","formData","LIB_NAME","LOG_LOCAL","LOGGER","Logger","FlowAPI","BaseAPI","config","client","wabaId","data","payload","flowId","fields","dateFormat","params","queryString","invalidate","formData","fileContent","flowJsonData","result","isValid","error","destinationWabaId","MediaAPI","BaseAPI","config","client","mediaId","file","messagingProduct","formData","mediaUrl","MessagesApi","BaseAPI","config","client","type","payload","to","replyMessageId","body","params","previewUrl","textObject","status","messageId","typingIndicator","bodyToSend","emoji","PhoneNumberApi","BaseAPI","config","client","fields","queryParams","objectToQueryString","requestVerificationCodeRequest","verifyCodeRequest","QrCodeAPI","BaseAPI","config","client","request","qrCodeId","RegistrationAPI","BaseAPI","config","client","pin","dataLocalizationRegion","body","TemplateApi","BaseAPI","config","client","templateId","template","params","objectToQueryString","TwoStepVerificationAPI","BaseAPI","config","client","pin","body","WabaAPI","BaseAPI","config","client","fields","queryString","buildFieldsQueryString","override_callback_uri","verify_token","body","import_https","LIB_NAME","LOG_LOCAL","LOGGER","Logger","HttpsClient","hostname","path","method","headers","timeout","body","url","controller","timeoutId","response","HttpsClientResponse","error","resp","err","LIB_NAME","LOG_LOCAL","LOGGER","Logger","Requester","apiVersion","phoneNumberId","accessToken","businessAcctId","userAgent","HttpsClient","contentType","additionalHeaders","headers","endpoint","method","timeout","body","effectiveContentType","path","response","errorData","isMetaError","error","formData","urlEncodedBody","LIB_NAME","LOG_LOCAL","LOGGER","Logger","headerPrefix","WhatsApp","enums_exports","config","importConfig","Requester","MessagesApi","TemplateApi","PhoneNumberApi","QrCodeAPI","EncryptionAPI","TwoStepVerificationAPI","RegistrationAPI","MediaAPI","WabaAPI","FlowAPI","BusinessProfileAPI","ms","phoneNumberId","accessToken","wabaId","LIB_NAME","LOG_LOCAL","LOGGER","Logger","WebhookHandler","config","configuration","importConfig","WhatsApp","req","res","mode","token","challenge","body","entry","changes","change","error","value","metadata","displayPhoneNumber","phoneNumberId","profileName","messages","message","messageType","processedMessage","handler","field","event","type","flowRequestData","decryptedBody","aesKeyBuffer","initialVectorBuffer","flowType","isFlowPingRequest","isFlowDataExchangeRequest","isFlowErrorRequest","processedRequest","response","encryptedResponse","appSecret","signatureHeader","signatureBuffer","digestString","crypto","digestBuffer","encrypted_aes_key","encrypted_flow_data","initial_vector","privatePem","passphrase","privateKey","decryptedAesKey","flowDataBuffer","TAG_LENGTH","encrypted_flow_data_body","encrypted_flow_data_tag","decipher","decryptedJSONString","flipped_iv","pair","cipher","index_default","WhatsApp"]}
@@ -1,25 +0,0 @@
1
- import { H as HttpMethodsEnum } from './enums-CI7vzKhn.mjs';
2
- import { RequesterClass } from './types/request.mjs';
3
- import { HttpsClientResponseClass } from './types/httpsClient.mjs';
4
- import HttpsClient from './httpsClient.mjs';
5
- import 'https';
6
-
7
- declare class Requester implements RequesterClass {
8
- client: Readonly<HttpsClient>;
9
- accessToken: Readonly<string>;
10
- phoneNumberId: Readonly<number>;
11
- businessAcctId: Readonly<string>;
12
- apiVersion: Readonly<string>;
13
- userAgent: Readonly<string>;
14
- host: Readonly<string>;
15
- protocol: Readonly<string>;
16
- constructor(apiVersion: string, phoneNumberId: number, accessToken: string, businessAcctId: string, userAgent: string);
17
- buildHeader(contentType: string, additionalHeaders?: Record<string, string>): HeadersInit;
18
- buildCAPIPath(endpoint: string): string;
19
- sendRequest(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any, contentType?: string, additionalHeaders?: Record<string, string>): Promise<HttpsClientResponseClass>;
20
- getJson<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any, additionalHeaders?: Record<string, string>): Promise<T>;
21
- sendFormData<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, formData: FormData, additionalHeaders?: Record<string, string>): Promise<T>;
22
- sendUrlEncodedForm<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, formData: Record<string, string>, additionalHeaders?: Record<string, string>): Promise<T>;
23
- }
24
-
25
- export { Requester as default };
package/dist/request.d.ts DELETED
@@ -1,25 +0,0 @@
1
- import { H as HttpMethodsEnum } from './enums-CI7vzKhn.js';
2
- import { RequesterClass } from './types/request.js';
3
- import { HttpsClientResponseClass } from './types/httpsClient.js';
4
- import HttpsClient from './httpsClient.js';
5
- import 'https';
6
-
7
- declare class Requester implements RequesterClass {
8
- client: Readonly<HttpsClient>;
9
- accessToken: Readonly<string>;
10
- phoneNumberId: Readonly<number>;
11
- businessAcctId: Readonly<string>;
12
- apiVersion: Readonly<string>;
13
- userAgent: Readonly<string>;
14
- host: Readonly<string>;
15
- protocol: Readonly<string>;
16
- constructor(apiVersion: string, phoneNumberId: number, accessToken: string, businessAcctId: string, userAgent: string);
17
- buildHeader(contentType: string, additionalHeaders?: Record<string, string>): HeadersInit;
18
- buildCAPIPath(endpoint: string): string;
19
- sendRequest(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any, contentType?: string, additionalHeaders?: Record<string, string>): Promise<HttpsClientResponseClass>;
20
- getJson<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any, additionalHeaders?: Record<string, string>): Promise<T>;
21
- sendFormData<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, formData: FormData, additionalHeaders?: Record<string, string>): Promise<T>;
22
- sendUrlEncodedForm<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, formData: Record<string, string>, additionalHeaders?: Record<string, string>): Promise<T>;
23
- }
24
-
25
- export { Requester as default };
package/dist/request.js DELETED
@@ -1,2 +0,0 @@
1
- "use strict";var g=Object.defineProperty;var w=Object.getOwnPropertyDescriptor;var R=Object.getOwnPropertyNames;var b=Object.prototype.hasOwnProperty;var E=(t,e)=>{for(var r in e)g(t,r,{get:e[r],enumerable:!0})},C=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of R(e))!b.call(t,s)&&s!==r&&g(t,s,{get:()=>e[s],enumerable:!(n=w(e,s))||n.enumerable});return t};var H=t=>C(g({},"__esModule",{value:!0}),t);var O={};E(O,{default:()=>m});module.exports=H(O);var y=require("https");var d=class{name;debug;constructor(e,r=!1){this.name=e,this.debug=r}log(...e){if(this.debug){let r=`[ ${Date.now()} ]`;this.name&&(r+=` - ${this.name}`),console.log.apply(console,[r,": ",...e])}}error(...e){let r=`[ ${Date.now()} ] - ERROR`;this.name&&(r+=` - ${this.name}`),console.error.apply(console,[r,": ",...e])}warn(...e){let r=`[ ${Date.now()} ] - WARN`;this.name&&(r+=` - ${this.name}`),console.warn.apply(console,[r,": ",...e])}info(...e){let r=`[ ${Date.now()} ] - INFO`;this.name&&(r+=` - ${this.name}`),console.info.apply(console,[r,": ",...e])}};var _="HttpsClient",$=!1,A=new d(_,process.env.DEBUG==="true"||$),l=class{agent;constructor(){this.agent=new y.Agent({keepAlive:!0})}clearSockets(){return this.agent.destroy(),!0}async sendRequest(e,r,n,s,a,p){let i=`https://${e}/${r}`,u=new AbortController,o=setTimeout(()=>u.abort(),a);try{let c=await fetch(i,{method:n,headers:s,body:p,signal:u.signal});return A.log(`${n} : ${i} - ${JSON.stringify(c)}`),clearTimeout(o),new h(c)}catch(c){throw c}}},h=class{res;respStatusCode;respHeaders;constructor(e){this.res=e,this.respStatusCode=e.status,this.respHeaders=Object.fromEntries(e.headers.entries())}statusCode(){return this.respStatusCode}headers(){return this.respHeaders}rawResponse(){return this.res}async json(){try{return await this.res.json()}catch(e){throw new Error("Failed to parse response body to JSON: "+e.message)}}};function f(t){return t!=null&&typeof t=="object"&&"error"in t&&typeof t.error=="object"&&t.error!=null&&"message"in t.error&&typeof t.error.message=="string"&&"type"in t.error&&typeof t.error.type=="string"&&"code"in t.error&&typeof t.error.code=="number"&&"fbtrace_id"in t.error&&typeof t.error.fbtrace_id=="string"&&(!("error_data"in t.error)||typeof t.error.error_data=="object"&&t.error.error_data!=null&&"messaging_product"in t.error.error_data&&t.error.error_data.messaging_product==="whatsapp"&&"details"in t.error.error_data&&typeof t.error.error_data.details=="string")&&(!("error_subcode"in t.error)||typeof t.error.error_subcode=="number")}var M="REQUESTER",T=!1,I=new d(M,process.env.DEBUG==="true"||T),m=class{client;accessToken;phoneNumberId;businessAcctId;apiVersion;userAgent;host;protocol="https:";constructor(e,r,n,s,a){this.client=new l,this.host="graph.facebook.com",this.apiVersion=e||"22",this.phoneNumberId=r,this.accessToken=n,this.businessAcctId=s,this.userAgent=a}buildHeader(e,r){let n={Authorization:`Bearer ${this.accessToken}`,"User-Agent":this.userAgent};return e!=="multipart/form-data"&&(n["Content-Type"]=e),r&&Object.assign(n,r),n}buildCAPIPath(e){return`v${this.apiVersion}.0/${e}`}async sendRequest(e,r,n,s,a="application/json",p){let i=a;s instanceof FormData?i="multipart/form-data":typeof s=="string"&&s.startsWith("<?xml")&&(i="application/xml");let u=`${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(r)}`;I.log(`${e} : ${u} (${i})`);try{let o=await this.client.sendRequest(this.host,this.buildCAPIPath(r),e,this.buildHeader(i,p),n,e==="POST"||e==="PUT"?s:void 0);if(!o.rawResponse().ok){let c=await o.json();throw f(c)?c:{name:"MetaError",message:"Unknown error occurred",error:{message:c.message||"Unknown error occurred",type:"UnknownError",code:o.statusCode(),fbtrace_id:""}}}return o}catch(o){throw f(o)?o:{name:"MetaError",message:o instanceof Error?o.message:"Network error occurred",error:{message:o instanceof Error?o.message:"Network error occurred",type:"NetworkError",code:500,fbtrace_id:""}}}}async getJson(e,r,n,s,a){return await(await this.sendRequest(e,r,n,s,"application/json",a)).json()}async sendFormData(e,r,n,s,a){return await(await this.sendRequest(e,r,n,s,"multipart/form-data",a)).json()}async sendUrlEncodedForm(e,r,n,s,a){let p=new URLSearchParams(s).toString();return await(await this.sendRequest(e,r,n,p,"application/x-www-form-urlencoded",a)).json()}};
2
- //# sourceMappingURL=request.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/request.ts","../src/httpsClient.ts","../src/utils/logger.ts","../src/utils/isMetaError.ts"],"sourcesContent":["import HttpsClient from './httpsClient';\nimport type { HttpMethodsEnum } from './types/enums';\nimport type { RequesterClass } from './types/request';\nimport { isMetaError, MetaError } from './utils/isMetaError';\nimport Logger from './utils/logger';\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 { Agent } from 'https';\n\nimport Logger from './utils/logger';\nimport { HttpMethodsEnum } from './types/enums';\nimport { HttpsClientClass, HttpsClientResponseClass, ResponseHeaders, ResponseJSONBody } from './types/httpsClient';\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 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","// @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","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"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,eAAAC,EAAAH,GCAA,IAAAI,EAAsB,iBCGtB,IAAqBC,EAArB,KAAuD,CAC3C,KACA,MAER,YAAYC,EAAcC,EAAiB,GAAO,CAC9C,KAAK,KAAOD,EACZ,KAAK,MAAQC,CACjB,CAEA,OAAOC,EAAa,CAChB,GAAI,KAAK,MAAO,CACZ,IAAIC,EAAS,KAAK,KAAK,IAAI,CAAC,KACxB,KAAK,OACLA,GAAU,MAAM,KAAK,IAAI,IAE7B,QAAQ,IAAI,MAAM,QAAS,CAACA,EAAQ,KAAM,GAAGD,CAAI,CAAC,CACtD,CACJ,CAEA,SAASA,EAAa,CAClB,IAAIC,EAAS,KAAK,KAAK,IAAI,CAAC,aACxB,KAAK,OACLA,GAAU,MAAM,KAAK,IAAI,IAE7B,QAAQ,MAAM,MAAM,QAAS,CAACA,EAAQ,KAAM,GAAGD,CAAI,CAAC,CACxD,CAEA,QAAQA,EAAa,CACjB,IAAIC,EAAS,KAAK,KAAK,IAAI,CAAC,YACxB,KAAK,OACLA,GAAU,MAAM,KAAK,IAAI,IAE7B,QAAQ,KAAK,MAAM,QAAS,CAACA,EAAQ,KAAM,GAAGD,CAAI,CAAC,CACvD,CAEA,QAAQA,EAAa,CACjB,IAAIC,EAAS,KAAK,KAAK,IAAI,CAAC,YACxB,KAAK,OACLA,GAAU,MAAM,KAAK,IAAI,IAE7B,QAAQ,KAAK,MAAM,QAAS,CAACA,EAAQ,KAAM,GAAG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B,KAAK,CAC3B,CAEA,MAAM,mBACFG,EACAD,EACAE,EACAQ,EACAZ,EACU,CACV,IAAMa,EAAiB,IAAI,gBAAgBD,CAAQ,EAAE,SAAS,EAS9D,OAAQ,MARI,MAAM,KAAK,YACnBT,EACAD,EACAE,EACAS,EACA,oCACAb,CACJ,GACkB,KAAK,CAC3B,CACJ","names":["request_exports","__export","Requester","__toCommonJS","import_https","Logger","name","debug","data","prefix","LIB_NAME","LOG_LOCAL","LOGGER","Logger","HttpsClient","hostname","path","method","headers","timeout","body","url","controller","timeoutId","response","HttpsClientResponse","error","resp","err","isMetaError","error","LIB_NAME","LOG_LOCAL","LOGGER","Logger","Requester","apiVersion","phoneNumberId","accessToken","businessAcctId","userAgent","HttpsClient","contentType","additionalHeaders","headers","endpoint","method","timeout","body","effectiveContentType","path","response","errorData","isMetaError","error","formData","urlEncodedBody"]}
package/dist/request.mjs DELETED
@@ -1,2 +0,0 @@
1
- import{Agent as f}from"https";var d=class{name;debug;constructor(e,t=!1){this.name=e,this.debug=t}log(...e){if(this.debug){let t=`[ ${Date.now()} ]`;this.name&&(t+=` - ${this.name}`),console.log.apply(console,[t,": ",...e])}}error(...e){let t=`[ ${Date.now()} ] - ERROR`;this.name&&(t+=` - ${this.name}`),console.error.apply(console,[t,": ",...e])}warn(...e){let t=`[ ${Date.now()} ] - WARN`;this.name&&(t+=` - ${this.name}`),console.warn.apply(console,[t,": ",...e])}info(...e){let t=`[ ${Date.now()} ] - INFO`;this.name&&(t+=` - ${this.name}`),console.info.apply(console,[t,": ",...e])}};var y="HttpsClient",w=!1,R=new d(y,process.env.DEBUG==="true"||w),l=class{agent;constructor(){this.agent=new f({keepAlive:!0})}clearSockets(){return this.agent.destroy(),!0}async sendRequest(e,t,s,n,a,p){let i=`https://${e}/${t}`,u=new AbortController,o=setTimeout(()=>u.abort(),a);try{let c=await fetch(i,{method:s,headers:n,body:p,signal:u.signal});return R.log(`${s} : ${i} - ${JSON.stringify(c)}`),clearTimeout(o),new m(c)}catch(c){throw c}}},m=class{res;respStatusCode;respHeaders;constructor(e){this.res=e,this.respStatusCode=e.status,this.respHeaders=Object.fromEntries(e.headers.entries())}statusCode(){return this.respStatusCode}headers(){return this.respHeaders}rawResponse(){return this.res}async json(){try{return await this.res.json()}catch(e){throw new Error("Failed to parse response body to JSON: "+e.message)}}};function g(r){return r!=null&&typeof r=="object"&&"error"in r&&typeof r.error=="object"&&r.error!=null&&"message"in r.error&&typeof r.error.message=="string"&&"type"in r.error&&typeof r.error.type=="string"&&"code"in r.error&&typeof r.error.code=="number"&&"fbtrace_id"in r.error&&typeof r.error.fbtrace_id=="string"&&(!("error_data"in r.error)||typeof r.error.error_data=="object"&&r.error.error_data!=null&&"messaging_product"in r.error.error_data&&r.error.error_data.messaging_product==="whatsapp"&&"details"in r.error.error_data&&typeof r.error.error_data.details=="string")&&(!("error_subcode"in r.error)||typeof r.error.error_subcode=="number")}var b="REQUESTER",E=!1,C=new d(b,process.env.DEBUG==="true"||E),h=class{client;accessToken;phoneNumberId;businessAcctId;apiVersion;userAgent;host;protocol="https:";constructor(e,t,s,n,a){this.client=new l,this.host="graph.facebook.com",this.apiVersion=e||"22",this.phoneNumberId=t,this.accessToken=s,this.businessAcctId=n,this.userAgent=a}buildHeader(e,t){let s={Authorization:`Bearer ${this.accessToken}`,"User-Agent":this.userAgent};return e!=="multipart/form-data"&&(s["Content-Type"]=e),t&&Object.assign(s,t),s}buildCAPIPath(e){return`v${this.apiVersion}.0/${e}`}async sendRequest(e,t,s,n,a="application/json",p){let i=a;n instanceof FormData?i="multipart/form-data":typeof n=="string"&&n.startsWith("<?xml")&&(i="application/xml");let u=`${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(t)}`;C.log(`${e} : ${u} (${i})`);try{let o=await this.client.sendRequest(this.host,this.buildCAPIPath(t),e,this.buildHeader(i,p),s,e==="POST"||e==="PUT"?n:void 0);if(!o.rawResponse().ok){let c=await o.json();throw g(c)?c:{name:"MetaError",message:"Unknown error occurred",error:{message:c.message||"Unknown error occurred",type:"UnknownError",code:o.statusCode(),fbtrace_id:""}}}return o}catch(o){throw g(o)?o:{name:"MetaError",message:o instanceof Error?o.message:"Network error occurred",error:{message:o instanceof Error?o.message:"Network error occurred",type:"NetworkError",code:500,fbtrace_id:""}}}}async getJson(e,t,s,n,a){return await(await this.sendRequest(e,t,s,n,"application/json",a)).json()}async sendFormData(e,t,s,n,a){return await(await this.sendRequest(e,t,s,n,"multipart/form-data",a)).json()}async sendUrlEncodedForm(e,t,s,n,a){let p=new URLSearchParams(n).toString();return await(await this.sendRequest(e,t,s,p,"application/x-www-form-urlencoded",a)).json()}};export{h as default};
2
- //# sourceMappingURL=request.mjs.map