meta-cloud-api 0.2.9 → 0.2.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- "use strict";var He=Object.create;var J=Object.defineProperty;var Ge=Object.getOwnPropertyDescriptor;var Le=Object.getOwnPropertyNames;var ke=Object.getPrototypeOf,Ke=Object.prototype.hasOwnProperty;var Se=(r,t)=>{for(var s in t)J(r,s,{get:t[s],enumerable:!0})},Te=(r,t,s,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Le(t))!Ke.call(r,o)&&o!==s&&J(r,o,{get:()=>t[o],enumerable:!(i=Ge(t,o))||i.enumerable});return r};var Ie=(r,t,s)=>(s=r!=null?He(ke(r)):{},Te(t||!r||!r.__esModule?J(s,"default",{value:r,enumerable:!0}):s,r)),Je=r=>Te(J({},"__esModule",{value:!0}),r);var ht={};Se(ht,{AudioMediaTypesEnum:()=>re,BusinessVerticalEnum:()=>ge,ButtonPositionEnum:()=>z,ButtonTypesEnum:()=>Q,CategoryEnum:()=>j,ComponentTypesEnum:()=>E,ConversationTypesEnum:()=>C,CurrencyCodesEnum:()=>fe,DataLocalizationRegionEnum:()=>de,DocumentMediaTypesEnum:()=>oe,EventField:()=>Pe,FlowActionEnum:()=>me,FlowCategoryEnum:()=>Me,FlowStatusEnum:()=>Ne,FlowTypeEnum:()=>Re,HttpMethodsEnum:()=>w,ImageMediaTypesEnum:()=>ie,InteractiveTypesEnum:()=>Z,LanguagesEnum:()=>ce,MessageStatus:()=>ve,MessageTypesEnum:()=>W,ParametersTypesEnum:()=>Y,ReferralSourceTypesEnum:()=>pe,RequestCodeMethodsEnum:()=>le,StatusEnum:()=>ee,StickerMediaTypesEnum:()=>se,SystemChangeTypesEnum:()=>ne,TemplateStatusEnum:()=>X,VideoMediaTypesEnum:()=>te,WabaAccountReviewStatus:()=>Be,WabaAccountStatus:()=>Oe,WabaBusinessVerificationStatus:()=>De,WabaConfigEnum:()=>A,WabaHealthStatusCanSendMessage:()=>ye,WebhookHandler:()=>K,WebhookTypesEnum:()=>ae,default:()=>gt,generateXHub256Sig:()=>$e,importConfig:()=>H,isFlowDataExchangeRequest:()=>Ae,isFlowErrorRequest:()=>_e,isFlowPingRequest:()=>be,isMetaError:()=>$,objectToQueryString:()=>S});module.exports=Je(ht);var he={};Se(he,{AudioMediaTypesEnum:()=>re,BusinessVerticalEnum:()=>ge,ButtonPositionEnum:()=>z,ButtonTypesEnum:()=>Q,CategoryEnum:()=>j,ComponentTypesEnum:()=>E,ConversationTypesEnum:()=>C,CurrencyCodesEnum:()=>fe,DataLocalizationRegionEnum:()=>de,DocumentMediaTypesEnum:()=>oe,HttpMethodsEnum:()=>w,ImageMediaTypesEnum:()=>ie,InteractiveTypesEnum:()=>Z,LanguagesEnum:()=>ce,MessageTypesEnum:()=>W,ParametersTypesEnum:()=>Y,ReferralSourceTypesEnum:()=>pe,RequestCodeMethodsEnum:()=>le,StatusEnum:()=>ee,StickerMediaTypesEnum:()=>se,SystemChangeTypesEnum:()=>ne,TemplateStatusEnum:()=>X,VideoMediaTypesEnum:()=>te,WabaConfigEnum:()=>A,WebhookTypesEnum:()=>ae});var j=(i=>(i.Authentication="AUTHENTICATION",i.Marketing="MARKETING",i.Utility="UTILITY",i))(j||{}),X=(i=>(i.Approved="APPROVED",i.Pending="PENDING",i.Rejected="REJECTED",i))(X||{}),w=(o=>(o.Get="GET",o.Post="POST",o.Put="PUT",o.Delete="DELETE",o))(w||{}),W=(d=>(d.Audio="audio",d.Contacts="contacts",d.Document="document",d.Image="image",d.Interactive="interactive",d.Location="location",d.Reaction="reaction",d.Sticker="sticker",d.Template="template",d.Text="text",d.Video="video",d.Button="button",d.Order="order",d.System="system",d.Unknown="unknown",d["*"]="*",d))(W||{}),Y=(p=>(p.Currency="currency",p.DateTime="date_time",p.Document="document",p.Image="image",p.Text="text",p.Video="video",p.Payload="payload",p))(Y||{}),Z=(l=>(l.Button="button",l.List="list",l.Product="product",l.ProductList="product_list",l.CtaUrl="cta_url",l.LocationRequest="location_request_message",l.AddressMessage="address_message",l.Flow="flow",l))(Z||{}),Q=(s=>(s.QuickReply="quick_reply",s.URL="url",s))(Q||{}),z=(i=>(i[i.First=0]="First",i[i.Second=1]="Second",i[i.Third=2]="Third",i))(z||{}),E=(o=>(o.Header="HEADER",o.Body="BODY",o.Button="BUTTON",o.Footer="FOOTER",o))(E||{}),A=(d=>(d.AppId="M4D_APP_ID",d.Port="WA_PORT",d.AppSecret="M4D_APP_SECRET",d.PhoneNumberId="WA_PHONE_NUMBER_ID",d.BusinessAcctId="WA_BUSINESS_ACCOUNT_ID",d.APIVersion="CLOUD_API_VERSION",d.AccessToken="CLOUD_API_ACCESS_TOKEN",d.WebhookEndpoint="WEBHOOK_ENDPOINT",d.WebhookVerificationToken="WEBHOOK_VERIFICATION_TOKEN",d.ListenerPort="LISTENER_PORT",d.MaxRetriesAfterWait="MAX_RETRIES_AFTER_WAIT",d.RequestTimeout="REQUEST_TIMEOUT",d.Debug="DEBUG",d.PrivatePem="FLOW_API_PRIVATE_PEM",d.Passphrase="FLOW_API_PASSPHRASE",d))(A||{}),C=(i=>(i.BusinessInitiated="business_initiated",i.CustomerInitiated="customer_initiated",i.ReferralConversion="referral_conversion",i))(C||{}),ee=(i=>(i.Delivered="delivered",i.Read="read",i.Sent="sent",i))(ee||{}),te=(s=>(s.Mp4="video/mp4",s.Threegp="video/3gp",s))(te||{}),se=(t=>(t.Webp="image/webp",t))(se||{}),ie=(s=>(s.Jpeg="image/jpeg",s.Png="image/png",s))(ie||{}),oe=(l=>(l.Text="text/plain",l.Pdf="application/pdf",l.Ppt="application/vnd.ms-powerpoint",l.Word="application/msword",l.Excel="application/vnd.ms-excel",l.OpenDoc="application/vnd.openxmlformats-officedocument.wordprocessingml.document",l.OpenPres="application/vnd.openxmlformats-officedocument.presentationml.presentation",l.OpenSheet="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",l))(oe||{}),re=(n=>(n.Aac="audio/aac",n.Mp4="audio/mp4",n.Mpeg="audio/mpeg",n.Amr="audio/amr",n.Ogg="audio/ogg",n))(re||{}),ae=(R=>(R.Audio="audio",R.Button="button",R.Document="document",R.Text="text",R.Image="image",R.Interactive="interactive",R.Order="order",R.Sticker="sticker",R.System="system",R.Unknown="unknown",R.Video="video",R))(ae||{}),ne=(s=>(s.CustomerChangedNumber="customer_changed_number",s.CustomerIdentityChanged="customer_identity_changed",s))(ne||{}),pe=(s=>(s.Ad="ad",s.Post="post",s))(pe||{}),le=(s=>(s.Sms="SMS",s.Voice="VOICE",s))(le||{}),ce=(a=>(a.Afrikaans="af",a.Albanian="sq",a.Arabic="ar",a.Azerbaijani="az",a.Bengali="bn",a.Bulgarian="bg",a.Catalan="ca",a.Chinese_CHN="zh_CN",a.Chinese_HKG="zh_HK",a.Chinese_TAI="zh_TW",a.Croatian="hr",a.Czech="cs",a.Danish="da",a.Dutch="nl",a.English="en",a.English_UK="en_GB",a.English_US="en_US",a.Estonian="et",a.Filipino="fil",a.Finnish="fi",a.French="fr",a.Georgian="ka",a.German="de",a.Greek="el",a.Gujarati="gu",a.Hausa="ha",a.Hebrew="he",a.Hindi="hi",a.Hungarian="hu",a.Indonesian="id",a.Irish="ga",a.Italian="it",a.Japanese="ja",a.Kannada="kn",a.Kazakh="kk",a.Kinyarwanda="rw_RW",a.Korean="ko",a.Kyrgyz_Kyrgyzstan="ky_KG",a.Lao="lo",a.Latvian="lv",a.Lithuanian="lt",a.Macedonian="mk",a.Malay="ms",a.Malayalam="ml",a.Marathi="mr",a.Norwegian="nb",a.Persian="fa",a.Polish="pl",a.Portuguese_BR="pt_BR",a.Portuguese_POR="pt_PT",a.Punjabi="pa",a.Romanian="ro",a.Russian="ru",a.Serbian="sr",a.Slovak="sk",a.Slovenian="sl",a.Spanish="es",a.Spanish_ARG="es_AR",a.Spanish_SPA="es_ES",a.Spanish_MEX="es_MX",a.Swahili="sw",a.Swedish="sv",a.Tamil="ta",a.Telugu="te",a.Thai="th",a.Turkish="tr",a.Ukrainian="uk",a.Urdu="ur",a.Uzbek="uz",a.Vietnamese="vi",a.Zulu="zu",a))(ce||{}),fe=(e=>(e.AFN="AFN",e.EUR="EUR",e.ALL="ALL",e.DZD="DZD",e.USD="USD",e.AOA="AOA",e.XCD="XCD",e.ARS="ARS",e.AMD="AMD",e.AWG="AWG",e.AUD="AUD",e.AZN="AZN",e.BSD="BSD",e.BHD="BHD",e.BDT="BDT",e.BBD="BBD",e.BYN="BYN",e.BZD="BZD",e.XOF="XOF",e.BMD="BMD",e.INR="INR",e.BTN="BTN",e.BOB="BOB",e.BOV="BOV",e.BAM="BAM",e.BWP="BWP",e.NOK="NOK",e.BRL="BRL",e.BND="BND",e.BGN="BGN",e.BIF="BIF",e.CVE="CVE",e.KHR="KHR",e.XAF="XAF",e.CAD="CAD",e.KYD="KYD",e.CLP="CLP",e.CLF="CLF",e.CNY="CNY",e.COP="COP",e.COU="COU",e.KMF="KMF",e.CDF="CDF",e.NZD="NZD",e.CRC="CRC",e.HRK="HRK",e.CUP="CUP",e.CUC="CUC",e.ANG="ANG",e.CZK="CZK",e.DKK="DKK",e.DJF="DJF",e.DOP="DOP",e.EGP="EGP",e.SVC="SVC",e.ERN="ERN",e.SZL="SZL",e.ETB="ETB",e.FKP="FKP",e.FJD="FJD",e.XPF="XPF",e.GMD="GMD",e.GEL="GEL",e.GHS="GHS",e.GIP="GIP",e.GTQ="GTQ",e.GBP="GBP",e.GNF="GNF",e.GYD="GYD",e.HTG="HTG",e.HNL="HNL",e.HKD="HKD",e.HUF="HUF",e.ISK="ISK",e.IDR="IDR",e.XDR="XDR",e.IRR="IRR",e.IQD="IQD",e.ILS="ILS",e.JMD="JMD",e.JPY="JPY",e.JOD="JOD",e.KZT="KZT",e.KES="KES",e.KPW="KPW",e.KRW="KRW",e.KWD="KWD",e.KGS="KGS",e.LAK="LAK",e.LBP="LBP",e.LSL="LSL",e.ZAR="ZAR",e.LRD="LRD",e.LYD="LYD",e.CHF="CHF",e.MOP="MOP",e.MKD="MKD",e.MGA="MGA",e.MWK="MWK",e.MYR="MYR",e.MVR="MVR",e.MRU="MRU",e.MUR="MUR",e.XUA="XUA",e.MXN="MXN",e.MXV="MXV",e.MDL="MDL",e.MNT="MNT",e.MAD="MAD",e.MZN="MZN",e.MMK="MMK",e.NAD="NAD",e.NPR="NPR",e.NIO="NIO",e.NGN="NGN",e.OMR="OMR",e.PKR="PKR",e.PAB="PAB",e.PGK="PGK",e.PYG="PYG",e.PEN="PEN",e.PHP="PHP",e.PLN="PLN",e.QAR="QAR",e.RON="RON",e.RUB="RUB",e.RWF="RWF",e.SHP="SHP",e.WST="WST",e.STN="STN",e.SAR="SAR",e.RSD="RSD",e.SCR="SCR",e.SLL="SLL",e.SGD="SGD",e.XSU="XSU",e.SBD="SBD",e.SOS="SOS",e.SSP="SSP",e.LKR="LKR",e.SDG="SDG",e.SRD="SRD",e.SEK="SEK",e.CHE="CHE",e.CHW="CHW",e.SYP="SYP",e.TWD="TWD",e.TJS="TJS",e.TZS="TZS",e.THB="THB",e.TOP="TOP",e.TTD="TTD",e.TND="TND",e.TRY="TRY",e.TMT="TMT",e.UGX="UGX",e.UAH="UAH",e.AED="AED",e.USN="USN",e.UYU="UYU",e.UYI="UYI",e.UYW="UYW",e.UZS="UZS",e.VUV="VUV",e.VES="VES",e.VND="VND",e.YER="YER",e.ZMW="ZMW",e.ZWL="ZWL",e.XBA="XBA",e.XBB="XBB",e.XBC="XBC",e.XBD="XBD",e.XTS="XTS",e.XXX="XXX",e.XAU="XAU",e.XPD="XPD",e.XPT="XPT",e.XAG="XAG",e.AFA="AFA",e.FIM="FIM",e.ALK="ALK",e.ADP="ADP",e.ESP="ESP",e.FRF="FRF",e.AOK="AOK",e.AON="AON",e.AOR="AOR",e.ARA="ARA",e.ARP="ARP",e.ARY="ARY",e.RUR="RUR",e.ATS="ATS",e.AYM="AYM",e.AZM="AZM",e.BYB="BYB",e.BYR="BYR",e.BEC="BEC",e.BEF="BEF",e.BEL="BEL",e.BOP="BOP",e.BAD="BAD",e.BRB="BRB",e.BRC="BRC",e.BRE="BRE",e.BRN="BRN",e.BRR="BRR",e.BGJ="BGJ",e.BGK="BGK",e.BGL="BGL",e.BUK="BUK",e.HRD="HRD",e.CYP="CYP",e.CSJ="CSJ",e.CSK="CSK",e.ECS="ECS",e.ECV="ECV",e.GQE="GQE",e.EEK="EEK",e.XEU="XEU",e.GEK="GEK",e.DDM="DDM",e.DEM="DEM",e.GHC="GHC",e.GHP="GHP",e.GRD="GRD",e.GNE="GNE",e.GNS="GNS",e.GWE="GWE",e.GWP="GWP",e.ITL="ITL",e.ISJ="ISJ",e.IEP="IEP",e.ILP="ILP",e.ILR="ILR",e.LAJ="LAJ",e.LVL="LVL",e.LVR="LVR",e.LSM="LSM",e.ZAL="ZAL",e.LTL="LTL",e.LTT="LTT",e.LUC="LUC",e.LUF="LUF",e.LUL="LUL",e.MGF="MGF",e.MVQ="MVQ",e.MLF="MLF",e.MTL="MTL",e.MTP="MTP",e.MRO="MRO",e.MXP="MXP",e.MZE="MZE",e.MZM="MZM",e.NLG="NLG",e.NIC="NIC",e.PEH="PEH",e.PEI="PEI",e.PES="PES",e.PLZ="PLZ",e.PTE="PTE",e.ROK="ROK",e.ROL="ROL",e.STD="STD",e.CSD="CSD",e.SKK="SKK",e.SIT="SIT",e.RHD="RHD",e.ESA="ESA",e.ESB="ESB",e.SDD="SDD",e.SDP="SDP",e.SRG="SRG",e.CHC="CHC",e.TJR="TJR",e.TPE="TPE",e.TRL="TRL",e.TMM="TMM",e.UGS="UGS",e.UGW="UGW",e.UAK="UAK",e.SUR="SUR",e.USS="USS",e.UYN="UYN",e.UYP="UYP",e.VEB="VEB",e.VEF="VEF",e.VNC="VNC",e.YDD="YDD",e.YUD="YUD",e.YUM="YUM",e.YUN="YUN",e.ZRN="ZRN",e.ZRZ="ZRZ",e.ZMK="ZMK",e.ZWC="ZWC",e.ZWD="ZWD",e.ZWN="ZWN",e.ZWR="ZWR",e.XFO="XFO",e.XRE="XRE",e.XFU="XFU",e))(fe||{}),de=(P=>(P.AU="AU",P.ID="ID",P.IN="IN",P.JP="JP",P.SG="SG",P.KR="KR",P.DE="DE",P.CH="CH",P.GB="GB",P.BR="BR",P.BH="BH",P.ZA="ZA",P.AE="AE",P.CA="CA",P))(de||{}),ge=(m=>(m.ALCOHOL="ALCOHOL",m.APPAREL="APPAREL",m.AUTO="AUTO",m.BEAUTY="BEAUTY",m.EDU="EDU",m.ENTERTAIN="ENTERTAIN",m.EVENT_PLAN="EVENT_PLAN",m.FINANCE="FINANCE",m.GOVT="GOVT",m.GROCERY="GROCERY",m.HEALTH="HEALTH",m.HOTEL="HOTEL",m.NONPROFIT="NONPROFIT",m.ONLINE_GAMBLING="ONLINE_GAMBLING",m.OTC_DRUGS="OTC_DRUGS",m.OTHER="OTHER",m.PHYSICAL_GAMBLING="PHYSICAL_GAMBLING",m.PROF_SERVICES="PROF_SERVICES",m.RESTAURANT="RESTAURANT",m.RETAIL="RETAIL",m.TRAVEL="TRAVEL",m))(ge||{});var Ne=(n=>(n.Draft="DRAFT",n.Published="PUBLISHED",n.Throttled="THROTTLED",n.Blocked="BLOCKED",n.Deprecated="DEPRECATED",n))(Ne||{}),Me=(l=>(l.SignUp="SIGN_UP",l.SignIn="SIGN_IN",l.AppointmentBooking="APPOINTMENT_BOOKING",l.LeadGeneration="LEAD_GENERATION",l.ContactUs="CONTACT_US",l.CustomerSupport="CUSTOMER_SUPPORT",l.Survey="SURVEY",l.Other="OTHER",l))(Me||{}),me=(i=>(i.INIT="INIT",i.BACK="BACK",i.DATA_EXCHANGE="data_exchange",i))(me||{}),Re=(o=>(o.Ping="ping",o.Change="data_exchange",o.Error="error",o.All="*",o))(Re||{});var Be=(o=>(o.Approved="APPROVED",o.Active="ACTIVE",o.Inactive="INACTIVE",o.Disabled="DISABLED",o))(Be||{}),ye=(i=>(i.Blocked="BLOCKED",i.Limited="LIMITED",i.Available="AVAILABLE",i))(ye||{}),Oe=(o=>(o.Approved="APPROVED",o.Active="ACTIVE",o.Inactive="INACTIVE",o.Disabled="DISABLED",o))(Oe||{}),De=(o=>(o.Verified="verified",o.PendingSubmission="pending_submission",o.Unverified="unverified",o.Rejected="rejected",o))(De||{});var ve=(i=>(i.DELIVERED="delivered",i.READ="read",i.SENT="sent",i))(ve||{}),Pe=(f=>(f.MESSAGES="messages",f.STATUSES="statuses",f.MESSAGE_TEMPLATE_STATUS_UPDATE="message_template_status_update",f.PHONE_NUMBER_QUALITY_UPDATE="phone_number_quality_update",f.PHONE_NUMBER_NAME_UPDATE="phone_number_name_update",f.UNKNOWN="unknown",f))(Pe||{});var T=Ie(require("crypto"));var xe=Ie(require("crypto")),$e=(r,t)=>xe.createHmac("sha256",t).update(r,"utf-8").digest("hex");var b=class{name;debug;constructor(t,s=!1){this.name=t,this.debug=s}log(...t){if(this.debug){let s=`[ ${Date.now()} ]`;this.name&&(s+=` - ${this.name}`),console.log.apply(console,[s,": ",...t])}}error(...t){let s=`[ ${Date.now()} ] - ERROR`;this.name&&(s+=` - ${this.name}`),console.error.apply(console,[s,": ",...t])}warn(...t){let s=`[ ${Date.now()} ] - WARN`;this.name&&(s+=` - ${this.name}`),console.warn.apply(console,[s,": ",...t])}info(...t){let s=`[ ${Date.now()} ] - INFO`;this.name&&(s+=` - ${this.name}`),console.info.apply(console,[s,": ",...t])}};var Ve="UTILS",je=!1,Fe=new b(Ve,process.env.DEBUG==="true"||je),Xe=3e3,Ye=30,Ze=2e4,Qe=r=>{if(!process.env.CLOUD_API_ACCESS_TOKEN&&!r?.accessToken)throw Fe.log("Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined."),new Error("Missing WhatsApp access token.")},H=r=>{Qe(r);let t={M4D_APP_ID:r?.appId||process.env.M4D_APP_ID||"",M4D_APP_SECRET:r?.appSecret||process.env.M4D_APP_SECRET||"",WA_PHONE_NUMBER_ID:r?.phoneNumberId||Number(process.env.WA_PHONE_NUMBER_ID),WA_BUSINESS_ACCOUNT_ID:r?.businessAcctId||process.env.WA_BUSINESS_ACCOUNT_ID||"",CLOUD_API_VERSION:r?.apiVersion||process.env.CLOUD_API_VERSION||"",CLOUD_API_ACCESS_TOKEN:r?.accessToken||process.env.CLOUD_API_ACCESS_TOKEN||"",WEBHOOK_ENDPOINT:r?.webhookEndpoint||process.env.WEBHOOK_ENDPOINT||"",WEBHOOK_VERIFICATION_TOKEN:r?.webhookVerificationToken||process.env.WEBHOOK_VERIFICATION_TOKEN||"",LISTENER_PORT:r?.listenerPort||parseInt(process.env.LISTENER_PORT||"")||Xe,MAX_RETRIES_AFTER_WAIT:r?.maxRetriesAfterWait||parseInt(process.env.MAX_RETRIES_AFTER_WAIT||"")||Ye,REQUEST_TIMEOUT:r?.requestTimeout||parseInt(process.env.REQUEST_TIMEOUT||"")||Ze,DEBUG:r?.debug||process.env.DEBUG==="true",FLOW_API_PRIVATE_PEM:r?.privatePem||process.env.FLOW_API_PRIVATE_PEM||"",FLOW_API_PASSPHRASE:r?.passphrase||process.env.FLOW_API_PASSPHRASE||""};return Fe.log(`Configuration loaded for App Id ${t.M4D_APP_ID}`),t};function $(r){return r!=null&&typeof r=="object"&&"error"in r&&typeof r.error=="object"&&r.error!=null&&"message"in r.error&&typeof r.error.message=="string"&&"type"in r.error&&typeof r.error.type=="string"&&"code"in r.error&&typeof r.error.code=="number"&&"fbtrace_id"in r.error&&typeof r.error.fbtrace_id=="string"&&(!("error_data"in r.error)||typeof r.error.error_data=="object"&&r.error.error_data!=null&&"messaging_product"in r.error.error_data&&r.error.error_data.messaging_product==="whatsapp"&&"details"in r.error.error_data&&typeof r.error.error_data.details=="string")&&(!("error_subcode"in r.error)||typeof r.error.error_subcode=="number")}var S=r=>{if(!r||Object.keys(r).length===0)return"";let t=new URLSearchParams;for(let[i,o]of Object.entries(r))o!==void 0&&t.append(i,String(o));let s=t.toString();return s?`?${s}`:""};function be(r){return"action"in r&&r.action==="ping"}function Ae(r){return"action"in r&&(r.action==="data_exchange"||r.action==="INIT"||r.action==="BACK")}function _e(r){return"action"in r&&r.action!=="BACK"&&"data"in r&&typeof r.data=="object"&&r.data!==null&&"error_message"in r.data&&r.data.error_message!==void 0}var ze="BaseAPI",Ee=!1,Ce=new b(ze,process.env.DEBUG==="true"||Ee),h=class{config;client;constructor(t,s){this.config=t,this.client=s,Ce.log("Initialized with HTTPSClient")}sendJson(t,s,i,o){return this.client.getJson(t,s,i,o)}sendFormData(t,s,i,o){return this.client.sendFormData(t,s,i,o)}sendUrlEncodedForm(t,s,i,o){return this.client.sendUrlEncodedForm(t,s,i,o)}};function V(r){if(!r)return"";let t="";return Array.isArray(r)?t=r.join(","):t=Object.entries(r).filter(([s,i])=>i).map(([s])=>s).join(","),t?`?fields=${t}`:""}var N=class extends h{endpoint="whatsapp_business_profile";constructor(t,s){super(t,s)}async getBusinessProfile(t){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}${V(t)}`,this.config.REQUEST_TIMEOUT,null)}async updateBusinessProfile(t){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async createUploadSession(t,s,i){let o=S({file_length:t,file_type:s,file_name:i});return this.sendJson("POST",`app/uploads/${o}`,this.config.REQUEST_TIMEOUT,null)}async uploadMedia(t,s){return this.sendJson("POST",`${t}`,this.config.REQUEST_TIMEOUT,s)}async getUploadHandle(t){return this.sendJson("GET",`${t}`,this.config.REQUEST_TIMEOUT,null)}};var M=class extends h{endpoint="whatsapp_business_encryption";constructor(t,s){super(t,s)}async getEncryptionPublicKey(){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async setEncryptionPublicKey(t){let s=new FormData;return s.append("business_public_key",t),this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,s)}};var et="FlowAPI",tt=!1,ue=new b(et,process.env.DEBUG==="true"||tt),B=class extends h{constructor(t,s){super(t,s),ue.log("FlowAPI initialized")}async listFlows(t){return this.sendJson("GET",`/${t}/flows`,this.config.REQUEST_TIMEOUT,null)}async createFlow(t,s){let i={name:s.name,categories:s.categories,...s.endpoint_uri&&{endpoint_uri:s.endpoint_uri},...s.clone_flow_id&&{clone_flow_id:s.clone_flow_id},...s.flow_json&&{flow_json:s.flow_json},...s.publish!==void 0&&{publish:s.publish}};return this.sendJson("POST",`/${t}/flows`,this.config.REQUEST_TIMEOUT,JSON.stringify(i))}async getFlow(t,s,i){let o=new URLSearchParams;s&&o.append("fields",s),i&&o.append("date_format",i);let n=o.toString()?`?${o.toString()}`:"";return this.sendJson("GET",`/${t}${n}`,this.config.REQUEST_TIMEOUT,null)}async getFlowPreview(t,s=!1){let i=`preview.invalidate(${s})`;return this.getFlow(t,i)}async updateFlowMetadata(t,s){let i={...s.name&&{name:s.name},...s.categories&&{categories:s.categories},...s.endpoint_uri&&{endpoint_uri:s.endpoint_uri},...s.application_id&&{application_id:s.application_id}};return this.sendJson("POST",`/${t}`,this.config.REQUEST_TIMEOUT,JSON.stringify(i))}async deleteFlow(t){return this.sendJson("DELETE",`/${t}`,this.config.REQUEST_TIMEOUT,null)}async listAssets(t){return this.sendJson("GET",`/${t}/assets`,this.config.REQUEST_TIMEOUT,null)}async updateFlowJson(t,s){let i=new FormData,o;if(s.file instanceof Buffer)o=new globalThis.Blob([s.file]),i.append("file",o);else if(typeof s.file=="object"&&!(s.file instanceof Blob))try{o=new globalThis.Blob([JSON.stringify(s.file,null,2)],{type:"application/json"}),i.append("file",o)}catch{throw new Error("Failed to stringify JSON object for Flow JSON update.")}else if(s.file instanceof Blob)o=s.file,i.append("file",o);else throw new Error("Invalid file type provided for Flow JSON update. Must be a Buffer, JSON object, or Blob.");return i.append("asset_type","FLOW_JSON"),i.append("name",s.name||"flow.json"),this.sendFormData("POST",`/${t}/assets`,this.config.REQUEST_TIMEOUT,i)}async validateFlowJson(t,s){try{let i=await this.updateFlowJson(t,{file:s}),o=!i.validation_errors||i.validation_errors.length===0;return{...i,valid:o}}catch(i){throw ue.error("Error during Flow JSON validation attempt:",i),i}}async publishFlow(t){return this.sendJson("POST",`/${t}/publish`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async deprecateFlow(t){return this.sendJson("POST",`/${t}/deprecate`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async migrateFlows(t,s){let i={source_waba_id:s.source_waba_id,...s.source_flow_names&&{source_flow_names:s.source_flow_names}};return this.sendJson("POST",`/${t}/migrate_flows`,this.config.REQUEST_TIMEOUT,JSON.stringify(i))}};var y=class extends h{endpoint="media";constructor(t,s){super(t,s)}async getMediaById(t){return this.sendJson("GET",`${t}`,this.config.REQUEST_TIMEOUT,null)}async uploadMedia(t,s="whatsapp"){let i=new FormData;return i.append("file",t),i.append("messaging_product",s),i.append("type",t.type),this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,i)}async deleteMedia(t){return this.sendJson("DELETE",`${t}`,this.config.REQUEST_TIMEOUT,null)}async downloadMedia(t){return this.sendJson("GET",t,this.config.REQUEST_TIMEOUT,null)}};var O=class extends h{commonMethod="POST";commonEndpoint="messages";constructor(t,s){super(t,s)}bodyBuilder(t,s,i,o){let n={messaging_product:"whatsapp",recipient_type:"individual",to:i,type:t,[t]:s};return o&&(n.context={message_id:o}),n}send(t){return this.sendJson(this.commonMethod,`${this.config.WA_PHONE_NUMBER_ID}/${this.commonEndpoint}`,this.config.REQUEST_TIMEOUT,t)}async audio(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("audio",s,i,o)))}async contacts(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("contacts",s,i,o)))}async document(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("document",s,i,o)))}async image(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("image",s,i,o)))}async interactive(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("interactive",s,i,o)))}async location(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("location",s,i,o)))}async sticker(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("sticker",s,i,o)))}async template(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("template",s,i,o)))}async text(t){let{body:s,previewUrl:i,to:o,replyMessageId:n}=t,f;return typeof s=="string"?f={body:s,preview_url:i}:f=s,this.send(JSON.stringify(this.bodyBuilder("text",f,o,n)))}async video(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("video",s,i,o)))}async status(t){let{status:s,messageId:i,typingIndicator:o}=t,n={messaging_product:"whatsapp",status:s,message_id:i,...o&&{typing_indicator:o}};return this.send(JSON.stringify(n))}async markAsRead(t){return this.status({status:"read",messageId:t.messageId})}async showTypingIndicator(t){return this.status({status:"read",messageId:t.messageId,typingIndicator:{type:"text"}})}async interactiveList(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("interactive",s,i,o)))}async interactiveCtaUrl(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("interactive",s,i,o)))}async interactiveLocationRequest(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("interactive",s,i,o)))}async interactiveAddressMessage(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("interactive",s,i,o)))}async interactiveReplyButtons(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("interactive",s,i,o)))}async interactiveFlow(t){let{body:s,to:i,replyMessageId:o}=t;return s.action.parameters.flow_message_version===void 0&&(s.action.parameters.flow_message_version="3"),s.action.parameters.mode===void 0&&(s.action.parameters.mode="published"),s.action.parameters.flow_action===void 0&&(s.action.parameters.flow_action="navigate"),s.action.parameters.flow_action==="navigate"?s.action.parameters.flow_action_payload?.screen===void 0&&(s.action.parameters.flow_action_payload={...s.action.parameters.flow_action_payload,screen:"INIT"}):s.action.parameters.flow_action==="data_exchange"&&delete s.action.parameters.flow_action_payload,this.send(JSON.stringify(this.bodyBuilder("interactive",s,i,o)))}async reaction(t){let{messageId:s,emoji:i,to:o}=t,n={messaging_product:"whatsapp",recipient_type:"individual",to:o,type:"reaction",reaction:{message_id:s,emoji:i}};return this.send(JSON.stringify(n))}};var D=class extends h{endpoint="phone_numbers";constructor(t,s){super(t,s)}async getPhoneNumberById(t){let s=t?S({fields:t}):"";return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}${s}`,this.config.REQUEST_TIMEOUT,null)}async getPhoneNumbers(){return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async requestVerificationCode(t){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/request_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async verifyCode(t){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/verify_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}};var v=class extends h{endpoint="message_qrdls";constructor(t,s){super(t,s)}async createQrCode(t){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getQrCodes(){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async getQrCode(t){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}/${t}`,this.config.REQUEST_TIMEOUT,null)}async updateQrCode(t){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async deleteQrCode(t){return this.sendJson("DELETE",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}/${t}`,this.config.REQUEST_TIMEOUT,null)}};var x=class extends h{constructor(t,s){super(t,s)}async register(t,s){let i={messaging_product:"whatsapp",pin:t,...s&&{data_localization_region:s}};return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/register`,this.config.REQUEST_TIMEOUT,JSON.stringify(i))}async deregister(){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/deregister`,this.config.REQUEST_TIMEOUT,null)}};var F=class extends h{endpoint="message_templates";constructor(t,s){super(t,s)}async getTemplate(t){return this.sendJson("GET",`${t}`,this.config.REQUEST_TIMEOUT,null)}async updateTemplate(t,s){return this.sendJson("POST",`${t}`,this.config.REQUEST_TIMEOUT,JSON.stringify(s))}async getTemplates(t){return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${S(t)}`,this.config.REQUEST_TIMEOUT,null)}async createTemplate(t){return this.sendJson("POST",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async deleteTemplate(t){return this.sendJson("DELETE",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${S(t)}`,this.config.REQUEST_TIMEOUT,null)}};var u=class extends h{constructor(t,s){super(t,s)}async setTwoStepVerificationCode(t){let s={pin:t};return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}`,this.config.REQUEST_TIMEOUT,JSON.stringify(s))}};var q=class extends h{constructor(t,s){super(t,s)}async getWabaAccount(t){let s=V(t)?.replace(/,/g,"%2C");return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}${s}`,this.config.REQUEST_TIMEOUT,null)}async getAllWabaSubscriptions(){return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,null)}async updateWabaSubscription({override_callback_uri:t,verify_token:s}){let i={override_callback_uri:t,verify_token:s};return this.sendJson("POST",`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,JSON.stringify(i))}async unsubscribeFromWaba(){return this.sendJson("DELETE",`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,null)}};var qe=require("https");var st="HttpsClient",it=!1,ot=new b(st,process.env.DEBUG==="true"||it),G=class{agent;constructor(){this.agent=new qe.Agent({keepAlive:!0})}clearSockets(){return this.agent.destroy(),!0}async sendRequest(t,s,i,o,n,f){let p=`https://${t}/${s}`,l=new AbortController,c=setTimeout(()=>l.abort(),n);try{let g=await fetch(p,{method:i,headers:o,body:f,signal:l.signal});return ot.log(`${i} : ${p} - ${JSON.stringify(g)}`),clearTimeout(c),new we(g)}catch(g){throw g}}},we=class{res;respStatusCode;respHeaders;constructor(t){this.res=t,this.respStatusCode=t.status,this.respHeaders=Object.fromEntries(t.headers.entries())}statusCode(){return this.respStatusCode}headers(){return this.respHeaders}rawResponse(){return this.res}async json(){try{return await this.res.json()}catch(t){throw new Error("Failed to parse response body to JSON: "+t.message)}}};var rt="REQUESTER",at=!1,nt=new b(rt,process.env.DEBUG==="true"||at),L=class{client;accessToken;phoneNumberId;businessAcctId;apiVersion;userAgent;host;protocol="https:";constructor(t,s,i,o,n){this.client=new G,this.host="graph.facebook.com",this.apiVersion=t||"22",this.phoneNumberId=s,this.accessToken=i,this.businessAcctId=o,this.userAgent=n}buildHeader(t,s){let i={Authorization:`Bearer ${this.accessToken}`,"User-Agent":this.userAgent};return t!=="multipart/form-data"&&(i["Content-Type"]=t),s&&Object.assign(i,s),i}buildCAPIPath(t){return`v${this.apiVersion}.0/${t}`}async sendRequest(t,s,i,o,n="application/json",f){let p=n;o instanceof FormData?p="multipart/form-data":typeof o=="string"&&o.startsWith("<?xml")&&(p="application/xml");let l=`${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(s)}`;nt.log(`${t} : ${l} (${p})`);try{let c=await this.client.sendRequest(this.host,this.buildCAPIPath(s),t,this.buildHeader(p,f),i,t==="POST"||t==="PUT"?o:void 0);if(!c.rawResponse().ok){let g=await c.json();throw $(g)?g:{name:"MetaError",message:"Unknown error occurred",error:{message:g.message||"Unknown error occurred",type:"UnknownError",code:c.statusCode(),fbtrace_id:""}}}return c}catch(c){throw $(c)?c:{name:"MetaError",message:c instanceof Error?c.message:"Network error occurred",error:{message:c instanceof Error?c.message:"Network error occurred",type:"NetworkError",code:500,fbtrace_id:""}}}}async getJson(t,s,i,o,n){return await(await this.sendRequest(t,s,i,o,"application/json",n)).json()}async sendFormData(t,s,i,o,n){return await(await this.sendRequest(t,s,i,o,"multipart/form-data",n)).json()}async sendUrlEncodedForm(t,s,i,o,n){let f=new URLSearchParams(o).toString();return await(await this.sendRequest(t,s,i,f,"application/x-www-form-urlencoded",n)).json()}};var pt="WHATSAPP",lt=!1,k=new b(pt,process.env.DEBUG==="true"||lt),ct="WA_SDK",I=class{config;requester;messages;templates;phoneNumber;qrCode;encryption;twoStepVerification;registration;media;waba;flow;businessProfile;static Enums=he;constructor(t){this.config=H(t),this.requester=new L(this.config.CLOUD_API_VERSION,this.config.WA_PHONE_NUMBER_ID,this.config.CLOUD_API_ACCESS_TOKEN,this.config.WA_BUSINESS_ACCOUNT_ID,this.userAgent()),this.messages=new O(this.config,this.requester),this.templates=new F(this.config,this.requester),this.phoneNumber=new D(this.config,this.requester),this.qrCode=new v(this.config,this.requester),this.encryption=new M(this.config,this.requester),this.twoStepVerification=new u(this.config,this.requester),this.registration=new x(this.config,this.requester),this.media=new y(this.config,this.requester),this.waba=new q(this.config,this.requester),this.flow=new B(this.config,this.requester),this.businessProfile=new N(this.config,this.requester),k.log("WhatsApp Node.js SDK instantiated!")}userAgent(){return`${ct}/0.0.1 (Node.js ${process.version})`}updateTimeout(t){return this.config.REQUEST_TIMEOUT=t,k.log(`Updated request timeout to ${t}ms`),!0}updatePhoneNumberId(t){return this.config.WA_PHONE_NUMBER_ID=t,k.log(`Updated sender phone number id to ${t}`),!0}updateAccessToken(t){return this.config.CLOUD_API_ACCESS_TOKEN=t,k.log("Updated access token"),!0}updateWabaId(t){return this.config.WA_BUSINESS_ACCOUNT_ID=t,k.log(`Updated business account id to ${t}`),!0}};var ft="WEBHOOK",dt=!1,_=new b(ft,process.env.DEBUG==="true"||dt),K=class{config;client;messageHandlers=new Map;eventHandlers=new Map;preProcessHandler=null;postProcessHandler=null;flowHandlers=new Map;constructor(t){let s=H(t);this.config=s,this.client=new I(t),_.log("WebhookHandler instantiated!")}handleVerificationRequest(t,s){let i=t.query["hub.mode"],o=t.query["hub.verify_token"],n=t.query["hub.challenge"];i==="subscribe"&&o===this.config.WEBHOOK_VERIFICATION_TOKEN?(_.log("Webhook verified successfully"),s.status(200).send(n)):(_.log("Webhook verification failed"),s.status(403).end())}async handleWebhookRequest(t,s){let i=t.body;if(i.object!=="whatsapp_business_account"){_.log("Received webhook for non-WhatsApp event"),s.status(404).end();return}for(let o of i.entry)try{let n=o.changes;for(let f of n)f.field==="messages"?await this.processMessages(f.value):await this.processEvent(f.field,f.value)}catch(n){_.log(`Error processing webhook: ${n}`)}s.status(200).end()}handleRequest(t,s){if(t.method==="GET")return this.handleVerificationRequest(t,s);if(t.method==="POST")return this.handleWebhookRequest(t,s);s.status(405).end()}async processMessages(t){let s=t.metadata,i=s.display_phone_number,o=s.phone_number_id,n=t.contacts[0].profile.name,f=t.messages;if(f&&f.length>0)for(let p of f){let l=p.type,c={id:p.id,from:p.from,timestamp:p.timestamp,type:p.type,phoneNumberId:o,displayPhoneNumber:i,profileName:n,originalData:p};switch(p.type){case"text":c.text=p.text;break;case"image":c.image=p.image;break;case"video":c.video=p.video;break;case"audio":c.audio=p.audio;break;case"document":c.document=p.document;break;case"sticker":c.sticker=p.sticker;break;case"location":c.location=p.location;break;case"contacts":c.contacts=p.contacts;break;case"interactive":c.interactive=p.interactive;break;case"button":c.button=p.button;break;case"order":c.order=p.order;break;case"system":c.system=p.system;break;default:break}if(p.context&&(c.context=p.context),p.errors&&(c.errors=p.errors),this.preProcessHandler&&await Promise.resolve(this.preProcessHandler(this.client,c)),this.messageHandlers.has(l)){let g=this.messageHandlers.get(l);g&&await Promise.resolve(g(this.client,c))}if(this.messageHandlers.has("*")){let g=this.messageHandlers.get("*");g&&await Promise.resolve(g(this.client,c))}this.postProcessHandler&&await Promise.resolve(this.postProcessHandler(this.client,c))}t.statuses&&t.statuses.length>0&&await this.processEvent("statuses",t)}async processEvent(t,s){let i={field:t,value:s};if(this.eventHandlers.has(t)){let o=this.eventHandlers.get(t);o&&await Promise.resolve(o(i))}if(this.eventHandlers.has("*")){let o=this.eventHandlers.get("*");o&&await Promise.resolve(o(i))}}onMessage(t,s){this.messageHandlers.set(t,s),_.log(`Registered handler for message type: ${t}`)}onEvent(t,s){this.eventHandlers.set(t,s),_.log(`Registered handler for event field: ${t}`)}onMessagePreProcess(t){this.preProcessHandler=t,_.log("Registered pre-processing handler for all messages")}onMessagePostProcess(t){this.postProcessHandler=t,_.log("Registered post-processing handler for all messages")}async handleFlowRequest(t,s){if(!this.isRequestSignatureValid(t)){s.status(403).end();return}let i;try{i=this.decryptRequest(t.body)}catch(g){if(_.error(g),g instanceof Error){s.status(421).send(g.message);return}s.status(500).send("internal server error, please check with logs");return}let{decryptedBody:o,aesKeyBuffer:n,initialVectorBuffer:f}=i,p;be(o)?p="ping":Ae(o)?p="data_exchange":_e(o)&&(p="error");let l=o;if(p&&this.flowHandlers.has(p)){let g=this.flowHandlers.get(p);if(g){let R=await Promise.resolve(g(this.client,l)),U=this.encryptResponse(R,n,f);s.status(200).send(U);return}}if(this.flowHandlers.has("*")){let g=this.flowHandlers.get("*");if(g){let R=await Promise.resolve(g(this.client,l)),U=this.encryptResponse(R,n,f);s.status(200).send(U);return}}let c=this.encryptResponse({},n,f);s.status(200).send(c)}isRequestSignatureValid(t){let s=this.config.M4D_APP_SECRET;if(!s)return _.warn("App Secret is not set up. Please Add M4D_APP_SECRET or configuration"),!1;let i=t.headers["x-hub-signature-256"];if(!i||typeof i!="string")return _.warn("x-hub-signature-256 header is missing"),!1;let o=Buffer.from(i.replace("sha256=",""),"utf-8"),f=T.default.createHmac("sha256",s).update(t.rawBody).digest("hex"),p=Buffer.from(f,"utf-8");return T.default.timingSafeEqual(p,o)?!0:(_.error("Error: Request Signature did not match"),!1)}decryptRequest(t){let{encrypted_aes_key:s,encrypted_flow_data:i,initial_vector:o}=t,n=this.config.FLOW_API_PRIVATE_PEM.replace(/\\n/g,`
2
- `),f=this.config.FLOW_API_PASSPHRASE,p=T.default.createPrivateKey({key:n,passphrase:f}),l=null;try{l=T.default.privateDecrypt({key:p,padding:T.default.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:"sha256"},Buffer.from(s,"base64"))}catch(We){throw _.error(We),new Error("Failed to decrypt the request. Please verify your private key.")}let c=Buffer.from(i,"base64"),g=Buffer.from(o,"base64"),R=16,U=c.subarray(0,-R),Ue=c.subarray(-R),P=T.default.createDecipheriv("aes-128-gcm",l,g);P.setAuthTag(Ue);let d=Buffer.concat([P.update(U),P.final()]).toString("utf-8");return{decryptedBody:JSON.parse(d),aesKeyBuffer:l,initialVectorBuffer:g}}encryptResponse(t,s,i){let o=[];for(let n of Array.from(i.entries()))o.push(~n[1]);try{let n=T.default.createCipheriv("aes-128-gcm",s,Buffer.from(o));return Buffer.concat([n.update(JSON.stringify(t||{}),"utf-8"),n.final(),n.getAuthTag()]).toString("base64")}catch(n){throw _.error("Response encryption error:",n),new Error("Failed to encrypt response. Internal server error.")}}onFlow(t,s){this.flowHandlers.set(t,s),_.log(`Registered handler for Flow type: ${t}`)}};var gt=I;0&&(module.exports={AudioMediaTypesEnum,BusinessVerticalEnum,ButtonPositionEnum,ButtonTypesEnum,CategoryEnum,ComponentTypesEnum,ConversationTypesEnum,CurrencyCodesEnum,DataLocalizationRegionEnum,DocumentMediaTypesEnum,EventField,FlowActionEnum,FlowCategoryEnum,FlowStatusEnum,FlowTypeEnum,HttpMethodsEnum,ImageMediaTypesEnum,InteractiveTypesEnum,LanguagesEnum,MessageStatus,MessageTypesEnum,ParametersTypesEnum,ReferralSourceTypesEnum,RequestCodeMethodsEnum,StatusEnum,StickerMediaTypesEnum,SystemChangeTypesEnum,TemplateStatusEnum,VideoMediaTypesEnum,WabaAccountReviewStatus,WabaAccountStatus,WabaBusinessVerificationStatus,WabaConfigEnum,WabaHealthStatusCanSendMessage,WebhookHandler,WebhookTypesEnum,generateXHub256Sig,importConfig,isFlowDataExchangeRequest,isFlowErrorRequest,isFlowPingRequest,isMetaError,objectToQueryString});
1
+ "use strict";var ke=Object.create;var $=Object.defineProperty;var Le=Object.getOwnPropertyDescriptor;var Je=Object.getOwnPropertyNames;var Ke=Object.getPrototypeOf,$e=Object.prototype.hasOwnProperty;var Te=(r,t)=>{for(var s in t)$(r,s,{get:t[s],enumerable:!0})},Ie=(r,t,s,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Je(t))!$e.call(r,o)&&o!==s&&$(r,o,{get:()=>t[o],enumerable:!(i=Le(t,o))||i.enumerable});return r};var Ne=(r,t,s)=>(s=r!=null?ke(Ke(r)):{},Ie(t||!r||!r.__esModule?$(s,"default",{value:r,enumerable:!0}):s,r)),Ve=r=>Ie($({},"__esModule",{value:!0}),r);var bt={};Te(bt,{AudioMediaTypesEnum:()=>ae,BusinessVerticalEnum:()=>he,ButtonPositionEnum:()=>E,ButtonTypesEnum:()=>z,CategoryEnum:()=>X,ComponentTypesEnum:()=>C,ConversationTypesEnum:()=>ee,CurrencyCodesEnum:()=>de,DataLocalizationRegionEnum:()=>ge,DocumentMediaTypesEnum:()=>re,EventField:()=>be,FlowActionEnum:()=>Re,FlowCategoryEnum:()=>ye,FlowStatusEnum:()=>Me,FlowTypeEnum:()=>Pe,HttpMethodsEnum:()=>S,ImageMediaTypesEnum:()=>oe,InteractiveTypesEnum:()=>Q,LanguagesEnum:()=>fe,MessageStatus:()=>xe,MessageTypesEnum:()=>W,ParametersTypesEnum:()=>Z,ReferralSourceTypesEnum:()=>le,RequestCodeMethodsEnum:()=>ce,StatusEnum:()=>te,StickerMediaTypesEnum:()=>ie,SystemChangeTypesEnum:()=>pe,TemplateStatusEnum:()=>Y,VideoMediaTypesEnum:()=>se,WabaAccountReviewStatus:()=>Be,WabaAccountStatus:()=>De,WabaBusinessVerificationStatus:()=>ve,WabaConfigEnum:()=>A,WabaHealthStatusCanSendMessage:()=>Oe,WebhookHandler:()=>K,WebhookTypesEnum:()=>ne,default:()=>Pt,generateXHub256Sig:()=>je,importConfig:()=>G,isFlowDataExchangeRequest:()=>_e,isFlowErrorRequest:()=>Ae,isFlowPingRequest:()=>Se,isMetaError:()=>V,objectToQueryString:()=>w});module.exports=Ve(bt);var me={};Te(me,{AudioMediaTypesEnum:()=>ae,BusinessVerticalEnum:()=>he,ButtonPositionEnum:()=>E,ButtonTypesEnum:()=>z,CategoryEnum:()=>X,ComponentTypesEnum:()=>C,ConversationTypesEnum:()=>ee,CurrencyCodesEnum:()=>de,DataLocalizationRegionEnum:()=>ge,DocumentMediaTypesEnum:()=>re,HttpMethodsEnum:()=>S,ImageMediaTypesEnum:()=>oe,InteractiveTypesEnum:()=>Q,LanguagesEnum:()=>fe,MessageTypesEnum:()=>W,ParametersTypesEnum:()=>Z,ReferralSourceTypesEnum:()=>le,RequestCodeMethodsEnum:()=>ce,StatusEnum:()=>te,StickerMediaTypesEnum:()=>ie,SystemChangeTypesEnum:()=>pe,TemplateStatusEnum:()=>Y,VideoMediaTypesEnum:()=>se,WabaConfigEnum:()=>A,WebhookTypesEnum:()=>ne});var X=(i=>(i.Authentication="AUTHENTICATION",i.Marketing="MARKETING",i.Utility="UTILITY",i))(X||{}),Y=(i=>(i.Approved="APPROVED",i.Pending="PENDING",i.Rejected="REJECTED",i))(Y||{}),S=(o=>(o.Get="GET",o.Post="POST",o.Put="PUT",o.Delete="DELETE",o))(S||{}),W=(d=>(d.Audio="audio",d.Contacts="contacts",d.Document="document",d.Image="image",d.Interactive="interactive",d.Location="location",d.Reaction="reaction",d.Sticker="sticker",d.Template="template",d.Text="text",d.Video="video",d.Button="button",d.Order="order",d.System="system",d.Unknown="unknown",d["*"]="*",d))(W||{}),Z=(p=>(p.Currency="currency",p.DateTime="date_time",p.Document="document",p.Image="image",p.Text="text",p.Video="video",p.Payload="payload",p))(Z||{}),Q=(l=>(l.Button="button",l.List="list",l.Product="product",l.ProductList="product_list",l.CtaUrl="cta_url",l.LocationRequest="location_request_message",l.AddressMessage="address_message",l.Flow="flow",l))(Q||{}),z=(s=>(s.QuickReply="quick_reply",s.URL="url",s))(z||{}),E=(i=>(i[i.First=0]="First",i[i.Second=1]="Second",i[i.Third=2]="Third",i))(E||{}),C=(o=>(o.Header="HEADER",o.Body="BODY",o.Button="BUTTON",o.Footer="FOOTER",o))(C||{}),A=(d=>(d.AppId="M4D_APP_ID",d.Port="WA_PORT",d.AppSecret="M4D_APP_SECRET",d.PhoneNumberId="WA_PHONE_NUMBER_ID",d.BusinessAcctId="WA_BUSINESS_ACCOUNT_ID",d.APIVersion="CLOUD_API_VERSION",d.AccessToken="CLOUD_API_ACCESS_TOKEN",d.WebhookEndpoint="WEBHOOK_ENDPOINT",d.WebhookVerificationToken="WEBHOOK_VERIFICATION_TOKEN",d.ListenerPort="LISTENER_PORT",d.MaxRetriesAfterWait="MAX_RETRIES_AFTER_WAIT",d.RequestTimeout="REQUEST_TIMEOUT",d.Debug="DEBUG",d.PrivatePem="FLOW_API_PRIVATE_PEM",d.Passphrase="FLOW_API_PASSPHRASE",d))(A||{}),ee=(i=>(i.BusinessInitiated="business_initiated",i.CustomerInitiated="customer_initiated",i.ReferralConversion="referral_conversion",i))(ee||{}),te=(i=>(i.Delivered="delivered",i.Read="read",i.Sent="sent",i))(te||{}),se=(s=>(s.Mp4="video/mp4",s.Threegp="video/3gp",s))(se||{}),ie=(t=>(t.Webp="image/webp",t))(ie||{}),oe=(s=>(s.Jpeg="image/jpeg",s.Png="image/png",s))(oe||{}),re=(l=>(l.Text="text/plain",l.Pdf="application/pdf",l.Ppt="application/vnd.ms-powerpoint",l.Word="application/msword",l.Excel="application/vnd.ms-excel",l.OpenDoc="application/vnd.openxmlformats-officedocument.wordprocessingml.document",l.OpenPres="application/vnd.openxmlformats-officedocument.presentationml.presentation",l.OpenSheet="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",l))(re||{}),ae=(n=>(n.Aac="audio/aac",n.Mp4="audio/mp4",n.Mpeg="audio/mpeg",n.Amr="audio/amr",n.Ogg="audio/ogg",n))(ae||{}),ne=(R=>(R.Audio="audio",R.Button="button",R.Document="document",R.Text="text",R.Image="image",R.Interactive="interactive",R.Order="order",R.Sticker="sticker",R.System="system",R.Unknown="unknown",R.Video="video",R))(ne||{}),pe=(s=>(s.CustomerChangedNumber="customer_changed_number",s.CustomerIdentityChanged="customer_identity_changed",s))(pe||{}),le=(s=>(s.Ad="ad",s.Post="post",s))(le||{}),ce=(s=>(s.Sms="SMS",s.Voice="VOICE",s))(ce||{}),fe=(a=>(a.Afrikaans="af",a.Albanian="sq",a.Arabic="ar",a.Azerbaijani="az",a.Bengali="bn",a.Bulgarian="bg",a.Catalan="ca",a.Chinese_CHN="zh_CN",a.Chinese_HKG="zh_HK",a.Chinese_TAI="zh_TW",a.Croatian="hr",a.Czech="cs",a.Danish="da",a.Dutch="nl",a.English="en",a.English_UK="en_GB",a.English_US="en_US",a.Estonian="et",a.Filipino="fil",a.Finnish="fi",a.French="fr",a.Georgian="ka",a.German="de",a.Greek="el",a.Gujarati="gu",a.Hausa="ha",a.Hebrew="he",a.Hindi="hi",a.Hungarian="hu",a.Indonesian="id",a.Irish="ga",a.Italian="it",a.Japanese="ja",a.Kannada="kn",a.Kazakh="kk",a.Kinyarwanda="rw_RW",a.Korean="ko",a.Kyrgyz_Kyrgyzstan="ky_KG",a.Lao="lo",a.Latvian="lv",a.Lithuanian="lt",a.Macedonian="mk",a.Malay="ms",a.Malayalam="ml",a.Marathi="mr",a.Norwegian="nb",a.Persian="fa",a.Polish="pl",a.Portuguese_BR="pt_BR",a.Portuguese_POR="pt_PT",a.Punjabi="pa",a.Romanian="ro",a.Russian="ru",a.Serbian="sr",a.Slovak="sk",a.Slovenian="sl",a.Spanish="es",a.Spanish_ARG="es_AR",a.Spanish_SPA="es_ES",a.Spanish_MEX="es_MX",a.Swahili="sw",a.Swedish="sv",a.Tamil="ta",a.Telugu="te",a.Thai="th",a.Turkish="tr",a.Ukrainian="uk",a.Urdu="ur",a.Uzbek="uz",a.Vietnamese="vi",a.Zulu="zu",a))(fe||{}),de=(e=>(e.AFN="AFN",e.EUR="EUR",e.ALL="ALL",e.DZD="DZD",e.USD="USD",e.AOA="AOA",e.XCD="XCD",e.ARS="ARS",e.AMD="AMD",e.AWG="AWG",e.AUD="AUD",e.AZN="AZN",e.BSD="BSD",e.BHD="BHD",e.BDT="BDT",e.BBD="BBD",e.BYN="BYN",e.BZD="BZD",e.XOF="XOF",e.BMD="BMD",e.INR="INR",e.BTN="BTN",e.BOB="BOB",e.BOV="BOV",e.BAM="BAM",e.BWP="BWP",e.NOK="NOK",e.BRL="BRL",e.BND="BND",e.BGN="BGN",e.BIF="BIF",e.CVE="CVE",e.KHR="KHR",e.XAF="XAF",e.CAD="CAD",e.KYD="KYD",e.CLP="CLP",e.CLF="CLF",e.CNY="CNY",e.COP="COP",e.COU="COU",e.KMF="KMF",e.CDF="CDF",e.NZD="NZD",e.CRC="CRC",e.HRK="HRK",e.CUP="CUP",e.CUC="CUC",e.ANG="ANG",e.CZK="CZK",e.DKK="DKK",e.DJF="DJF",e.DOP="DOP",e.EGP="EGP",e.SVC="SVC",e.ERN="ERN",e.SZL="SZL",e.ETB="ETB",e.FKP="FKP",e.FJD="FJD",e.XPF="XPF",e.GMD="GMD",e.GEL="GEL",e.GHS="GHS",e.GIP="GIP",e.GTQ="GTQ",e.GBP="GBP",e.GNF="GNF",e.GYD="GYD",e.HTG="HTG",e.HNL="HNL",e.HKD="HKD",e.HUF="HUF",e.ISK="ISK",e.IDR="IDR",e.XDR="XDR",e.IRR="IRR",e.IQD="IQD",e.ILS="ILS",e.JMD="JMD",e.JPY="JPY",e.JOD="JOD",e.KZT="KZT",e.KES="KES",e.KPW="KPW",e.KRW="KRW",e.KWD="KWD",e.KGS="KGS",e.LAK="LAK",e.LBP="LBP",e.LSL="LSL",e.ZAR="ZAR",e.LRD="LRD",e.LYD="LYD",e.CHF="CHF",e.MOP="MOP",e.MKD="MKD",e.MGA="MGA",e.MWK="MWK",e.MYR="MYR",e.MVR="MVR",e.MRU="MRU",e.MUR="MUR",e.XUA="XUA",e.MXN="MXN",e.MXV="MXV",e.MDL="MDL",e.MNT="MNT",e.MAD="MAD",e.MZN="MZN",e.MMK="MMK",e.NAD="NAD",e.NPR="NPR",e.NIO="NIO",e.NGN="NGN",e.OMR="OMR",e.PKR="PKR",e.PAB="PAB",e.PGK="PGK",e.PYG="PYG",e.PEN="PEN",e.PHP="PHP",e.PLN="PLN",e.QAR="QAR",e.RON="RON",e.RUB="RUB",e.RWF="RWF",e.SHP="SHP",e.WST="WST",e.STN="STN",e.SAR="SAR",e.RSD="RSD",e.SCR="SCR",e.SLL="SLL",e.SGD="SGD",e.XSU="XSU",e.SBD="SBD",e.SOS="SOS",e.SSP="SSP",e.LKR="LKR",e.SDG="SDG",e.SRD="SRD",e.SEK="SEK",e.CHE="CHE",e.CHW="CHW",e.SYP="SYP",e.TWD="TWD",e.TJS="TJS",e.TZS="TZS",e.THB="THB",e.TOP="TOP",e.TTD="TTD",e.TND="TND",e.TRY="TRY",e.TMT="TMT",e.UGX="UGX",e.UAH="UAH",e.AED="AED",e.USN="USN",e.UYU="UYU",e.UYI="UYI",e.UYW="UYW",e.UZS="UZS",e.VUV="VUV",e.VES="VES",e.VND="VND",e.YER="YER",e.ZMW="ZMW",e.ZWL="ZWL",e.XBA="XBA",e.XBB="XBB",e.XBC="XBC",e.XBD="XBD",e.XTS="XTS",e.XXX="XXX",e.XAU="XAU",e.XPD="XPD",e.XPT="XPT",e.XAG="XAG",e.AFA="AFA",e.FIM="FIM",e.ALK="ALK",e.ADP="ADP",e.ESP="ESP",e.FRF="FRF",e.AOK="AOK",e.AON="AON",e.AOR="AOR",e.ARA="ARA",e.ARP="ARP",e.ARY="ARY",e.RUR="RUR",e.ATS="ATS",e.AYM="AYM",e.AZM="AZM",e.BYB="BYB",e.BYR="BYR",e.BEC="BEC",e.BEF="BEF",e.BEL="BEL",e.BOP="BOP",e.BAD="BAD",e.BRB="BRB",e.BRC="BRC",e.BRE="BRE",e.BRN="BRN",e.BRR="BRR",e.BGJ="BGJ",e.BGK="BGK",e.BGL="BGL",e.BUK="BUK",e.HRD="HRD",e.CYP="CYP",e.CSJ="CSJ",e.CSK="CSK",e.ECS="ECS",e.ECV="ECV",e.GQE="GQE",e.EEK="EEK",e.XEU="XEU",e.GEK="GEK",e.DDM="DDM",e.DEM="DEM",e.GHC="GHC",e.GHP="GHP",e.GRD="GRD",e.GNE="GNE",e.GNS="GNS",e.GWE="GWE",e.GWP="GWP",e.ITL="ITL",e.ISJ="ISJ",e.IEP="IEP",e.ILP="ILP",e.ILR="ILR",e.LAJ="LAJ",e.LVL="LVL",e.LVR="LVR",e.LSM="LSM",e.ZAL="ZAL",e.LTL="LTL",e.LTT="LTT",e.LUC="LUC",e.LUF="LUF",e.LUL="LUL",e.MGF="MGF",e.MVQ="MVQ",e.MLF="MLF",e.MTL="MTL",e.MTP="MTP",e.MRO="MRO",e.MXP="MXP",e.MZE="MZE",e.MZM="MZM",e.NLG="NLG",e.NIC="NIC",e.PEH="PEH",e.PEI="PEI",e.PES="PES",e.PLZ="PLZ",e.PTE="PTE",e.ROK="ROK",e.ROL="ROL",e.STD="STD",e.CSD="CSD",e.SKK="SKK",e.SIT="SIT",e.RHD="RHD",e.ESA="ESA",e.ESB="ESB",e.SDD="SDD",e.SDP="SDP",e.SRG="SRG",e.CHC="CHC",e.TJR="TJR",e.TPE="TPE",e.TRL="TRL",e.TMM="TMM",e.UGS="UGS",e.UGW="UGW",e.UAK="UAK",e.SUR="SUR",e.USS="USS",e.UYN="UYN",e.UYP="UYP",e.VEB="VEB",e.VEF="VEF",e.VNC="VNC",e.YDD="YDD",e.YUD="YUD",e.YUM="YUM",e.YUN="YUN",e.ZRN="ZRN",e.ZRZ="ZRZ",e.ZMK="ZMK",e.ZWC="ZWC",e.ZWD="ZWD",e.ZWN="ZWN",e.ZWR="ZWR",e.XFO="XFO",e.XRE="XRE",e.XFU="XFU",e))(de||{}),ge=(P=>(P.AU="AU",P.ID="ID",P.IN="IN",P.JP="JP",P.SG="SG",P.KR="KR",P.DE="DE",P.CH="CH",P.GB="GB",P.BR="BR",P.BH="BH",P.ZA="ZA",P.AE="AE",P.CA="CA",P))(ge||{}),he=(m=>(m.ALCOHOL="ALCOHOL",m.APPAREL="APPAREL",m.AUTO="AUTO",m.BEAUTY="BEAUTY",m.EDU="EDU",m.ENTERTAIN="ENTERTAIN",m.EVENT_PLAN="EVENT_PLAN",m.FINANCE="FINANCE",m.GOVT="GOVT",m.GROCERY="GROCERY",m.HEALTH="HEALTH",m.HOTEL="HOTEL",m.NONPROFIT="NONPROFIT",m.ONLINE_GAMBLING="ONLINE_GAMBLING",m.OTC_DRUGS="OTC_DRUGS",m.OTHER="OTHER",m.PHYSICAL_GAMBLING="PHYSICAL_GAMBLING",m.PROF_SERVICES="PROF_SERVICES",m.RESTAURANT="RESTAURANT",m.RETAIL="RETAIL",m.TRAVEL="TRAVEL",m))(he||{});var Me=(n=>(n.Draft="DRAFT",n.Published="PUBLISHED",n.Throttled="THROTTLED",n.Blocked="BLOCKED",n.Deprecated="DEPRECATED",n))(Me||{}),ye=(l=>(l.SignUp="SIGN_UP",l.SignIn="SIGN_IN",l.AppointmentBooking="APPOINTMENT_BOOKING",l.LeadGeneration="LEAD_GENERATION",l.ContactUs="CONTACT_US",l.CustomerSupport="CUSTOMER_SUPPORT",l.Survey="SURVEY",l.Other="OTHER",l))(ye||{}),Re=(i=>(i.INIT="INIT",i.BACK="BACK",i.DATA_EXCHANGE="data_exchange",i))(Re||{}),Pe=(o=>(o.Ping="ping",o.Change="data_exchange",o.Error="error",o.All="*",o))(Pe||{});var Be=(o=>(o.Approved="APPROVED",o.Active="ACTIVE",o.Inactive="INACTIVE",o.Disabled="DISABLED",o))(Be||{}),Oe=(i=>(i.Blocked="BLOCKED",i.Limited="LIMITED",i.Available="AVAILABLE",i))(Oe||{}),De=(o=>(o.Approved="APPROVED",o.Active="ACTIVE",o.Inactive="INACTIVE",o.Disabled="DISABLED",o))(De||{}),ve=(o=>(o.Verified="verified",o.PendingSubmission="pending_submission",o.Unverified="unverified",o.Rejected="rejected",o))(ve||{});var xe=(i=>(i.DELIVERED="delivered",i.READ="read",i.SENT="sent",i))(xe||{}),be=(c=>(c.MESSAGES="messages",c.STATUSES="statuses",c.MESSAGE_TEMPLATE_STATUS_UPDATE="message_template_status_update",c.PHONE_NUMBER_QUALITY_UPDATE="phone_number_quality_update",c.PHONE_NUMBER_NAME_UPDATE="phone_number_name_update",c.UNKNOWN="unknown",c))(be||{});var T=Ne(require("crypto"));var ue=Ne(require("crypto")),je=(r,t)=>ue.createHmac("sha256",t).update(r,"utf-8").digest("hex");var b=class{name;debug;constructor(t,s=!1){this.name=t,this.debug=s}log(...t){if(this.debug){let s=`[ ${Date.now()} ]`;this.name&&(s+=` - ${this.name}`),console.log.apply(console,[s,": ",...t])}}error(...t){let s=`[ ${Date.now()} ] - ERROR`;this.name&&(s+=` - ${this.name}`),console.error.apply(console,[s,": ",...t])}warn(...t){let s=`[ ${Date.now()} ] - WARN`;this.name&&(s+=` - ${this.name}`),console.warn.apply(console,[s,": ",...t])}info(...t){let s=`[ ${Date.now()} ] - INFO`;this.name&&(s+=` - ${this.name}`),console.info.apply(console,[s,": ",...t])}};var Xe="UTILS",Ye=!1,Fe=new b(Xe,process.env.DEBUG==="true"||Ye),Ze=3e3,Qe=30,ze=2e4,Ee=r=>{if(!process.env.CLOUD_API_ACCESS_TOKEN&&!r?.accessToken)throw Fe.log("Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined."),new Error("Missing WhatsApp access token.")},G=r=>{Ee(r);let t={M4D_APP_ID:r?.appId||process.env.M4D_APP_ID||"",M4D_APP_SECRET:r?.appSecret||process.env.M4D_APP_SECRET||"",WA_PHONE_NUMBER_ID:r?.phoneNumberId||Number(process.env.WA_PHONE_NUMBER_ID),WA_BUSINESS_ACCOUNT_ID:r?.businessAcctId||process.env.WA_BUSINESS_ACCOUNT_ID||"",CLOUD_API_VERSION:r?.apiVersion||process.env.CLOUD_API_VERSION||"",CLOUD_API_ACCESS_TOKEN:r?.accessToken||process.env.CLOUD_API_ACCESS_TOKEN||"",WEBHOOK_ENDPOINT:r?.webhookEndpoint||process.env.WEBHOOK_ENDPOINT||"",WEBHOOK_VERIFICATION_TOKEN:r?.webhookVerificationToken||process.env.WEBHOOK_VERIFICATION_TOKEN||"",LISTENER_PORT:r?.listenerPort||parseInt(process.env.LISTENER_PORT||"")||Ze,MAX_RETRIES_AFTER_WAIT:r?.maxRetriesAfterWait||parseInt(process.env.MAX_RETRIES_AFTER_WAIT||"")||Qe,REQUEST_TIMEOUT:r?.requestTimeout||parseInt(process.env.REQUEST_TIMEOUT||"")||ze,DEBUG:r?.debug||process.env.DEBUG==="true",FLOW_API_PRIVATE_PEM:r?.privatePem||process.env.FLOW_API_PRIVATE_PEM||"",FLOW_API_PASSPHRASE:r?.passphrase||process.env.FLOW_API_PASSPHRASE||""};return Fe.log(`Configuration loaded for App Id ${t.M4D_APP_ID}`),t};function V(r){return r!=null&&typeof r=="object"&&"error"in r&&typeof r.error=="object"&&r.error!=null&&"message"in r.error&&typeof r.error.message=="string"&&"type"in r.error&&typeof r.error.type=="string"&&"code"in r.error&&typeof r.error.code=="number"&&"fbtrace_id"in r.error&&typeof r.error.fbtrace_id=="string"&&(!("error_data"in r.error)||typeof r.error.error_data=="object"&&r.error.error_data!=null&&"messaging_product"in r.error.error_data&&r.error.error_data.messaging_product==="whatsapp"&&"details"in r.error.error_data&&typeof r.error.error_data.details=="string")&&(!("error_subcode"in r.error)||typeof r.error.error_subcode=="number")}var w=r=>{if(!r||Object.keys(r).length===0)return"";let t=new URLSearchParams;for(let[i,o]of Object.entries(r))o!==void 0&&t.append(i,String(o));let s=t.toString();return s?`?${s}`:""};function qe(r){return typeof r=="object"&&r!==null}function N(r){return typeof r=="string"}var Ce=["data_exchange","INIT","BACK"],et=["data_exchange","INIT"];function _e(r){if(!("flow_token"in r&&N(r.flow_token)&&"action"in r))return!1;let{action:t,version:s,screen:i,data:o}=r,n=s==="3.0",c=Ce.includes(t),p=typeof i>"u"||N(i)&&i!=="SUCCESS",l=t==="data_exchange"||qe(o);return n&&c&&p&&l}function Ae(r){if(!("flow_token"in r&&N(r.flow_token)&&"action"in r))return!1;let{action:t,screen:s,data:i}=r,o=et.includes(t),n=N(s),c=qe(i)&&"error_key"in i&&N(i.error)&&"error_message"in i&&N(i.error_message);return o&&n&&c}function Se(r){return"action"in r&&r.action==="ping"}var tt="BaseAPI",st=!1,it=new b(tt,process.env.DEBUG==="true"||st),h=class{config;client;constructor(t,s){this.config=t,this.client=s,it.log("Initialized with HTTPSClient")}sendJson(t,s,i,o){return this.client.getJson(t,s,i,o)}sendFormData(t,s,i,o){return this.client.sendFormData(t,s,i,o)}sendUrlEncodedForm(t,s,i,o){return this.client.sendUrlEncodedForm(t,s,i,o)}};function j(r){if(!r)return"";let t="";return Array.isArray(r)?t=r.join(","):t=Object.entries(r).filter(([s,i])=>i).map(([s])=>s).join(","),t?`?fields=${t}`:""}var M=class extends h{endpoint="whatsapp_business_profile";constructor(t,s){super(t,s)}async getBusinessProfile(t){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}${j(t)}`,this.config.REQUEST_TIMEOUT,null)}async updateBusinessProfile(t){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async createUploadSession(t,s,i){let o=w({file_length:t,file_type:s,file_name:i});return this.sendJson("POST",`app/uploads/${o}`,this.config.REQUEST_TIMEOUT,null)}async uploadMedia(t,s){return this.sendJson("POST",`${t}`,this.config.REQUEST_TIMEOUT,s)}async getUploadHandle(t){return this.sendJson("GET",`${t}`,this.config.REQUEST_TIMEOUT,null)}};var y=class extends h{endpoint="whatsapp_business_encryption";constructor(t,s){super(t,s)}async getEncryptionPublicKey(){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async setEncryptionPublicKey(t){let s=new FormData;return s.append("business_public_key",t),this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,s)}};var ot="FlowAPI",rt=!1,Ue=new b(ot,process.env.DEBUG==="true"||rt),B=class extends h{constructor(t,s){super(t,s),Ue.log("FlowAPI initialized")}async listFlows(t){return this.sendJson("GET",`/${t}/flows`,this.config.REQUEST_TIMEOUT,null)}async createFlow(t,s){let i={name:s.name,categories:s.categories,...s.endpoint_uri&&{endpoint_uri:s.endpoint_uri},...s.clone_flow_id&&{clone_flow_id:s.clone_flow_id},...s.flow_json&&{flow_json:s.flow_json},...s.publish!==void 0&&{publish:s.publish}};return this.sendJson("POST",`/${t}/flows`,this.config.REQUEST_TIMEOUT,JSON.stringify(i))}async getFlow(t,s,i){let o=new URLSearchParams;s&&o.append("fields",s),i&&o.append("date_format",i);let n=o.toString()?`?${o.toString()}`:"";return this.sendJson("GET",`/${t}${n}`,this.config.REQUEST_TIMEOUT,null)}async getFlowPreview(t,s=!1){let i=`preview.invalidate(${s})`;return this.getFlow(t,i)}async updateFlowMetadata(t,s){let i={...s.name&&{name:s.name},...s.categories&&{categories:s.categories},...s.endpoint_uri&&{endpoint_uri:s.endpoint_uri},...s.application_id&&{application_id:s.application_id}};return this.sendJson("POST",`/${t}`,this.config.REQUEST_TIMEOUT,JSON.stringify(i))}async deleteFlow(t){return this.sendJson("DELETE",`/${t}`,this.config.REQUEST_TIMEOUT,null)}async listAssets(t){return this.sendJson("GET",`/${t}/assets`,this.config.REQUEST_TIMEOUT,null)}async updateFlowJson(t,s){let i=new FormData,o;if(s.file instanceof Buffer)o=new globalThis.Blob([s.file]),i.append("file",o);else if(typeof s.file=="object"&&!(s.file instanceof Blob))try{o=new globalThis.Blob([JSON.stringify(s.file,null,2)],{type:"application/json"}),i.append("file",o)}catch{throw new Error("Failed to stringify JSON object for Flow JSON update.")}else if(s.file instanceof Blob)o=s.file,i.append("file",o);else throw new Error("Invalid file type provided for Flow JSON update. Must be a Buffer, JSON object, or Blob.");return i.append("asset_type","FLOW_JSON"),i.append("name",s.name||"flow.json"),this.sendFormData("POST",`/${t}/assets`,this.config.REQUEST_TIMEOUT,i)}async validateFlowJson(t,s){try{let i=await this.updateFlowJson(t,{file:s}),o=!i.validation_errors||i.validation_errors.length===0;return{...i,valid:o}}catch(i){throw Ue.error("Error during Flow JSON validation attempt:",i),i}}async publishFlow(t){return this.sendJson("POST",`/${t}/publish`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async deprecateFlow(t){return this.sendJson("POST",`/${t}/deprecate`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async migrateFlows(t,s){let i={source_waba_id:s.source_waba_id,...s.source_flow_names&&{source_flow_names:s.source_flow_names}};return this.sendJson("POST",`/${t}/migrate_flows`,this.config.REQUEST_TIMEOUT,JSON.stringify(i))}};var O=class extends h{endpoint="media";constructor(t,s){super(t,s)}async getMediaById(t){return this.sendJson("GET",`${t}`,this.config.REQUEST_TIMEOUT,null)}async uploadMedia(t,s="whatsapp"){let i=new FormData;return i.append("file",t),i.append("messaging_product",s),i.append("type",t.type),this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,i)}async deleteMedia(t){return this.sendJson("DELETE",`${t}`,this.config.REQUEST_TIMEOUT,null)}async downloadMedia(t){return this.sendJson("GET",t,this.config.REQUEST_TIMEOUT,null)}};var D=class extends h{commonMethod="POST";commonEndpoint="messages";constructor(t,s){super(t,s)}bodyBuilder(t,s,i,o){let n={messaging_product:"whatsapp",recipient_type:"individual",to:i,type:t,[t]:s};return o&&(n.context={message_id:o}),n}send(t){return this.sendJson(this.commonMethod,`${this.config.WA_PHONE_NUMBER_ID}/${this.commonEndpoint}`,this.config.REQUEST_TIMEOUT,t)}async audio(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("audio",s,i,o)))}async contacts(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("contacts",s,i,o)))}async document(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("document",s,i,o)))}async image(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("image",s,i,o)))}async interactive(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("interactive",s,i,o)))}async location(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("location",s,i,o)))}async sticker(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("sticker",s,i,o)))}async template(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("template",s,i,o)))}async text(t){let{body:s,previewUrl:i,to:o,replyMessageId:n}=t,c;return typeof s=="string"?c={body:s,preview_url:i}:c=s,this.send(JSON.stringify(this.bodyBuilder("text",c,o,n)))}async video(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("video",s,i,o)))}async status(t){let{status:s,messageId:i,typingIndicator:o}=t,n={messaging_product:"whatsapp",status:s,message_id:i,...o&&{typing_indicator:o}};return this.send(JSON.stringify(n))}async markAsRead(t){return this.status({status:"read",messageId:t.messageId})}async showTypingIndicator(t){return this.status({status:"read",messageId:t.messageId,typingIndicator:{type:"text"}})}async interactiveList(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("interactive",s,i,o)))}async interactiveCtaUrl(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("interactive",s,i,o)))}async interactiveLocationRequest(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("interactive",s,i,o)))}async interactiveAddressMessage(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("interactive",s,i,o)))}async interactiveReplyButtons(t){let{body:s,to:i,replyMessageId:o}=t;return this.send(JSON.stringify(this.bodyBuilder("interactive",s,i,o)))}async interactiveFlow(t){let{body:s,to:i,replyMessageId:o}=t;return s.action.parameters.flow_message_version===void 0&&(s.action.parameters.flow_message_version="3"),s.action.parameters.mode===void 0&&(s.action.parameters.mode="published"),s.action.parameters.flow_action===void 0&&(s.action.parameters.flow_action="navigate"),s.action.parameters.flow_action==="navigate"?s.action.parameters.flow_action_payload?.screen===void 0&&(s.action.parameters.flow_action_payload={...s.action.parameters.flow_action_payload,screen:"INIT"}):s.action.parameters.flow_action==="data_exchange"&&delete s.action.parameters.flow_action_payload,this.send(JSON.stringify(this.bodyBuilder("interactive",s,i,o)))}async reaction(t){let{messageId:s,emoji:i,to:o}=t,n={messaging_product:"whatsapp",recipient_type:"individual",to:o,type:"reaction",reaction:{message_id:s,emoji:i}};return this.send(JSON.stringify(n))}};var v=class extends h{endpoint="phone_numbers";constructor(t,s){super(t,s)}async getPhoneNumberById(t){let s=t?w({fields:t}):"";return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}${s}`,this.config.REQUEST_TIMEOUT,null)}async getPhoneNumbers(){return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async requestVerificationCode(t){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/request_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async verifyCode(t){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/verify_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}};var x=class extends h{endpoint="message_qrdls";constructor(t,s){super(t,s)}async createQrCode(t){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getQrCodes(){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async getQrCode(t){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}/${t}`,this.config.REQUEST_TIMEOUT,null)}async updateQrCode(t){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async deleteQrCode(t){return this.sendJson("DELETE",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}/${t}`,this.config.REQUEST_TIMEOUT,null)}};var u=class extends h{constructor(t,s){super(t,s)}async register(t,s){let i={messaging_product:"whatsapp",pin:t,...s&&{data_localization_region:s}};return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/register`,this.config.REQUEST_TIMEOUT,JSON.stringify(i))}async deregister(){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/deregister`,this.config.REQUEST_TIMEOUT,null)}};var F=class extends h{endpoint="message_templates";constructor(t,s){super(t,s)}async getTemplate(t){return this.sendJson("GET",`${t}`,this.config.REQUEST_TIMEOUT,null)}async updateTemplate(t,s){return this.sendJson("POST",`${t}`,this.config.REQUEST_TIMEOUT,JSON.stringify(s))}async getTemplates(t){return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${w(t)}`,this.config.REQUEST_TIMEOUT,null)}async createTemplate(t){return this.sendJson("POST",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async deleteTemplate(t){return this.sendJson("DELETE",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${w(t)}`,this.config.REQUEST_TIMEOUT,null)}};var q=class extends h{constructor(t,s){super(t,s)}async setTwoStepVerificationCode(t){let s={pin:t};return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}`,this.config.REQUEST_TIMEOUT,JSON.stringify(s))}};var U=class extends h{constructor(t,s){super(t,s)}async getWabaAccount(t){let s=j(t)?.replace(/,/g,"%2C");return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}${s}`,this.config.REQUEST_TIMEOUT,null)}async getAllWabaSubscriptions(){return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,null)}async updateWabaSubscription({override_callback_uri:t,verify_token:s}){let i={override_callback_uri:t,verify_token:s};return this.sendJson("POST",`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,JSON.stringify(i))}async unsubscribeFromWaba(){return this.sendJson("DELETE",`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,null)}};var He=require("https");var at="HttpsClient",nt=!1,pt=new b(at,process.env.DEBUG==="true"||nt),k=class{agent;constructor(){this.agent=new He.Agent({keepAlive:!0})}clearSockets(){return this.agent.destroy(),!0}async sendRequest(t,s,i,o,n,c){let p=`https://${t}/${s}`,l=new AbortController,f=setTimeout(()=>l.abort(),n);try{let g=await fetch(p,{method:i,headers:o,body:c,signal:l.signal});return pt.log(`${i} : ${p} - ${JSON.stringify(g)}`),clearTimeout(f),new we(g)}catch(g){throw g}}},we=class{res;respStatusCode;respHeaders;constructor(t){this.res=t,this.respStatusCode=t.status,this.respHeaders=Object.fromEntries(t.headers.entries())}statusCode(){return this.respStatusCode}headers(){return this.respHeaders}rawResponse(){return this.res}async json(){try{return await this.res.json()}catch(t){throw new Error("Failed to parse response body to JSON: "+t.message)}}};var lt="REQUESTER",ct=!1,ft=new b(lt,process.env.DEBUG==="true"||ct),L=class{client;accessToken;phoneNumberId;businessAcctId;apiVersion;userAgent;host;protocol="https:";constructor(t,s,i,o,n){this.client=new k,this.host="graph.facebook.com",this.apiVersion=t||"22",this.phoneNumberId=s,this.accessToken=i,this.businessAcctId=o,this.userAgent=n}buildHeader(t,s){let i={Authorization:`Bearer ${this.accessToken}`,"User-Agent":this.userAgent};return t!=="multipart/form-data"&&(i["Content-Type"]=t),s&&Object.assign(i,s),i}buildCAPIPath(t){return`v${this.apiVersion}.0/${t}`}async sendRequest(t,s,i,o,n="application/json",c){let p=n;o instanceof FormData?p="multipart/form-data":typeof o=="string"&&o.startsWith("<?xml")&&(p="application/xml");let l=`${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(s)}`;ft.log(`${t} : ${l} (${p})`);try{let f=await this.client.sendRequest(this.host,this.buildCAPIPath(s),t,this.buildHeader(p,c),i,t==="POST"||t==="PUT"?o:void 0);if(!f.rawResponse().ok){let g=await f.json();throw V(g)?g:{name:"MetaError",message:"Unknown error occurred",error:{message:g.message||"Unknown error occurred",type:"UnknownError",code:f.statusCode(),fbtrace_id:""}}}return f}catch(f){throw V(f)?f:{name:"MetaError",message:f instanceof Error?f.message:"Network error occurred",error:{message:f instanceof Error?f.message:"Network error occurred",type:"NetworkError",code:500,fbtrace_id:""}}}}async getJson(t,s,i,o,n){return await(await this.sendRequest(t,s,i,o,"application/json",n)).json()}async sendFormData(t,s,i,o,n){return await(await this.sendRequest(t,s,i,o,"multipart/form-data",n)).json()}async sendUrlEncodedForm(t,s,i,o,n){let c=new URLSearchParams(o).toString();return await(await this.sendRequest(t,s,i,c,"application/x-www-form-urlencoded",n)).json()}};var dt="WHATSAPP",gt=!1,J=new b(dt,process.env.DEBUG==="true"||gt),ht="WA_SDK",I=class{config;requester;messages;templates;phoneNumber;qrCode;encryption;twoStepVerification;registration;media;waba;flow;businessProfile;static Enums=me;constructor(t){this.config=G(t),this.requester=new L(this.config.CLOUD_API_VERSION,this.config.WA_PHONE_NUMBER_ID,this.config.CLOUD_API_ACCESS_TOKEN,this.config.WA_BUSINESS_ACCOUNT_ID,this.userAgent()),this.messages=new D(this.config,this.requester),this.templates=new F(this.config,this.requester),this.phoneNumber=new v(this.config,this.requester),this.qrCode=new x(this.config,this.requester),this.encryption=new y(this.config,this.requester),this.twoStepVerification=new q(this.config,this.requester),this.registration=new u(this.config,this.requester),this.media=new O(this.config,this.requester),this.waba=new U(this.config,this.requester),this.flow=new B(this.config,this.requester),this.businessProfile=new M(this.config,this.requester),J.log("WhatsApp Node.js SDK instantiated!")}userAgent(){return`${ht}/0.0.1 (Node.js ${process.version})`}updateTimeout(t){return this.config.REQUEST_TIMEOUT=t,J.log(`Updated request timeout to ${t}ms`),!0}updatePhoneNumberId(t){return this.config.WA_PHONE_NUMBER_ID=t,J.log(`Updated sender phone number id to ${t}`),!0}updateAccessToken(t){return this.config.CLOUD_API_ACCESS_TOKEN=t,J.log("Updated access token"),!0}updateWabaId(t){return this.config.WA_BUSINESS_ACCOUNT_ID=t,J.log(`Updated business account id to ${t}`),!0}};var mt="WEBHOOK",Rt=!1,_=new b(mt,process.env.DEBUG==="true"||Rt),K=class{config;client;messageHandlers=new Map;eventHandlers=new Map;preProcessHandler=null;postProcessHandler=null;flowHandlers=new Map;constructor(t){let s=G(t);this.config=s,this.client=new I(t),_.log("WebhookHandler instantiated!")}handleVerificationRequest(t,s){let i=t.query["hub.mode"],o=t.query["hub.verify_token"],n=t.query["hub.challenge"];i==="subscribe"&&o===this.config.WEBHOOK_VERIFICATION_TOKEN?(_.log("Webhook verified successfully"),s.status(200).send(n)):(_.log("Webhook verification failed"),s.status(403).end())}async handleWebhookRequest(t,s){let i=t.body;if(i.object!=="whatsapp_business_account"){_.log("Received webhook for non-WhatsApp event"),s.status(404).end();return}for(let o of i.entry)try{let n=o.changes;for(let c of n)c.field==="messages"?await this.processMessages(c.value):await this.processEvent(c.field,c.value)}catch(n){_.log(`Error processing webhook: ${n}`)}s.status(200).end()}handleRequest(t,s){if(t.method==="GET")return this.handleVerificationRequest(t,s);if(t.method==="POST")return this.handleWebhookRequest(t,s);s.status(405).end()}async processMessages(t){let s=t.metadata,i=s.display_phone_number,o=s.phone_number_id,n=t.contacts[0].profile.name,c=t.messages;if(c&&c.length>0)for(let p of c){let l=p.type,f={id:p.id,from:p.from,timestamp:p.timestamp,type:p.type,phoneNumberId:o,displayPhoneNumber:i,profileName:n,originalData:p};switch(p.type){case"text":f.text=p.text;break;case"image":f.image=p.image;break;case"video":f.video=p.video;break;case"audio":f.audio=p.audio;break;case"document":f.document=p.document;break;case"sticker":f.sticker=p.sticker;break;case"location":f.location=p.location;break;case"contacts":f.contacts=p.contacts;break;case"interactive":f.interactive=p.interactive;break;case"button":f.button=p.button;break;case"order":f.order=p.order;break;case"system":f.system=p.system;break;default:break}if(p.context&&(f.context=p.context),p.errors&&(f.errors=p.errors),this.preProcessHandler&&await Promise.resolve(this.preProcessHandler(this.client,f)),this.messageHandlers.has(l)){let g=this.messageHandlers.get(l);g&&await Promise.resolve(g(this.client,f))}if(this.messageHandlers.has("*")){let g=this.messageHandlers.get("*");g&&await Promise.resolve(g(this.client,f))}this.postProcessHandler&&await Promise.resolve(this.postProcessHandler(this.client,f))}t.statuses&&t.statuses.length>0&&await this.processEvent("statuses",t)}async processEvent(t,s){let i={field:t,value:s};if(this.eventHandlers.has(t)){let o=this.eventHandlers.get(t);o&&await Promise.resolve(o(i))}if(this.eventHandlers.has("*")){let o=this.eventHandlers.get("*");o&&await Promise.resolve(o(i))}}onMessage(t,s){this.messageHandlers.set(t,s),_.log(`Registered handler for message type: ${t}`)}onEvent(t,s){this.eventHandlers.set(t,s),_.log(`Registered handler for event field: ${t}`)}onMessagePreProcess(t){this.preProcessHandler=t,_.log("Registered pre-processing handler for all messages")}onMessagePostProcess(t){this.postProcessHandler=t,_.log("Registered post-processing handler for all messages")}async handleFlowRequest(t,s){if(!this.isRequestSignatureValid(t)){s.status(403).end();return}let i;try{i=this.decryptRequest(t.body)}catch(g){if(_.error(g),g instanceof Error){s.status(421).send(g.message);return}s.status(500).send("internal server error, please check with logs");return}let{decryptedBody:o,aesKeyBuffer:n,initialVectorBuffer:c}=i,p;Se(o)?p="ping":_e(o)?p="data_exchange":Ae(o)&&(p="error");let l=o;if(p&&this.flowHandlers.has(p)){let g=this.flowHandlers.get(p);if(g){let R=await Promise.resolve(g(this.client,l)),H=this.encryptResponse(R,n,c);s.status(200).send(H);return}}if(this.flowHandlers.has("*")){let g=this.flowHandlers.get("*");if(g){let R=await Promise.resolve(g(this.client,l)),H=this.encryptResponse(R,n,c);s.status(200).send(H);return}}_.log("No handler found, sending an empty response");let f=this.encryptResponse({},n,c);s.status(200).send(f)}isRequestSignatureValid(t){let s=this.config.M4D_APP_SECRET;if(!s)return _.warn("App Secret is not set up. Please Add M4D_APP_SECRET or configuration"),!1;let i=t.headers["x-hub-signature-256"];if(!i||typeof i!="string")return _.warn("x-hub-signature-256 header is missing"),!1;let o=Buffer.from(i.replace("sha256=",""),"utf-8"),c=T.default.createHmac("sha256",s).update(t.rawBody).digest("hex"),p=Buffer.from(c,"utf-8");return T.default.timingSafeEqual(p,o)?!0:(_.error("Error: Request Signature did not match"),!1)}decryptRequest(t){let{encrypted_aes_key:s,encrypted_flow_data:i,initial_vector:o}=t,n=this.config.FLOW_API_PRIVATE_PEM.replace(/\\n/g,`
2
+ `),c=this.config.FLOW_API_PASSPHRASE,p=T.default.createPrivateKey({key:n,passphrase:c}),l=null;try{l=T.default.privateDecrypt({key:p,padding:T.default.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:"sha256"},Buffer.from(s,"base64"))}catch(Ge){throw _.error(Ge),new Error("Failed to decrypt the request. Please verify your private key.")}let f=Buffer.from(i,"base64"),g=Buffer.from(o,"base64"),R=16,H=f.subarray(0,-R),We=f.subarray(-R),P=T.default.createDecipheriv("aes-128-gcm",l,g);P.setAuthTag(We);let d=Buffer.concat([P.update(H),P.final()]).toString("utf-8");return{decryptedBody:JSON.parse(d),aesKeyBuffer:l,initialVectorBuffer:g}}encryptResponse(t,s,i){let o=[];for(let n of Array.from(i.entries()))o.push(~n[1]);try{let n=T.default.createCipheriv("aes-128-gcm",s,Buffer.from(o));return Buffer.concat([n.update(JSON.stringify(t||{}),"utf-8"),n.final(),n.getAuthTag()]).toString("base64")}catch(n){throw _.error("Response encryption error:",n),new Error("Failed to encrypt response. Internal server error.")}}onFlow(t,s){this.flowHandlers.set(t,s),_.log(`Registered handler for Flow type: ${t}`)}};var Pt=I;0&&(module.exports={AudioMediaTypesEnum,BusinessVerticalEnum,ButtonPositionEnum,ButtonTypesEnum,CategoryEnum,ComponentTypesEnum,ConversationTypesEnum,CurrencyCodesEnum,DataLocalizationRegionEnum,DocumentMediaTypesEnum,EventField,FlowActionEnum,FlowCategoryEnum,FlowStatusEnum,FlowTypeEnum,HttpMethodsEnum,ImageMediaTypesEnum,InteractiveTypesEnum,LanguagesEnum,MessageStatus,MessageTypesEnum,ParametersTypesEnum,ReferralSourceTypesEnum,RequestCodeMethodsEnum,StatusEnum,StickerMediaTypesEnum,SystemChangeTypesEnum,TemplateStatusEnum,VideoMediaTypesEnum,WabaAccountReviewStatus,WabaAccountStatus,WabaBusinessVerificationStatus,WabaConfigEnum,WabaHealthStatusCanSendMessage,WebhookHandler,WebhookTypesEnum,generateXHub256Sig,importConfig,isFlowDataExchangeRequest,isFlowErrorRequest,isFlowPingRequest,isMetaError,objectToQueryString});
3
3
  //# sourceMappingURL=index.js.map