meta-cloud-api 0.2.36 → 0.2.37

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 (34) hide show
  1. package/dist/{BusinessProfileApi-DO28tMcf.d.ts → BusinessProfileApi-C1x8w77V.d.ts} +1 -1
  2. package/dist/{EncryptionApi-CFuuNH2K.d.ts → EncryptionApi-udtMPgrF.d.ts} +1 -1
  3. package/dist/{FlowApi-Mwlby1Rl.d.ts → FlowApi-B_S2OAFn.d.ts} +1 -1
  4. package/dist/{MediaApi-CyoByati.d.ts → MediaApi-Raddyh38.d.ts} +1 -1
  5. package/dist/{MessageApi-BU1WUNKS.d.ts → MessageApi-CsdVH_9V.d.ts} +1 -1
  6. package/dist/{PhoneNumberApi-C3Hmh_nZ.d.ts → PhoneNumberApi-DVUn9x88.d.ts} +1 -1
  7. package/dist/{QrCodeApi-BPsHp3ad.d.ts → QrCodeApi-lDLJYnCg.d.ts} +1 -1
  8. package/dist/{RegistrationApi-DI9NskvK.d.ts → RegistrationApi-Co1NiWw_.d.ts} +1 -1
  9. package/dist/{TemplateApi-DXr47lZe.d.ts → TemplateApi-DhR1Xy73.d.ts} +1 -1
  10. package/dist/{TwoStepVerificationApi-CICKknhN.d.ts → TwoStepVerificationApi-ByTfkum8.d.ts} +1 -1
  11. package/dist/{WabaApi-DZurKSzA.d.ts → WabaApi-CXb5Z_Ek.d.ts} +1 -1
  12. package/dist/{WebhookHandler-q8tq2j0d.d.ts → WebhookHandler-BcVZPlq8.d.ts} +2 -2
  13. package/dist/{base-GKqD_DhO.d.ts → base-WGahY7ao.d.ts} +19 -1
  14. package/dist/chunk-4ZHGFSME.js +3 -0
  15. package/dist/{chunk-MTRF47KZ.js.map → chunk-4ZHGFSME.js.map} +1 -1
  16. package/dist/core/webhook/index.d.ts +14 -14
  17. package/dist/core/webhook/index.js +1 -1
  18. package/dist/core/whatsapp/index.d.ts +16 -100
  19. package/dist/features/encryption/index.d.ts +3 -3
  20. package/dist/features/flow/index.d.ts +3 -3
  21. package/dist/features/media/index.d.ts +3 -3
  22. package/dist/features/messages/index.d.ts +3 -3
  23. package/dist/features/phone/index.d.ts +3 -3
  24. package/dist/features/profile/index.d.ts +3 -3
  25. package/dist/features/qrCode/index.d.ts +3 -3
  26. package/dist/features/registration/index.d.ts +3 -3
  27. package/dist/features/template/index.d.ts +3 -3
  28. package/dist/features/twoStepVerification/index.d.ts +3 -3
  29. package/dist/features/waba/index.d.ts +3 -3
  30. package/dist/index-BBvXSzXG.d.ts +100 -0
  31. package/dist/index.d.ts +16 -16
  32. package/dist/index.js +1 -1
  33. package/package.json +1 -1
  34. package/dist/chunk-MTRF47KZ.js +0 -3
@@ -1,4 +1,4 @@
1
- import { d as BaseClass, R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-GKqD_DhO.js';
1
+ import { d as BaseClass, R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-WGahY7ao.js';
2
2
  import { WabaConfigType } from './shared/types/config.js';
3
3
  import { B as BusinessVerticalEnum } from './enums-CM95zXd_.js';
4
4
 
@@ -1,4 +1,4 @@
1
- import { c as ResponseData, R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-GKqD_DhO.js';
1
+ import { c as ResponseData, R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-WGahY7ao.js';
2
2
  import { WabaConfigType } from './shared/types/config.js';
3
3
 
4
4
  type EncryptionPublicKeyResponse = ResponseData<{
@@ -1,4 +1,4 @@
1
- import { R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-GKqD_DhO.js';
1
+ import { R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-WGahY7ao.js';
2
2
  import { WabaConfigType } from './shared/types/config.js';
3
3
 
4
4
  /**
@@ -1,4 +1,4 @@
1
- import { R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-GKqD_DhO.js';
1
+ import { R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-WGahY7ao.js';
2
2
  import { WabaConfigType } from './shared/types/config.js';
3
3
 
4
4
  type MediaResponse = {
@@ -1,4 +1,4 @@
1
- import { d as BaseClass, G as GeneralRequestBody, B as BaseAPI, a as RequesterClass } from './base-GKqD_DhO.js';
1
+ import { d as BaseClass, G as GeneralRequestBody, B as BaseAPI, a as RequesterClass } from './base-WGahY7ao.js';
2
2
  import { WabaConfigType } from './shared/types/config.js';
3
3
  import { g as InteractiveTypesEnum, d as ComponentTypesEnum, L as LanguagesEnum, P as ParametersTypesEnum, C as CurrencyCodesEnum, c as ButtonTypesEnum, b as ButtonPositionEnum, M as MessageTypesEnum } from './enums-CM95zXd_.js';
4
4
 
@@ -1,4 +1,4 @@
1
- import { P as Paging, R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-GKqD_DhO.js';
1
+ import { P as Paging, R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-WGahY7ao.js';
2
2
  import { WabaConfigType } from './shared/types/config.js';
3
3
 
4
4
  type QualityRating = 'GREEN' | 'YELLOW' | 'RED' | 'NA';
@@ -1,4 +1,4 @@
1
- import { c as ResponseData, R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-GKqD_DhO.js';
1
+ import { c as ResponseData, R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-WGahY7ao.js';
2
2
  import { WabaConfigType } from './shared/types/config.js';
3
3
 
4
4
  type QrCodeResponse = {
@@ -1,4 +1,4 @@
1
- import { R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-GKqD_DhO.js';
1
+ import { R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-WGahY7ao.js';
2
2
  import { WabaConfigType } from './shared/types/config.js';
3
3
  import { D as DataLocalizationRegionEnum } from './enums-CM95zXd_.js';
4
4
 
@@ -1,4 +1,4 @@
1
- import { G as GeneralRequestBody, R as ResponseSuccess, b as ResponsePagination, B as BaseAPI, a as RequesterClass } from './base-GKqD_DhO.js';
1
+ import { G as GeneralRequestBody, R as ResponseSuccess, b as ResponsePagination, B as BaseAPI, a as RequesterClass } from './base-WGahY7ao.js';
2
2
  import { WabaConfigType } from './shared/types/config.js';
3
3
  import { L as LanguagesEnum, a as CategoryEnum, T as TemplateStatusEnum } from './enums-CM95zXd_.js';
4
4
 
@@ -1,4 +1,4 @@
1
- import { R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-GKqD_DhO.js';
1
+ import { R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-WGahY7ao.js';
2
2
  import { WabaConfigType } from './shared/types/config.js';
3
3
 
4
4
  type TwoStepVerificationRequest = {
@@ -1,4 +1,4 @@
1
- import { R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-GKqD_DhO.js';
1
+ import { R as ResponseSuccess, B as BaseAPI, a as RequesterClass } from './base-WGahY7ao.js';
2
2
  import { WabaConfigType } from './shared/types/config.js';
3
3
 
4
4
  /**
@@ -1,7 +1,7 @@
1
1
  import { WabaConfigType, WhatsAppConfig } from './shared/types/config.js';
2
2
  import { M as MessageTypesEnum } from './enums-CM95zXd_.js';
3
- import { g as FlowEndpointRequest, n as FlowTypeEnum } from './FlowApi-Mwlby1Rl.js';
4
- import { WhatsApp } from './core/whatsapp/index.js';
3
+ import { g as FlowEndpointRequest, n as FlowTypeEnum } from './FlowApi-B_S2OAFn.js';
4
+ import { W as WhatsApp } from './index-BBvXSzXG.js';
5
5
 
6
6
  interface WebhookContact {
7
7
  /**
@@ -2,6 +2,24 @@ import { WabaConfigType } from './shared/types/config.js';
2
2
  import { H as HttpMethodsEnum } from './enums-CM95zXd_.js';
3
3
 
4
4
  type GeneralRequestBody = Record<string, unknown>;
5
+ interface GeneralHeaderInterface {
6
+ /**
7
+ * Authorization token. This is required for all HTTP requests made to the graph API.
8
+ * @default 'Bearer '
9
+ */
10
+ Authorization: string;
11
+ /**
12
+ * Content type of the message being sent. This is required for all HTTP requests made to the graph API.
13
+ * @default 'application/json'
14
+ */
15
+ 'Content-Type': string;
16
+ /**
17
+ * User agent field sent in all requests. This is used to gather SDK usage metrics and help
18
+ * better triage support requests.
19
+ * @default `WA_SDK/${ SDK_version } (Node.js ${ process.version })`
20
+ */
21
+ 'User-Agent': string;
22
+ }
5
23
  interface RequesterResponseInterface<T> {
6
24
  json: () => Promise<T>;
7
25
  }
@@ -43,4 +61,4 @@ declare class BaseAPI implements BaseClass {
43
61
  protected sendUrlEncodedForm<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any): Promise<T>;
44
62
  }
45
63
 
46
- export { BaseAPI as B, type GeneralRequestBody as G, type Paging as P, type ResponseSuccess as R, RequesterClass as a, type ResponsePagination as b, type ResponseData as c, BaseClass as d };
64
+ export { BaseAPI as B, type GeneralRequestBody as G, type Paging as P, type ResponseSuccess as R, RequesterClass as a, type ResponsePagination as b, type ResponseData as c, BaseClass as d, type GeneralHeaderInterface as e, type RequesterResponseInterface as f };
@@ -0,0 +1,3 @@
1
+ import {a as a$1,b}from'./chunk-4LWNMCXG.js';import {a}from'./chunk-VW3LGHTJ.js';import*as f from'crypto';import f__default from'crypto';function M(s){return typeof s=="object"&&s!==null}function m(s){return typeof s=="string"}var F=["data_exchange","INIT","BACK"],v=["data_exchange","INIT"];function _(s){if(!("flow_token"in s&&m(s.flow_token)&&"action"in s))return false;let{action:e,version:r,screen:t,data:o}=s,a=r==="3.0",c=F.includes(e),p=typeof t>"u"||m(t)&&t!=="SUCCESS",d=e==="data_exchange"||M(o);return a&&c&&p&&d}function T(s){if(!("flow_token"in s&&m(s.flow_token)&&"action"in s))return false;let{action:e,screen:r,data:t}=s,o=v.includes(e),a=m(r),c=M(t)&&"error_key"in t&&m(t.error)&&"error_message"in t&&m(t.error_message);return o&&a&&c}function S(s){return "action"in s&&s.action==="ping"}var B="WEBHOOK_UTILS",u=new a(B,process.env.DEBUG==="true");function R(s,e){let r=s.query["hub.mode"],t=s.query["hub.verify_token"],o=s.query["hub.challenge"];return r!==void 0&&t!==void 0&&o!==void 0?r==="subscribe"&&t===e?(u.log("Webhook verified successfully"),{statusCode:200,body:o}):(u.log("Webhook verification failed"),{statusCode:403}):(u.log("Not a webhook verification request - missing required parameters"),{statusCode:400,body:{error:"Invalid webhook verification request"}})}async function k(s,e,r){let t=s.body,o=[];if(t.object!=="whatsapp_business_account"){let a="Received webhook for non-WhatsApp event";return u.log(a),{statusCode:404,body:{error:a}}}for(let a of t.entry)try{let c=a.changes;for(let p of c)p.field==="messages"&&await I(a.id,p.value,e,r);}catch(c){let p=`Error processing webhook: ${c}`;u.log(p),o.push(p);}return {statusCode:200,body:o.length>0?{errors:o}:void 0}}async function H(s,e,r,t){try{if(!x(s,e.WEBHOOK_VERIFICATION_TOKEN||""))return u.log("Invalid request signature"),{statusCode:401,body:{error:"Unauthorized"}};let o=JSON.parse(s.rawBody||"{}"),{decryptedBody:a}=N(o,e),c=t.get("*");if(!c)return u.log(`No handler registered for flow action: ${a.action}`),{statusCode:404,body:{error:"Handler not found"}};if(S(a))return {statusCode:200,body:{version:"3.0",data:{status:"active"}}};if(T(a))return u.log(`Flow error: ${JSON.stringify(a)}`),{statusCode:200,body:{}};if(_(a)){let p=await c(r,a);return {statusCode:200,body:O(p,Buffer.from(o.aes_key,"base64"),Buffer.from(o.initial_vector,"base64"))}}return u.log(`Unknown flow request type: ${JSON.stringify(a)}`),{statusCode:400,body:{error:"Unknown request type"}}}catch(o){return u.log(`Error handling flow request: ${o}`),{statusCode:500,body:{error:"Internal server error"}}}}async function I(s,e,r,t){let o=e.metadata,a=e.contacts,c=s,p=o?.display_phone_number||"",d=o?.phone_number_id||"",y=a?.[0]?.profile?.name||"";if(e.statuses&&e.statuses.length>0){let g=e.statuses;for(let n of g){let l={wabaId:c,id:n.id,from:n.recipient_id,timestamp:n.timestamp,type:"statuses",phoneNumberId:d,displayPhoneNumber:p,profileName:y,statuses:e.statuses[0],originalData:n};await E(t.messageHandlers.get("statuses"),r,l,"statuses");}return}if(e.messages&&e.messages.length>0){let g=e.messages;for(let n of g){let l=n.type,i={wabaId:c,id:n.id,from:n.from,timestamp:n.timestamp,type:n.type,phoneNumberId:d,displayPhoneNumber:p,profileName:y,originalData:n};switch(l){case "text":i.text=n.text;break;case "image":i.image=n.image;break;case "video":i.video=n.video;break;case "audio":i.audio=n.audio;break;case "document":i.document=n.document;break;case "sticker":i.sticker=n.sticker;break;case "location":i.location=n.location;break;case "contacts":i.contacts=n.contacts;break;case "interactive":i.interactive=n.interactive;break;case "button":i.button=n.button;break;case "order":i.order=n.order;break;case "system":i.system=n.system;break;case "reaction":i.reaction=n.reaction;break;default:u.log(`Unknown message type: ${l}`);break}await E(t.preProcessHandler,r,i,"pre-process"),await E(t.messageHandlers.get(l),r,i,l),await E(t.postProcessHandler,r,i,"post-process");}}}async function E(s,e,r,t){if(s)try{await s(e,r);}catch(o){u.log(`Error in ${t} handler: ${o}`);}}function x(s,e){let r=s.headers["x-hub-signature-256"];if(!r||!s.rawBody)return false;let o=`sha256=${f__default.createHmac("sha256",e).update(s.rawBody,"utf8").digest("hex")}`;return f__default.timingSafeEqual(Buffer.from(r),Buffer.from(o))}function N(s,e){let{encrypted_aes_key:r,encrypted_flow_data:t,initial_vector:o}=s;if(!r||!t||!o)throw new Error("Missing required encryption properties");let a=e.FLOW_API_PRIVATE_PEM.replace(/\\n/g,`
2
+ `),c=e.FLOW_API_PASSPHRASE,p=f__default.createPrivateKey({key:a,passphrase:c}),d;try{d=f__default.privateDecrypt({key:p,padding:f__default.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:"sha256"},Buffer.from(r,"base64"));}catch{throw new Error("Failed to decrypt the request. Please verify your private key.")}let y=Buffer.from(t,"base64"),g=Buffer.from(o,"base64"),l=y.subarray(0,-16),i=y.subarray(-16),w=f__default.createDecipheriv("aes-128-gcm",d,g);w.setAuthTag(i);let P=Buffer.concat([w.update(l),w.final()]).toString("utf-8");return {decryptedBody:JSON.parse(P),aesKeyBuffer:d,initialVectorBuffer:g}}function O(s,e,r){let t=[];for(let o of Array.from(r.entries()))t.push(~o[1]);try{let o=f__default.createCipheriv("aes-128-gcm",e,Buffer.from(t));return Buffer.concat([o.update(JSON.stringify(s||{}),"utf-8"),o.final(),o.getAuthTag()]).toString("base64")}catch(o){throw u.log("Response encryption error:",o),new Error("Failed to encrypt response. Internal server error.")}}var V="WEBHOOK",h=new a(V,process.env.DEBUG==="true"),W=class{config;client;messageHandlers=new Map;preProcessHandler=void 0;postProcessHandler=void 0;flowHandlers=new Map;constructor(e){this.config=a$1(e),this.client=new b(e),h.log("WebhookHandler instantiated!");}handleVerification=e=>R(e,this.config.WEBHOOK_VERIFICATION_TOKEN||"");handleWebhook=async e=>k(e,this.client,{messageHandlers:this.messageHandlers,preProcessHandler:this.preProcessHandler,postProcessHandler:this.postProcessHandler});handleFlow=async e=>H(e,this.config,this.client,this.flowHandlers);onMessage(e,r){this.messageHandlers.set(e,r),h.log(`Registered message handler for ${e}`);}onMessagePreProcess(e){this.preProcessHandler=e,h.log("Registered pre-process handler");}onMessagePostProcess(e){this.postProcessHandler=e,h.log("Registered post-process handler");}onFlow(e,r){this.flowHandlers.set(e,r),h.log(`Registered flow handler for ${e}`);}};var Pe=(s,e)=>f.createHmac("sha256",e).update(s,"utf-8").digest("hex");export{_ as a,T as b,S as c,R as d,k as e,H as f,W as g,Pe as h};//# sourceMappingURL=chunk-4ZHGFSME.js.map
3
+ //# sourceMappingURL=chunk-4ZHGFSME.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/shared/utils/flowTypeGuards.ts","../src/core/webhook/utils/webhookUtils.ts","../src/core/webhook/WebhookHandler.ts","../src/core/webhook/utils/generateXHub256Sig.ts"],"names":["isObject","value","isString","DATA_EXCHANGE_ACTIONS","ERROR_ACTIONS","isFlowDataExchangeRequest","request","action","version","screen","data","hasValidVersion","hasValidAction","hasValidScreen","hasValidData","isFlowErrorRequest","isFlowPingRequest","LIB_NAME","LOGGER","Logger","verifyWebhook","verificationToken","mode","token","challenge","processWebhookMessages","whatsapp","handlers","body","errors","errorMsg","entry","changes","change","processMessages","error","processFlowRequest","config","flowHandlers","isRequestSignatureValid","decryptedBody","decryptFlowRequest","handler","result","encryptFlowResponse","waba_id","metadata","contacts","wabaId","displayPhoneNumber","phoneNumberId","profileName","statuses","status","processedStatus","executeHandler","messages","message","messageType","processedMessage","handlerType","signature","formattedExpectedSignature","crypto","encrypted_aes_key","encrypted_flow_data","initial_vector","privatePem","passphrase","privateKey","decryptedAesKey","flowDataBuffer","initialVectorBuffer","TAG_LENGTH","encrypted_flow_data_body","encrypted_flow_data_tag","decipher","decryptedJSONString","response","aesKeyBuffer","flipped_iv","pair","cipher","WebhookHandler","importConfig","WhatsApp","type","generateXHub256Sig","appSecret","v"],"mappings":"yIAaA,SAASA,CAAAA,CAASC,EAAkD,CAChE,OAAO,OAAOA,CAAU,EAAA,QAAA,EAAYA,CAAU,GAAA,IAClD,CAOA,SAASC,EAASD,CAAiC,CAAA,CAC/C,OAAO,OAAOA,CAAU,EAAA,QAC5B,CAGA,IAAME,CAAAA,CAAwB,CAAuE,eAAA,CAAA,MAAA,CAAA,MAAA,CAAA,CAG/FC,CAAgB,CAAA,CAAA,eAAA,CAAA,MAAkD,EASjE,SAASC,CAAAA,CAA0BC,EAKxC,CAEE,GAAI,EAAE,YAAgBA,GAAAA,CAAAA,EAAWJ,CAASI,CAAAA,CAAAA,CAAQ,UAAU,CAAA,EAAK,WAAYA,CACzE,CAAA,CAAA,OAAO,MAGX,CAAA,GAAM,CAAE,MAAA,CAAAC,EAAQ,OAAAC,CAAAA,CAAAA,CAAS,MAAAC,CAAAA,CAAAA,CAAQ,IAAAC,CAAAA,CAAK,EAAIJ,CAGpCK,CAAAA,CAAAA,CAAkBH,IAAY,KAG9BI,CAAAA,CAAAA,CAAiBT,EAAsB,QAASI,CAAAA,CAAa,CAG7DM,CAAAA,CAAAA,CAAiB,OAAOJ,CAAAA,CAAW,KAAgBP,CAASO,CAAAA,CAAM,CAAKA,EAAAA,CAAAA,GAAW,SAGlFK,CAAAA,CA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AM3E,UAAUgF,CAAwB5C,CAAAA,CAAAA,CAA+B,CACpE,IAAK,CAAA,eAAA,CAAgB,IAAI4C,CAAM5C,CAAAA,CAAO,CACtCxB,CAAAA,CAAAA,CAAO,IAAI,CAAkCoE,+BAAAA,EAAAA,CAAI,EAAE,EACvD,CAKO,oBAAoB5C,CAA+B,CAAA,CACtD,IAAK,CAAA,iBAAA,CAAoBA,EACzBxB,CAAO,CAAA,GAAA,CAAI,gCAAgC,EAC/C,CAKO,qBAAqBwB,CAA+B,CAAA,CACvD,IAAK,CAAA,kBAAA,CAAqBA,EAC1BxB,CAAO,CAAA,GAAA,CAAI,iCAAiC,EAChD,CAKO,OAAOoE,CAAoB5C,CAAAA,CAAAA,CAA4B,CAC1D,IAAA,CAAK,aAAa,GAAI4C,CAAAA,CAAAA,CAAM5C,CAAO,CACnCxB,CAAAA,CAAAA,CAAO,IAAI,CAA+BoE,4BAAAA,EAAAA,CAAI,CAAE,CAAA,EACpD,CACJ,EC3FO,IAAMC,GAAqB,CAAC3D,CAAAA,CAAc4D,IAC/BC,CAAW,CAAA,UAAA,CAAA,QAAA,CAAUD,CAAS,CAAE,CAAA,MAAA,CAAO5D,EAAM,OAAO,CAAA,CAAE,OAAO,KAAK","file":"chunk-MTRF47KZ.js","sourcesContent":["import {\n FlowActionEnum,\n FlowDataExchangeRequest,\n FlowEndpointRequest,\n FlowErrorNotificationRequest,\n FlowHealthCheckRequest,\n} from '@features/flow/types';\n\n/**\n * Helper function to check if a value is an object\n * @param value The value to check\n * @returns True if the value is a non-null object\n */\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/**\n * Helper function to check if a value is a string\n * @param value The value to check\n * @returns True if the value is a string\n */\nfunction isString(value: unknown): value is string {\n return typeof value === 'string';\n}\n\n// Array of allowed action types for data exchange requests\nconst DATA_EXCHANGE_ACTIONS = [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT, FlowActionEnum.BACK] as const;\n\n// Array of allowed action types for error notification requests\nconst ERROR_ACTIONS = [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT] as const;\n\n/**\n * Type guard to check if a request is a Data Exchange request\n * Validates the request structure according to the Flow API specifications\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a valid Data Exchange request, false otherwise\n */\nexport function isFlowDataExchangeRequest(request: FlowEndpointRequest): request is FlowDataExchangeRequest & {\n action: (typeof DATA_EXCHANGE_ACTIONS)[number];\n screen?: string;\n flow_token: string;\n data?: Record<string, any>;\n} {\n // Check for basic required fields\n if (!('flow_token' in request && isString(request.flow_token) && 'action' in request)) {\n return false;\n }\n\n const { action, version, screen, data } = request;\n\n // Validate API version\n const hasValidVersion = version === '3.0';\n\n // Check if the action is one of the allowed actions for data exchange\n const hasValidAction = DATA_EXCHANGE_ACTIONS.includes(action as any);\n\n // Screen is optional, but when present must be a string and not 'SUCCESS'\n const hasValidScreen = typeof screen === 'undefined' || (isString(screen) && screen !== 'SUCCESS');\n\n // Data is required except for DATA_EXCHANGE action\n const hasValidData = action === FlowActionEnum.DATA_EXCHANGE || isObject(data);\n\n // All conditions must be met for a valid data exchange request\n return hasValidVersion && hasValidAction && hasValidScreen && hasValidData;\n}\n\n/**\n * Type guard to check if a request is an Error Notification request\n * Validates the request structure according to the Flow API error specifications\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a valid Error Notification request, false otherwise\n */\nexport function isFlowErrorRequest(request: FlowEndpointRequest): request is FlowErrorNotificationRequest & {\n action: (typeof ERROR_ACTIONS)[number];\n screen: string;\n flow_token: string;\n data: {\n error: string;\n error_message: string;\n };\n} {\n // Check for basic required fields\n if (!('flow_token' in request && isString(request.flow_token) && 'action' in request)) {\n return false;\n }\n\n const { action, screen, data } = request;\n\n // Check if the action is one of the allowed actions for error notifications\n const hasValidAction = ERROR_ACTIONS.includes(action as any);\n\n // Screen is required for error notifications\n const hasValidScreen = isString(screen);\n\n // Validate error data structure\n const hasValidData =\n isObject(data) &&\n 'error_key' in data &&\n isString(data.error) &&\n 'error_message' in data &&\n isString(data.error_message);\n\n // All conditions must be met for a valid error notification request\n return hasValidAction && hasValidScreen && hasValidData;\n}\n\n/**\n * Type guard to check if a request is a Ping (health check) request\n * Simple validation for health check endpoints in the Flow API\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a Ping request, false otherwise\n */\nexport function isFlowPingRequest(request: FlowEndpointRequest): request is FlowHealthCheckRequest {\n // A ping request only requires the 'action' field with value 'ping'\n return 'action' in request && request.action === 'ping';\n}\n","import { FlowEndpointRequest } from '@features/flow';\nimport { FlowTypeEnum } from '@features/flow/types';\nimport { MessageTypesEnum } from '@shared/types';\nimport { WabaConfigType } from '@shared/types/config';\nimport { isFlowDataExchangeRequest, isFlowErrorRequest, isFlowPingRequest } from '@shared/utils/flowTypeGuards';\nimport Logger from '@shared/utils/logger';\nimport crypto from 'crypto';\nimport { WhatsApp } from '../../whatsapp';\nimport { WebhookMessage, WebhookMessageValue } from '../types';\n\nconst LIB_NAME = 'WEBHOOK_UTILS';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\nexport interface WebhookRequest {\n method: string;\n query: Record<string, any>;\n body: any;\n headers: Record<string, string | string[] | undefined>;\n rawBody?: string;\n}\n\nexport interface WebhookResponse {\n statusCode: number;\n body?: any;\n headers?: Record<string, string>;\n}\n\nexport type MessageHandler = (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>;\nexport type FlowHandler = (whatsapp: WhatsApp, request: FlowEndpointRequest) => any | Promise<any>;\n\n/**\n * Pure function to handle webhook verification\n */\nexport function verifyWebhook(request: Pick<WebhookRequest, 'query'>, verificationToken: string): WebhookResponse {\n const mode = request.query['hub.mode'];\n const token = request.query['hub.verify_token'];\n const challenge = request.query['hub.challenge'];\n\n // Check if this is actually a webhook verification request\n const isWebhookVerificationRequest = mode !== undefined && token !== undefined && challenge !== undefined;\n\n if (!isWebhookVerificationRequest) {\n LOGGER.log('Not a webhook verification request - missing required parameters');\n return {\n statusCode: 400,\n body: { error: 'Invalid webhook verification request' },\n };\n }\n\n const VERIFICATION_SUCCESS = mode === 'subscribe' && token === verificationToken;\n\n if (VERIFICATION_SUCCESS) {\n LOGGER.log('Webhook verified successfully');\n return {\n statusCode: 200,\n body: challenge,\n };\n } else {\n LOGGER.log('Webhook verification failed');\n return {\n statusCode: 403,\n };\n }\n}\n\n/**\n * Pure function to process webhook messages\n */\nexport async function processWebhookMessages(\n request: WebhookRequest,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<WebhookResponse> {\n const body = request.body;\n const errors: string[] = [];\n\n // Check this is a WhatsApp Business Account webhook\n if (body.object !== 'whatsapp_business_account') {\n const errorMsg = 'Received webhook for non-WhatsApp event';\n LOGGER.log(errorMsg);\n return {\n statusCode: 404,\n body: { error: errorMsg },\n };\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 === 'messages') {\n await processMessages(entry.id, change.value, whatsapp, handlers);\n }\n }\n } catch (error) {\n const errorMsg = `Error processing webhook: ${error}`;\n LOGGER.log(errorMsg);\n errors.push(errorMsg);\n }\n }\n\n return {\n statusCode: 200,\n body: errors.length > 0 ? { errors } : undefined,\n };\n}\n\n/**\n * Pure function to handle flow requests\n */\nexport async function processFlowRequest(\n request: WebhookRequest,\n config: WabaConfigType,\n whatsapp: WhatsApp,\n flowHandlers: Map<FlowTypeEnum, FlowHandler>,\n): Promise<WebhookResponse> {\n try {\n // Validate request signature\n if (!isRequestSignatureValid(request, config.WEBHOOK_VERIFICATION_TOKEN || '')) {\n LOGGER.log('Invalid request signature');\n return {\n statusCode: 401,\n body: { error: 'Unauthorized' },\n };\n }\n\n const body = JSON.parse(request.rawBody || '{}');\n\n // Decrypt the request\n const { decryptedBody } = decryptFlowRequest(body, config);\n\n // Get the flow handler\n const handler = flowHandlers.get(FlowTypeEnum.All);\n if (!handler) {\n LOGGER.log(`No handler registered for flow action: ${decryptedBody.action}`);\n return {\n statusCode: 404,\n body: { error: 'Handler not found' },\n };\n }\n\n // Handle different flow types\n if (isFlowPingRequest(decryptedBody)) {\n return {\n statusCode: 200,\n body: {\n version: '3.0',\n data: { status: 'active' },\n },\n };\n }\n\n if (isFlowErrorRequest(decryptedBody)) {\n LOGGER.log(`Flow error: ${JSON.stringify(decryptedBody)}`);\n return {\n statusCode: 200,\n body: {},\n };\n }\n\n if (isFlowDataExchangeRequest(decryptedBody)) {\n const result = await handler(whatsapp, decryptedBody);\n const encryptedResponse = encryptFlowResponse(\n result,\n Buffer.from(body.aes_key, 'base64'),\n Buffer.from(body.initial_vector, 'base64'),\n );\n\n return {\n statusCode: 200,\n body: encryptedResponse,\n };\n }\n\n LOGGER.log(`Unknown flow request type: ${JSON.stringify(decryptedBody)}`);\n return {\n statusCode: 400,\n body: { error: 'Unknown request type' },\n };\n } catch (error) {\n LOGGER.log(`Error handling flow request: ${error}`);\n return {\n statusCode: 500,\n body: { error: 'Internal server error' },\n };\n }\n}\n\n/**\n * Private helper functions\n */\nasync function processMessages(\n waba_id: string,\n value: WebhookMessageValue,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<void> {\n const metadata = value.metadata;\n const contacts = value.contacts;\n const wabaId = waba_id;\n const displayPhoneNumber = metadata?.display_phone_number || '';\n const phoneNumberId = metadata?.phone_number_id || '';\n const profileName = contacts?.[0]?.profile?.name || '';\n\n if (value.statuses && value.statuses.length > 0) {\n const statuses = value.statuses;\n for (const status of statuses) {\n const processedStatus: WebhookMessage = {\n wabaId,\n id: status.id,\n from: status.recipient_id,\n timestamp: status.timestamp,\n type: MessageTypesEnum.Statuses,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n statuses: value.statuses[0],\n originalData: status,\n };\n\n await executeHandler(\n handlers.messageHandlers.get(MessageTypesEnum.Statuses),\n whatsapp,\n processedStatus,\n MessageTypesEnum.Statuses,\n );\n }\n return;\n }\n\n if (value.messages && value.messages.length > 0) {\n const messages = value.messages;\n\n for (const message of messages) {\n const messageType = message.type;\n\n const processedMessage: WebhookMessage = {\n wabaId,\n id: message.id,\n from: message.from,\n timestamp: message.timestamp,\n type: message.type,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n originalData: message,\n };\n\n switch (messageType) {\n case MessageTypesEnum.Text:\n processedMessage.text = message.text;\n break;\n case MessageTypesEnum.Image:\n processedMessage.image = message.image;\n break;\n case MessageTypesEnum.Video:\n processedMessage.video = message.video;\n break;\n case MessageTypesEnum.Audio:\n processedMessage.audio = message.audio;\n break;\n case MessageTypesEnum.Document:\n processedMessage.document = message.document;\n break;\n case MessageTypesEnum.Sticker:\n processedMessage.sticker = message.sticker;\n break;\n case MessageTypesEnum.Location:\n processedMessage.location = message.location;\n break;\n case MessageTypesEnum.Contacts:\n processedMessage.contacts = message.contacts;\n break;\n case MessageTypesEnum.Interactive:\n processedMessage.interactive = message.interactive;\n break;\n case MessageTypesEnum.Button:\n processedMessage.button = message.button;\n break;\n case MessageTypesEnum.Order:\n processedMessage.order = message.order;\n break;\n case MessageTypesEnum.System:\n processedMessage.system = message.system;\n break;\n case MessageTypesEnum.Reaction:\n processedMessage.reaction = message.reaction;\n break;\n default:\n LOGGER.log(`Unknown message type: ${messageType}`);\n break;\n }\n\n // Execute handlers in sequence\n await executeHandler(handlers.preProcessHandler, whatsapp, processedMessage, 'pre-process');\n await executeHandler(handlers.messageHandlers.get(messageType), whatsapp, processedMessage, messageType);\n await executeHandler(handlers.postProcessHandler, whatsapp, processedMessage, 'post-process');\n }\n }\n}\n\nasync function executeHandler(\n handler: MessageHandler | undefined,\n whatsapp: WhatsApp,\n message: WebhookMessage,\n handlerType: string,\n): Promise<void> {\n if (handler) {\n try {\n await handler(whatsapp, message);\n } catch (error) {\n LOGGER.log(`Error in ${handlerType} handler: ${error}`);\n }\n }\n}\n\nfunction isRequestSignatureValid(request: WebhookRequest, verificationToken: string): boolean {\n const signature = request.headers['x-hub-signature-256'] as string;\n if (!signature || !request.rawBody) {\n return false;\n }\n\n const expectedSignature = crypto\n .createHmac('sha256', verificationToken)\n .update(request.rawBody, 'utf8')\n .digest('hex');\n\n const formattedExpectedSignature = `sha256=${expectedSignature}`;\n\n return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(formattedExpectedSignature));\n}\n\nfunction decryptFlowRequest(\n body: any,\n config: WabaConfigType,\n): {\n decryptedBody: FlowEndpointRequest;\n aesKeyBuffer: Buffer;\n initialVectorBuffer: Buffer;\n} {\n const { encrypted_aes_key, encrypted_flow_data, initial_vector } = body;\n\n if (!encrypted_aes_key || !encrypted_flow_data || !initial_vector) {\n throw new Error('Missing required encryption properties');\n }\n\n const privatePem = config.FLOW_API_PRIVATE_PEM.replace(/\\\\n/g, '\\n');\n const passphrase = config.FLOW_API_PASSPHRASE;\n\n const privateKey = crypto.createPrivateKey({ key: privatePem, passphrase });\n let decryptedAesKey: Buffer;\n\n try {\n 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 throw new Error('Failed to decrypt the request. Please verify your private key.');\n }\n\n const flowDataBuffer = Buffer.from(encrypted_flow_data, 'base64');\n const initialVectorBuffer = Buffer.from(initial_vector, 'base64');\n\n const TAG_LENGTH = 16;\n const encrypted_flow_data_body = flowDataBuffer.subarray(0, -TAG_LENGTH);\n const encrypted_flow_data_tag = flowDataBuffer.subarray(-TAG_LENGTH);\n\n const decipher = crypto.createDecipheriv('aes-128-gcm', decryptedAesKey, initialVectorBuffer);\n decipher.setAuthTag(encrypted_flow_data_tag);\n\n const decryptedJSONString = Buffer.concat([decipher.update(encrypted_flow_data_body), decipher.final()]).toString(\n 'utf-8',\n );\n\n return {\n decryptedBody: JSON.parse(decryptedJSONString),\n aesKeyBuffer: decryptedAesKey,\n initialVectorBuffer,\n };\n}\n\nfunction encryptFlowResponse(response: any, aesKeyBuffer: Buffer, initialVectorBuffer: Buffer): string {\n const flipped_iv: number[] = [];\n for (const pair of Array.from(initialVectorBuffer.entries())) {\n flipped_iv.push(~pair[1]);\n }\n\n try {\n const cipher = crypto.createCipheriv('aes-128-gcm', aesKeyBuffer, Buffer.from(flipped_iv));\n 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.log('Response encryption error:', error);\n throw new Error('Failed to encrypt response. Internal server error.');\n }\n}\n","import { MessageTypesEnum } from '@shared/types';\nimport { WabaConfigType, WhatsAppConfig } from '@shared/types/config';\n\nimport { FlowTypeEnum } from '@features/flow/types';\nimport { importConfig } from '@shared/config/importConfig';\nimport Logger from '@shared/utils/logger';\nimport { WhatsApp } from '../whatsapp';\nimport {\n FlowHandler,\n MessageHandler,\n processFlowRequest,\n processWebhookMessages,\n verifyWebhook,\n WebhookRequest,\n WebhookResponse,\n} from './utils/webhookUtils';\n\nconst LIB_NAME = 'WEBHOOK';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\n/**\n * Framework-agnostic WebhookHandler using pure functions\n */\nexport class WebhookHandler {\n private config: WabaConfigType;\n private client: WhatsApp;\n private messageHandlers: Map<MessageTypesEnum, MessageHandler> = new Map();\n private preProcessHandler: MessageHandler | undefined = undefined;\n private postProcessHandler: MessageHandler | undefined = undefined;\n private flowHandlers: Map<FlowTypeEnum, FlowHandler> = new Map();\n\n constructor(config: WhatsAppConfig) {\n this.config = importConfig(config);\n this.client = new WhatsApp(config);\n LOGGER.log('WebhookHandler instantiated!');\n }\n\n /**\n * Handle webhook verification (framework-agnostic)\n */\n public handleVerification = (request: Pick<WebhookRequest, 'query'>): WebhookResponse => {\n return verifyWebhook(request, this.config.WEBHOOK_VERIFICATION_TOKEN || '');\n };\n\n /**\n * Handle webhook messages (framework-agnostic)\n */\n public handleWebhook = async (request: WebhookRequest): Promise<WebhookResponse> => {\n return processWebhookMessages(request, this.client, {\n messageHandlers: this.messageHandlers,\n preProcessHandler: this.preProcessHandler,\n postProcessHandler: this.postProcessHandler,\n });\n };\n\n /**\n * Handle flow requests (framework-agnostic)\n */\n public handleFlow = async (request: WebhookRequest): Promise<WebhookResponse> => {\n return processFlowRequest(request, this.config, this.client, this.flowHandlers);\n };\n\n /**\n * Register a message handler for a specific message type\n */\n public onMessage(type: MessageTypesEnum, handler: MessageHandler): void {\n this.messageHandlers.set(type, handler);\n LOGGER.log(`Registered message handler for ${type}`);\n }\n\n /**\n * Register a pre-process handler that runs before all message handlers\n */\n public onMessagePreProcess(handler: MessageHandler): void {\n this.preProcessHandler = handler;\n LOGGER.log('Registered pre-process handler');\n }\n\n /**\n * Register a post-process handler that runs after all message handlers\n */\n public onMessagePostProcess(handler: MessageHandler): void {\n this.postProcessHandler = handler;\n LOGGER.log('Registered post-process handler');\n }\n\n /**\n * Register a flow handler for a specific flow type\n */\n public onFlow(type: FlowTypeEnum, handler: FlowHandler): void {\n this.flowHandlers.set(type, handler);\n LOGGER.log(`Registered flow handler for ${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"]}
1
+ {"version":3,"sources":["../src/shared/utils/flowTypeGuards.ts","../src/core/webhook/utils/webhookUtils.ts","../src/core/webhook/WebhookHandler.ts","../src/core/webhook/utils/generateXHub256Sig.ts"],"names":["isObject","value","isString","DATA_EXCHANGE_ACTIONS","ERROR_ACTIONS","isFlowDataExchangeRequest","request","action","version","screen","data","hasValidVersion","hasValidAction","hasValidScreen","hasValidData","isFlowErrorRequest","isFlowPingRequest","LIB_NAME","LOGGER","Logger","verifyWebhook","verificationToken","mode","token","challenge","processWebhookMessages","whatsapp","handlers","body","errors","errorMsg","entry","changes","change","processMessages","error","processFlowRequest","config","flowHandlers","isRequestSignatureValid","decryptedBody","decryptFlowRequest","handler","result","encryptFlowResponse","waba_id","metadata","contacts","wabaId","displayPhoneNumber","phoneNumberId","profileName","statuses","status","processedStatus","executeHandler","messages","message","messageType","processedMessage","handlerType","signature","formattedExpectedSignature","crypto","encrypted_aes_key","encrypted_flow_data","initial_vector","privatePem","passphrase","privateKey","decryptedAesKey","flowDataBuffer","initialVectorBuffer","TAG_LENGTH","encrypted_flow_data_body","encrypted_flow_data_tag","decipher","decryptedJSONString","response","aesKeyBuffer","flipped_iv","pair","cipher","WebhookHandler","importConfig","WhatsApp","type","generateXHub256Sig","appSecret","q"],"mappings":"yIAaA,SAASA,CAAAA,CAASC,EAAkD,CAChE,OAAO,OAAOA,CAAU,EAAA,QAAA,EAAYA,CAAU,GAAA,IAClD,CAOA,SAASC,EAASD,CAAiC,CAAA,CAC/C,OAAO,OAAOA,CAAU,EAAA,QAC5B,CAGA,IAAME,CAAAA,CAAwB,CAAuE,eAAA,CAAA,MAAA,CAAA,MAAA,CAAA,CAG/FC,CAAgB,CAAA,CAAA,eAAA,CAAA,MAAkD,EASjE,SAASC,CAAAA,CAA0BC,EAKxC,CAEE,GAAI,EAAE,YAAgBA,GAAAA,CAAAA,EAAWJ,CAASI,CAAAA,CAAAA,CAAQ,UAAU,CAAA,EAAK,WAAYA,CACzE,CAAA,CAAA,OAAO,MAGX,CAAA,GAAM,CAAE,MAAA,CAAAC,EAAQ,OAAAC,CAAAA,CAAAA,CAAS,MAAAC,CAAAA,CAAAA,CAAQ,IAAAC,CAAAA,CAAK,EAAIJ,CAGpCK,CAAAA,CAAAA,CAAkBH,IAAY,KAG9BI,CAAAA,CAAAA,CAAiBT,EAAsB,QAASI,CAAAA,CAAa,CAG7DM,CAAAA,CAAAA,CAAiB,OAAOJ,CAAAA,CAAW,KAAgBP,CAASO,C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MAAA,CAAQ,KAAK,MAAQ,CAAA,IAAA,CAAK,YAAY,CAAA,CAM3E,UAAUgF,CAAwB5C,CAAAA,CAAAA,CAA+B,CACpE,IAAK,CAAA,eAAA,CAAgB,IAAI4C,CAAM5C,CAAAA,CAAO,CACtCxB,CAAAA,CAAAA,CAAO,IAAI,CAAkCoE,+BAAAA,EAAAA,CAAI,EAAE,EACvD,CAKO,oBAAoB5C,CAA+B,CAAA,CACtD,IAAK,CAAA,iBAAA,CAAoBA,EACzBxB,CAAO,CAAA,GAAA,CAAI,gCAAgC,EAC/C,CAKO,qBAAqBwB,CAA+B,CAAA,CACvD,IAAK,CAAA,kBAAA,CAAqBA,EAC1BxB,CAAO,CAAA,GAAA,CAAI,iCAAiC,EAChD,CAKO,OAAOoE,CAAoB5C,CAAAA,CAAAA,CAA4B,CAC1D,IAAA,CAAK,aAAa,GAAI4C,CAAAA,CAAAA,CAAM5C,CAAO,CACnCxB,CAAAA,CAAAA,CAAO,IAAI,CAA+BoE,4BAAAA,EAAAA,CAAI,CAAE,CAAA,EACpD,CACJ,EC3FO,IAAMC,GAAqB,CAAC3D,CAAAA,CAAc4D,IAC/BC,CAAW,CAAA,UAAA,CAAA,QAAA,CAAUD,CAAS,CAAE,CAAA,MAAA,CAAO5D,EAAM,OAAO,CAAA,CAAE,OAAO,KAAK","file":"chunk-4ZHGFSME.js","sourcesContent":["import {\n FlowActionEnum,\n FlowDataExchangeRequest,\n FlowEndpointRequest,\n FlowErrorNotificationRequest,\n FlowHealthCheckRequest,\n} from '@features/flow/types';\n\n/**\n * Helper function to check if a value is an object\n * @param value The value to check\n * @returns True if the value is a non-null object\n */\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/**\n * Helper function to check if a value is a string\n * @param value The value to check\n * @returns True if the value is a string\n */\nfunction isString(value: unknown): value is string {\n return typeof value === 'string';\n}\n\n// Array of allowed action types for data exchange requests\nconst DATA_EXCHANGE_ACTIONS = [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT, FlowActionEnum.BACK] as const;\n\n// Array of allowed action types for error notification requests\nconst ERROR_ACTIONS = [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT] as const;\n\n/**\n * Type guard to check if a request is a Data Exchange request\n * Validates the request structure according to the Flow API specifications\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a valid Data Exchange request, false otherwise\n */\nexport function isFlowDataExchangeRequest(request: FlowEndpointRequest): request is FlowDataExchangeRequest & {\n action: (typeof DATA_EXCHANGE_ACTIONS)[number];\n screen?: string;\n flow_token: string;\n data?: Record<string, any>;\n} {\n // Check for basic required fields\n if (!('flow_token' in request && isString(request.flow_token) && 'action' in request)) {\n return false;\n }\n\n const { action, version, screen, data } = request;\n\n // Validate API version\n const hasValidVersion = version === '3.0';\n\n // Check if the action is one of the allowed actions for data exchange\n const hasValidAction = DATA_EXCHANGE_ACTIONS.includes(action as any);\n\n // Screen is optional, but when present must be a string and not 'SUCCESS'\n const hasValidScreen = typeof screen === 'undefined' || (isString(screen) && screen !== 'SUCCESS');\n\n // Data is required except for DATA_EXCHANGE action\n const hasValidData = action === FlowActionEnum.DATA_EXCHANGE || isObject(data);\n\n // All conditions must be met for a valid data exchange request\n return hasValidVersion && hasValidAction && hasValidScreen && hasValidData;\n}\n\n/**\n * Type guard to check if a request is an Error Notification request\n * Validates the request structure according to the Flow API error specifications\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a valid Error Notification request, false otherwise\n */\nexport function isFlowErrorRequest(request: FlowEndpointRequest): request is FlowErrorNotificationRequest & {\n action: (typeof ERROR_ACTIONS)[number];\n screen: string;\n flow_token: string;\n data: {\n error: string;\n error_message: string;\n };\n} {\n // Check for basic required fields\n if (!('flow_token' in request && isString(request.flow_token) && 'action' in request)) {\n return false;\n }\n\n const { action, screen, data } = request;\n\n // Check if the action is one of the allowed actions for error notifications\n const hasValidAction = ERROR_ACTIONS.includes(action as any);\n\n // Screen is required for error notifications\n const hasValidScreen = isString(screen);\n\n // Validate error data structure\n const hasValidData =\n isObject(data) &&\n 'error_key' in data &&\n isString(data.error) &&\n 'error_message' in data &&\n isString(data.error_message);\n\n // All conditions must be met for a valid error notification request\n return hasValidAction && hasValidScreen && hasValidData;\n}\n\n/**\n * Type guard to check if a request is a Ping (health check) request\n * Simple validation for health check endpoints in the Flow API\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a Ping request, false otherwise\n */\nexport function isFlowPingRequest(request: FlowEndpointRequest): request is FlowHealthCheckRequest {\n // A ping request only requires the 'action' field with value 'ping'\n return 'action' in request && request.action === 'ping';\n}\n","import { FlowEndpointRequest } from '@features/flow';\nimport { FlowTypeEnum } from '@features/flow/types';\nimport { MessageTypesEnum } from '@shared/types';\nimport { WabaConfigType } from '@shared/types/config';\nimport { isFlowDataExchangeRequest, isFlowErrorRequest, isFlowPingRequest } from '@shared/utils/flowTypeGuards';\nimport Logger from '@shared/utils/logger';\nimport crypto from 'crypto';\nimport { WhatsApp } from '../../whatsapp';\nimport { WebhookMessage, WebhookMessageValue } from '../types';\n\nconst LIB_NAME = 'WEBHOOK_UTILS';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\nexport interface WebhookRequest {\n method: string;\n query: Record<string, any>;\n body: any;\n headers: Record<string, string | string[] | undefined>;\n rawBody?: string;\n}\n\nexport interface WebhookResponse {\n statusCode: number;\n body?: any;\n headers?: Record<string, string>;\n}\n\nexport type MessageHandler = (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>;\nexport type FlowHandler = (whatsapp: WhatsApp, request: FlowEndpointRequest) => any | Promise<any>;\n\n/**\n * Pure function to handle webhook verification\n */\nexport function verifyWebhook(request: Pick<WebhookRequest, 'query'>, verificationToken: string): WebhookResponse {\n const mode = request.query['hub.mode'];\n const token = request.query['hub.verify_token'];\n const challenge = request.query['hub.challenge'];\n\n // Check if this is actually a webhook verification request\n const isWebhookVerificationRequest = mode !== undefined && token !== undefined && challenge !== undefined;\n\n if (!isWebhookVerificationRequest) {\n LOGGER.log('Not a webhook verification request - missing required parameters');\n return {\n statusCode: 400,\n body: { error: 'Invalid webhook verification request' },\n };\n }\n\n const VERIFICATION_SUCCESS = mode === 'subscribe' && token === verificationToken;\n\n if (VERIFICATION_SUCCESS) {\n LOGGER.log('Webhook verified successfully');\n return {\n statusCode: 200,\n body: challenge,\n };\n } else {\n LOGGER.log('Webhook verification failed');\n return {\n statusCode: 403,\n };\n }\n}\n\n/**\n * Pure function to process webhook messages\n */\nexport async function processWebhookMessages(\n request: WebhookRequest,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<WebhookResponse> {\n const body = request.body;\n const errors: string[] = [];\n\n // Check this is a WhatsApp Business Account webhook\n if (body.object !== 'whatsapp_business_account') {\n const errorMsg = 'Received webhook for non-WhatsApp event';\n LOGGER.log(errorMsg);\n return {\n statusCode: 404,\n body: { error: errorMsg },\n };\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 === 'messages') {\n await processMessages(entry.id, change.value, whatsapp, handlers);\n }\n }\n } catch (error) {\n const errorMsg = `Error processing webhook: ${error}`;\n LOGGER.log(errorMsg);\n errors.push(errorMsg);\n }\n }\n\n return {\n statusCode: 200,\n body: errors.length > 0 ? { errors } : undefined,\n };\n}\n\n/**\n * Pure function to handle flow requests\n */\nexport async function processFlowRequest(\n request: WebhookRequest,\n config: WabaConfigType,\n whatsapp: WhatsApp,\n flowHandlers: Map<FlowTypeEnum, FlowHandler>,\n): Promise<WebhookResponse> {\n try {\n // Validate request signature\n if (!isRequestSignatureValid(request, config.WEBHOOK_VERIFICATION_TOKEN || '')) {\n LOGGER.log('Invalid request signature');\n return {\n statusCode: 401,\n body: { error: 'Unauthorized' },\n };\n }\n\n const body = JSON.parse(request.rawBody || '{}');\n\n // Decrypt the request\n const { decryptedBody } = decryptFlowRequest(body, config);\n\n // Get the flow handler\n const handler = flowHandlers.get(FlowTypeEnum.All);\n if (!handler) {\n LOGGER.log(`No handler registered for flow action: ${decryptedBody.action}`);\n return {\n statusCode: 404,\n body: { error: 'Handler not found' },\n };\n }\n\n // Handle different flow types\n if (isFlowPingRequest(decryptedBody)) {\n return {\n statusCode: 200,\n body: {\n version: '3.0',\n data: { status: 'active' },\n },\n };\n }\n\n if (isFlowErrorRequest(decryptedBody)) {\n LOGGER.log(`Flow error: ${JSON.stringify(decryptedBody)}`);\n return {\n statusCode: 200,\n body: {},\n };\n }\n\n if (isFlowDataExchangeRequest(decryptedBody)) {\n const result = await handler(whatsapp, decryptedBody);\n const encryptedResponse = encryptFlowResponse(\n result,\n Buffer.from(body.aes_key, 'base64'),\n Buffer.from(body.initial_vector, 'base64'),\n );\n\n return {\n statusCode: 200,\n body: encryptedResponse,\n };\n }\n\n LOGGER.log(`Unknown flow request type: ${JSON.stringify(decryptedBody)}`);\n return {\n statusCode: 400,\n body: { error: 'Unknown request type' },\n };\n } catch (error) {\n LOGGER.log(`Error handling flow request: ${error}`);\n return {\n statusCode: 500,\n body: { error: 'Internal server error' },\n };\n }\n}\n\n/**\n * Private helper functions\n */\nasync function processMessages(\n waba_id: string,\n value: WebhookMessageValue,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<void> {\n const metadata = value.metadata;\n const contacts = value.contacts;\n const wabaId = waba_id;\n const displayPhoneNumber = metadata?.display_phone_number || '';\n const phoneNumberId = metadata?.phone_number_id || '';\n const profileName = contacts?.[0]?.profile?.name || '';\n\n if (value.statuses && value.statuses.length > 0) {\n const statuses = value.statuses;\n for (const status of statuses) {\n const processedStatus: WebhookMessage = {\n wabaId,\n id: status.id,\n from: status.recipient_id,\n timestamp: status.timestamp,\n type: MessageTypesEnum.Statuses,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n statuses: value.statuses[0],\n originalData: status,\n };\n\n await executeHandler(\n handlers.messageHandlers.get(MessageTypesEnum.Statuses),\n whatsapp,\n processedStatus,\n MessageTypesEnum.Statuses,\n );\n }\n return;\n }\n\n if (value.messages && value.messages.length > 0) {\n const messages = value.messages;\n\n for (const message of messages) {\n const messageType = message.type;\n\n const processedMessage: WebhookMessage = {\n wabaId,\n id: message.id,\n from: message.from,\n timestamp: message.timestamp,\n type: message.type,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n originalData: message,\n };\n\n switch (messageType) {\n case MessageTypesEnum.Text:\n processedMessage.text = message.text;\n break;\n case MessageTypesEnum.Image:\n processedMessage.image = message.image;\n break;\n case MessageTypesEnum.Video:\n processedMessage.video = message.video;\n break;\n case MessageTypesEnum.Audio:\n processedMessage.audio = message.audio;\n break;\n case MessageTypesEnum.Document:\n processedMessage.document = message.document;\n break;\n case MessageTypesEnum.Sticker:\n processedMessage.sticker = message.sticker;\n break;\n case MessageTypesEnum.Location:\n processedMessage.location = message.location;\n break;\n case MessageTypesEnum.Contacts:\n processedMessage.contacts = message.contacts;\n break;\n case MessageTypesEnum.Interactive:\n processedMessage.interactive = message.interactive;\n break;\n case MessageTypesEnum.Button:\n processedMessage.button = message.button;\n break;\n case MessageTypesEnum.Order:\n processedMessage.order = message.order;\n break;\n case MessageTypesEnum.System:\n processedMessage.system = message.system;\n break;\n case MessageTypesEnum.Reaction:\n processedMessage.reaction = message.reaction;\n break;\n default:\n LOGGER.log(`Unknown message type: ${messageType}`);\n break;\n }\n\n // Execute handlers in sequence\n await executeHandler(handlers.preProcessHandler, whatsapp, processedMessage, 'pre-process');\n await executeHandler(handlers.messageHandlers.get(messageType), whatsapp, processedMessage, messageType);\n await executeHandler(handlers.postProcessHandler, whatsapp, processedMessage, 'post-process');\n }\n }\n}\n\nasync function executeHandler(\n handler: MessageHandler | undefined,\n whatsapp: WhatsApp,\n message: WebhookMessage,\n handlerType: string,\n): Promise<void> {\n if (handler) {\n try {\n await handler(whatsapp, message);\n } catch (error) {\n LOGGER.log(`Error in ${handlerType} handler: ${error}`);\n }\n }\n}\n\nfunction isRequestSignatureValid(request: WebhookRequest, verificationToken: string): boolean {\n const signature = request.headers['x-hub-signature-256'] as string;\n if (!signature || !request.rawBody) {\n return false;\n }\n\n const expectedSignature = crypto\n .createHmac('sha256', verificationToken)\n .update(request.rawBody, 'utf8')\n .digest('hex');\n\n const formattedExpectedSignature = `sha256=${expectedSignature}`;\n\n return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(formattedExpectedSignature));\n}\n\nfunction decryptFlowRequest(\n body: any,\n config: WabaConfigType,\n): {\n decryptedBody: FlowEndpointRequest;\n aesKeyBuffer: Buffer;\n initialVectorBuffer: Buffer;\n} {\n const { encrypted_aes_key, encrypted_flow_data, initial_vector } = body;\n\n if (!encrypted_aes_key || !encrypted_flow_data || !initial_vector) {\n throw new Error('Missing required encryption properties');\n }\n\n const privatePem = config.FLOW_API_PRIVATE_PEM.replace(/\\\\n/g, '\\n');\n const passphrase = config.FLOW_API_PASSPHRASE;\n\n const privateKey = crypto.createPrivateKey({ key: privatePem, passphrase });\n let decryptedAesKey: Buffer;\n\n try {\n 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 throw new Error('Failed to decrypt the request. Please verify your private key.');\n }\n\n const flowDataBuffer = Buffer.from(encrypted_flow_data, 'base64');\n const initialVectorBuffer = Buffer.from(initial_vector, 'base64');\n\n const TAG_LENGTH = 16;\n const encrypted_flow_data_body = flowDataBuffer.subarray(0, -TAG_LENGTH);\n const encrypted_flow_data_tag = flowDataBuffer.subarray(-TAG_LENGTH);\n\n const decipher = crypto.createDecipheriv('aes-128-gcm', decryptedAesKey, initialVectorBuffer);\n decipher.setAuthTag(encrypted_flow_data_tag);\n\n const decryptedJSONString = Buffer.concat([decipher.update(encrypted_flow_data_body), decipher.final()]).toString(\n 'utf-8',\n );\n\n return {\n decryptedBody: JSON.parse(decryptedJSONString),\n aesKeyBuffer: decryptedAesKey,\n initialVectorBuffer,\n };\n}\n\nfunction encryptFlowResponse(response: any, aesKeyBuffer: Buffer, initialVectorBuffer: Buffer): string {\n const flipped_iv: number[] = [];\n for (const pair of Array.from(initialVectorBuffer.entries())) {\n flipped_iv.push(~pair[1]);\n }\n\n try {\n const cipher = crypto.createCipheriv('aes-128-gcm', aesKeyBuffer, Buffer.from(flipped_iv));\n 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.log('Response encryption error:', error);\n throw new Error('Failed to encrypt response. Internal server error.');\n }\n}\n","import { MessageTypesEnum } from '@shared/types';\nimport { WabaConfigType, WhatsAppConfig } from '@shared/types/config';\n\nimport { FlowTypeEnum } from '@features/flow/types';\nimport { importConfig } from '@shared/config/importConfig';\nimport Logger from '@shared/utils/logger';\nimport { WhatsApp } from '../whatsapp';\nimport {\n FlowHandler,\n MessageHandler,\n processFlowRequest,\n processWebhookMessages,\n verifyWebhook,\n WebhookRequest,\n WebhookResponse,\n} from './utils/webhookUtils';\n\nconst LIB_NAME = 'WEBHOOK';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\n/**\n * Framework-agnostic WebhookHandler using pure functions\n */\nexport class WebhookHandler {\n private config: WabaConfigType;\n private client: WhatsApp;\n private messageHandlers: Map<MessageTypesEnum, MessageHandler> = new Map();\n private preProcessHandler: MessageHandler | undefined = undefined;\n private postProcessHandler: MessageHandler | undefined = undefined;\n private flowHandlers: Map<FlowTypeEnum, FlowHandler> = new Map();\n\n constructor(config: WhatsAppConfig) {\n this.config = importConfig(config);\n this.client = new WhatsApp(config);\n LOGGER.log('WebhookHandler instantiated!');\n }\n\n /**\n * Handle webhook verification (framework-agnostic)\n */\n public handleVerification = (request: Pick<WebhookRequest, 'query'>): WebhookResponse => {\n return verifyWebhook(request, this.config.WEBHOOK_VERIFICATION_TOKEN || '');\n };\n\n /**\n * Handle webhook messages (framework-agnostic)\n */\n public handleWebhook = async (request: WebhookRequest): Promise<WebhookResponse> => {\n return processWebhookMessages(request, this.client, {\n messageHandlers: this.messageHandlers,\n preProcessHandler: this.preProcessHandler,\n postProcessHandler: this.postProcessHandler,\n });\n };\n\n /**\n * Handle flow requests (framework-agnostic)\n */\n public handleFlow = async (request: WebhookRequest): Promise<WebhookResponse> => {\n return processFlowRequest(request, this.config, this.client, this.flowHandlers);\n };\n\n /**\n * Register a message handler for a specific message type\n */\n public onMessage(type: MessageTypesEnum, handler: MessageHandler): void {\n this.messageHandlers.set(type, handler);\n LOGGER.log(`Registered message handler for ${type}`);\n }\n\n /**\n * Register a pre-process handler that runs before all message handlers\n */\n public onMessagePreProcess(handler: MessageHandler): void {\n this.preProcessHandler = handler;\n LOGGER.log('Registered pre-process handler');\n }\n\n /**\n * Register a post-process handler that runs after all message handlers\n */\n public onMessagePostProcess(handler: MessageHandler): void {\n this.postProcessHandler = handler;\n LOGGER.log('Registered post-process handler');\n }\n\n /**\n * Register a flow handler for a specific flow type\n */\n public onFlow(type: FlowTypeEnum, handler: FlowHandler): void {\n this.flowHandlers.set(type, handler);\n LOGGER.log(`Registered flow handler for ${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"]}
@@ -1,19 +1,19 @@
1
- export { F as FlowHandler, M as MessageStatus, W as WebhookContact, a as WebhookEvent, c as WebhookHandler, b as WebhookMessage, e as WebhookRequest, f as WebhookResponse, p as processFlowRequest, d as processWebhookMessages, v as verifyWebhook } from '../../WebhookHandler-q8tq2j0d.js';
1
+ export { F as FlowHandler, M as MessageStatus, W as WebhookContact, a as WebhookEvent, c as WebhookHandler, b as WebhookMessage, e as WebhookRequest, f as WebhookResponse, p as processFlowRequest, d as processWebhookMessages, v as verifyWebhook } from '../../WebhookHandler-BcVZPlq8.js';
2
2
  import '../../shared/types/config.js';
3
3
  import '../../enums-CM95zXd_.js';
4
- import '../../FlowApi-Mwlby1Rl.js';
5
- import '../../base-GKqD_DhO.js';
6
- import '../whatsapp/index.js';
7
- import '../../EncryptionApi-CFuuNH2K.js';
8
- import '../../MediaApi-CyoByati.js';
9
- import '../../MessageApi-BU1WUNKS.js';
10
- import '../../PhoneNumberApi-C3Hmh_nZ.js';
11
- import '../../BusinessProfileApi-DO28tMcf.js';
12
- import '../../QrCodeApi-BPsHp3ad.js';
13
- import '../../RegistrationApi-DI9NskvK.js';
14
- import '../../TemplateApi-DXr47lZe.js';
15
- import '../../TwoStepVerificationApi-CICKknhN.js';
16
- import '../../WabaApi-DZurKSzA.js';
4
+ import '../../FlowApi-B_S2OAFn.js';
5
+ import '../../base-WGahY7ao.js';
6
+ import '../../index-BBvXSzXG.js';
7
+ import '../../EncryptionApi-udtMPgrF.js';
8
+ import '../../MediaApi-Raddyh38.js';
9
+ import '../../MessageApi-CsdVH_9V.js';
10
+ import '../../PhoneNumberApi-DVUn9x88.js';
11
+ import '../../BusinessProfileApi-C1x8w77V.js';
12
+ import '../../QrCodeApi-lDLJYnCg.js';
13
+ import '../../RegistrationApi-Co1NiWw_.js';
14
+ import '../../TemplateApi-DhR1Xy73.js';
15
+ import '../../TwoStepVerificationApi-ByTfkum8.js';
16
+ import '../../WabaApi-CXb5Z_Ek.js';
17
17
  import 'https';
18
18
 
19
19
  declare const generateXHub256Sig: (body: string, appSecret: string) => string;
@@ -1,2 +1,2 @@
1
- export{g as WebhookHandler,h as generateXHub256Sig,f as processFlowRequest,e as processWebhookMessages,d as verifyWebhook}from'../../chunk-MTRF47KZ.js';import'../../chunk-4LWNMCXG.js';import'../../chunk-3MO3BTBC.js';import'../../chunk-R36L2XYO.js';import'../../chunk-GT3XQN7Y.js';import'../../chunk-O2OTHNWM.js';import'../../chunk-7NQLQPLH.js';import'../../chunk-UQPD6GIF.js';import'../../chunk-5JGM556C.js';import'../../chunk-2NJVBJUN.js';import'../../chunk-XPPDOFBN.js';import'../../chunk-KFPOVYEJ.js';import'../../chunk-7GL74SXM.js';import'../../chunk-LGLRGXCE.js';import'../../chunk-GIQLIMOD.js';import'../../chunk-BZ5QDXNR.js';import'../../chunk-VW3LGHTJ.js';import'../../chunk-QCFJGLDQ.js';import'../../chunk-4C666HHU.js';//# sourceMappingURL=index.js.map
1
+ export{g as WebhookHandler,h as generateXHub256Sig,f as processFlowRequest,e as processWebhookMessages,d as verifyWebhook}from'../../chunk-4ZHGFSME.js';import'../../chunk-4LWNMCXG.js';import'../../chunk-3MO3BTBC.js';import'../../chunk-R36L2XYO.js';import'../../chunk-GT3XQN7Y.js';import'../../chunk-O2OTHNWM.js';import'../../chunk-7NQLQPLH.js';import'../../chunk-UQPD6GIF.js';import'../../chunk-5JGM556C.js';import'../../chunk-2NJVBJUN.js';import'../../chunk-XPPDOFBN.js';import'../../chunk-KFPOVYEJ.js';import'../../chunk-7GL74SXM.js';import'../../chunk-LGLRGXCE.js';import'../../chunk-GIQLIMOD.js';import'../../chunk-BZ5QDXNR.js';import'../../chunk-VW3LGHTJ.js';import'../../chunk-QCFJGLDQ.js';import'../../chunk-4C666HHU.js';//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
@@ -1,100 +1,16 @@
1
- import { E as EncryptionApi } from '../../EncryptionApi-CFuuNH2K.js';
2
- import { F as FlowApi } from '../../FlowApi-Mwlby1Rl.js';
3
- import { WhatsAppConfig, WabaConfigType } from '../../shared/types/config.js';
4
- import { M as MediaApi } from '../../MediaApi-CyoByati.js';
5
- import { M as MessagesApi } from '../../MessageApi-BU1WUNKS.js';
6
- import { P as PhoneNumberApi } from '../../PhoneNumberApi-C3Hmh_nZ.js';
7
- import { B as BusinessProfileApi } from '../../BusinessProfileApi-DO28tMcf.js';
8
- import { Q as QrCodeApi } from '../../QrCodeApi-BPsHp3ad.js';
9
- import { R as RegistrationApi } from '../../RegistrationApi-DI9NskvK.js';
10
- import { f as TemplateApi } from '../../TemplateApi-DXr47lZe.js';
11
- import { T as TwoStepVerificationApi } from '../../TwoStepVerificationApi-CICKknhN.js';
12
- import { W as WabaApi } from '../../WabaApi-DZurKSzA.js';
13
- import { H as HttpMethodsEnum, l as SDKEnums } from '../../enums-CM95zXd_.js';
14
- import { a as RequesterClass } from '../../base-GKqD_DhO.js';
15
- import { Agent } from 'https';
16
-
17
- type ResponseHeaderValue = string | string[] | undefined;
18
- type ResponseHeaders = Record<string, ResponseHeaderValue>;
19
- type ResponseJSONBody = Record<string, unknown>;
20
- declare class HttpsClientResponseClass {
21
- constructor(resp: Response);
22
- statusCode: () => number;
23
- headers: () => ResponseHeaders;
24
- rawResponse: () => Response;
25
- json: () => Promise<ResponseJSONBody>;
26
- }
27
- declare class HttpsClientClass {
28
- constructor();
29
- clearSockets: () => boolean;
30
- sendRequest: (host: string, path: string, method: HttpMethodsEnum, headers: HeadersInit, timeout: number, body?: BodyInit | null) => Promise<HttpsClientResponseClass>;
31
- }
32
-
33
- declare class WhatsAppClass {
34
- constructor(config?: WhatsAppConfig);
35
- readonly messages: MessagesApi;
36
- readonly templates: TemplateApi;
37
- readonly phoneNumber: PhoneNumberApi;
38
- readonly qrCode: QrCodeApi;
39
- readonly encryption: EncryptionApi;
40
- readonly twoStepVerification: TwoStepVerificationApi;
41
- readonly registration: RegistrationApi;
42
- readonly media: MediaApi;
43
- readonly waba: WabaApi;
44
- readonly flow: FlowApi;
45
- readonly businessProfile: BusinessProfileApi;
46
- updateTimeout(ms: number): boolean;
47
- updatePhoneNumberId(phoneNumberId: number): boolean;
48
- updateAccessToken(accessToken: string): boolean;
49
- updateWabaId(wabaId: string): boolean;
50
- }
51
-
52
- declare class HttpsClient implements HttpsClientClass {
53
- agent: Agent;
54
- constructor();
55
- clearSockets(): boolean;
56
- sendRequest(hostname: string, path: string, method: HttpMethodsEnum, headers: HeadersInit, timeout: number, body?: BodyInit | null): Promise<HttpsClientResponseClass>;
57
- }
58
-
59
- declare class Requester implements RequesterClass {
60
- client: Readonly<HttpsClient>;
61
- accessToken: Readonly<string>;
62
- phoneNumberId: Readonly<number>;
63
- businessAcctId: Readonly<string>;
64
- apiVersion: Readonly<string>;
65
- userAgent: Readonly<string>;
66
- host: Readonly<string>;
67
- protocol: Readonly<string>;
68
- constructor(apiVersion: string, phoneNumberId: number, accessToken: string, businessAcctId: string, userAgent: string);
69
- buildHeader(contentType: string, additionalHeaders?: Record<string, string>): HeadersInit;
70
- buildCAPIPath(endpoint: string): string;
71
- sendRequest(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any, contentType?: string, additionalHeaders?: Record<string, string>): Promise<HttpsClientResponseClass>;
72
- getJson<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any, additionalHeaders?: Record<string, string>): Promise<T>;
73
- sendFormData<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, formData: FormData, additionalHeaders?: Record<string, string>): Promise<T>;
74
- sendUrlEncodedForm<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, formData: Record<string, string>, additionalHeaders?: Record<string, string>): Promise<T>;
75
- }
76
-
77
- declare class WhatsApp implements WhatsAppClass {
78
- config: WabaConfigType;
79
- requester: Readonly<Requester>;
80
- readonly messages: MessagesApi;
81
- readonly templates: TemplateApi;
82
- readonly phoneNumber: PhoneNumberApi;
83
- readonly qrCode: QrCodeApi;
84
- readonly encryption: EncryptionApi;
85
- readonly twoStepVerification: TwoStepVerificationApi;
86
- readonly registration: RegistrationApi;
87
- readonly media: MediaApi;
88
- readonly waba: WabaApi;
89
- readonly flow: FlowApi;
90
- readonly businessProfile: BusinessProfileApi;
91
- static readonly Enums: typeof SDKEnums;
92
- constructor(config?: WhatsAppConfig);
93
- private userAgent;
94
- updateTimeout(ms: number): boolean;
95
- updatePhoneNumberId(phoneNumberId: number): boolean;
96
- updateAccessToken(accessToken: string): boolean;
97
- updateWabaId(wabaId: string): boolean;
98
- }
99
-
100
- export { WhatsApp, WhatsAppClass };
1
+ export { W as WhatsApp, d as WhatsAppClass } from '../../index-BBvXSzXG.js';
2
+ import '../../EncryptionApi-udtMPgrF.js';
3
+ import '../../base-WGahY7ao.js';
4
+ import '../../shared/types/config.js';
5
+ import '../../enums-CM95zXd_.js';
6
+ import '../../FlowApi-B_S2OAFn.js';
7
+ import '../../MediaApi-Raddyh38.js';
8
+ import '../../MessageApi-CsdVH_9V.js';
9
+ import '../../PhoneNumberApi-DVUn9x88.js';
10
+ import '../../BusinessProfileApi-C1x8w77V.js';
11
+ import '../../QrCodeApi-lDLJYnCg.js';
12
+ import '../../RegistrationApi-Co1NiWw_.js';
13
+ import '../../TemplateApi-DhR1Xy73.js';
14
+ import '../../TwoStepVerificationApi-ByTfkum8.js';
15
+ import '../../WabaApi-CXb5Z_Ek.js';
16
+ import 'https';
@@ -1,6 +1,6 @@
1
- import { E as EncryptionApi } from '../../EncryptionApi-CFuuNH2K.js';
2
- export { a as EncryptionClass, b as EncryptionPublicKeyResponse } from '../../EncryptionApi-CFuuNH2K.js';
3
- import '../../base-GKqD_DhO.js';
1
+ import { E as EncryptionApi } from '../../EncryptionApi-udtMPgrF.js';
2
+ export { a as EncryptionClass, b as EncryptionPublicKeyResponse } from '../../EncryptionApi-udtMPgrF.js';
3
+ import '../../base-WGahY7ao.js';
4
4
  import '../../shared/types/config.js';
5
5
  import '../../enums-CM95zXd_.js';
6
6
 
@@ -1,6 +1,6 @@
1
- import { F as FlowApi } from '../../FlowApi-Mwlby1Rl.js';
2
- export { C as CreateFlowResponse, a as Flow, c as FlowActionEnum, d as FlowAssetsResponse, e as FlowCategoryEnum, f as FlowClass, g as FlowEndpointRequest, h as FlowEndpointResponse, i as FlowMigrationResponse, j as FlowPreviewResponse, l as FlowStatusEnum, b as FlowType, n as FlowTypeEnum, m as FlowValidationError, k as FlowsListResponse, U as UpdateFlowResponse, V as ValidateFlowJsonResponse } from '../../FlowApi-Mwlby1Rl.js';
3
- import '../../base-GKqD_DhO.js';
1
+ import { F as FlowApi } from '../../FlowApi-B_S2OAFn.js';
2
+ export { C as CreateFlowResponse, a as Flow, c as FlowActionEnum, d as FlowAssetsResponse, e as FlowCategoryEnum, f as FlowClass, g as FlowEndpointRequest, h as FlowEndpointResponse, i as FlowMigrationResponse, j as FlowPreviewResponse, l as FlowStatusEnum, b as FlowType, n as FlowTypeEnum, m as FlowValidationError, k as FlowsListResponse, U as UpdateFlowResponse, V as ValidateFlowJsonResponse } from '../../FlowApi-B_S2OAFn.js';
3
+ import '../../base-WGahY7ao.js';
4
4
  import '../../shared/types/config.js';
5
5
  import '../../enums-CM95zXd_.js';
6
6
 
@@ -1,6 +1,6 @@
1
- import { M as MediaApi } from '../../MediaApi-CyoByati.js';
2
- export { a as MediaClass, b as MediaResponse, c as MediasResponse, U as UploadMediaResponse } from '../../MediaApi-CyoByati.js';
3
- import '../../base-GKqD_DhO.js';
1
+ import { M as MediaApi } from '../../MediaApi-Raddyh38.js';
2
+ export { a as MediaClass, b as MediaResponse, c as MediasResponse, U as UploadMediaResponse } from '../../MediaApi-Raddyh38.js';
3
+ import '../../base-WGahY7ao.js';
4
4
  import '../../shared/types/config.js';
5
5
  import '../../enums-CM95zXd_.js';
6
6
 
@@ -1,6 +1,6 @@
1
- import { M as MessagesApi } from '../../MessageApi-BU1WUNKS.js';
2
- export { A as AudioMediaObject, C as ContactObject, D as DocumentMediaObject, I as ImageMediaObject, a as InteractiveObject, L as LocationObject, b as MessageRequestParams, d as MessageTemplateObject, c as MessagesResponse, R as ReactionParams, S as StatusParams, e as StickerMediaObject, T as TextMessageParams, f as TextObject, V as VideoMediaObject } from '../../MessageApi-BU1WUNKS.js';
3
- import '../../base-GKqD_DhO.js';
1
+ import { M as MessagesApi } from '../../MessageApi-CsdVH_9V.js';
2
+ export { A as AudioMediaObject, C as ContactObject, D as DocumentMediaObject, I as ImageMediaObject, a as InteractiveObject, L as LocationObject, b as MessageRequestParams, d as MessageTemplateObject, c as MessagesResponse, R as ReactionParams, S as StatusParams, e as StickerMediaObject, T as TextMessageParams, f as TextObject, V as VideoMediaObject } from '../../MessageApi-CsdVH_9V.js';
3
+ import '../../base-WGahY7ao.js';
4
4
  import '../../shared/types/config.js';
5
5
  import '../../enums-CM95zXd_.js';
6
6
 
@@ -1,6 +1,6 @@
1
- import { P as PhoneNumberApi } from '../../PhoneNumberApi-C3Hmh_nZ.js';
2
- export { A as AccountMode, C as CodeVerificationStatus, a as Cursors, H as HealthStatus, b as HealthStatusEntity, M as MessagingLimitTier, c as PhoneNumberClass, d as PhoneNumberResponse, e as PhoneNumbersResponse, f as PlatformType, Q as QualityRating, g as QualityScore, R as RequestVerificationCodeRequest, T as Throughput, h as ThroughputLevel, i as TwoStepVerificationParams, V as VerifyCodeRequest } from '../../PhoneNumberApi-C3Hmh_nZ.js';
3
- import '../../base-GKqD_DhO.js';
1
+ import { P as PhoneNumberApi } from '../../PhoneNumberApi-DVUn9x88.js';
2
+ export { A as AccountMode, C as CodeVerificationStatus, a as Cursors, H as HealthStatus, b as HealthStatusEntity, M as MessagingLimitTier, c as PhoneNumberClass, d as PhoneNumberResponse, e as PhoneNumbersResponse, f as PlatformType, Q as QualityRating, g as QualityScore, R as RequestVerificationCodeRequest, T as Throughput, h as ThroughputLevel, i as TwoStepVerificationParams, V as VerifyCodeRequest } from '../../PhoneNumberApi-DVUn9x88.js';
3
+ import '../../base-WGahY7ao.js';
4
4
  import '../../shared/types/config.js';
5
5
  import '../../enums-CM95zXd_.js';
6
6
 
@@ -1,6 +1,6 @@
1
- import { B as BusinessProfileApi } from '../../BusinessProfileApi-DO28tMcf.js';
2
- export { a as BusinessProfileClass, b as BusinessProfileData, c as BusinessProfileField, d as BusinessProfileFieldsParam, e as BusinessProfileResponse, C as CreateUploadSessionParams, G as GetUploadHandleParams, U as UpdateBusinessProfileRequest, f as UploadBusinessProfileResponse, g as UploadHandle, h as UploadMediaParams, i as UploadSession, j as UploadSessionResponse } from '../../BusinessProfileApi-DO28tMcf.js';
3
- import '../../base-GKqD_DhO.js';
1
+ import { B as BusinessProfileApi } from '../../BusinessProfileApi-C1x8w77V.js';
2
+ export { a as BusinessProfileClass, b as BusinessProfileData, c as BusinessProfileField, d as BusinessProfileFieldsParam, e as BusinessProfileResponse, C as CreateUploadSessionParams, G as GetUploadHandleParams, U as UpdateBusinessProfileRequest, f as UploadBusinessProfileResponse, g as UploadHandle, h as UploadMediaParams, i as UploadSession, j as UploadSessionResponse } from '../../BusinessProfileApi-C1x8w77V.js';
3
+ import '../../base-WGahY7ao.js';
4
4
  import '../../shared/types/config.js';
5
5
  import '../../enums-CM95zXd_.js';
6
6
 
@@ -1,6 +1,6 @@
1
- import { Q as QrCodeApi } from '../../QrCodeApi-BPsHp3ad.js';
2
- export { C as CreateQrCodeRequest, a as QrCodeClass, b as QrCodeResponse, c as QrCodesResponse, U as UpdateQrCodeRequest } from '../../QrCodeApi-BPsHp3ad.js';
3
- import '../../base-GKqD_DhO.js';
1
+ import { Q as QrCodeApi } from '../../QrCodeApi-lDLJYnCg.js';
2
+ export { C as CreateQrCodeRequest, a as QrCodeClass, b as QrCodeResponse, c as QrCodesResponse, U as UpdateQrCodeRequest } from '../../QrCodeApi-lDLJYnCg.js';
3
+ import '../../base-WGahY7ao.js';
4
4
  import '../../shared/types/config.js';
5
5
  import '../../enums-CM95zXd_.js';
6
6
 
@@ -1,6 +1,6 @@
1
- import { R as RegistrationApi } from '../../RegistrationApi-DI9NskvK.js';
2
- export { a as RegistrationClass, b as RegistrationRequest } from '../../RegistrationApi-DI9NskvK.js';
3
- import '../../base-GKqD_DhO.js';
1
+ import { R as RegistrationApi } from '../../RegistrationApi-Co1NiWw_.js';
2
+ export { a as RegistrationClass, b as RegistrationRequest } from '../../RegistrationApi-Co1NiWw_.js';
3
+ import '../../base-WGahY7ao.js';
4
4
  import '../../shared/types/config.js';
5
5
  import '../../enums-CM95zXd_.js';
6
6
 
@@ -1,7 +1,7 @@
1
- import { T as TemplateFormat, a as TemplateRequestBody } from '../../TemplateApi-DXr47lZe.js';
2
- export { C as CatalogButton, g as ComponentTypes, h as CopyCodeButton, F as FlowButton, M as MPMButton, O as OTPButton, P as PhoneNumberButton, Q as QuickReplyButton, S as SPMButton, f as TemplateApi, i as TemplateBody, j as TemplateButton, k as TemplateButtons, l as TemplateCarousel, b as TemplateClass, c as TemplateDeleteParams, m as TemplateFooter, d as TemplateGetParams, n as TemplateHeader, o as TemplateHeaderExample, p as TemplateLimitedTimeOffer, e as TemplateResponse, U as URLButton, f as default } from '../../TemplateApi-DXr47lZe.js';
1
+ import { T as TemplateFormat, a as TemplateRequestBody } from '../../TemplateApi-DhR1Xy73.js';
2
+ export { C as CatalogButton, g as ComponentTypes, h as CopyCodeButton, F as FlowButton, M as MPMButton, O as OTPButton, P as PhoneNumberButton, Q as QuickReplyButton, S as SPMButton, f as TemplateApi, i as TemplateBody, j as TemplateButton, k as TemplateButtons, l as TemplateCarousel, b as TemplateClass, c as TemplateDeleteParams, m as TemplateFooter, d as TemplateGetParams, n as TemplateHeader, o as TemplateHeaderExample, p as TemplateLimitedTimeOffer, e as TemplateResponse, U as URLButton, f as default } from '../../TemplateApi-DhR1Xy73.js';
3
3
  import { L as LanguagesEnum, C as CurrencyCodesEnum, a as CategoryEnum } from '../../enums-CM95zXd_.js';
4
- import '../../base-GKqD_DhO.js';
4
+ import '../../base-WGahY7ao.js';
5
5
  import '../../shared/types/config.js';
6
6
 
7
7
  interface TextParameter {
@@ -1,6 +1,6 @@
1
- import { T as TwoStepVerificationApi } from '../../TwoStepVerificationApi-CICKknhN.js';
2
- export { a as TwoStepVerificationClass, b as TwoStepVerificationRequest } from '../../TwoStepVerificationApi-CICKknhN.js';
3
- import '../../base-GKqD_DhO.js';
1
+ import { T as TwoStepVerificationApi } from '../../TwoStepVerificationApi-ByTfkum8.js';
2
+ export { a as TwoStepVerificationClass, b as TwoStepVerificationRequest } from '../../TwoStepVerificationApi-ByTfkum8.js';
3
+ import '../../base-WGahY7ao.js';
4
4
  import '../../shared/types/config.js';
5
5
  import '../../enums-CM95zXd_.js';
6
6
 
@@ -1,6 +1,6 @@
1
- import { W as WabaApi } from '../../WabaApi-DZurKSzA.js';
2
- export { U as UpdateWabaSubscription, b as WABAClass, a as WabaAccount, c as WabaSubscriptions } from '../../WabaApi-DZurKSzA.js';
3
- import '../../base-GKqD_DhO.js';
1
+ import { W as WabaApi } from '../../WabaApi-CXb5Z_Ek.js';
2
+ export { U as UpdateWabaSubscription, b as WABAClass, a as WabaAccount, c as WabaSubscriptions } from '../../WabaApi-CXb5Z_Ek.js';
3
+ import '../../base-WGahY7ao.js';
4
4
  import '../../shared/types/config.js';
5
5
  import '../../enums-CM95zXd_.js';
6
6
 
@@ -0,0 +1,100 @@
1
+ import { E as EncryptionApi } from './EncryptionApi-udtMPgrF.js';
2
+ import { F as FlowApi } from './FlowApi-B_S2OAFn.js';
3
+ import { WhatsAppConfig, WabaConfigType } from './shared/types/config.js';
4
+ import { M as MediaApi } from './MediaApi-Raddyh38.js';
5
+ import { M as MessagesApi } from './MessageApi-CsdVH_9V.js';
6
+ import { P as PhoneNumberApi } from './PhoneNumberApi-DVUn9x88.js';
7
+ import { B as BusinessProfileApi } from './BusinessProfileApi-C1x8w77V.js';
8
+ import { Q as QrCodeApi } from './QrCodeApi-lDLJYnCg.js';
9
+ import { R as RegistrationApi } from './RegistrationApi-Co1NiWw_.js';
10
+ import { f as TemplateApi } from './TemplateApi-DhR1Xy73.js';
11
+ import { T as TwoStepVerificationApi } from './TwoStepVerificationApi-ByTfkum8.js';
12
+ import { W as WabaApi } from './WabaApi-CXb5Z_Ek.js';
13
+ import { H as HttpMethodsEnum, l as SDKEnums } from './enums-CM95zXd_.js';
14
+ import { a as RequesterClass } from './base-WGahY7ao.js';
15
+ import { Agent } from 'https';
16
+
17
+ type ResponseHeaderValue = string | string[] | undefined;
18
+ type ResponseHeaders = Record<string, ResponseHeaderValue>;
19
+ type ResponseJSONBody = Record<string, unknown>;
20
+ declare class HttpsClientResponseClass {
21
+ constructor(resp: Response);
22
+ statusCode: () => number;
23
+ headers: () => ResponseHeaders;
24
+ rawResponse: () => Response;
25
+ json: () => Promise<ResponseJSONBody>;
26
+ }
27
+ declare class HttpsClientClass {
28
+ constructor();
29
+ clearSockets: () => boolean;
30
+ sendRequest: (host: string, path: string, method: HttpMethodsEnum, headers: HeadersInit, timeout: number, body?: BodyInit | null) => Promise<HttpsClientResponseClass>;
31
+ }
32
+
33
+ declare class WhatsAppClass {
34
+ constructor(config?: WhatsAppConfig);
35
+ readonly messages: MessagesApi;
36
+ readonly templates: TemplateApi;
37
+ readonly phoneNumber: PhoneNumberApi;
38
+ readonly qrCode: QrCodeApi;
39
+ readonly encryption: EncryptionApi;
40
+ readonly twoStepVerification: TwoStepVerificationApi;
41
+ readonly registration: RegistrationApi;
42
+ readonly media: MediaApi;
43
+ readonly waba: WabaApi;
44
+ readonly flow: FlowApi;
45
+ readonly businessProfile: BusinessProfileApi;
46
+ updateTimeout(ms: number): boolean;
47
+ updatePhoneNumberId(phoneNumberId: number): boolean;
48
+ updateAccessToken(accessToken: string): boolean;
49
+ updateWabaId(wabaId: string): boolean;
50
+ }
51
+
52
+ declare class HttpsClient implements HttpsClientClass {
53
+ agent: Agent;
54
+ constructor();
55
+ clearSockets(): boolean;
56
+ sendRequest(hostname: string, path: string, method: HttpMethodsEnum, headers: HeadersInit, timeout: number, body?: BodyInit | null): Promise<HttpsClientResponseClass>;
57
+ }
58
+
59
+ declare class Requester implements RequesterClass {
60
+ client: Readonly<HttpsClient>;
61
+ accessToken: Readonly<string>;
62
+ phoneNumberId: Readonly<number>;
63
+ businessAcctId: Readonly<string>;
64
+ apiVersion: Readonly<string>;
65
+ userAgent: Readonly<string>;
66
+ host: Readonly<string>;
67
+ protocol: Readonly<string>;
68
+ constructor(apiVersion: string, phoneNumberId: number, accessToken: string, businessAcctId: string, userAgent: string);
69
+ buildHeader(contentType: string, additionalHeaders?: Record<string, string>): HeadersInit;
70
+ buildCAPIPath(endpoint: string): string;
71
+ sendRequest(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any, contentType?: string, additionalHeaders?: Record<string, string>): Promise<HttpsClientResponseClass>;
72
+ getJson<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any, additionalHeaders?: Record<string, string>): Promise<T>;
73
+ sendFormData<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, formData: FormData, additionalHeaders?: Record<string, string>): Promise<T>;
74
+ sendUrlEncodedForm<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, formData: Record<string, string>, additionalHeaders?: Record<string, string>): Promise<T>;
75
+ }
76
+
77
+ declare class WhatsApp implements WhatsAppClass {
78
+ config: WabaConfigType;
79
+ requester: Readonly<Requester>;
80
+ readonly messages: MessagesApi;
81
+ readonly templates: TemplateApi;
82
+ readonly phoneNumber: PhoneNumberApi;
83
+ readonly qrCode: QrCodeApi;
84
+ readonly encryption: EncryptionApi;
85
+ readonly twoStepVerification: TwoStepVerificationApi;
86
+ readonly registration: RegistrationApi;
87
+ readonly media: MediaApi;
88
+ readonly waba: WabaApi;
89
+ readonly flow: FlowApi;
90
+ readonly businessProfile: BusinessProfileApi;
91
+ static readonly Enums: typeof SDKEnums;
92
+ constructor(config?: WhatsAppConfig);
93
+ private userAgent;
94
+ updateTimeout(ms: number): boolean;
95
+ updatePhoneNumberId(phoneNumberId: number): boolean;
96
+ updateAccessToken(accessToken: string): boolean;
97
+ updateWabaId(wabaId: string): boolean;
98
+ }
99
+
100
+ export { HttpsClientClass as H, type ResponseHeaders as R, WhatsApp as W, HttpsClientResponseClass as a, type ResponseHeaderValue as b, type ResponseJSONBody as c, WhatsAppClass as d };
package/dist/index.d.ts CHANGED
@@ -1,21 +1,21 @@
1
- export { W as WebhookContact, a as WebhookEvent, c as WebhookHandler, b as WebhookMessage } from './WebhookHandler-q8tq2j0d.js';
2
- import { g as FlowEndpointRequest, o as FlowDataExchangeRequest, c as FlowActionEnum, p as FlowErrorNotificationRequest, q as FlowHealthCheckRequest } from './FlowApi-Mwlby1Rl.js';
3
- export { a as Flow, F as FlowApi, f as FlowClass, h as FlowEndpointResponse, b as FlowType, n as FlowTypeEnum } from './FlowApi-Mwlby1Rl.js';
1
+ export { W as WebhookContact, a as WebhookEvent, c as WebhookHandler, b as WebhookMessage } from './WebhookHandler-BcVZPlq8.js';
2
+ import { g as FlowEndpointRequest, o as FlowDataExchangeRequest, c as FlowActionEnum, p as FlowErrorNotificationRequest, q as FlowHealthCheckRequest } from './FlowApi-B_S2OAFn.js';
3
+ export { a as Flow, F as FlowApi, f as FlowClass, h as FlowEndpointResponse, b as FlowType, n as FlowTypeEnum } from './FlowApi-B_S2OAFn.js';
4
+ export { B as BaseAPI, d as BaseClass, e as GeneralHeaderInterface, G as GeneralRequestBody, P as Paging, a as RequesterClass, f as RequesterResponseInterface, c as ResponseData, b as ResponsePagination, R as ResponseSuccess } from './base-WGahY7ao.js';
4
5
  export { WabaConfigType, WhatsAppConfig } from './shared/types/config.js';
6
+ export { H as HttpsClientClass, a as HttpsClientResponseClass, b as ResponseHeaderValue, R as ResponseHeaders, c as ResponseJSONBody, W as WhatsApp } from './index-BBvXSzXG.js';
5
7
  export { A as AudioMediaTypesEnum, B as BusinessVerticalEnum, b as ButtonPositionEnum, c as ButtonTypesEnum, a as CategoryEnum, d as ComponentTypesEnum, e as ConversationTypesEnum, C as CurrencyCodesEnum, D as DataLocalizationRegionEnum, f as DocumentMediaTypesEnum, H as HttpMethodsEnum, I as ImageMediaTypesEnum, g as InteractiveTypesEnum, L as LanguagesEnum, M as MessageTypesEnum, P as ParametersTypesEnum, R as ReferralSourceTypesEnum, h as RequestCodeMethodsEnum, S as StatusEnum, i as StickerMediaTypesEnum, j as SystemChangeTypesEnum, T as TemplateStatusEnum, V as VideoMediaTypesEnum, W as WabaConfigEnum, k as WebhookTypesEnum } from './enums-CM95zXd_.js';
6
- export { E as EncryptionApi } from './EncryptionApi-CFuuNH2K.js';
7
- export { a as MediaClass, b as MediaResponse, c as MediasResponse, U as UploadMediaResponse } from './MediaApi-CyoByati.js';
8
- export { A as AudioMediaObject, C as ContactObject, D as DocumentMediaObject, I as ImageMediaObject, a as InteractiveObject, L as LocationObject, b as MessageRequestParams, d as MessageTemplateObject, M as MessagesApi, c as MessagesResponse, R as ReactionParams, S as StatusParams, e as StickerMediaObject, T as TextMessageParams, f as TextObject, V as VideoMediaObject } from './MessageApi-BU1WUNKS.js';
9
- export { P as PhoneNumberApi, c as PhoneNumberClass, d as PhoneNumberResponse } from './PhoneNumberApi-C3Hmh_nZ.js';
10
- export { B as BusinessProfileApi, a as BusinessProfileClass, e as BusinessProfileResponse } from './BusinessProfileApi-DO28tMcf.js';
11
- export { Q as QrCodeApi, a as QrCodeClass, b as QrCodeResponse } from './QrCodeApi-BPsHp3ad.js';
12
- export { R as RegistrationApi, a as RegistrationClass } from './RegistrationApi-DI9NskvK.js';
13
- export { f as TemplateApi, b as TemplateClass, e as TemplateResponse } from './TemplateApi-DXr47lZe.js';
14
- export { T as TwoStepVerificationApi } from './TwoStepVerificationApi-CICKknhN.js';
15
- export { b as WABAClass, a as WabaAccount, W as WabaApi } from './WabaApi-DZurKSzA.js';
16
- export { WhatsApp } from './core/whatsapp/index.js';
8
+ export { E as EncryptionApi } from './EncryptionApi-udtMPgrF.js';
9
+ export { a as MediaClass, b as MediaResponse, c as MediasResponse, U as UploadMediaResponse } from './MediaApi-Raddyh38.js';
10
+ export { A as AudioMediaObject, C as ContactObject, D as DocumentMediaObject, I as ImageMediaObject, a as InteractiveObject, L as LocationObject, b as MessageRequestParams, d as MessageTemplateObject, M as MessagesApi, c as MessagesResponse, R as ReactionParams, S as StatusParams, e as StickerMediaObject, T as TextMessageParams, f as TextObject, V as VideoMediaObject } from './MessageApi-CsdVH_9V.js';
11
+ export { P as PhoneNumberApi, c as PhoneNumberClass, d as PhoneNumberResponse } from './PhoneNumberApi-DVUn9x88.js';
12
+ export { B as BusinessProfileApi, a as BusinessProfileClass, e as BusinessProfileResponse } from './BusinessProfileApi-C1x8w77V.js';
13
+ export { Q as QrCodeApi, a as QrCodeClass, b as QrCodeResponse } from './QrCodeApi-lDLJYnCg.js';
14
+ export { R as RegistrationApi, a as RegistrationClass } from './RegistrationApi-Co1NiWw_.js';
15
+ export { f as TemplateApi, b as TemplateClass, e as TemplateResponse } from './TemplateApi-DhR1Xy73.js';
16
+ export { T as TwoStepVerificationApi } from './TwoStepVerificationApi-ByTfkum8.js';
17
+ export { b as WABAClass, a as WabaAccount, W as WabaApi } from './WabaApi-CXb5Z_Ek.js';
17
18
  export { MetaError, isMetaError } from './shared/utils/isMetaError.js';
18
- import './base-GKqD_DhO.js';
19
19
  import 'https';
20
20
 
21
21
  interface LoggerInterface {
@@ -80,4 +80,4 @@ declare function isFlowErrorRequest(request: FlowEndpointRequest): request is Fl
80
80
  */
81
81
  declare function isFlowPingRequest(request: FlowEndpointRequest): request is FlowHealthCheckRequest;
82
82
 
83
- export { FlowEndpointRequest, Logger, buildFieldsQueryString, isFlowDataExchangeRequest, isFlowErrorRequest, isFlowPingRequest, objectToQueryString };
83
+ export { FlowEndpointRequest, Logger, type LoggerInterface, buildFieldsQueryString, isFlowDataExchangeRequest, isFlowErrorRequest, isFlowPingRequest, objectToQueryString };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import'./chunk-FLDBNTNY.js';export{a as QrCodeApi}from'./chunk-I222VSWK.js';export{g as WebhookHandler,a as isFlowDataExchangeRequest,b as isFlowErrorRequest,c as isFlowPingRequest}from'./chunk-MTRF47KZ.js';export{b as WhatsApp}from'./chunk-4LWNMCXG.js';export{a as isMetaError}from'./chunk-3MO3BTBC.js';export{a as TemplateApi}from'./chunk-R36L2XYO.js';import'./chunk-GT3XQN7Y.js';export{b as RegistrationApi}from'./chunk-O2OTHNWM.js';export{b as EncryptionApi}from'./chunk-7NQLQPLH.js';export{b as TwoStepVerificationApi}from'./chunk-UQPD6GIF.js';export{b as WabaApi}from'./chunk-5JGM556C.js';export{b as MessagesApi}from'./chunk-2NJVBJUN.js';import'./chunk-XPPDOFBN.js';export{b as BusinessProfileApi}from'./chunk-KFPOVYEJ.js';export{a as buildFieldsQueryString}from'./chunk-7GL74SXM.js';export{c as FlowApi}from'./chunk-LGLRGXCE.js';export{b as PhoneNumberApi}from'./chunk-GIQLIMOD.js';export{a as objectToQueryString}from'./chunk-BZ5QDXNR.js';export{a as Logger}from'./chunk-VW3LGHTJ.js';import'./chunk-QCFJGLDQ.js';import'./chunk-4C666HHU.js';//# sourceMappingURL=index.js.map
1
+ import'./chunk-FLDBNTNY.js';export{a as QrCodeApi}from'./chunk-I222VSWK.js';export{g as WebhookHandler,a as isFlowDataExchangeRequest,b as isFlowErrorRequest,c as isFlowPingRequest}from'./chunk-4ZHGFSME.js';export{b as WhatsApp}from'./chunk-4LWNMCXG.js';export{a as isMetaError}from'./chunk-3MO3BTBC.js';export{a as TemplateApi}from'./chunk-R36L2XYO.js';import'./chunk-GT3XQN7Y.js';export{b as RegistrationApi}from'./chunk-O2OTHNWM.js';export{b as EncryptionApi}from'./chunk-7NQLQPLH.js';export{b as TwoStepVerificationApi}from'./chunk-UQPD6GIF.js';export{b as WabaApi}from'./chunk-5JGM556C.js';export{b as MessagesApi}from'./chunk-2NJVBJUN.js';import'./chunk-XPPDOFBN.js';export{b as BusinessProfileApi}from'./chunk-KFPOVYEJ.js';export{a as buildFieldsQueryString}from'./chunk-7GL74SXM.js';export{c as FlowApi}from'./chunk-LGLRGXCE.js';export{b as PhoneNumberApi}from'./chunk-GIQLIMOD.js';export{a as objectToQueryString}from'./chunk-BZ5QDXNR.js';export{b as BaseAPI,a as Logger}from'./chunk-VW3LGHTJ.js';export{q as AudioMediaTypesEnum,y as BusinessVerticalEnum,h as ButtonPositionEnum,g as ButtonTypesEnum,a as CategoryEnum,i as ComponentTypesEnum,k as ConversationTypesEnum,w as CurrencyCodesEnum,x as DataLocalizationRegionEnum,p as DocumentMediaTypesEnum,c as HttpMethodsEnum,o as ImageMediaTypesEnum,f as InteractiveTypesEnum,v as LanguagesEnum,d as MessageTypesEnum,e as ParametersTypesEnum,t as ReferralSourceTypesEnum,u as RequestCodeMethodsEnum,l as StatusEnum,n as StickerMediaTypesEnum,s as SystemChangeTypesEnum,b as TemplateStatusEnum,m as VideoMediaTypesEnum,j as WabaConfigEnum,r as WebhookTypesEnum}from'./chunk-QCFJGLDQ.js';import'./chunk-4C666HHU.js';//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "meta-cloud-api",
3
- "version": "0.2.36",
3
+ "version": "0.2.37",
4
4
  "description": "TypeScript wrapper for Meta's Cloud API",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,3 +0,0 @@
1
- import {a as a$1,b}from'./chunk-4LWNMCXG.js';import {a}from'./chunk-VW3LGHTJ.js';import*as l from'crypto';import l__default from'crypto';function M(s){return typeof s=="object"&&s!==null}function h(s){return typeof s=="string"}var P=["data_exchange","INIT","BACK"],T=["data_exchange","INIT"];function C(s){if(!("flow_token"in s&&h(s.flow_token)&&"action"in s))return false;let{action:e,version:r,screen:t,data:o}=s,a=r==="3.0",c=P.includes(e),d=typeof t>"u"||h(t)&&t!=="SUCCESS",u=e==="data_exchange"||M(o);return a&&c&&d&&u}function F(s){if(!("flow_token"in s&&h(s.flow_token)&&"action"in s))return false;let{action:e,screen:r,data:t}=s,o=T.includes(e),a=h(r),c=M(t)&&"error_key"in t&&h(t.error)&&"error_message"in t&&h(t.error_message);return o&&a&&c}function q(s){return "action"in s&&s.action==="ping"}var B="WEBHOOK_UTILS",p=new a(B,process.env.DEBUG==="true");function R(s,e){let r=s.query["hub.mode"],t=s.query["hub.verify_token"],o=s.query["hub.challenge"];return r!==void 0&&t!==void 0&&o!==void 0?r==="subscribe"&&t===e?(p.log("Webhook verified successfully"),{statusCode:200,body:o}):(p.log("Webhook verification failed"),{statusCode:403}):(p.log("Not a webhook verification request - missing required parameters"),{statusCode:400,body:{error:"Invalid webhook verification request"}})}async function E(s,e,r){let t=s.body,o=[];if(t.object!=="whatsapp_business_account"){let a="Received webhook for non-WhatsApp event";return p.log(a),{statusCode:404,body:{error:a}}}for(let a of t.entry)try{let c=a.changes;for(let d of c)d.field==="messages"&&await I(a.id,d.value,e,r);}catch(c){let d=`Error processing webhook: ${c}`;p.log(d),o.push(d);}return {statusCode:200,body:o.length>0?{errors:o}:void 0}}async function H(s,e,r,t){try{if(!N(s,e.WEBHOOK_VERIFICATION_TOKEN||""))return p.log("Invalid request signature"),{statusCode:401,body:{error:"Unauthorized"}};let o=JSON.parse(s.rawBody||"{}"),{decryptedBody:a}=O(o,e),c=t.get("*");if(!c)return p.log(`No handler registered for flow action: ${a.action}`),{statusCode:404,body:{error:"Handler not found"}};if(q(a))return {statusCode:200,body:{version:"3.0",data:{status:"active"}}};if(F(a))return p.log(`Flow error: ${JSON.stringify(a)}`),{statusCode:200,body:{}};if(C(a)){let d=await c(r,a);return {statusCode:200,body:x(d,Buffer.from(o.aes_key,"base64"),Buffer.from(o.initial_vector,"base64"))}}return p.log(`Unknown flow request type: ${JSON.stringify(a)}`),{statusCode:400,body:{error:"Unknown request type"}}}catch(o){return p.log(`Error handling flow request: ${o}`),{statusCode:500,body:{error:"Internal server error"}}}}async function I(s,e,r,t){let o=e.metadata,a=e.contacts,c=s,d=o?.display_phone_number||"",u=o?.phone_number_id||"",y=a?.[0]?.profile?.name||"";if(e.statuses&&e.statuses.length>0){let g=e.statuses;for(let n of g){let f={wabaId:c,id:n.id,from:n.recipient_id,timestamp:n.timestamp,type:"statuses",phoneNumberId:u,displayPhoneNumber:d,profileName:y,statuses:e.statuses[0],originalData:n};await w(t.messageHandlers.get("statuses"),r,f,"statuses");}return}if(e.messages&&e.messages.length>0){let g=e.messages;for(let n of g){let f=n.type,i={wabaId:c,id:n.id,from:n.from,timestamp:n.timestamp,type:n.type,phoneNumberId:u,displayPhoneNumber:d,profileName:y,originalData:n};switch(f){case "text":i.text=n.text;break;case "image":i.image=n.image;break;case "video":i.video=n.video;break;case "audio":i.audio=n.audio;break;case "document":i.document=n.document;break;case "sticker":i.sticker=n.sticker;break;case "location":i.location=n.location;break;case "contacts":i.contacts=n.contacts;break;case "interactive":i.interactive=n.interactive;break;case "button":i.button=n.button;break;case "order":i.order=n.order;break;case "system":i.system=n.system;break;case "reaction":i.reaction=n.reaction;break;default:p.log(`Unknown message type: ${f}`);break}await w(t.preProcessHandler,r,i,"pre-process"),await w(t.messageHandlers.get(f),r,i,f),await w(t.postProcessHandler,r,i,"post-process");}}}async function w(s,e,r,t){if(s)try{await s(e,r);}catch(o){p.log(`Error in ${t} handler: ${o}`);}}function N(s,e){let r=s.headers["x-hub-signature-256"];if(!r||!s.rawBody)return false;let o=`sha256=${l__default.createHmac("sha256",e).update(s.rawBody,"utf8").digest("hex")}`;return l__default.timingSafeEqual(Buffer.from(r),Buffer.from(o))}function O(s,e){let{encrypted_aes_key:r,encrypted_flow_data:t,initial_vector:o}=s;if(!r||!t||!o)throw new Error("Missing required encryption properties");let a=e.FLOW_API_PRIVATE_PEM.replace(/\\n/g,`
2
- `),c=e.FLOW_API_PASSPHRASE,d=l__default.createPrivateKey({key:a,passphrase:c}),u;try{u=l__default.privateDecrypt({key:d,padding:l__default.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:"sha256"},Buffer.from(r,"base64"));}catch{throw new Error("Failed to decrypt the request. Please verify your private key.")}let y=Buffer.from(t,"base64"),g=Buffer.from(o,"base64"),f=y.subarray(0,-16),i=y.subarray(-16),k=l__default.createDecipheriv("aes-128-gcm",u,g);k.setAuthTag(i);let S=Buffer.concat([k.update(f),k.final()]).toString("utf-8");return {decryptedBody:JSON.parse(S),aesKeyBuffer:u,initialVectorBuffer:g}}function x(s,e,r){let t=[];for(let o of Array.from(r.entries()))t.push(~o[1]);try{let o=l__default.createCipheriv("aes-128-gcm",e,Buffer.from(t));return Buffer.concat([o.update(JSON.stringify(s||{}),"utf-8"),o.final(),o.getAuthTag()]).toString("base64")}catch(o){throw p.log("Response encryption error:",o),new Error("Failed to encrypt response. Internal server error.")}}var V="WEBHOOK",m=new a(V,process.env.DEBUG==="true"),W=class{config;client;messageHandlers=new Map;preProcessHandler=void 0;postProcessHandler=void 0;flowHandlers=new Map;constructor(e){this.config=a$1(e),this.client=new b(e),m.log("WebhookHandler instantiated!");}handleVerification=e=>R(e,this.config.WEBHOOK_VERIFICATION_TOKEN||"");handleWebhook=async e=>E(e,this.client,{messageHandlers:this.messageHandlers,preProcessHandler:this.preProcessHandler,postProcessHandler:this.postProcessHandler});handleFlow=async e=>H(e,this.config,this.client,this.flowHandlers);onMessage(e,r){this.messageHandlers.set(e,r),m.log(`Registered message handler for ${e}`);}onMessagePreProcess(e){this.preProcessHandler=e,m.log("Registered pre-process handler");}onMessagePostProcess(e){this.postProcessHandler=e,m.log("Registered post-process handler");}onFlow(e,r){this.flowHandlers.set(e,r),m.log(`Registered flow handler for ${e}`);}};var oe=(s,e)=>l.createHmac("sha256",e).update(s,"utf-8").digest("hex");export{C as a,F as b,q as c,R as d,E as e,H as f,W as g,oe as h};//# sourceMappingURL=chunk-MTRF47KZ.js.map
3
- //# sourceMappingURL=chunk-MTRF47KZ.js.map