meta-cloud-api 0.1.18 → 0.1.19
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 +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/utils/importConfig.js +1 -1
- package/dist/utils/importConfig.js.map +1 -1
- package/dist/utils/importConfig.mjs +1 -1
- package/dist/utils/importConfig.mjs.map +1 -1
- package/dist/utils/index.js +1 -1
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/index.mjs +1 -1
- package/dist/utils/index.mjs.map +1 -1
- package/dist/webhook.js +1 -1
- package/dist/webhook.js.map +1 -1
- package/dist/webhook.mjs +1 -1
- package/dist/webhook.mjs.map +1 -1
- package/dist/whatsapp.js +1 -1
- package/dist/whatsapp.js.map +1 -1
- package/dist/whatsapp.mjs +1 -1
- package/dist/whatsapp.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var De=Object.create;var K=Object.defineProperty;var Be=Object.getOwnPropertyDescriptor;var ve=Object.getOwnPropertyNames;var xe=Object.getPrototypeOf,Ue=Object.prototype.hasOwnProperty;var he=(r,t)=>{for(var s in t)K(r,s,{get:t[s],enumerable:!0})},Re=(r,t,s,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ve(t))!Ue.call(r,o)&&o!==s&&K(r,o,{get:()=>t[o],enumerable:!(i=Be(t,o))||i.enumerable});return r};var Fe=(r,t,s)=>(s=r!=null?De(xe(r)):{},Re(t||!r||!r.__esModule?K(s,"default",{value:r,enumerable:!0}):s,r)),qe=r=>Re(K({},"__esModule",{value:!0}),r);var at={};he(at,{AudioMediaTypesEnum:()=>ie,BusinessVerticalEnum:()=>ge,ButtonPositionEnum:()=>Z,ButtonTypesEnum:()=>Y,CategoryEnum:()=>u,ComponentTypesEnum:()=>Q,ConversationTypesEnum:()=>z,CurrencyCodesEnum:()=>le,DataLocalizationRegionEnum:()=>ce,DocumentMediaTypesEnum:()=>se,EventField:()=>de,FlowCategoryEnum:()=>be,FlowStatusEnum:()=>Pe,HttpMethodsEnum:()=>A,ImageMediaTypesEnum:()=>te,InteractiveTypesEnum:()=>X,LanguagesEnum:()=>pe,MessageStatus:()=>Ie,MessageTypesEnum:()=>y,ParametersTypesEnum:()=>V,ReferralSourceTypesEnum:()=>ae,RequestCodeMethodsEnum:()=>ne,StatusEnum:()=>E,StickerMediaTypesEnum:()=>ee,SystemChangeTypesEnum:()=>re,TemplateStatusEnum:()=>j,VideoMediaTypesEnum:()=>C,WabaAccountReviewStatus:()=>Ae,WabaAccountStatus:()=>Te,WabaBusinessVerificationStatus:()=>Se,WabaConfigEnum:()=>P,WabaHealthStatusCanSendMessage:()=>_e,WebhookHandler:()=>J,WebhookTypesEnum:()=>oe,default:()=>rt,generateXHub256Sig:()=>ye,importConfig:()=>W,isMetaError:()=>k,objectToQueryString:()=>S});module.exports=qe(at);var fe={};he(fe,{AudioMediaTypesEnum:()=>ie,BusinessVerticalEnum:()=>ge,ButtonPositionEnum:()=>Z,ButtonTypesEnum:()=>Y,CategoryEnum:()=>u,ComponentTypesEnum:()=>Q,ConversationTypesEnum:()=>z,CurrencyCodesEnum:()=>le,DataLocalizationRegionEnum:()=>ce,DocumentMediaTypesEnum:()=>se,HttpMethodsEnum:()=>A,ImageMediaTypesEnum:()=>te,InteractiveTypesEnum:()=>X,LanguagesEnum:()=>pe,MessageTypesEnum:()=>y,ParametersTypesEnum:()=>V,ReferralSourceTypesEnum:()=>ae,RequestCodeMethodsEnum:()=>ne,StatusEnum:()=>E,StickerMediaTypesEnum:()=>ee,SystemChangeTypesEnum:()=>re,TemplateStatusEnum:()=>j,VideoMediaTypesEnum:()=>C,WabaConfigEnum:()=>P,WebhookTypesEnum:()=>oe});var u=(i=>(i.Authentication="AUTHENTICATION",i.Marketing="MARKETING",i.Utility="UTILITY",i))(u||{}),j=(i=>(i.Approved="APPROVED",i.Pending="PENDING",i.Rejected="REJECTED",i))(j||{}),A=(o=>(o.Get="GET",o.Post="POST",o.Put="PUT",o.Delete="DELETE",o))(A||{}),y=(R=>(R.Audio="audio",R.Contacts="contacts",R.Document="document",R.Image="image",R.Interactive="interactive",R.Location="location",R.Reaction="sticker",R.Sticker="sticker",R.Template="template",R.Text="text",R.Video="video",R.Button="button",R.Order="order",R.System="system",R.Unknown="unknown",R["*"]="*",R))(y||{}),V=(p=>(p.Currency="currency",p.DateTime="date_time",p.Document="document",p.Image="image",p.Text="text",p.Video="video",p.Payload="payload",p))(V||{}),X=(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))(X||{}),Y=(s=>(s.QuickReply="quick_reply",s.URL="url",s))(Y||{}),Z=(i=>(i[i.First=0]="First",i[i.Second=1]="Second",i[i.Third=2]="Third",i))(Z||{}),Q=(o=>(o.Header="HEADER",o.Body="BODY",o.Button="BUTTON",o.Footer="FOOTER",o))(Q||{}),P=(f=>(f.BaseURL="WA_BASE_URL",f.AppId="M4D_APP_ID",f.Port="WA_PORT",f.AppSecret="M4D_APP_SECRET",f.PhoneNumberId="WA_PHONE_NUMBER_ID",f.BusinessAcctId="WA_BUSINESS_ACCOUNT_ID",f.APIVersion="CLOUD_API_VERSION",f.AccessToken="CLOUD_API_ACCESS_TOKEN",f.WebhookEndpoint="WEBHOOK_ENDPOINT",f.WebhookVerificationToken="WEBHOOK_VERIFICATION_TOKEN",f.ListenerPort="LISTENER_PORT",f.MaxRetriesAfterWait="MAX_RETRIES_AFTER_WAIT",f.RequestTimeout="REQUEST_TIMEOUT",f.Debug="DEBUG",f))(P||{}),z=(i=>(i.BusinessInitiated="business_initiated",i.CustomerInitiated="customer_initiated",i.ReferralConversion="referral_conversion",i))(z||{}),E=(i=>(i.Delivered="delivered",i.Read="read",i.Sent="sent",i))(E||{}),C=(s=>(s.Mp4="video/mp4",s.Threegp="video/3gp",s))(C||{}),ee=(t=>(t.Webp="image/webp",t))(ee||{}),te=(s=>(s.Jpeg="image/jpeg",s.Png="image/png",s))(te||{}),se=(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))(se||{}),ie=(n=>(n.Aac="audio/aac",n.Mp4="audio/mp4",n.Mpeg="audio/mpeg",n.Amr="audio/amr",n.Ogg="audio/ogg",n))(ie||{}),oe=(_=>(_.Audio="audio",_.Button="button",_.Document="document",_.Text="text",_.Image="image",_.Interactive="interactive",_.Order="order",_.Sticker="sticker",_.System="system",_.Unknown="unknown",_.Video="video",_))(oe||{}),re=(s=>(s.CustomerChangedNumber="customer_changed_number",s.CustomerIdentityChanged="customer_identity_changed",s))(re||{}),ae=(s=>(s.Ad="ad",s.Post="post",s))(ae||{}),ne=(s=>(s.Sms="SMS",s.Voice="VOICE",s))(ne||{}),pe=(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))(pe||{}),le=(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))(le||{}),ce=(f=>(f.AU="AU",f.ID="ID",f.IN="IN",f.JP="JP",f.SG="SG",f.KR="KR",f.DE="DE",f.CH="CH",f.GB="GB",f.BR="BR",f.BH="BH",f.ZA="ZA",f.AE="AE",f.CA="CA",f))(ce||{}),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 Pe=(n=>(n.Draft="DRAFT",n.Published="PUBLISHED",n.Throttled="THROTTLED",n.Blocked="BLOCKED",n.Deprecated="DEPRECATED",n))(Pe||{}),be=(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))(be||{});var Ae=(o=>(o.Approved="APPROVED",o.Active="ACTIVE",o.Inactive="INACTIVE",o.Disabled="DISABLED",o))(Ae||{}),_e=(i=>(i.Blocked="BLOCKED",i.Limited="LIMITED",i.Available="AVAILABLE",i))(_e||{}),Te=(o=>(o.Approved="APPROVED",o.Active="ACTIVE",o.Inactive="INACTIVE",o.Disabled="DISABLED",o))(Te||{}),Se=(o=>(o.Verified="verified",o.PendingSubmission="pending_submission",o.Unverified="unverified",o.Rejected="rejected",o))(Se||{});var Ie=(i=>(i.DELIVERED="delivered",i.READ="read",i.SENT="sent",i))(Ie||{}),de=(g=>(g.MESSAGES="messages",g.STATUSES="statuses",g.MESSAGE_TEMPLATE_STATUS_UPDATE="message_template_status_update",g.PHONE_NUMBER_QUALITY_UPDATE="phone_number_quality_update",g.PHONE_NUMBER_NAME_UPDATE="phone_number_name_update",g.UNKNOWN="unknown",g))(de||{});var we=Fe(require("crypto")),ye=(r,t)=>we.createHmac("sha256",t).update(r,"utf-8").digest("hex");var h=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 We="UTILS",Ge=!1,Me=new h(We,process.env.DEBUG==="true"||Ge),He="graph.facebook.com",Le=3e3,Je=30,Ke=2e4,ke=r=>{if(!process.env.CLOUD_API_ACCESS_TOKEN&&!r?.accessToken)throw Me.log("Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined."),new Error("Missing WhatsApp access token.")},W=r=>{ke(r);let t={WA_BASE_URL:process.env.WA_BASE_URL||He,M4D_APP_ID:process.env.M4D_APP_ID||"",M4D_APP_SECRET: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:process.env.CLOUD_API_VERSION||"",CLOUD_API_ACCESS_TOKEN:r?.accessToken||process.env.CLOUD_API_ACCESS_TOKEN||"",WEBHOOK_ENDPOINT:process.env.WEBHOOK_ENDPOINT||"",WEBHOOK_VERIFICATION_TOKEN:process.env.WEBHOOK_VERIFICATION_TOKEN||"",LISTENER_PORT:parseInt(process.env.LISTENER_PORT||"")||Le,MAX_RETRIES_AFTER_WAIT:parseInt(process.env.MAX_RETRIES_AFTER_WAIT||"")||Je,REQUEST_TIMEOUT:parseInt(process.env.REQUEST_TIMEOUT||"")||Ke,DEBUG:process.env.DEBUG==="true"};return Me.log(`Configuration loaded for App Id ${t.M4D_APP_ID}`),t};function k(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}`:""};var $e="BaseAPI",ue=!1,je=new h($e,process.env.DEBUG==="true"||ue),d=class{config;client;constructor(t,s){this.config=t,this.client=s,je.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 $(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 w=class extends d{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}${$(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 d{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 Ve="FlowAPI",Xe=!1,Ne=new h(Ve,process.env.DEBUG==="true"||Xe),N=class extends d{constructor(t,s){super(t,s),Ne.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 Ne.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 d{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 d{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,g;return typeof s=="string"?g={body:s,preview_url:i}:g=s,this.send(JSON.stringify(this.bodyBuilder("text",g,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 B=class extends d{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 d{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 d{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 U=class extends d{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 F=class extends d{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 d{constructor(t,s){super(t,s)}async getWabaAccount(t){let s=$(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 Oe=require("https");var Ye="HttpsClient",Ze=!1,Qe=new h(Ye,process.env.DEBUG==="true"||Ze),G=class{agent;constructor(){this.agent=new Oe.Agent({keepAlive:!0})}clearSockets(){return this.agent.destroy(),!0}async sendRequest(t,s,i,o,n,g){let p=`https://${t}/${s}`,l=new AbortController,c=setTimeout(()=>l.abort(),n);try{let b=await fetch(p,{method:i,headers:o,body:g,signal:l.signal});return Qe.log(`${i} : ${p} - ${JSON.stringify(b)}`),clearTimeout(c),new me(b)}catch(b){throw b}}},me=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 ze="REQUESTER",Ee=!1,Ce=new h(ze,process.env.DEBUG==="true"||Ee),H=class{client;accessToken;phoneNumberId;businessAcctId;apiVersion;userAgent;host;protocol="https:";constructor(t,s,i,o,n,g){this.client=new G,this.host=t||"graph.facebook.com",this.apiVersion=s||"22",this.phoneNumberId=i,this.accessToken=o,this.businessAcctId=n,this.userAgent=g}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",g){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)}`;Ce.log(`${t} : ${l} (${p})`);try{let c=await this.client.sendRequest(this.host,this.buildCAPIPath(s),t,this.buildHeader(p,g),i,t==="POST"||t==="PUT"?o:void 0);if(!c.rawResponse().ok){let b=await c.json();throw k(b)?b:{name:"MetaError",message:"Unknown error occurred",error:{message:b.message||"Unknown error occurred",type:"UnknownError",code:c.statusCode(),fbtrace_id:""}}}return c}catch(c){throw k(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 g=new URLSearchParams(o).toString();return await(await this.sendRequest(t,s,i,g,"application/x-www-form-urlencoded",n)).json()}};var et="WHATSAPP",tt=!1,L=new h(et,process.env.DEBUG==="true"||tt),st="WA_SDK",I=class{config;requester;messages;templates;phoneNumber;qrCode;encryption;twoStepVerification;registration;media;waba;flow;businessProfile;static Enums=fe;constructor(t){this.config=W(t),this.requester=new H(this.config.WA_BASE_URL,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 U(this.config,this.requester),this.phoneNumber=new B(this.config,this.requester),this.qrCode=new v(this.config,this.requester),this.encryption=new M(this.config,this.requester),this.twoStepVerification=new F(this.config,this.requester),this.registration=new x(this.config,this.requester),this.media=new O(this.config,this.requester),this.waba=new q(this.config,this.requester),this.flow=new N(this.config,this.requester),this.businessProfile=new w(this.config,this.requester),L.log("WhatsApp Node.js SDK instantiated!")}userAgent(){return`${st}/0.0.1 (Node.js ${process.version})`}updateTimeout(t){return this.config.REQUEST_TIMEOUT=t,L.log(`Updated request timeout to ${t}ms`),!0}updatePhoneNumberId(t){return this.config.WA_PHONE_NUMBER_ID=t,L.log(`Updated sender phone number id to ${t}`),!0}updateAccessToken(t){return this.config.CLOUD_API_ACCESS_TOKEN=t,L.log("Updated access token"),!0}updateWabaId(t){return this.config.WA_BUSINESS_ACCOUNT_ID=t,L.log(`Updated business account id to ${t}`),!0}};var it="WEBHOOK",ot=!1,T=new h(it,process.env.DEBUG==="true"||ot),J=class{config;client;messageHandlers=new Map;eventHandlers=new Map;preProcessHandler=null;postProcessHandler=null;constructor(t){let s=W(t);this.config=s,this.client=new I(t),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?(T.log("Webhook verified successfully"),s.status(200).send(n)):(T.log("Webhook verification failed"),s.status(403).end())}async handleWebhookRequest(t,s){let i=t.body;if(i.object!=="whatsapp_business_account"){T.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 g of n)g.field==="messages"?await this.processMessages(g.value):await this.processEvent(g.field,g.value)}catch(n){T.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,g=t.messages;if(g&&g.length>0)for(let p of g){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 b=this.messageHandlers.get(l);b&&await Promise.resolve(b(this.client,c))}if(this.messageHandlers.has("*")){let b=this.messageHandlers.get("*");b&&await Promise.resolve(b(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),T.log(`Registered handler for message type: ${t}`)}onEvent(t,s){this.eventHandlers.set(t,s),T.log(`Registered handler for event field: ${t}`)}onMessagePreProcess(t){this.preProcessHandler=t,T.log("Registered pre-processing handler for all messages")}onMessagePostProcess(t){this.postProcessHandler=t,T.log("Registered post-processing handler for all messages")}};var rt=I;0&&(module.exports={AudioMediaTypesEnum,BusinessVerticalEnum,ButtonPositionEnum,ButtonTypesEnum,CategoryEnum,ComponentTypesEnum,ConversationTypesEnum,CurrencyCodesEnum,DataLocalizationRegionEnum,DocumentMediaTypesEnum,EventField,FlowCategoryEnum,FlowStatusEnum,HttpMethodsEnum,ImageMediaTypesEnum,InteractiveTypesEnum,LanguagesEnum,MessageStatus,MessageTypesEnum,ParametersTypesEnum,ReferralSourceTypesEnum,RequestCodeMethodsEnum,StatusEnum,StickerMediaTypesEnum,SystemChangeTypesEnum,TemplateStatusEnum,VideoMediaTypesEnum,WabaAccountReviewStatus,WabaAccountStatus,WabaBusinessVerificationStatus,WabaConfigEnum,WabaHealthStatusCanSendMessage,WebhookHandler,WebhookTypesEnum,generateXHub256Sig,importConfig,isMetaError,objectToQueryString});
|
|
1
|
+
"use strict";var De=Object.create;var K=Object.defineProperty;var Be=Object.getOwnPropertyDescriptor;var ve=Object.getOwnPropertyNames;var xe=Object.getPrototypeOf,Ue=Object.prototype.hasOwnProperty;var he=(r,t)=>{for(var s in t)K(r,s,{get:t[s],enumerable:!0})},Re=(r,t,s,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ve(t))!Ue.call(r,o)&&o!==s&&K(r,o,{get:()=>t[o],enumerable:!(i=Be(t,o))||i.enumerable});return r};var Fe=(r,t,s)=>(s=r!=null?De(xe(r)):{},Re(t||!r||!r.__esModule?K(s,"default",{value:r,enumerable:!0}):s,r)),qe=r=>Re(K({},"__esModule",{value:!0}),r);var at={};he(at,{AudioMediaTypesEnum:()=>ie,BusinessVerticalEnum:()=>ge,ButtonPositionEnum:()=>Z,ButtonTypesEnum:()=>Y,CategoryEnum:()=>u,ComponentTypesEnum:()=>Q,ConversationTypesEnum:()=>z,CurrencyCodesEnum:()=>le,DataLocalizationRegionEnum:()=>ce,DocumentMediaTypesEnum:()=>se,EventField:()=>fe,FlowCategoryEnum:()=>be,FlowStatusEnum:()=>Pe,HttpMethodsEnum:()=>A,ImageMediaTypesEnum:()=>te,InteractiveTypesEnum:()=>X,LanguagesEnum:()=>pe,MessageStatus:()=>Ie,MessageTypesEnum:()=>y,ParametersTypesEnum:()=>V,ReferralSourceTypesEnum:()=>ae,RequestCodeMethodsEnum:()=>ne,StatusEnum:()=>E,StickerMediaTypesEnum:()=>ee,SystemChangeTypesEnum:()=>re,TemplateStatusEnum:()=>j,VideoMediaTypesEnum:()=>C,WabaAccountReviewStatus:()=>Ae,WabaAccountStatus:()=>Te,WabaBusinessVerificationStatus:()=>Se,WabaConfigEnum:()=>P,WabaHealthStatusCanSendMessage:()=>_e,WebhookHandler:()=>J,WebhookTypesEnum:()=>oe,default:()=>rt,generateXHub256Sig:()=>ye,importConfig:()=>W,isMetaError:()=>k,objectToQueryString:()=>S});module.exports=qe(at);var de={};he(de,{AudioMediaTypesEnum:()=>ie,BusinessVerticalEnum:()=>ge,ButtonPositionEnum:()=>Z,ButtonTypesEnum:()=>Y,CategoryEnum:()=>u,ComponentTypesEnum:()=>Q,ConversationTypesEnum:()=>z,CurrencyCodesEnum:()=>le,DataLocalizationRegionEnum:()=>ce,DocumentMediaTypesEnum:()=>se,HttpMethodsEnum:()=>A,ImageMediaTypesEnum:()=>te,InteractiveTypesEnum:()=>X,LanguagesEnum:()=>pe,MessageTypesEnum:()=>y,ParametersTypesEnum:()=>V,ReferralSourceTypesEnum:()=>ae,RequestCodeMethodsEnum:()=>ne,StatusEnum:()=>E,StickerMediaTypesEnum:()=>ee,SystemChangeTypesEnum:()=>re,TemplateStatusEnum:()=>j,VideoMediaTypesEnum:()=>C,WabaConfigEnum:()=>P,WebhookTypesEnum:()=>oe});var u=(i=>(i.Authentication="AUTHENTICATION",i.Marketing="MARKETING",i.Utility="UTILITY",i))(u||{}),j=(i=>(i.Approved="APPROVED",i.Pending="PENDING",i.Rejected="REJECTED",i))(j||{}),A=(o=>(o.Get="GET",o.Post="POST",o.Put="PUT",o.Delete="DELETE",o))(A||{}),y=(R=>(R.Audio="audio",R.Contacts="contacts",R.Document="document",R.Image="image",R.Interactive="interactive",R.Location="location",R.Reaction="sticker",R.Sticker="sticker",R.Template="template",R.Text="text",R.Video="video",R.Button="button",R.Order="order",R.System="system",R.Unknown="unknown",R["*"]="*",R))(y||{}),V=(p=>(p.Currency="currency",p.DateTime="date_time",p.Document="document",p.Image="image",p.Text="text",p.Video="video",p.Payload="payload",p))(V||{}),X=(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))(X||{}),Y=(s=>(s.QuickReply="quick_reply",s.URL="url",s))(Y||{}),Z=(i=>(i[i.First=0]="First",i[i.Second=1]="Second",i[i.Third=2]="Third",i))(Z||{}),Q=(o=>(o.Header="HEADER",o.Body="BODY",o.Button="BUTTON",o.Footer="FOOTER",o))(Q||{}),P=(d=>(d.BaseURL="WA_BASE_URL",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))(P||{}),z=(i=>(i.BusinessInitiated="business_initiated",i.CustomerInitiated="customer_initiated",i.ReferralConversion="referral_conversion",i))(z||{}),E=(i=>(i.Delivered="delivered",i.Read="read",i.Sent="sent",i))(E||{}),C=(s=>(s.Mp4="video/mp4",s.Threegp="video/3gp",s))(C||{}),ee=(t=>(t.Webp="image/webp",t))(ee||{}),te=(s=>(s.Jpeg="image/jpeg",s.Png="image/png",s))(te||{}),se=(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))(se||{}),ie=(n=>(n.Aac="audio/aac",n.Mp4="audio/mp4",n.Mpeg="audio/mpeg",n.Amr="audio/amr",n.Ogg="audio/ogg",n))(ie||{}),oe=(_=>(_.Audio="audio",_.Button="button",_.Document="document",_.Text="text",_.Image="image",_.Interactive="interactive",_.Order="order",_.Sticker="sticker",_.System="system",_.Unknown="unknown",_.Video="video",_))(oe||{}),re=(s=>(s.CustomerChangedNumber="customer_changed_number",s.CustomerIdentityChanged="customer_identity_changed",s))(re||{}),ae=(s=>(s.Ad="ad",s.Post="post",s))(ae||{}),ne=(s=>(s.Sms="SMS",s.Voice="VOICE",s))(ne||{}),pe=(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))(pe||{}),le=(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))(le||{}),ce=(d=>(d.AU="AU",d.ID="ID",d.IN="IN",d.JP="JP",d.SG="SG",d.KR="KR",d.DE="DE",d.CH="CH",d.GB="GB",d.BR="BR",d.BH="BH",d.ZA="ZA",d.AE="AE",d.CA="CA",d))(ce||{}),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 Pe=(n=>(n.Draft="DRAFT",n.Published="PUBLISHED",n.Throttled="THROTTLED",n.Blocked="BLOCKED",n.Deprecated="DEPRECATED",n))(Pe||{}),be=(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))(be||{});var Ae=(o=>(o.Approved="APPROVED",o.Active="ACTIVE",o.Inactive="INACTIVE",o.Disabled="DISABLED",o))(Ae||{}),_e=(i=>(i.Blocked="BLOCKED",i.Limited="LIMITED",i.Available="AVAILABLE",i))(_e||{}),Te=(o=>(o.Approved="APPROVED",o.Active="ACTIVE",o.Inactive="INACTIVE",o.Disabled="DISABLED",o))(Te||{}),Se=(o=>(o.Verified="verified",o.PendingSubmission="pending_submission",o.Unverified="unverified",o.Rejected="rejected",o))(Se||{});var Ie=(i=>(i.DELIVERED="delivered",i.READ="read",i.SENT="sent",i))(Ie||{}),fe=(g=>(g.MESSAGES="messages",g.STATUSES="statuses",g.MESSAGE_TEMPLATE_STATUS_UPDATE="message_template_status_update",g.PHONE_NUMBER_QUALITY_UPDATE="phone_number_quality_update",g.PHONE_NUMBER_NAME_UPDATE="phone_number_name_update",g.UNKNOWN="unknown",g))(fe||{});var we=Fe(require("crypto")),ye=(r,t)=>we.createHmac("sha256",t).update(r,"utf-8").digest("hex");var h=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 We="UTILS",Ge=!1,Me=new h(We,process.env.DEBUG==="true"||Ge),He="graph.facebook.com",Le=3e3,Je=30,Ke=2e4,ke=r=>{if(!process.env.CLOUD_API_ACCESS_TOKEN&&!r?.accessToken)throw Me.log("Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined."),new Error("Missing WhatsApp access token.")},W=r=>{ke(r);let t={WA_BASE_URL:r?.baseUrl||process.env.WA_BASE_URL||He,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||"")||Le,MAX_RETRIES_AFTER_WAIT:r?.maxRetriesAfterWait||parseInt(process.env.MAX_RETRIES_AFTER_WAIT||"")||Je,REQUEST_TIMEOUT:r?.requestTimeout||parseInt(process.env.REQUEST_TIMEOUT||"")||Ke,DEBUG:r?.debug||process.env.DEBUG==="true"};return Me.log(`Configuration loaded for App Id ${t.M4D_APP_ID}`),t};function k(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}`:""};var $e="BaseAPI",ue=!1,je=new h($e,process.env.DEBUG==="true"||ue),f=class{config;client;constructor(t,s){this.config=t,this.client=s,je.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 $(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 w=class extends f{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}${$(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 f{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 Ve="FlowAPI",Xe=!1,Ne=new h(Ve,process.env.DEBUG==="true"||Xe),N=class extends f{constructor(t,s){super(t,s),Ne.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 Ne.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 f{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 f{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,g;return typeof s=="string"?g={body:s,preview_url:i}:g=s,this.send(JSON.stringify(this.bodyBuilder("text",g,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 B=class extends f{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 f{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 f{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 U=class extends f{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 F=class extends f{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 f{constructor(t,s){super(t,s)}async getWabaAccount(t){let s=$(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 Oe=require("https");var Ye="HttpsClient",Ze=!1,Qe=new h(Ye,process.env.DEBUG==="true"||Ze),G=class{agent;constructor(){this.agent=new Oe.Agent({keepAlive:!0})}clearSockets(){return this.agent.destroy(),!0}async sendRequest(t,s,i,o,n,g){let p=`https://${t}/${s}`,l=new AbortController,c=setTimeout(()=>l.abort(),n);try{let b=await fetch(p,{method:i,headers:o,body:g,signal:l.signal});return Qe.log(`${i} : ${p} - ${JSON.stringify(b)}`),clearTimeout(c),new me(b)}catch(b){throw b}}},me=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 ze="REQUESTER",Ee=!1,Ce=new h(ze,process.env.DEBUG==="true"||Ee),H=class{client;accessToken;phoneNumberId;businessAcctId;apiVersion;userAgent;host;protocol="https:";constructor(t,s,i,o,n,g){this.client=new G,this.host=t||"graph.facebook.com",this.apiVersion=s||"22",this.phoneNumberId=i,this.accessToken=o,this.businessAcctId=n,this.userAgent=g}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",g){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)}`;Ce.log(`${t} : ${l} (${p})`);try{let c=await this.client.sendRequest(this.host,this.buildCAPIPath(s),t,this.buildHeader(p,g),i,t==="POST"||t==="PUT"?o:void 0);if(!c.rawResponse().ok){let b=await c.json();throw k(b)?b:{name:"MetaError",message:"Unknown error occurred",error:{message:b.message||"Unknown error occurred",type:"UnknownError",code:c.statusCode(),fbtrace_id:""}}}return c}catch(c){throw k(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 g=new URLSearchParams(o).toString();return await(await this.sendRequest(t,s,i,g,"application/x-www-form-urlencoded",n)).json()}};var et="WHATSAPP",tt=!1,L=new h(et,process.env.DEBUG==="true"||tt),st="WA_SDK",I=class{config;requester;messages;templates;phoneNumber;qrCode;encryption;twoStepVerification;registration;media;waba;flow;businessProfile;static Enums=de;constructor(t){this.config=W(t),this.requester=new H(this.config.WA_BASE_URL,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 U(this.config,this.requester),this.phoneNumber=new B(this.config,this.requester),this.qrCode=new v(this.config,this.requester),this.encryption=new M(this.config,this.requester),this.twoStepVerification=new F(this.config,this.requester),this.registration=new x(this.config,this.requester),this.media=new O(this.config,this.requester),this.waba=new q(this.config,this.requester),this.flow=new N(this.config,this.requester),this.businessProfile=new w(this.config,this.requester),L.log("WhatsApp Node.js SDK instantiated!")}userAgent(){return`${st}/0.0.1 (Node.js ${process.version})`}updateTimeout(t){return this.config.REQUEST_TIMEOUT=t,L.log(`Updated request timeout to ${t}ms`),!0}updatePhoneNumberId(t){return this.config.WA_PHONE_NUMBER_ID=t,L.log(`Updated sender phone number id to ${t}`),!0}updateAccessToken(t){return this.config.CLOUD_API_ACCESS_TOKEN=t,L.log("Updated access token"),!0}updateWabaId(t){return this.config.WA_BUSINESS_ACCOUNT_ID=t,L.log(`Updated business account id to ${t}`),!0}};var it="WEBHOOK",ot=!1,T=new h(it,process.env.DEBUG==="true"||ot),J=class{config;client;messageHandlers=new Map;eventHandlers=new Map;preProcessHandler=null;postProcessHandler=null;constructor(t){let s=W(t);this.config=s,this.client=new I(t),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?(T.log("Webhook verified successfully"),s.status(200).send(n)):(T.log("Webhook verification failed"),s.status(403).end())}async handleWebhookRequest(t,s){let i=t.body;if(i.object!=="whatsapp_business_account"){T.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 g of n)g.field==="messages"?await this.processMessages(g.value):await this.processEvent(g.field,g.value)}catch(n){T.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,g=t.messages;if(g&&g.length>0)for(let p of g){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 b=this.messageHandlers.get(l);b&&await Promise.resolve(b(this.client,c))}if(this.messageHandlers.has("*")){let b=this.messageHandlers.get("*");b&&await Promise.resolve(b(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),T.log(`Registered handler for message type: ${t}`)}onEvent(t,s){this.eventHandlers.set(t,s),T.log(`Registered handler for event field: ${t}`)}onMessagePreProcess(t){this.preProcessHandler=t,T.log("Registered pre-processing handler for all messages")}onMessagePostProcess(t){this.postProcessHandler=t,T.log("Registered post-processing handler for all messages")}};var rt=I;0&&(module.exports={AudioMediaTypesEnum,BusinessVerticalEnum,ButtonPositionEnum,ButtonTypesEnum,CategoryEnum,ComponentTypesEnum,ConversationTypesEnum,CurrencyCodesEnum,DataLocalizationRegionEnum,DocumentMediaTypesEnum,EventField,FlowCategoryEnum,FlowStatusEnum,HttpMethodsEnum,ImageMediaTypesEnum,InteractiveTypesEnum,LanguagesEnum,MessageStatus,MessageTypesEnum,ParametersTypesEnum,ReferralSourceTypesEnum,RequestCodeMethodsEnum,StatusEnum,StickerMediaTypesEnum,SystemChangeTypesEnum,TemplateStatusEnum,VideoMediaTypesEnum,WabaAccountReviewStatus,WabaAccountStatus,WabaBusinessVerificationStatus,WabaConfigEnum,WabaHealthStatusCanSendMessage,WebhookHandler,WebhookTypesEnum,generateXHub256Sig,importConfig,isMetaError,objectToQueryString});
|
|
2
2
|
//# sourceMappingURL=index.js.map
|