meta-cloud-api 3.6.1 → 3.7.0
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/README.md +1 -0
- package/dist/index.d.mts +238 -6
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +4 -4
- package/dist/index.mjs.map +1 -1
- package/dist/types/index.d.ts +72 -4
- package/dist/types/index.d.ts.map +1 -1
- package/dist/utils/index.d.ts +2 -2
- package/dist/utils/index.js +1 -1
- package/dist/utils/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{t as e}from"./chunk.mjs";import{inspect as t}from"node:util";import*as n from"node:crypto";import r from"node:crypto";import{Agent as i}from"node:https";import{readFileSync as a}from"node:fs";import{join as o}from"node:path";const s=`whatsapp`;var c=class{config;client;constructor(e,t){this.config=e,this.client=t}sendJson(e,t,n,r){return this.client.getJson(e,t,n,r)}sendFormData(e,t,n,r){return this.client.sendFormData(e,t,n,r)}sendUrlEncodedForm(e,t,n,r){return this.client.sendUrlEncodedForm(e,t,n,r)}},l=e({AudioMediaTypesEnum:()=>le,BusinessVerticalEnum:()=>_e,ButtonPositionEnum:()=>_,CategoryEnum:()=>u,ComponentTypesEnum:()=>te,ConversationTypesEnum:()=>re,CurrencyCodesEnum:()=>he,DataLocalizationRegionEnum:()=>ge,DocumentMediaTypesEnum:()=>ce,HttpMethodsEnum:()=>p,ImageMediaTypesEnum:()=>se,InteractiveTypesEnum:()=>g,LanguagesEnum:()=>me,MessageCategoryEnum:()=>d,MessageTypesEnum:()=>m,ParametersTypesEnum:()=>h,ReferralSourceTypesEnum:()=>fe,RequestCodeMethodsEnum:()=>pe,StatusEnum:()=>ie,StickerMediaTypesEnum:()=>oe,SubTypeEnum:()=>ee,SystemChangeTypesEnum:()=>de,TemplateStatusEnum:()=>f,VideoMediaTypesEnum:()=>ae,WabaConfigEnum:()=>ne,WebhookTypesEnum:()=>ue});let u=function(e){return e.Authentication=`AUTHENTICATION`,e.Marketing=`MARKETING`,e.Utility=`UTILITY`,e}({}),d=function(e){return e.Authentication=`authentication`,e.Service=`service`,e.Utility=`utility`,e}({}),f=function(e){return e.Approved=`APPROVED`,e.Pending=`PENDING`,e.Rejected=`REJECTED`,e}({}),p=function(e){return e.Get=`GET`,e.Post=`POST`,e.Put=`PUT`,e.Delete=`DELETE`,e}({}),m=function(e){return e.Audio=`audio`,e.Contacts=`contacts`,e.Document=`document`,e.Image=`image`,e.Interactive=`interactive`,e.Location=`location`,e.Reaction=`reaction`,e.Sticker=`sticker`,e.Template=`template`,e.Text=`text`,e.Video=`video`,e.Button=`button`,e.Order=`order`,e.System=`system`,e.Edit=`edit`,e.Revoke=`revoke`,e.Unsupported=`unsupported`,e.Unknown=`unknown`,e.Statuses=`statuses`,e[`*`]=`*`,e}({}),h=function(e){return e.Action=`ACTION`,e.CouponCode=`COUPON_CODE`,e.Currency=`CURRENCY`,e.DateTime=`DATE_TIME`,e.Document=`DOCUMENT`,e.ExpirationTimeMs=`EXPIRATION_TIME_MS`,e.Image=`IMAGE`,e.LimitedTimeOffer=`LIMITED_TIME_OFFER`,e.Location=`LOCATION`,e.OrderStatus=`ORDER_STATUS`,e.Payload=`PAYLOAD`,e.Product=`PRODUCT`,e.Text=`TEXT`,e.TtlMinutes=`TTL_MINUTES`,e.Video=`VIDEO`,e.WebviewInteraction=`WEBVIEW_INTERACTION`,e.WebviewPresentation=`WEBVIEW_PRESENTATION`,e}({}),g=function(e){return e.Button=`button`,e.List=`list`,e.Product=`product`,e.ProductList=`product_list`,e.CatalogMessage=`catalog_message`,e.CallPermissionRequest=`call_permission_request`,e.CtaUrl=`cta_url`,e.Carousel=`carousel`,e.LocationRequest=`location_request_message`,e.AddressMessage=`address_message`,e.Flow=`flow`,e.VoiceCall=`voice_call`,e}({}),_=function(e){return e[e.First=1]=`First`,e[e.Second=2]=`Second`,e[e.Third=3]=`Third`,e[e.Fourth=4]=`Fourth`,e[e.Fifth=5]=`Fifth`,e}({}),ee=function(e){return e.Catalog=`CATALOG`,e.CopyCode=`COPY_CODE`,e.Flow=`FLOW`,e.Mpm=`MPM`,e.OrderDetails=`ORDER_DETAILS`,e.PhoneNumber=`PHONE_NUMBER`,e.QuickReply=`QUICK_REPLY`,e.Reminder=`REMINDER`,e.Url=`URL`,e.VoiceCall=`VOICE_CALL`,e}({}),te=function(e){return e.Header=`HEADER`,e.Body=`BODY`,e.Button=`BUTTON`,e.Footer=`FOOTER`,e}({}),ne=function(e){return e.AppId=`M4D_APP_ID`,e.Port=`WA_PORT`,e.AppSecret=`M4D_APP_SECRET`,e.PhoneNumberId=`WA_PHONE_NUMBER_ID`,e.BusinessAcctId=`WA_BUSINESS_ACCOUNT_ID`,e.APIVersion=`CLOUD_API_VERSION`,e.AccessToken=`CLOUD_API_ACCESS_TOKEN`,e.WebhookEndpoint=`WEBHOOK_ENDPOINT`,e.WebhookVerificationToken=`WEBHOOK_VERIFICATION_TOKEN`,e.ListenerPort=`LISTENER_PORT`,e.MaxRetriesAfterWait=`MAX_RETRIES_AFTER_WAIT`,e.RequestTimeout=`REQUEST_TIMEOUT`,e.Debug=`DEBUG`,e.PrivatePem=`FLOW_API_PRIVATE_PEM`,e.Passphrase=`FLOW_API_PASSPHRASE`,e}({}),re=function(e){return e.BusinessInitiated=`business_initiated`,e.CustomerInitiated=`customer_initiated`,e.ReferralConversion=`referral_conversion`,e}({}),ie=function(e){return e.Delivered=`delivered`,e.Read=`read`,e.Sent=`sent`,e}({}),ae=function(e){return e.Mp4=`video/mp4`,e.Threegp=`video/3gp`,e}({}),oe=function(e){return e.Webp=`image/webp`,e}({}),se=function(e){return e.Jpeg=`image/jpeg`,e.Png=`image/png`,e}({}),ce=function(e){return e.Text=`text/plain`,e.Pdf=`application/pdf`,e.Ppt=`application/vnd.ms-powerpoint`,e.Word=`application/msword`,e.Excel=`application/vnd.ms-excel`,e.OpenDoc=`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,e.OpenPres=`application/vnd.openxmlformats-officedocument.presentationml.presentation`,e.OpenSheet=`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,e}({}),le=function(e){return e.Aac=`audio/aac`,e.Mp4=`audio/mp4`,e.Mpeg=`audio/mpeg`,e.Amr=`audio/amr`,e.Ogg=`audio/ogg`,e}({}),ue=function(e){return e.Audio=`audio`,e.Button=`button`,e.Document=`document`,e.Text=`text`,e.Image=`image`,e.Interactive=`interactive`,e.Order=`order`,e.Sticker=`sticker`,e.System=`system`,e.Unknown=`unknown`,e.Video=`video`,e}({}),de=function(e){return e.CustomerChangedNumber=`customer_changed_number`,e.CustomerIdentityChanged=`customer_identity_changed`,e.UserChangedNumber=`user_changed_number`,e.UserIdentityChanged=`user_identity_changed`,e.UserChangedUserId=`user_changed_user_id`,e}({}),fe=function(e){return e.Ad=`ad`,e.Post=`post`,e}({}),pe=function(e){return e.Sms=`SMS`,e.Voice=`VOICE`,e}({}),me=function(e){return e.Afrikaans=`af`,e.Albanian=`sq`,e.Arabic=`ar`,e.Azerbaijani=`az`,e.Bengali=`bn`,e.Bulgarian=`bg`,e.Catalan=`ca`,e.Chinese_CHN=`zh_CN`,e.Chinese_HKG=`zh_HK`,e.Chinese_TAI=`zh_TW`,e.Croatian=`hr`,e.Czech=`cs`,e.Danish=`da`,e.Dutch=`nl`,e.English=`en`,e.English_UK=`en_GB`,e.English_US=`en_US`,e.Estonian=`et`,e.Filipino=`fil`,e.Finnish=`fi`,e.French=`fr`,e.Georgian=`ka`,e.German=`de`,e.Greek=`el`,e.Gujarati=`gu`,e.Hausa=`ha`,e.Hebrew=`he`,e.Hindi=`hi`,e.Hungarian=`hu`,e.Indonesian=`id`,e.Irish=`ga`,e.Italian=`it`,e.Japanese=`ja`,e.Kannada=`kn`,e.Kazakh=`kk`,e.Kinyarwanda=`rw_RW`,e.Korean=`ko`,e.Kyrgyz_Kyrgyzstan=`ky_KG`,e.Lao=`lo`,e.Latvian=`lv`,e.Lithuanian=`lt`,e.Macedonian=`mk`,e.Malay=`ms`,e.Malayalam=`ml`,e.Marathi=`mr`,e.Norwegian=`nb`,e.Persian=`fa`,e.Polish=`pl`,e.Portuguese_BR=`pt_BR`,e.Portuguese_POR=`pt_PT`,e.Punjabi=`pa`,e.Romanian=`ro`,e.Russian=`ru`,e.Serbian=`sr`,e.Slovak=`sk`,e.Slovenian=`sl`,e.Spanish=`es`,e.Spanish_ARG=`es_AR`,e.Spanish_SPA=`es_ES`,e.Spanish_MEX=`es_MX`,e.Swahili=`sw`,e.Swedish=`sv`,e.Tamil=`ta`,e.Telugu=`te`,e.Thai=`th`,e.Turkish=`tr`,e.Ukrainian=`uk`,e.Urdu=`ur`,e.Uzbek=`uz`,e.Vietnamese=`vi`,e.Zulu=`zu`,e}({}),he=function(e){return 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}({}),ge=function(e){return e.AU=`AU`,e.ID=`ID`,e.IN=`IN`,e.JP=`JP`,e.SG=`SG`,e.KR=`KR`,e.DE=`DE`,e.CH=`CH`,e.GB=`GB`,e.BR=`BR`,e.BH=`BH`,e.ZA=`ZA`,e.AE=`AE`,e.CA=`CA`,e}({}),_e=function(e){return e.ALCOHOL=`ALCOHOL`,e.APPAREL=`APPAREL`,e.AUTO=`AUTO`,e.BEAUTY=`BEAUTY`,e.EDU=`EDU`,e.ENTERTAIN=`ENTERTAIN`,e.EVENT_PLAN=`EVENT_PLAN`,e.FINANCE=`FINANCE`,e.GOVT=`GOVT`,e.GROCERY=`GROCERY`,e.HEALTH=`HEALTH`,e.HOTEL=`HOTEL`,e.NONPROFIT=`NONPROFIT`,e.ONLINE_GAMBLING=`ONLINE_GAMBLING`,e.OTC_DRUGS=`OTC_DRUGS`,e.OTHER=`OTHER`,e.PHYSICAL_GAMBLING=`PHYSICAL_GAMBLING`,e.PROF_SERVICES=`PROF_SERVICES`,e.RESTAURANT=`RESTAURANT`,e.RETAIL=`RETAIL`,e.TRAVEL=`TRAVEL`,e}({});const v=e=>{if(!e||Object.keys(e).length===0)return``;let t=[];for(let[n,r]of Object.entries(e))if(r!==void 0){let e=encodeURIComponent(n),i=encodeURIComponent(String(r));t.push(`${e}=${i}`)}return t.length>0?`?${t.join(`&`)}`:``},ve=[0,1,2,3,4,10,33,100,190,200,299,368,613,80007,130429,130472,130497,131e3,131005,131008,131009,131016,131020,131021,131026,131030,131031,131037,131041,131042,131044,131045,131047,131048,131049,131050,131051,131052,131053,131055,131056,131057,131059,131061,131062,131201,131202,131203,131204,131207,131208,131209,131210,131211,131212,131213,131214,131215,132e3,132001,132005,132007,132008,132012,132015,132016,132068,132069,133e3,133004,133005,133006,133008,133009,133010,133015,133016,134011,134100,134101,134102,135e3,137e3,138e3,138001,138002,138003,138004,138005,138006,138007,138009,138012,138013,138018,139e3,139001,139002,139003,139004,139100,139101,139102,139103,147005,200005,200006,200007,1752041,2388001,2388012,2388019,2388040,2388047,2388072,2388073,2388091,2388093,2388103,2388293,2388299,2494100,2593079,2593085,2593107,2593108],ye=new Set(ve),be=[0,3,10,190],xe=[4,80007,130429,131048,131056],Se=[368,130497,131031],Ce=[130472,131e3,131005,131008,131009,131016,131021,131026,131030,131042,131044,131045,131047,131050,131051,131052,131053,131056,131057,131048,131061,131062,132e3,132001,132005,132007,132008,132012,132015,132016,132068,132069,135e3,137e3],we=[139e3,139001,139002,139003,139004],Te=[139100,139101,139102,139103],Ee=[138e3,138001,138002,138003,138004,138005,138006,138007,138009,138012,138013,138018,613],De=[131020,131041,131059,131201,131202,131203,131204,131207,131208,131209,131210,131211,131212,131213,131214,131215],Oe=new Set(be),ke=new Set(xe),Ae=new Set(Se),je=new Set(Ce),Me=new Set(we),Ne=new Set(Te),Pe=new Set(Ee),Fe=new Set(De);function Ie(e){return y(e)?!0:ye.has(e)}function y(e){return e>=200&&e<300}function Le(e){return y(e)||Oe.has(e)}function Re(e){return ke.has(e)}function ze(e){return Ae.has(e)}function Be(e){return je.has(e)}function Ve(e){return Me.has(e)}function He(e){return Ne.has(e)}function Ue(e){return Pe.has(e)}function We(e){return Fe.has(e)}var b=class extends Error{constructor(e){super(e),this.name=`WhatsAppError`}},x=class extends b{error;statusCode;constructor(e,t,n){super(e),this.name=`WhatsAppApiError`,this.error=t,this.statusCode=n}},S=class extends x{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppAuthorizationError`}},C=class extends x{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppThrottlingError`}},w=class extends x{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppIntegrityError`}},T=class extends x{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppSendMessageError`}},E=class extends x{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppFlowError`}},D=class extends x{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppBlockUserError`}},O=class extends x{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppCallingError`}},k=class extends x{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppGroupError`}};function A(e,t){let n=e.code;return Le(n)?new S(e.message,e,t):Re(n)?new C(e.message,e,t):ze(n)?new w(e.message,e,t):Be(n)?new T(e.message,e,t):Ve(n)?new E(e.message,e,t):He(n)?new D(e.message,e,t):Ue(n)?new O(e.message,e,t):We(n)?new k(e.message,e,t):new x(e.message,e,t)}var Ge=class extends b{cause;constructor(e,t){super(e),this.name=`WhatsAppNetworkError`,this.cause=t}},Ke=class extends b{cause;constructor(e,t){super(e),this.name=`WhatsAppUnknownError`,this.cause=t}},j=class extends Error{constructor(e){super(e),this.name=`WhatsAppValidationError`}};function M(e){if(typeof e!=`object`||!e||!(`error`in e)||typeof e.error!=`object`||e.error==null)return!1;let t=e.error;if(typeof t.message!=`string`||typeof t.type!=`string`||typeof t.code!=`number`||typeof t.fbtrace_id!=`string`)return!1;if(`error_data`in t&&t.error_data!=null){if(typeof t.error_data!=`object`)return!1;let e=t.error_data;if(`messaging_product`in e&&e.messaging_product!==`whatsapp`||`details`in e&&typeof e.details!=`string`)return!1}return!(`error_subcode`in t&&typeof t.error_subcode!=`number`)}function qe(e){return M(e)&&Ie(e.error.code)}function Je(e){return e instanceof S}function Ye(e){return e instanceof C}function Xe(e){return e instanceof w}function Ze(e){return e instanceof T}function Qe(e){return e instanceof E}function $e(e){return e instanceof D}function et(e){return e instanceof O}function tt(e){return e instanceof k}function nt(e,t){if(M(e))return e;let n=`Unknown error occurred`;if(e&&typeof e==`object`&&`message`in e){let t=e.message;typeof t==`string`&&(n=t)}return{name:`MetaError`,message:n,error:{message:n,type:`UnknownError`,code:typeof t==`number`?t:500,fbtrace_id:``}}}function rt(e){if(!/^\+?\d{10,15}$/.test(e))throw new j(`Invalid phone number: "${e}". Expected E.164 format (e.g. +14155552671 or 14155552671).`)}function N(e,t){if(!e||e.length===0)throw new j(`"${t}" must contain at least one item.`)}var it=class extends c{endpoint=`block_users`;buildBlockUsersBody(e){return{messaging_product:s,block_users:e.map(e=>({user:e}))}}async block(e){N(e,`users`);let t=this.buildBlockUsersBody(e);return await this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async unblock(e){N(e,`users`);let t=this.buildBlockUsersBody(e);return await this.sendJson(`DELETE`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async listBlockedUsers(e){let t=`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`;if(e){let n=v(e);n&&(t+=n)}return await this.sendJson(`GET`,t,this.config.REQUEST_TIMEOUT)}},at=class extends c{toQuery(e){return e?v({fields:Array.isArray(e.fields)?e.fields.join(`,`):e.fields,filtering:Array.isArray(e.filtering)?JSON.stringify(e.filtering):e.filtering,sort:e.sort,limit:e.limit,after:e.after,before:e.before}):``}fieldsQuery(e){let t=Array.isArray(e)?e.join(`,`):e;return t?v({fields:t}):``}async getConnectedClientBusinesses(e=this.config.M4D_APP_ID,t){return this.sendJson(`GET`,`${e}/connected_client_businesses${this.toQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async addPhoneNumbers(e,t){return this.sendJson(`POST`,`${e}/add_phone_numbers`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getBusinessPortfolio(e,t){return this.sendJson(`GET`,`${e}${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async getPreVerifiedPhoneNumbers(e,t){return this.sendJson(`GET`,`${e}/preverified_numbers${this.toQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async getClientWhatsAppBusinessAccounts(e,t){return this.sendJson(`GET`,`${e}/client_whatsapp_business_accounts${this.toQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async onboardPartnersToMMLite(e,t){return this.sendJson(`POST`,`${e}/onboard_partners_to_mm_lite`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getOwnedWhatsAppBusinessAccounts(e,t){return this.sendJson(`GET`,`${e}/owned_whatsapp_business_accounts${this.toQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async sharePreVerifiedPhoneNumber(e,t){return this.sendJson(`POST`,`${e}/share_preverified_numbers`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getCreditLines(e){return this.sendJson(`GET`,`${e}/extendedcredits`,this.config.REQUEST_TIMEOUT,null)}async getAssignedWhatsAppBusinessAccounts(e,t){return this.sendJson(`GET`,`${e}/assigned_whatsapp_business_accounts${this.toQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async getWhatsAppAccountNumberDetails(e,t){return this.sendJson(`GET`,`${e}${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async getPreVerifiedPhoneNumberDetails(e,t){return this.sendJson(`GET`,`${e}${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async deletePreVerifiedPhoneNumber(e){return this.sendJson(`DELETE`,e,this.config.REQUEST_TIMEOUT,null)}async getPreVerifiedPhoneNumberPartners(e,t){return this.sendJson(`GET`,`${e}/partners${this.toQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async requestPreVerifiedPhoneNumberCode(e,t){return this.sendJson(`POST`,`${e}/request_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async verifyPreVerifiedPhoneNumberCode(e,t){return this.sendJson(`POST`,`${e}/verify_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}},ot=class extends c{endpoint=`calls`;async updateCallingSettings(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/settings`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getCallingSettings(e){let t=Array.isArray(e?.fields)?e?.fields.join(`,`):e?.fields,n=v({...t?{fields:t}:{},...e?.include_sip_credentials===void 0?{}:{include_sip_credentials:e.include_sip_credentials}});return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/settings${n}`,this.config.REQUEST_TIMEOUT,null)}async getCallPermissions(e){let t=v({user_wa_id:e.userWaId});return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/call_permissions${t}`,this.config.REQUEST_TIMEOUT,null)}async initiateCall(e){let t={messaging_product:s,to:e.to,action:`connect`,session:e.session};return e.biz_opaque_callback_data&&(t.biz_opaque_callback_data=e.biz_opaque_callback_data),e.recording&&(t.recording=e.recording),e.transcription&&(t.transcription=e.transcription),this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async preAcceptCall(e){let t={messaging_product:s,call_id:e.call_id,action:`pre_accept`};return e.session&&(t.session=e.session),this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async acceptCall(e){let t={messaging_product:s,call_id:e.call_id,action:`accept`};return e.session&&(t.session=e.session),e.biz_opaque_callback_data&&(t.biz_opaque_callback_data=e.biz_opaque_callback_data),e.recording&&(t.recording=e.recording),e.transcription&&(t.transcription=e.transcription),this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async rejectCall(e){let t={messaging_product:s,call_id:e.call_id,action:`reject`};return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async terminateCall(e){let t={messaging_product:s,call_id:e.call_id,action:`terminate`};return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}},st=class extends c{endpoint=`whatsapp_commerce_settings`;async getCommerceSettings(){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async updateCommerceSettings(e){let t=v(e);return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}${t}`,this.config.REQUEST_TIMEOUT,null)}},ct=class extends c{endpoint=`contact_book`;async deleteEntry(e){if(!e?.bsuid)throw new j(`"bsuid" is required to delete a contact book entry.`);let t=v({messaging_product:s,bsuid:e.bsuid});return await this.sendJson(`DELETE`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}${t}`,this.config.REQUEST_TIMEOUT)}},lt=class extends c{endpoint=`whatsapp_business_encryption`;async getEncryptionPublicKey(){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async setEncryptionPublicKey(e){let t=new FormData;return t.append(`business_public_key`,e),this.sendFormData(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,t)}},ut=class extends c{appendFormValue(e,t,n){n!==void 0&&e.append(t,Array.isArray(n)?JSON.stringify(n):String(n))}async listFlows(e){return this.sendJson(`GET`,`/${e}/flows`,this.config.REQUEST_TIMEOUT,null)}async createFlow(e,t){let n=new FormData;return this.appendFormValue(n,`name`,t.name),this.appendFormValue(n,`categories`,t.categories),this.appendFormValue(n,`endpoint_uri`,t.endpoint_uri),this.appendFormValue(n,`clone_flow_id`,t.clone_flow_id),this.appendFormValue(n,`flow_json`,t.flow_json),this.appendFormValue(n,`publish`,t.publish),this.sendFormData(`POST`,`/${e}/flows`,this.config.REQUEST_TIMEOUT,n)}async getFlow(e,t,n){let r=new URLSearchParams;t&&r.append(`fields`,t),n&&r.append(`date_format`,n);let i=r.toString()?`?${r.toString()}`:``;return this.sendJson(`GET`,`/${e}${i}`,this.config.REQUEST_TIMEOUT,null)}async getFlowPreview(e,t=!1){let n=`preview.invalidate(${t})`;return this.getFlow(e,n)}async updateFlowMetadata(e,t){let n=new FormData;return this.appendFormValue(n,`name`,t.name),this.appendFormValue(n,`categories`,t.categories),this.appendFormValue(n,`endpoint_uri`,t.endpoint_uri),this.appendFormValue(n,`application_id`,t.application_id),this.sendFormData(`POST`,`/${e}`,this.config.REQUEST_TIMEOUT,n)}async deleteFlow(e){return this.sendJson(`DELETE`,`/${e}`,this.config.REQUEST_TIMEOUT,null)}async listAssets(e){return this.sendJson(`GET`,`/${e}/assets`,this.config.REQUEST_TIMEOUT,null)}async updateFlowJson(e,t){let n=new FormData,r;if(t.file instanceof Buffer)r=new globalThis.Blob([new Uint8Array(t.file)]),n.append(`file`,r);else if(typeof t.file==`object`&&!(t.file instanceof Blob))try{r=new globalThis.Blob([JSON.stringify(t.file,null,2)],{type:`application/json`}),n.append(`file`,r)}catch{throw Error(`Failed to stringify JSON object for Flow JSON update.`)}else if(t.file instanceof Blob)r=t.file,n.append(`file`,r);else throw Error(`Invalid file type provided for Flow JSON update. Must be a Buffer, JSON object, or Blob.`);return n.append(`asset_type`,`FLOW_JSON`),n.append(`name`,t.name||`flow.json`),this.sendFormData(`POST`,`/${e}/assets`,this.config.REQUEST_TIMEOUT,n)}async validateFlowJson(e,t){let n=await this.updateFlowJson(e,{file:t}),r=!n.validation_errors||n.validation_errors.length===0;return{...n,valid:r}}async publishFlow(e){return this.sendJson(`POST`,`/${e}/publish`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async deprecateFlow(e){return this.sendJson(`POST`,`/${e}/deprecate`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async migrateFlows(e,t){let n=new FormData;return this.appendFormValue(n,`source_waba_id`,t.source_waba_id),this.appendFormValue(n,`source_flow_names`,t.source_flow_names),this.sendFormData(`POST`,`/${e}/migrate_flows`,this.config.REQUEST_TIMEOUT,n)}};let dt=function(e){return e.Draft=`DRAFT`,e.Published=`PUBLISHED`,e.Throttled=`THROTTLED`,e.Blocked=`BLOCKED`,e.Deprecated=`DEPRECATED`,e}({}),ft=function(e){return e.SignUp=`SIGN_UP`,e.SignIn=`SIGN_IN`,e.AppointmentBooking=`APPOINTMENT_BOOKING`,e.LeadGeneration=`LEAD_GENERATION`,e.ContactUs=`CONTACT_US`,e.CustomerSupport=`CUSTOMER_SUPPORT`,e.Survey=`SURVEY`,e.Other=`OTHER`,e}({}),pt=function(e){return e.INIT=`INIT`,e.BACK=`BACK`,e.DATA_EXCHANGE=`data_exchange`,e}({}),mt=function(e){return e.Ping=`ping`,e.Change=`data_exchange`,e.Error=`error`,e.All=`*`,e}({});var ht=class extends c{async createGroup(e){let t={messaging_product:s,subject:e.subject};return e.description&&(t.description=e.description),e.join_approval_mode&&(t.join_approval_mode=e.join_approval_mode),this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/groups`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async deleteGroup(e){return this.sendJson(`DELETE`,e,this.config.REQUEST_TIMEOUT,null)}async getGroupInfo(e,t){let n=Array.isArray(t)?t.join(`,`):t,r=n?v({fields:n}):``;return this.sendJson(`GET`,`${e}${r}`,this.config.REQUEST_TIMEOUT,null)}async getActiveGroups(e){let t=e?v(e):``;return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/groups${t}`,this.config.REQUEST_TIMEOUT,null)}async getGroupInviteLink(e){return this.sendJson(`GET`,`${e}/invite_link`,this.config.REQUEST_TIMEOUT,null)}async createGroupInviteLink(e){let t={messaging_product:s};return this.sendJson(`POST`,`${e}/invite_link`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async resetGroupInviteLink(e){let t={messaging_product:s};return this.sendJson(`POST`,`${e}/invite_link`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async deleteGroupInviteLink(e){let t={messaging_product:s};return this.sendJson(`DELETE`,`${e}/invite_link`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getJoinRequests(e){return this.sendJson(`GET`,`${e}/join_requests`,this.config.REQUEST_TIMEOUT,null)}async approveJoinRequests(e,t){let n={messaging_product:s,join_requests:t};return this.sendJson(`POST`,`${e}/join_requests`,this.config.REQUEST_TIMEOUT,JSON.stringify(n))}async rejectJoinRequests(e,t){let n={messaging_product:s,join_requests:t};return this.sendJson(`DELETE`,`${e}/join_requests`,this.config.REQUEST_TIMEOUT,JSON.stringify(n))}async addParticipants(e,t){N(t,`participants`);let n={messaging_product:s,participants:t.map(e=>({user:e}))};return this.sendJson(`POST`,`${e}/participants`,this.config.REQUEST_TIMEOUT,JSON.stringify(n))}async removeParticipants(e,t){N(t,`participants`);let n={messaging_product:s,participants:t.map(e=>({user:e}))};return this.sendJson(`DELETE`,`${e}/participants`,this.config.REQUEST_TIMEOUT,JSON.stringify(n))}async updateGroupSettings(e,t){if(t.profilePictureFile){let n=new FormData;if(n.append(`messaging_product`,s),t.subject&&n.append(`subject`,t.subject),t.description&&n.append(`description`,t.description),t.profilePictureFile instanceof Buffer){let e=new globalThis.Blob([new Uint8Array(t.profilePictureFile)],{type:`image/jpeg`});n.append(`file`,e)}else if(t.profilePictureFile instanceof Blob)n.append(`file`,t.profilePictureFile);else throw Error(`Invalid profile picture file type. Use a Buffer or Blob.`);return this.sendFormData(`POST`,e,this.config.REQUEST_TIMEOUT,n)}let n={messaging_product:s};return t.subject&&(n.subject=t.subject),t.description&&(n.description=t.description),this.sendJson(`POST`,e,this.config.REQUEST_TIMEOUT,JSON.stringify(n))}},gt=class extends c{endpoint=`marketing_messages`;async sendTemplateMessage(e){if(!e.to==!e.recipient)throw new j(`Provide exactly one of "to" (phone number) or "recipient" (BSUID).`);let t={messaging_product:s,recipient_type:`individual`,type:`template`,template:e.template};return e.to!==void 0&&(t.to=e.to),e.recipient!==void 0&&(t.recipient=e.recipient),e.message_activity_sharing!==void 0&&(t.message_activity_sharing=e.message_activity_sharing),e.product_policy!==void 0&&(t.product_policy=e.product_policy),e.bid_spec!==void 0&&(t.bid_spec=e.bid_spec),this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}},_t=class extends c{endpoint=`media`;async getMediaById(e){return this.sendJson(`GET`,`${e}`,this.config.REQUEST_TIMEOUT,null)}async uploadMedia(e,t=s){let n=new FormData;return n.append(`file`,e),n.append(`messaging_product`,t),n.append(`type`,e.type),this.sendFormData(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,n)}async deleteMedia(e){return this.sendJson(`DELETE`,`${e}`,this.config.REQUEST_TIMEOUT,null)}async downloadMedia(e){return this.sendJson(`GET`,e,this.config.REQUEST_TIMEOUT,null)}},vt=class extends c{resolveFields(e){return Array.isArray(e)?e.join(`,`):e}async getMessageHistory(e){let t=e?v({fields:this.resolveFields(e.fields),message_id:e.message_id,start_time:e.start_time,end_time:e.end_time,limit:e.limit,after:e.after,before:e.before}):``;return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/message_history${t}`,this.config.REQUEST_TIMEOUT,null)}async getMessageHistoryEvents(e,t){let n=t?v({fields:this.resolveFields(t.fields),status_filter:t.status_filter,limit:t.limit,after:t.after,before:t.before}):``;return this.sendJson(`GET`,`${e}/events${n}`,this.config.REQUEST_TIMEOUT,null)}},P=class extends c{commonMethod=`POST`;commonEndpoint=`messages`;bodyBuilder(e,t,n,r,i=`individual`,a){i===`individual`&&rt(n);let o={messaging_product:s,recipient_type:i,to:n,type:e,[e]:t};return r&&(o.context={message_id:r}),a?.category&&(o.category=a.category),a?.directSendConfig&&(o.direct_send_config=a.directSendConfig),o}send(e){return this.sendJson(this.commonMethod,`${this.config.WA_PHONE_NUMBER_ID}/${this.commonEndpoint}`,this.config.REQUEST_TIMEOUT,e)}sendEncrypted(e){return this.sendJson(this.commonMethod,`${this.config.WA_PHONE_NUMBER_ID}/messages_encrypted`,this.config.REQUEST_TIMEOUT,e)}async audio(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`audio`,t,n,r,i,{category:a,directSendConfig:o})))}async contacts(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`contacts`,t,n,r,i,{category:a,directSendConfig:o})))}async document(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`document`,t,n,r,i,{category:a,directSendConfig:o})))}async image(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`image`,t,n,r,i,{category:a,directSendConfig:o})))}async interactive(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`interactive`,t,n,r,i,{category:a,directSendConfig:o})))}async location(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`location`,t,n,r,i,{category:a,directSendConfig:o})))}async sticker(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`sticker`,t,n,r,i,{category:a,directSendConfig:o})))}async template(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`template`,t,n,r,i,{category:a,directSendConfig:o})))}async text(e){let{body:t,to:n,replyMessageId:r,previewUrl:i,recipientType:a,category:o,directSendConfig:s}=e,c=typeof t==`string`?{body:t,preview_url:i??!0}:{...t,preview_url:i??t.preview_url??!0};return this.send(JSON.stringify(this.bodyBuilder(`text`,c,n,r,a,{category:o,directSendConfig:s})))}async video(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`video`,t,n,r,i,{category:a,directSendConfig:o})))}async status(e){let t={messaging_product:s,status:e.status,message_id:e.messageId,...e.typingIndicator&&{typing_indicator:e.typingIndicator}};return this.send(JSON.stringify(t))}async markAsRead(e){return this.status({status:`read`,messageId:e.messageId})}async showTypingIndicator(e){let t={messaging_product:s,status:`typing`,message_id:e.messageId,typing_indicator:{type:`text`}};return this.send(JSON.stringify(t))}async interactiveList(e){return this.interactive(e)}async interactiveCtaUrl(e){return this.interactive(e)}async interactiveVoiceCall(e){return this.interactive({...e,category:e.category??`utility`})}async interactiveLocationRequest(e){return this.interactive(e)}async interactiveAddressMessage(e){return this.interactive(e)}async interactiveReplyButtons(e){return this.interactive(e)}async interactiveFlow(e){return this.interactive(e)}async interactiveCarousel(e){return this.interactive(e)}async reaction(e){let t={message_id:e.messageId,emoji:e.emoji};return this.send(JSON.stringify(this.bodyBuilder(`reaction`,t,e.to,void 0,e.recipientType)))}async encrypted(e){return this.sendEncrypted(JSON.stringify(e))}},yt=class extends c{async listPaymentConfigurations(e){return this.sendJson(`GET`,`/${e}/payment_configurations`,this.config.REQUEST_TIMEOUT,null)}async getPaymentConfiguration(e,t){let n=encodeURIComponent(t);return this.sendJson(`GET`,`/${e}/payment_configuration/${n}`,this.config.REQUEST_TIMEOUT,null)}async createPaymentConfiguration(e,t){return this.sendJson(`POST`,`/${e}/payment_configuration`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async updatePaymentConfiguration(e,t,n){let r=encodeURIComponent(t);return this.sendJson(`POST`,`/${e}/payment_configuration/${r}`,this.config.REQUEST_TIMEOUT,JSON.stringify(n))}async generatePaymentConfigurationOauthLink(e,t){return this.sendJson(`POST`,`/${e}/generate_payment_configuration_oauth_link`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async deletePaymentConfiguration(e,t){return this.sendJson(`DELETE`,`/${e}/payment_configuration`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}},bt=class extends c{endpoint=`phone_numbers`;async getPhoneNumberById(e){let t=Array.isArray(e)?e.join(`,`):e,n=t?v({fields:t}):``;return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}${n}`,this.config.REQUEST_TIMEOUT,null)}async getPhoneNumbers(e){let t=v({fields:Array.isArray(e?.fields)?e.fields.join(`,`):e?.fields,filtering:Array.isArray(e?.filtering)?JSON.stringify(e.filtering):e?.filtering,sort:e?.sort,limit:e?.limit,after:e?.after,before:e?.before});return this.sendJson(`GET`,`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${t}`,this.config.REQUEST_TIMEOUT,null)}async createPhoneNumber(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){return this.sendJson(`POST`,`${t}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async updatePhoneNumberStatus(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async requestVerificationCode(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/request_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async verifyCode(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/verify_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getPhoneNumberSettings(e){let t=Array.isArray(e?.fields)?e.fields.join(`,`):e?.fields,n=v({...t?{fields:t}:{},...e?.include_sip_credentials===void 0?{}:{include_sip_credentials:e.include_sip_credentials}});return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/settings${n}`,this.config.REQUEST_TIMEOUT,null)}async updatePhoneNumberSettings(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/settings`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async setConversationalAutomation(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/conversational_automation`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getConversationalAutomation(){let e=v({fields:`conversational_automation`});return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}${e}`,this.config.REQUEST_TIMEOUT,null)}async getThroughput(){let e=v({fields:`throughput`});return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}${e}`,this.config.REQUEST_TIMEOUT,null)}async getOfficialBusinessAccountStatus(){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/official_business_account`,this.config.REQUEST_TIMEOUT,null)}async updateOfficialBusinessAccountStatus(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/official_business_account`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getBusinessComplianceInfo(){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/business_compliance_info`,this.config.REQUEST_TIMEOUT,null)}async updateBusinessComplianceInfo(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/business_compliance_info`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getUsername(){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/username`,this.config.REQUEST_TIMEOUT,null)}async updateUsername(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/username`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async deleteUsername(){return this.sendJson(`DELETE`,`${this.config.WA_PHONE_NUMBER_ID}/username`,this.config.REQUEST_TIMEOUT,null)}async getUsernameSuggestions(){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/username_suggestions`,this.config.REQUEST_TIMEOUT,null)}};function F(e){if(!e)return``;let t=``;return t=Array.isArray(e)?e.join(`,`):typeof e==`string`?e:Object.entries(e).filter(([e,t])=>t).map(([e])=>e).join(`,`),t?`?fields=${t}`:``}var xt=class extends c{endpoint=`whatsapp_business_profile`;async getBusinessProfile(e){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}${F(e)}`,this.config.REQUEST_TIMEOUT,null)}async updateBusinessProfile(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async createUploadSession(e,t,n){let r=v({file_length:e,file_type:t,file_name:n});return this.sendJson(`POST`,`app/uploads/${r}`,this.config.REQUEST_TIMEOUT,null)}async uploadMedia(e,t){return this.sendJson(`POST`,`${e}`,this.config.REQUEST_TIMEOUT,t)}async getUploadHandle(e){return this.sendJson(`GET`,`${e}`,this.config.REQUEST_TIMEOUT,null)}},St=class extends c{endpoint=`message_qrdls`;async createQrCode(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getQrCodes(){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async getQrCode(e){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}/${e}`,this.config.REQUEST_TIMEOUT,null)}async updateQrCode(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async deleteQrCode(e){return this.sendJson(`DELETE`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}/${e}`,this.config.REQUEST_TIMEOUT,null)}},Ct=class extends c{async register(e,t){let n={messaging_product:s,pin:e,...t&&{data_localization_region:t}};return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/register`,this.config.REQUEST_TIMEOUT,JSON.stringify(n))}async deregister(){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/deregister`,this.config.REQUEST_TIMEOUT,null)}},wt=class extends c{toQuery(e){return e?v({fields:Array.isArray(e.fields)?e.fields.join(`,`):e.fields,role:e.role,status:e.status,limit:e.limit,after:e.after,before:e.before}):``}fieldsQuery(e){let t=Array.isArray(e)?e.join(`,`):e;return t?v({fields:t}):``}async createWhatsAppBusinessSolution(e,t){return this.sendJson(`POST`,`${e}/whatsapp_business_solution`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getApplicationWhatsAppBusinessSolutions(e,t){return this.sendJson(`GET`,`${e}/whatsapp_business_solutions${this.toQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async getSolutionAccessToken(e,t){return this.sendJson(`GET`,`${e}/access_token${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async acceptSolutionDeactivationRequest(e,t={}){return this.sendJson(`POST`,`${e}/accept_deactivation_request`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async acceptSolution(e,t={}){return this.sendJson(`POST`,`${e}/accept`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getSolutionDetails(e,t){return this.sendJson(`GET`,`${e}${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async rejectSolutionDeactivationRequest(e,t={}){return this.sendJson(`POST`,`${e}/reject_deactivation_request`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async rejectSolutionRequest(e,t={}){return this.sendJson(`POST`,`${e}/reject`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async sendSolutionDeactivationRequest(e,t={}){return this.sendJson(`POST`,`${e}/send_deactivation_request`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getMigrationIntentDetails(e,t){return this.sendJson(`GET`,`${e}${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async listWabaSolutions(e=this.config.WA_BUSINESS_ACCOUNT_ID,t){return this.sendJson(`GET`,`${e}/solutions${this.toQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async setSolutionMigrationIntent(e,t){return this.sendJson(`POST`,`${e}/set_solution_migration_intent`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}};function I(e){let t={type:`HEADER`,format:e.format};return e.text&&(t.text=e.text),e.example&&(t.example=e.example),t}function L(e){let t={type:`BODY`,text:e.text};return e.example&&(t.example=e.example),t}function R(e){return{type:`FOOTER`,text:e.text}}function z(e){let t=[];if(e.phone_number&&t.push({type:`PHONE_NUMBER`,text:e.phone_number.text,phone_number:e.phone_number.phone_number}),e.url){let n={type:`URL`,text:e.url.text,url:e.url.url};e.url.example&&(n.example=[e.url.example]),t.push(n)}if(e.quick_reply&&e.quick_reply.forEach(e=>{t.push({type:`QUICK_REPLY`,text:e.text})}),e.copy_code&&t.push({type:`COPY_CODE`,example:e.copy_code.example}),e.flow){let n={type:`FLOW`,text:e.flow.text};e.flow.flow_id&&(n.flow_id=e.flow.flow_id),e.flow.flow_name&&(n.flow_name=e.flow.flow_name),e.flow.flow_json&&(n.flow_json=e.flow.flow_json),e.flow.flow_action&&(n.flow_action=e.flow.flow_action),e.flow.navigate_screen&&(n.navigate_screen=e.flow.navigate_screen),t.push(n)}return e.mpm&&t.push({type:`MPM`}),e.otp&&t.push({type:`OTP`}),e.spm&&t.push({type:`SPM`}),t.length>0?[{type:`BUTTONS`,buttons:t}]:[]}function Tt(e){return e.map(e=>{switch(e.type){case`text`:return e.value;case`currency`:return e.fallback_value;case`date_time`:return e.fallback_value;case`image`:case`video`:case`document`:return e.handle||e.link||``;case`location`:return e.name||``;case`product`:return e.product_retailer_id;default:return``}})}function Et(e){let t=[];if(e.header&&t.push(I(e.header)),e.body&&t.push(L(e.body)),e.footer&&t.push(R(e.footer)),e.buttons&&t.push(...z(e.buttons)),e.carousel){let n=[];e.carousel.cards.forEach((e,t)=>{if(e.image||e.video||e.product){let t=e.image?`IMAGE`:e.video?`VIDEO`:`DOCUMENT`,r=e.image||e.video||e.product||``;n.push({type:`HEADER`,format:t,example:{header_handle:[r]}})}e.body&&n.push({type:`BODY`,text:e.body,example:e.bodyParameters?{body_text:[Tt(e.bodyParameters)]}:void 0}),e.buttons&&n.push(...z(e.buttons))}),t.push(...n)}return e.limitedTimeOffer&&t.push({type:`LIMITED_TIME_OFFER`,limited_time_offer:{expiration_time_ms:e.limitedTimeOffer.expiration_time_ms}}),{name:e.name,language:e.language,category:e.category,components:t.length>0?t:void 0}}function Dt(e){let t=[],n=`*{{1}}* is your verification code.`;return e.add_security_recommendation&&(n+=` For your security, do not share this code.`),e.code_expiration_minutes&&(n+=` This code expires in ${e.code_expiration_minutes} minutes.`),t.push({type:`BODY`,text:n,example:{body_text:[[`123456`]]}}),t.push({type:`BUTTONS`,buttons:[{type:`OTP`}]}),{name:e.name,language:e.language,category:`AUTHENTICATION`,components:t}}function Ot(e){let t=[],n=`Your security code is *{{1}}*.`;return e.add_security_recommendation&&(n+=` Do not share this code with anyone.`),e.code_expiration_minutes&&(n+=` This code expires in ${e.code_expiration_minutes} minutes.`),t.push({type:`BODY`,text:n,example:{body_text:[[`ABCD1234`]]}}),e.copy_code_button&&t.push({type:`BUTTONS`,buttons:[{type:`COPY_CODE`,example:`ABCD1234`}]}),{name:e.name,language:e.language,category:`AUTHENTICATION`,components:t}}function kt(e){let t=[];return e.header&&t.push(I({...e.header,format:`TEXT`})),t.push(L(e.body)),e.footer&&t.push(R(e.footer)),t.push({type:`BUTTONS`,buttons:[{type:`CATALOG`,action:{thumbnail_product_retailer_id:e.thumbnail_product_retailer_id}}]}),{name:e.name,language:e.language,category:`MARKETING`,components:t}}function At(e){let t=[];return e.header&&t.push(I({...e.header,format:`TEXT`})),t.push(L(e.body)),e.footer&&t.push(R(e.footer)),t.push({type:`BUTTONS`,buttons:[{type:`COPY_CODE`,example:e.coupon_code}]}),{name:e.name,language:e.language,category:`MARKETING`,components:t}}function jt(e){let t=[];return t.push({type:`LIMITED_TIME_OFFER`,limited_time_offer:{expiration_time_ms:e.expiration_time_ms}}),e.header&&t.push(I({...e.header,format:`TEXT`})),t.push(L(e.body)),e.footer&&t.push(R(e.footer)),{name:e.name,language:e.language,category:`MARKETING`,components:t}}function Mt(e){let t=[],n=[];return e.cards.forEach((e,t)=>{let r=[];r.push({type:`HEADER`,format:e.header.format,example:e.header.example}),r.push(L(e.body)),e.buttons&&r.push(...z(e.buttons)),n.push({card_index:t,components:r})}),t.push({type:`CAROUSEL`,cards:n}),{name:e.name,language:e.language,category:`MARKETING`,components:t}}function Nt(e){let t=[];return e.header&&t.push(I({...e.header,format:`TEXT`})),t.push(L(e.body)),e.footer&&t.push(R(e.footer)),t.push({type:`BUTTONS`,buttons:[{type:`MPM`,action:{thumbnail_product_retailer_id:e.thumbnail_product_retailer_id,sections:e.sections}}]}),{name:e.name,language:e.language,category:`MARKETING`,components:t}}function Pt(e){let t=[];e.header&&t.push(I({...e.header,format:`TEXT`})),t.push(L(e.body)),e.footer&&t.push(R(e.footer));let n=e.cards.map((e,t)=>({card_index:t,components:[{type:`HEADER`,format:`PRODUCT`,example:{header_handle:[e.product_retailer_id]}}]}));return t.push({type:`CAROUSEL`,cards:n}),{name:e.name,language:e.language,category:`MARKETING`,components:t}}function Ft(e){let t=[];return e.header&&t.push(I({...e.header,format:`TEXT`})),t.push(L(e.body)),e.footer&&t.push(R(e.footer)),t.push({type:`BUTTONS`,buttons:[{type:`SPM`,action:{product_retailer_id:e.product_retailer_id}}]}),{name:e.name,language:e.language,category:`MARKETING`,components:t}}var It=class extends c{endpoint=`message_templates`;async getTemplate(e){return this.sendJson(`GET`,`${e}`,this.config.REQUEST_TIMEOUT,null)}async updateTemplate(e,t){return this.sendJson(`POST`,`${e}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getTemplates(e){return this.sendJson(`GET`,`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${v(e??{})}`,this.config.REQUEST_TIMEOUT,null)}async createTemplate(e){return this.sendJson(`POST`,`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async deleteTemplate(e){return this.sendJson(`DELETE`,`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${v(e)}`,this.config.REQUEST_TIMEOUT,null)}},Lt=class extends c{async setTwoStepVerificationCode(e){let t={pin:e};return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}},Rt=class extends c{toQuery(e){return e?v({fields:Array.isArray(e.fields)?e.fields.join(`,`):e.fields,filtering:Array.isArray(e.filtering)?JSON.stringify(e.filtering):e.filtering,sort:e.sort,limit:e.limit,after:e.after,before:e.before}):``}fieldsQuery(e){let t=Array.isArray(e)?e.join(`,`):e;return t?v({fields:t}):``}async getWabaAccount(e){let t=F(e)?.replace(/,/g,`%2C`);return this.sendJson(`GET`,`${this.config.WA_BUSINESS_ACCOUNT_ID}${t}`,this.config.REQUEST_TIMEOUT,null)}async updateWabaAccount(e){return this.sendJson(`POST`,`${this.config.WA_BUSINESS_ACCOUNT_ID}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getWabaActivities(e){return this.sendJson(`GET`,`${this.config.WA_BUSINESS_ACCOUNT_ID}/activities${this.toQuery(e)}`,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:e,verify_token:t}){let n={override_callback_uri:e,verify_token:t};return this.sendJson(`POST`,`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,JSON.stringify(n))}async unsubscribeFromWaba(){return this.sendJson(`DELETE`,`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,null)}async getAssignedUsers(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){return this.sendJson(`GET`,`${t}/assigned_users${this.toQuery(e)}`,this.config.REQUEST_TIMEOUT,null)}async addAssignedUser(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){let n={user:e.user,tasks:e.tasks};return this.sendUrlEncodedForm(`POST`,`${t}/assigned_users`,this.config.REQUEST_TIMEOUT,n)}async removeAssignedUser(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){return this.sendUrlEncodedForm(`DELETE`,`${t}/assigned_users`,this.config.REQUEST_TIMEOUT,{user:e.user})}async getInProgressOnBehalfRequests(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){return this.sendJson(`GET`,`${t}/in_progress_onbehalf_request${this.toQuery(e)}`,this.config.REQUEST_TIMEOUT,null)}async getOBOMobilityIntent(e,t){return this.sendJson(`GET`,`${e}${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async createOBOMobilityIntent(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){return this.sendJson(`POST`,`${t}/obo_mobility_intent`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async setOBOMobilityIntent(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){return this.sendJson(`POST`,`${t}/set_obo_mobility_intent`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getWabaSchedules(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){return this.sendJson(`GET`,`${t}/schedules${this.toQuery(e)}`,this.config.REQUEST_TIMEOUT,null)}async createWabaSchedule(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){return this.sendJson(`POST`,`${t}/schedules`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getWhatsAppBusinessBotDetails(e,t){return this.sendJson(`GET`,`${e}${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async getWhatsAppBusinessProfileDetails(e,t){return this.sendJson(`GET`,`${e}${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async updateWhatsAppBusinessProfile(e,t){return this.sendJson(`POST`,e,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}};let zt=function(e){return e.Approved=`APPROVED`,e.Active=`ACTIVE`,e.Inactive=`INACTIVE`,e.Disabled=`DISABLED`,e}({}),Bt=function(e){return e.Blocked=`BLOCKED`,e.Limited=`LIMITED`,e.Available=`AVAILABLE`,e}({}),Vt=function(e){return e.Approved=`APPROVED`,e.Active=`ACTIVE`,e.Inactive=`INACTIVE`,e.Disabled=`DISABLED`,e}({}),Ht=function(e){return e.Verified=`verified`,e.PendingSubmission=`pending_submission`,e.Unverified=`unverified`,e.Rejected=`rejected`,e}({});var B=class{name;debug;constructor(e,t=!1){this.name=e,this.debug=t}formatData(e){return e.map(e=>typeof e==`object`?t(e,{depth:null,colors:!0}):e).join(` `)}log(...e){if(this.debug){let t=`[ ${Date.now()} ]`;this.name&&(t+=` - ${this.name}`),console.log(t,`: `,this.formatData(e))}}error(...e){let t=`[ ${Date.now()} ] - ERROR`;this.name&&(t+=` - ${this.name}`),console.error(t,`: `,this.formatData(e))}warn(...e){if(this.debug){let t=`[ ${Date.now()} ] - WARN`;this.name&&(t+=` - ${this.name}`),console.warn(t,`: `,this.formatData(e))}}info(...e){if(this.debug){let t=`[ ${Date.now()} ] - INFO`;this.name&&(t+=` - ${this.name}`),console.info(t,`: `,this.formatData(e))}}};const Ut=new B(`UTILS`,process.env.DEBUG===`true`||!1),Wt=e=>{if(!process.env.CLOUD_API_ACCESS_TOKEN&&!e?.accessToken)throw Ut.log(`Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined.`),Error(`Missing WhatsApp access token.`)},Gt=e=>(Wt(e),{M4D_APP_ID:e?.appId||process.env.M4D_APP_ID||``,M4D_APP_SECRET:e?.appSecret||process.env.M4D_APP_SECRET||``,WA_PHONE_NUMBER_ID:e?.phoneNumberId||(process.env.WA_PHONE_NUMBER_ID?Number(process.env.WA_PHONE_NUMBER_ID):0),WA_BUSINESS_ACCOUNT_ID:e?.businessAcctId||process.env.WA_BUSINESS_ACCOUNT_ID||``,CLOUD_API_VERSION:e?.apiVersion||process.env.CLOUD_API_VERSION||`v23.0`,CLOUD_API_ACCESS_TOKEN:e?.accessToken||process.env.CLOUD_API_ACCESS_TOKEN||``,WEBHOOK_ENDPOINT:e?.webhookEndpoint||process.env.WEBHOOK_ENDPOINT||``,WEBHOOK_VERIFICATION_TOKEN:e?.webhookVerificationToken||process.env.WEBHOOK_VERIFICATION_TOKEN||``,LISTENER_PORT:e?.listenerPort||parseInt(process.env.LISTENER_PORT||``,10)||3e3,MAX_RETRIES_AFTER_WAIT:e?.maxRetriesAfterWait||parseInt(process.env.MAX_RETRIES_AFTER_WAIT||``,10)||30,REQUEST_TIMEOUT:e?.requestTimeout||parseInt(process.env.REQUEST_TIMEOUT||``,10)||2e4,DEBUG:e?.debug||process.env.DEBUG===`true`,FLOW_API_PRIVATE_PEM:e?.privatePem||process.env.FLOW_API_PRIVATE_PEM||``,FLOW_API_PASSPHRASE:e?.passphrase||process.env.FLOW_API_PASSPHRASE||``,retry:e?.retry});function Kt(e){let t=[[`App ID`,e.M4D_APP_ID||`Not Set`],[`Phone Number ID`,e.WA_PHONE_NUMBER_ID?.toString()||`Not Set`],[`Business Account ID`,e.WA_BUSINESS_ACCOUNT_ID||`Not Set`],[`API Version`,e.CLOUD_API_VERSION||`Not Set`],[`Access Token`,e.CLOUD_API_ACCESS_TOKEN?`${e.CLOUD_API_ACCESS_TOKEN.substring(0,20)}...`:`Not Set`],[`Webhook Endpoint`,e.WEBHOOK_ENDPOINT||`Not Set`],[`Webhook Verification Token`,e.WEBHOOK_VERIFICATION_TOKEN?`${e.WEBHOOK_VERIFICATION_TOKEN.substring(0,10)}...`:`Not Set`],[`Listener Port`,e.LISTENER_PORT?.toString()||`Not Set`],[`Debug Mode`,e.DEBUG?`Enabled`:`Disabled`],[`Max Retries`,e.MAX_RETRIES_AFTER_WAIT?.toString()||`Not Set`],[`Request Timeout`,e.REQUEST_TIMEOUT?`${e.REQUEST_TIMEOUT}ms`:`Not Set`],[`Private PEM`,e.FLOW_API_PRIVATE_PEM?`Configured`:`Not Set`],[`Passphrase`,e.FLOW_API_PASSPHRASE?`Configured`:`Not Set`]],n=Math.max(...t.map(([e])=>e?.length||0)),r=Math.max(...t.map(([,e])=>e?.length||0)),i=Math.max(n,20),a=Math.max(r,30),o=`┌${`─`.repeat(i+2)}┬${`─`.repeat(a+2)}┐`,s=`├${`─`.repeat(i+2)}┼${`─`.repeat(a+2)}┤`,c=`└${`─`.repeat(i+2)}┴${`─`.repeat(a+2)}┘`;return[o,`│ ${`Configuration`.padEnd(i)} │ ${`Value`.padEnd(a)} │`,s,...t.map(([e,t])=>`│ ${e?.padEnd(i)} │ ${t?.padEnd(a)} │`),c].join(`
|
|
2
|
-
`)}const V=new B(`FLOW_ENCRYPTION_UTILS`,process.env.DEBUG===`true`);function
|
|
1
|
+
import{t as e}from"./chunk.mjs";import{inspect as t}from"node:util";import*as n from"node:crypto";import r from"node:crypto";import{Agent as i}from"node:https";import{readFileSync as a}from"node:fs";import{join as o}from"node:path";const s=`whatsapp`;var c=class{config;client;constructor(e,t){this.config=e,this.client=t}sendJson(e,t,n,r){return this.client.getJson(e,t,n,r)}sendFormData(e,t,n,r){return this.client.sendFormData(e,t,n,r)}sendUrlEncodedForm(e,t,n,r){return this.client.sendUrlEncodedForm(e,t,n,r)}},l=e({AudioMediaTypesEnum:()=>le,BusinessVerticalEnum:()=>_e,ButtonPositionEnum:()=>_,CategoryEnum:()=>u,ComponentTypesEnum:()=>te,ConversationTypesEnum:()=>re,CurrencyCodesEnum:()=>he,DataLocalizationRegionEnum:()=>ge,DocumentMediaTypesEnum:()=>ce,HttpMethodsEnum:()=>p,ImageMediaTypesEnum:()=>se,InteractiveTypesEnum:()=>g,LanguagesEnum:()=>me,MessageCategoryEnum:()=>d,MessageTypesEnum:()=>m,ParametersTypesEnum:()=>h,ReferralSourceTypesEnum:()=>fe,RequestCodeMethodsEnum:()=>pe,StatusEnum:()=>ie,StickerMediaTypesEnum:()=>oe,SubTypeEnum:()=>ee,SystemChangeTypesEnum:()=>de,TemplateStatusEnum:()=>f,VideoMediaTypesEnum:()=>ae,WabaConfigEnum:()=>ne,WebhookTypesEnum:()=>ue});let u=function(e){return e.Authentication=`AUTHENTICATION`,e.Marketing=`MARKETING`,e.Utility=`UTILITY`,e}({}),d=function(e){return e.Authentication=`authentication`,e.Service=`service`,e.Utility=`utility`,e}({}),f=function(e){return e.Approved=`APPROVED`,e.Pending=`PENDING`,e.Rejected=`REJECTED`,e}({}),p=function(e){return e.Get=`GET`,e.Post=`POST`,e.Put=`PUT`,e.Delete=`DELETE`,e}({}),m=function(e){return e.Audio=`audio`,e.Contacts=`contacts`,e.Document=`document`,e.Image=`image`,e.Interactive=`interactive`,e.Location=`location`,e.Reaction=`reaction`,e.Sticker=`sticker`,e.Template=`template`,e.Text=`text`,e.Video=`video`,e.Button=`button`,e.Order=`order`,e.System=`system`,e.Edit=`edit`,e.Revoke=`revoke`,e.Unsupported=`unsupported`,e.Unknown=`unknown`,e.Statuses=`statuses`,e[`*`]=`*`,e}({}),h=function(e){return e.Action=`ACTION`,e.CouponCode=`COUPON_CODE`,e.Currency=`CURRENCY`,e.DateTime=`DATE_TIME`,e.Document=`DOCUMENT`,e.ExpirationTimeMs=`EXPIRATION_TIME_MS`,e.Image=`IMAGE`,e.LimitedTimeOffer=`LIMITED_TIME_OFFER`,e.Location=`LOCATION`,e.OrderStatus=`ORDER_STATUS`,e.Payload=`PAYLOAD`,e.Product=`PRODUCT`,e.Text=`TEXT`,e.TtlMinutes=`TTL_MINUTES`,e.Video=`VIDEO`,e.WebviewInteraction=`WEBVIEW_INTERACTION`,e.WebviewPresentation=`WEBVIEW_PRESENTATION`,e}({}),g=function(e){return e.Button=`button`,e.List=`list`,e.Product=`product`,e.ProductList=`product_list`,e.CatalogMessage=`catalog_message`,e.CallPermissionRequest=`call_permission_request`,e.CtaUrl=`cta_url`,e.Carousel=`carousel`,e.LocationRequest=`location_request_message`,e.AddressMessage=`address_message`,e.Flow=`flow`,e.VoiceCall=`voice_call`,e}({}),_=function(e){return e[e.First=1]=`First`,e[e.Second=2]=`Second`,e[e.Third=3]=`Third`,e[e.Fourth=4]=`Fourth`,e[e.Fifth=5]=`Fifth`,e}({}),ee=function(e){return e.Catalog=`CATALOG`,e.CopyCode=`COPY_CODE`,e.Flow=`FLOW`,e.Mpm=`MPM`,e.OrderDetails=`ORDER_DETAILS`,e.PhoneNumber=`PHONE_NUMBER`,e.QuickReply=`QUICK_REPLY`,e.Reminder=`REMINDER`,e.Url=`URL`,e.VoiceCall=`VOICE_CALL`,e}({}),te=function(e){return e.Header=`HEADER`,e.Body=`BODY`,e.Button=`BUTTON`,e.Footer=`FOOTER`,e}({}),ne=function(e){return e.AppId=`M4D_APP_ID`,e.Port=`WA_PORT`,e.AppSecret=`M4D_APP_SECRET`,e.PhoneNumberId=`WA_PHONE_NUMBER_ID`,e.BusinessAcctId=`WA_BUSINESS_ACCOUNT_ID`,e.APIVersion=`CLOUD_API_VERSION`,e.AccessToken=`CLOUD_API_ACCESS_TOKEN`,e.WebhookEndpoint=`WEBHOOK_ENDPOINT`,e.WebhookVerificationToken=`WEBHOOK_VERIFICATION_TOKEN`,e.ListenerPort=`LISTENER_PORT`,e.MaxRetriesAfterWait=`MAX_RETRIES_AFTER_WAIT`,e.RequestTimeout=`REQUEST_TIMEOUT`,e.Debug=`DEBUG`,e.PrivatePem=`FLOW_API_PRIVATE_PEM`,e.Passphrase=`FLOW_API_PASSPHRASE`,e}({}),re=function(e){return e.BusinessInitiated=`business_initiated`,e.CustomerInitiated=`customer_initiated`,e.ReferralConversion=`referral_conversion`,e}({}),ie=function(e){return e.Delivered=`delivered`,e.Read=`read`,e.Sent=`sent`,e}({}),ae=function(e){return e.Mp4=`video/mp4`,e.Threegp=`video/3gp`,e}({}),oe=function(e){return e.Webp=`image/webp`,e}({}),se=function(e){return e.Jpeg=`image/jpeg`,e.Png=`image/png`,e}({}),ce=function(e){return e.Text=`text/plain`,e.Pdf=`application/pdf`,e.Ppt=`application/vnd.ms-powerpoint`,e.Word=`application/msword`,e.Excel=`application/vnd.ms-excel`,e.OpenDoc=`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,e.OpenPres=`application/vnd.openxmlformats-officedocument.presentationml.presentation`,e.OpenSheet=`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,e}({}),le=function(e){return e.Aac=`audio/aac`,e.Mp4=`audio/mp4`,e.Mpeg=`audio/mpeg`,e.Amr=`audio/amr`,e.Ogg=`audio/ogg`,e}({}),ue=function(e){return e.Audio=`audio`,e.Button=`button`,e.Document=`document`,e.Text=`text`,e.Image=`image`,e.Interactive=`interactive`,e.Order=`order`,e.Sticker=`sticker`,e.System=`system`,e.Unknown=`unknown`,e.Video=`video`,e}({}),de=function(e){return e.CustomerChangedNumber=`customer_changed_number`,e.CustomerIdentityChanged=`customer_identity_changed`,e.UserChangedNumber=`user_changed_number`,e.UserIdentityChanged=`user_identity_changed`,e.UserChangedUserId=`user_changed_user_id`,e}({}),fe=function(e){return e.Ad=`ad`,e.Post=`post`,e}({}),pe=function(e){return e.Sms=`SMS`,e.Voice=`VOICE`,e}({}),me=function(e){return e.Afrikaans=`af`,e.Albanian=`sq`,e.Arabic=`ar`,e.Azerbaijani=`az`,e.Bengali=`bn`,e.Bulgarian=`bg`,e.Catalan=`ca`,e.Chinese_CHN=`zh_CN`,e.Chinese_HKG=`zh_HK`,e.Chinese_TAI=`zh_TW`,e.Croatian=`hr`,e.Czech=`cs`,e.Danish=`da`,e.Dutch=`nl`,e.English=`en`,e.English_UK=`en_GB`,e.English_US=`en_US`,e.Estonian=`et`,e.Filipino=`fil`,e.Finnish=`fi`,e.French=`fr`,e.Georgian=`ka`,e.German=`de`,e.Greek=`el`,e.Gujarati=`gu`,e.Hausa=`ha`,e.Hebrew=`he`,e.Hindi=`hi`,e.Hungarian=`hu`,e.Indonesian=`id`,e.Irish=`ga`,e.Italian=`it`,e.Japanese=`ja`,e.Kannada=`kn`,e.Kazakh=`kk`,e.Kinyarwanda=`rw_RW`,e.Korean=`ko`,e.Kyrgyz_Kyrgyzstan=`ky_KG`,e.Lao=`lo`,e.Latvian=`lv`,e.Lithuanian=`lt`,e.Macedonian=`mk`,e.Malay=`ms`,e.Malayalam=`ml`,e.Marathi=`mr`,e.Norwegian=`nb`,e.Persian=`fa`,e.Polish=`pl`,e.Portuguese_BR=`pt_BR`,e.Portuguese_POR=`pt_PT`,e.Punjabi=`pa`,e.Romanian=`ro`,e.Russian=`ru`,e.Serbian=`sr`,e.Slovak=`sk`,e.Slovenian=`sl`,e.Spanish=`es`,e.Spanish_ARG=`es_AR`,e.Spanish_SPA=`es_ES`,e.Spanish_MEX=`es_MX`,e.Swahili=`sw`,e.Swedish=`sv`,e.Tamil=`ta`,e.Telugu=`te`,e.Thai=`th`,e.Turkish=`tr`,e.Ukrainian=`uk`,e.Urdu=`ur`,e.Uzbek=`uz`,e.Vietnamese=`vi`,e.Zulu=`zu`,e}({}),he=function(e){return 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}({}),ge=function(e){return e.AU=`AU`,e.ID=`ID`,e.IN=`IN`,e.JP=`JP`,e.SG=`SG`,e.KR=`KR`,e.DE=`DE`,e.CH=`CH`,e.GB=`GB`,e.BR=`BR`,e.BH=`BH`,e.ZA=`ZA`,e.AE=`AE`,e.CA=`CA`,e}({}),_e=function(e){return e.ALCOHOL=`ALCOHOL`,e.APPAREL=`APPAREL`,e.AUTO=`AUTO`,e.BEAUTY=`BEAUTY`,e.EDU=`EDU`,e.ENTERTAIN=`ENTERTAIN`,e.EVENT_PLAN=`EVENT_PLAN`,e.FINANCE=`FINANCE`,e.GOVT=`GOVT`,e.GROCERY=`GROCERY`,e.HEALTH=`HEALTH`,e.HOTEL=`HOTEL`,e.NONPROFIT=`NONPROFIT`,e.ONLINE_GAMBLING=`ONLINE_GAMBLING`,e.OTC_DRUGS=`OTC_DRUGS`,e.OTHER=`OTHER`,e.PHYSICAL_GAMBLING=`PHYSICAL_GAMBLING`,e.PROF_SERVICES=`PROF_SERVICES`,e.RESTAURANT=`RESTAURANT`,e.RETAIL=`RETAIL`,e.TRAVEL=`TRAVEL`,e}({});const v=e=>{if(!e||Object.keys(e).length===0)return``;let t=[];for(let[n,r]of Object.entries(e))if(r!==void 0){let e=encodeURIComponent(n),i=encodeURIComponent(String(r));t.push(`${e}=${i}`)}return t.length>0?`?${t.join(`&`)}`:``},ve=[0,1,2,3,4,10,33,100,190,200,299,368,613,80007,130429,130472,130497,131e3,131005,131008,131009,131016,131020,131021,131026,131030,131031,131037,131041,131042,131044,131045,131047,131048,131049,131050,131051,131052,131053,131055,131056,131057,131059,131061,131062,131063,131201,131202,131203,131204,131207,131208,131209,131210,131211,131212,131213,131214,131215,132e3,132001,132005,132007,132008,132012,132015,132016,132068,132069,133e3,133004,133005,133006,133008,133009,133010,133015,133016,134011,134100,134101,134102,135e3,137e3,138e3,138001,138002,138003,138004,138005,138006,138007,138009,138012,138013,138018,139e3,139001,139002,139003,139004,139100,139101,139102,139103,147005,200005,200006,200007,1752041,2388001,2388012,2388019,2388040,2388047,2388072,2388073,2388091,2388093,2388103,2388293,2388299,2494100,2494191,2593079,2593085,2593107,2593108],ye=new Set(ve),be=[0,3,10,190],xe=[4,80007,130429,131048,131056],Se=[368,130497,131031],Ce=[130472,131e3,131005,131008,131009,131016,131021,131026,131030,131042,131044,131045,131047,131050,131051,131052,131053,131056,131057,131048,131061,131062,131063,132e3,132001,132005,132007,132008,132012,132015,132016,132068,132069,135e3,137e3],we=[139e3,139001,139002,139003,139004],Te=[139100,139101,139102,139103],Ee=[138e3,138001,138002,138003,138004,138005,138006,138007,138009,138012,138013,138018,613],De=[131020,131041,131059,131201,131202,131203,131204,131207,131208,131209,131210,131211,131212,131213,131214,131215],Oe=new Set(be),ke=new Set(xe),Ae=new Set(Se),je=new Set(Ce),Me=new Set(we),Ne=new Set(Te),Pe=new Set(Ee),Fe=new Set(De);function Ie(e){return y(e)?!0:ye.has(e)}function y(e){return e>=200&&e<300}function Le(e){return y(e)||Oe.has(e)}function Re(e){return ke.has(e)}function ze(e){return Ae.has(e)}function Be(e){return je.has(e)}function Ve(e){return Me.has(e)}function He(e){return Ne.has(e)}function Ue(e){return Pe.has(e)}function We(e){return Fe.has(e)}var b=class extends Error{constructor(e){super(e),this.name=`WhatsAppError`}},x=class extends b{error;statusCode;constructor(e,t,n){super(e),this.name=`WhatsAppApiError`,this.error=t,this.statusCode=n}},S=class extends x{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppAuthorizationError`}},C=class extends x{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppThrottlingError`}},w=class extends x{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppIntegrityError`}},T=class extends x{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppSendMessageError`}},E=class extends x{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppFlowError`}},D=class extends x{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppBlockUserError`}},O=class extends x{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppCallingError`}},k=class extends x{constructor(e,t,n){super(e,t,n),this.name=`WhatsAppGroupError`}};function A(e,t){let n=e.code;return Le(n)?new S(e.message,e,t):Re(n)?new C(e.message,e,t):ze(n)?new w(e.message,e,t):Be(n)?new T(e.message,e,t):Ve(n)?new E(e.message,e,t):He(n)?new D(e.message,e,t):Ue(n)?new O(e.message,e,t):We(n)?new k(e.message,e,t):new x(e.message,e,t)}var Ge=class extends b{cause;constructor(e,t){super(e),this.name=`WhatsAppNetworkError`,this.cause=t}},Ke=class extends b{cause;constructor(e,t){super(e),this.name=`WhatsAppUnknownError`,this.cause=t}},j=class extends Error{constructor(e){super(e),this.name=`WhatsAppValidationError`}};function M(e){if(typeof e!=`object`||!e||!(`error`in e)||typeof e.error!=`object`||e.error==null)return!1;let t=e.error;if(typeof t.message!=`string`||typeof t.type!=`string`||typeof t.code!=`number`||typeof t.fbtrace_id!=`string`)return!1;if(`error_data`in t&&t.error_data!=null){if(typeof t.error_data!=`object`)return!1;let e=t.error_data;if(`messaging_product`in e&&e.messaging_product!==`whatsapp`||`details`in e&&typeof e.details!=`string`)return!1}return!(`error_subcode`in t&&typeof t.error_subcode!=`number`)}function qe(e){return M(e)&&Ie(e.error.code)}function Je(e){return e instanceof S}function Ye(e){return e instanceof C}function Xe(e){return e instanceof w}function Ze(e){return e instanceof T}function Qe(e){return e instanceof E}function $e(e){return e instanceof D}function et(e){return e instanceof O}function tt(e){return e instanceof k}function nt(e,t){if(M(e))return e;let n=`Unknown error occurred`;if(e&&typeof e==`object`&&`message`in e){let t=e.message;typeof t==`string`&&(n=t)}return{name:`MetaError`,message:n,error:{message:n,type:`UnknownError`,code:typeof t==`number`?t:500,fbtrace_id:``}}}function rt(e){if(!/^\+?\d{10,15}$/.test(e))throw new j(`Invalid phone number: "${e}". Expected E.164 format (e.g. +14155552671 or 14155552671).`)}function N(e,t){if(!e||e.length===0)throw new j(`"${t}" must contain at least one item.`)}var it=class extends c{endpoint=`block_users`;buildBlockUsersBody(e){return{messaging_product:s,block_users:e.map(e=>({user:e}))}}async block(e){N(e,`users`);let t=this.buildBlockUsersBody(e);return await this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async unblock(e){N(e,`users`);let t=this.buildBlockUsersBody(e);return await this.sendJson(`DELETE`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async listBlockedUsers(e){let t=`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`;if(e){let n=v(e);n&&(t+=n)}return await this.sendJson(`GET`,t,this.config.REQUEST_TIMEOUT)}},at=class extends c{toQuery(e){return e?v({fields:Array.isArray(e.fields)?e.fields.join(`,`):e.fields,filtering:Array.isArray(e.filtering)?JSON.stringify(e.filtering):e.filtering,sort:e.sort,limit:e.limit,after:e.after,before:e.before}):``}fieldsQuery(e){let t=Array.isArray(e)?e.join(`,`):e;return t?v({fields:t}):``}async getConnectedClientBusinesses(e=this.config.M4D_APP_ID,t){return this.sendJson(`GET`,`${e}/connected_client_businesses${this.toQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async addPhoneNumbers(e,t){return this.sendJson(`POST`,`${e}/add_phone_numbers`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getBusinessPortfolio(e,t){return this.sendJson(`GET`,`${e}${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async getPreVerifiedPhoneNumbers(e,t){return this.sendJson(`GET`,`${e}/preverified_numbers${this.toQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async getClientWhatsAppBusinessAccounts(e,t){return this.sendJson(`GET`,`${e}/client_whatsapp_business_accounts${this.toQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async onboardPartnersToMMLite(e,t){return this.sendJson(`POST`,`${e}/onboard_partners_to_mm_lite`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getOwnedWhatsAppBusinessAccounts(e,t){return this.sendJson(`GET`,`${e}/owned_whatsapp_business_accounts${this.toQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async sharePreVerifiedPhoneNumber(e,t){return this.sendJson(`POST`,`${e}/share_preverified_numbers`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getCreditLines(e){return this.sendJson(`GET`,`${e}/extendedcredits`,this.config.REQUEST_TIMEOUT,null)}async getAssignedWhatsAppBusinessAccounts(e,t){return this.sendJson(`GET`,`${e}/assigned_whatsapp_business_accounts${this.toQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async getWhatsAppAccountNumberDetails(e,t){return this.sendJson(`GET`,`${e}${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async getPreVerifiedPhoneNumberDetails(e,t){return this.sendJson(`GET`,`${e}${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async deletePreVerifiedPhoneNumber(e){return this.sendJson(`DELETE`,e,this.config.REQUEST_TIMEOUT,null)}async getPreVerifiedPhoneNumberPartners(e,t){return this.sendJson(`GET`,`${e}/partners${this.toQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async requestPreVerifiedPhoneNumberCode(e,t){return this.sendJson(`POST`,`${e}/request_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async verifyPreVerifiedPhoneNumberCode(e,t){return this.sendJson(`POST`,`${e}/verify_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}},ot=class extends c{endpoint=`calls`;async updateCallingSettings(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/settings`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getCallingSettings(e){let t=Array.isArray(e?.fields)?e?.fields.join(`,`):e?.fields,n=v({...t?{fields:t}:{},...e?.include_sip_credentials===void 0?{}:{include_sip_credentials:e.include_sip_credentials}});return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/settings${n}`,this.config.REQUEST_TIMEOUT,null)}async getCallPermissions(e){let t=v({user_wa_id:e.userWaId});return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/call_permissions${t}`,this.config.REQUEST_TIMEOUT,null)}async initiateCall(e){let t={messaging_product:s,to:e.to,action:`connect`,session:e.session};return e.biz_opaque_callback_data&&(t.biz_opaque_callback_data=e.biz_opaque_callback_data),e.recording&&(t.recording=e.recording),e.transcription&&(t.transcription=e.transcription),this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async preAcceptCall(e){let t={messaging_product:s,call_id:e.call_id,action:`pre_accept`};return e.session&&(t.session=e.session),this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async acceptCall(e){let t={messaging_product:s,call_id:e.call_id,action:`accept`};return e.session&&(t.session=e.session),e.biz_opaque_callback_data&&(t.biz_opaque_callback_data=e.biz_opaque_callback_data),e.recording&&(t.recording=e.recording),e.transcription&&(t.transcription=e.transcription),this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async rejectCall(e){let t={messaging_product:s,call_id:e.call_id,action:`reject`};return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async terminateCall(e){let t={messaging_product:s,call_id:e.call_id,action:`terminate`};return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}},st=class extends c{endpoint=`whatsapp_commerce_settings`;async getCommerceSettings(){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async updateCommerceSettings(e){let t=v(e);return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}${t}`,this.config.REQUEST_TIMEOUT,null)}},ct=class extends c{endpoint=`contact_book`;async deleteEntry(e){if(!e?.bsuid)throw new j(`"bsuid" is required to delete a contact book entry.`);let t=v({messaging_product:s,bsuid:e.bsuid});return await this.sendJson(`DELETE`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}${t}`,this.config.REQUEST_TIMEOUT)}},lt=class extends c{endpoint=`whatsapp_business_encryption`;async getEncryptionPublicKey(){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async setEncryptionPublicKey(e){let t=new FormData;return t.append(`business_public_key`,e),this.sendFormData(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,t)}},ut=class extends c{appendFormValue(e,t,n){n!==void 0&&e.append(t,Array.isArray(n)?JSON.stringify(n):String(n))}async listFlows(e){return this.sendJson(`GET`,`/${e}/flows`,this.config.REQUEST_TIMEOUT,null)}async createFlow(e,t){let n=new FormData;return this.appendFormValue(n,`name`,t.name),this.appendFormValue(n,`categories`,t.categories),this.appendFormValue(n,`endpoint_uri`,t.endpoint_uri),this.appendFormValue(n,`clone_flow_id`,t.clone_flow_id),this.appendFormValue(n,`flow_json`,t.flow_json),this.appendFormValue(n,`publish`,t.publish),this.sendFormData(`POST`,`/${e}/flows`,this.config.REQUEST_TIMEOUT,n)}async getFlow(e,t,n){let r=new URLSearchParams;t&&r.append(`fields`,t),n&&r.append(`date_format`,n);let i=r.toString()?`?${r.toString()}`:``;return this.sendJson(`GET`,`/${e}${i}`,this.config.REQUEST_TIMEOUT,null)}async getFlowPreview(e,t=!1){let n=`preview.invalidate(${t})`;return this.getFlow(e,n)}async updateFlowMetadata(e,t){let n=new FormData;return this.appendFormValue(n,`name`,t.name),this.appendFormValue(n,`categories`,t.categories),this.appendFormValue(n,`endpoint_uri`,t.endpoint_uri),this.appendFormValue(n,`application_id`,t.application_id),this.sendFormData(`POST`,`/${e}`,this.config.REQUEST_TIMEOUT,n)}async deleteFlow(e){return this.sendJson(`DELETE`,`/${e}`,this.config.REQUEST_TIMEOUT,null)}async listAssets(e){return this.sendJson(`GET`,`/${e}/assets`,this.config.REQUEST_TIMEOUT,null)}async updateFlowJson(e,t){let n=new FormData,r;if(t.file instanceof Buffer)r=new globalThis.Blob([new Uint8Array(t.file)]),n.append(`file`,r);else if(typeof t.file==`object`&&!(t.file instanceof Blob))try{r=new globalThis.Blob([JSON.stringify(t.file,null,2)],{type:`application/json`}),n.append(`file`,r)}catch{throw Error(`Failed to stringify JSON object for Flow JSON update.`)}else if(t.file instanceof Blob)r=t.file,n.append(`file`,r);else throw Error(`Invalid file type provided for Flow JSON update. Must be a Buffer, JSON object, or Blob.`);return n.append(`asset_type`,`FLOW_JSON`),n.append(`name`,t.name||`flow.json`),this.sendFormData(`POST`,`/${e}/assets`,this.config.REQUEST_TIMEOUT,n)}async validateFlowJson(e,t){let n=await this.updateFlowJson(e,{file:t}),r=!n.validation_errors||n.validation_errors.length===0;return{...n,valid:r}}async publishFlow(e){return this.sendJson(`POST`,`/${e}/publish`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async deprecateFlow(e){return this.sendJson(`POST`,`/${e}/deprecate`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async migrateFlows(e,t){let n=new FormData;return this.appendFormValue(n,`source_waba_id`,t.source_waba_id),this.appendFormValue(n,`source_flow_names`,t.source_flow_names),this.sendFormData(`POST`,`/${e}/migrate_flows`,this.config.REQUEST_TIMEOUT,n)}};let dt=function(e){return e.Draft=`DRAFT`,e.Published=`PUBLISHED`,e.Throttled=`THROTTLED`,e.Blocked=`BLOCKED`,e.Deprecated=`DEPRECATED`,e}({}),ft=function(e){return e.SignUp=`SIGN_UP`,e.SignIn=`SIGN_IN`,e.AppointmentBooking=`APPOINTMENT_BOOKING`,e.LeadGeneration=`LEAD_GENERATION`,e.ContactUs=`CONTACT_US`,e.CustomerSupport=`CUSTOMER_SUPPORT`,e.Survey=`SURVEY`,e.Other=`OTHER`,e}({}),pt=function(e){return e.INIT=`INIT`,e.BACK=`BACK`,e.DATA_EXCHANGE=`data_exchange`,e}({}),mt=function(e){return e.Ping=`ping`,e.Change=`data_exchange`,e.Error=`error`,e.All=`*`,e}({});var ht=class extends c{async createGroup(e){let t={messaging_product:s,subject:e.subject};return e.description&&(t.description=e.description),e.join_approval_mode&&(t.join_approval_mode=e.join_approval_mode),this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/groups`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async deleteGroup(e){return this.sendJson(`DELETE`,e,this.config.REQUEST_TIMEOUT,null)}async getGroupInfo(e,t){let n=Array.isArray(t)?t.join(`,`):t,r=n?v({fields:n}):``;return this.sendJson(`GET`,`${e}${r}`,this.config.REQUEST_TIMEOUT,null)}async getActiveGroups(e){let t=e?v(e):``;return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/groups${t}`,this.config.REQUEST_TIMEOUT,null)}async getGroupInviteLink(e){return this.sendJson(`GET`,`${e}/invite_link`,this.config.REQUEST_TIMEOUT,null)}async createGroupInviteLink(e){let t={messaging_product:s};return this.sendJson(`POST`,`${e}/invite_link`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async resetGroupInviteLink(e){let t={messaging_product:s};return this.sendJson(`POST`,`${e}/invite_link`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async deleteGroupInviteLink(e){let t={messaging_product:s};return this.sendJson(`DELETE`,`${e}/invite_link`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getJoinRequests(e){return this.sendJson(`GET`,`${e}/join_requests`,this.config.REQUEST_TIMEOUT,null)}async approveJoinRequests(e,t){let n={messaging_product:s,join_requests:t};return this.sendJson(`POST`,`${e}/join_requests`,this.config.REQUEST_TIMEOUT,JSON.stringify(n))}async rejectJoinRequests(e,t){let n={messaging_product:s,join_requests:t};return this.sendJson(`DELETE`,`${e}/join_requests`,this.config.REQUEST_TIMEOUT,JSON.stringify(n))}async addParticipants(e,t){N(t,`participants`);let n={messaging_product:s,participants:t.map(e=>({user:e}))};return this.sendJson(`POST`,`${e}/participants`,this.config.REQUEST_TIMEOUT,JSON.stringify(n))}async removeParticipants(e,t){N(t,`participants`);let n={messaging_product:s,participants:t.map(e=>({user:e}))};return this.sendJson(`DELETE`,`${e}/participants`,this.config.REQUEST_TIMEOUT,JSON.stringify(n))}async updateGroupSettings(e,t){if(t.profilePictureFile){let n=new FormData;if(n.append(`messaging_product`,s),t.subject&&n.append(`subject`,t.subject),t.description&&n.append(`description`,t.description),t.profilePictureFile instanceof Buffer){let e=new globalThis.Blob([new Uint8Array(t.profilePictureFile)],{type:`image/jpeg`});n.append(`file`,e)}else if(t.profilePictureFile instanceof Blob)n.append(`file`,t.profilePictureFile);else throw Error(`Invalid profile picture file type. Use a Buffer or Blob.`);return this.sendFormData(`POST`,e,this.config.REQUEST_TIMEOUT,n)}let n={messaging_product:s};return t.subject&&(n.subject=t.subject),t.description&&(n.description=t.description),this.sendJson(`POST`,e,this.config.REQUEST_TIMEOUT,JSON.stringify(n))}},gt=class extends c{endpoint=`marketing_messages`;async sendTemplateMessage(e){if(!e.to==!e.recipient)throw new j(`Provide exactly one of "to" (phone number) or "recipient" (BSUID).`);let t={messaging_product:s,recipient_type:`individual`,type:`template`,template:e.template};return e.to!==void 0&&(t.to=e.to),e.recipient!==void 0&&(t.recipient=e.recipient),e.message_activity_sharing!==void 0&&(t.message_activity_sharing=e.message_activity_sharing),e.product_policy!==void 0&&(t.product_policy=e.product_policy),e.bid_spec!==void 0&&(t.bid_spec=e.bid_spec),this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}},_t=class extends c{endpoint=`media`;async getMediaById(e){return this.sendJson(`GET`,`${e}`,this.config.REQUEST_TIMEOUT,null)}async uploadMedia(e,t=s){let n=new FormData;return n.append(`file`,e),n.append(`messaging_product`,t),n.append(`type`,e.type),this.sendFormData(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,n)}async deleteMedia(e){return this.sendJson(`DELETE`,`${e}`,this.config.REQUEST_TIMEOUT,null)}async downloadMedia(e){return this.sendJson(`GET`,e,this.config.REQUEST_TIMEOUT,null)}},vt=class extends c{resolveFields(e){return Array.isArray(e)?e.join(`,`):e}async getMessageHistory(e){let t=e?v({fields:this.resolveFields(e.fields),message_id:e.message_id,start_time:e.start_time,end_time:e.end_time,limit:e.limit,after:e.after,before:e.before}):``;return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/message_history${t}`,this.config.REQUEST_TIMEOUT,null)}async getMessageHistoryEvents(e,t){let n=t?v({fields:this.resolveFields(t.fields),status_filter:t.status_filter,limit:t.limit,after:t.after,before:t.before}):``;return this.sendJson(`GET`,`${e}/events${n}`,this.config.REQUEST_TIMEOUT,null)}},P=class extends c{commonMethod=`POST`;commonEndpoint=`messages`;bodyBuilder(e,t,n,r,i=`individual`,a){i===`individual`&&rt(n);let o={messaging_product:s,recipient_type:i,to:n,type:e,[e]:t};return r&&(o.context={message_id:r}),a?.category&&(o.category=a.category),a?.directSendConfig&&(o.direct_send_config=a.directSendConfig),o}send(e){return this.sendJson(this.commonMethod,`${this.config.WA_PHONE_NUMBER_ID}/${this.commonEndpoint}`,this.config.REQUEST_TIMEOUT,e)}sendEncrypted(e){return this.sendJson(this.commonMethod,`${this.config.WA_PHONE_NUMBER_ID}/messages_encrypted`,this.config.REQUEST_TIMEOUT,e)}async audio(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`audio`,t,n,r,i,{category:a,directSendConfig:o})))}async contacts(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`contacts`,t,n,r,i,{category:a,directSendConfig:o})))}async document(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`document`,t,n,r,i,{category:a,directSendConfig:o})))}async image(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`image`,t,n,r,i,{category:a,directSendConfig:o})))}async interactive(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`interactive`,t,n,r,i,{category:a,directSendConfig:o})))}async location(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`location`,t,n,r,i,{category:a,directSendConfig:o})))}async sticker(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`sticker`,t,n,r,i,{category:a,directSendConfig:o})))}async template(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`template`,t,n,r,i,{category:a,directSendConfig:o})))}async text(e){let{body:t,to:n,replyMessageId:r,previewUrl:i,recipientType:a,category:o,directSendConfig:s}=e,c=typeof t==`string`?{body:t,preview_url:i??!0}:{...t,preview_url:i??t.preview_url??!0};return this.send(JSON.stringify(this.bodyBuilder(`text`,c,n,r,a,{category:o,directSendConfig:s})))}async video(e){let{body:t,to:n,replyMessageId:r,recipientType:i,category:a,directSendConfig:o}=e;return this.send(JSON.stringify(this.bodyBuilder(`video`,t,n,r,i,{category:a,directSendConfig:o})))}async status(e){let t={messaging_product:s,status:e.status,message_id:e.messageId,...e.typingIndicator&&{typing_indicator:e.typingIndicator}};return this.send(JSON.stringify(t))}async markAsRead(e){return this.status({status:`read`,messageId:e.messageId})}async showTypingIndicator(e){let t={messaging_product:s,status:`typing`,message_id:e.messageId,typing_indicator:{type:`text`}};return this.send(JSON.stringify(t))}async interactiveList(e){return this.interactive(e)}async interactiveCtaUrl(e){return this.interactive(e)}async interactiveVoiceCall(e){return this.interactive({...e,category:e.category??`utility`})}async interactiveLocationRequest(e){return this.interactive(e)}async interactiveAddressMessage(e){return this.interactive(e)}async interactiveReplyButtons(e){return this.interactive(e)}async interactiveFlow(e){return this.interactive(e)}async interactiveCarousel(e){return this.interactive(e)}async reaction(e){let t={message_id:e.messageId,emoji:e.emoji};return this.send(JSON.stringify(this.bodyBuilder(`reaction`,t,e.to,void 0,e.recipientType)))}async encrypted(e){return this.sendEncrypted(JSON.stringify(e))}},yt=class extends c{async listPaymentConfigurations(e){return this.sendJson(`GET`,`/${e}/payment_configurations`,this.config.REQUEST_TIMEOUT,null)}async getPaymentConfiguration(e,t){let n=encodeURIComponent(t);return this.sendJson(`GET`,`/${e}/payment_configuration/${n}`,this.config.REQUEST_TIMEOUT,null)}async createPaymentConfiguration(e,t){return this.sendJson(`POST`,`/${e}/payment_configuration`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async updatePaymentConfiguration(e,t,n){let r=encodeURIComponent(t);return this.sendJson(`POST`,`/${e}/payment_configuration/${r}`,this.config.REQUEST_TIMEOUT,JSON.stringify(n))}async generatePaymentConfigurationOauthLink(e,t){return this.sendJson(`POST`,`/${e}/generate_payment_configuration_oauth_link`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async deletePaymentConfiguration(e,t){return this.sendJson(`DELETE`,`/${e}/payment_configuration`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}},bt=class extends c{endpoint=`phone_numbers`;async getPhoneNumberById(e){let t=Array.isArray(e)?e.join(`,`):e,n=t?v({fields:t}):``;return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}${n}`,this.config.REQUEST_TIMEOUT,null)}async getPhoneNumbers(e){let t=v({fields:Array.isArray(e?.fields)?e.fields.join(`,`):e?.fields,filtering:Array.isArray(e?.filtering)?JSON.stringify(e.filtering):e?.filtering,sort:e?.sort,limit:e?.limit,after:e?.after,before:e?.before});return this.sendJson(`GET`,`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${t}`,this.config.REQUEST_TIMEOUT,null)}async createPhoneNumber(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){return this.sendJson(`POST`,`${t}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async updatePhoneNumberStatus(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async requestVerificationCode(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/request_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async verifyCode(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/verify_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getPhoneNumberSettings(e){let t=Array.isArray(e?.fields)?e.fields.join(`,`):e?.fields,n=v({...t?{fields:t}:{},...e?.include_sip_credentials===void 0?{}:{include_sip_credentials:e.include_sip_credentials}});return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/settings${n}`,this.config.REQUEST_TIMEOUT,null)}async updatePhoneNumberSettings(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/settings`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async setConversationalAutomation(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/conversational_automation`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getConversationalAutomation(){let e=v({fields:`conversational_automation`});return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}${e}`,this.config.REQUEST_TIMEOUT,null)}async getThroughput(){let e=v({fields:`throughput`});return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}${e}`,this.config.REQUEST_TIMEOUT,null)}async getOfficialBusinessAccountStatus(){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/official_business_account`,this.config.REQUEST_TIMEOUT,null)}async updateOfficialBusinessAccountStatus(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/official_business_account`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getBusinessComplianceInfo(){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/business_compliance_info`,this.config.REQUEST_TIMEOUT,null)}async updateBusinessComplianceInfo(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/business_compliance_info`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getUsername(){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/username`,this.config.REQUEST_TIMEOUT,null)}async updateUsername(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/username`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async deleteUsername(){return this.sendJson(`DELETE`,`${this.config.WA_PHONE_NUMBER_ID}/username`,this.config.REQUEST_TIMEOUT,null)}async getUsernameSuggestions(){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/username_suggestions`,this.config.REQUEST_TIMEOUT,null)}};function F(e){if(!e)return``;let t=``;return t=Array.isArray(e)?e.join(`,`):typeof e==`string`?e:Object.entries(e).filter(([e,t])=>t).map(([e])=>e).join(`,`),t?`?fields=${t}`:``}var xt=class extends c{endpoint=`whatsapp_business_profile`;async getBusinessProfile(e){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}${F(e)}`,this.config.REQUEST_TIMEOUT,null)}async updateBusinessProfile(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async createUploadSession(e,t,n){let r=v({file_length:e,file_type:t,file_name:n});return this.sendJson(`POST`,`app/uploads/${r}`,this.config.REQUEST_TIMEOUT,null)}async uploadMedia(e,t){return this.sendJson(`POST`,`${e}`,this.config.REQUEST_TIMEOUT,t)}async getUploadHandle(e){return this.sendJson(`GET`,`${e}`,this.config.REQUEST_TIMEOUT,null)}},St=class extends c{endpoint=`message_qrdls`;async createQrCode(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getQrCodes(){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async getQrCode(e){return this.sendJson(`GET`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}/${e}`,this.config.REQUEST_TIMEOUT,null)}async updateQrCode(e){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async deleteQrCode(e){return this.sendJson(`DELETE`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}/${e}`,this.config.REQUEST_TIMEOUT,null)}},Ct=class extends c{async register(e,t){let n={messaging_product:s,pin:e,...t&&{data_localization_region:t}};return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/register`,this.config.REQUEST_TIMEOUT,JSON.stringify(n))}async deregister(){return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/deregister`,this.config.REQUEST_TIMEOUT,null)}},wt=class extends c{toQuery(e){return e?v({fields:Array.isArray(e.fields)?e.fields.join(`,`):e.fields,role:e.role,status:e.status,limit:e.limit,after:e.after,before:e.before}):``}fieldsQuery(e){let t=Array.isArray(e)?e.join(`,`):e;return t?v({fields:t}):``}async createWhatsAppBusinessSolution(e,t){return this.sendJson(`POST`,`${e}/whatsapp_business_solution`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getApplicationWhatsAppBusinessSolutions(e,t){return this.sendJson(`GET`,`${e}/whatsapp_business_solutions${this.toQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async getSolutionAccessToken(e,t){return this.sendJson(`GET`,`${e}/access_token${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async acceptSolutionDeactivationRequest(e,t={}){return this.sendJson(`POST`,`${e}/accept_deactivation_request`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async acceptSolution(e,t={}){return this.sendJson(`POST`,`${e}/accept`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getSolutionDetails(e,t){return this.sendJson(`GET`,`${e}${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async rejectSolutionDeactivationRequest(e,t={}){return this.sendJson(`POST`,`${e}/reject_deactivation_request`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async rejectSolutionRequest(e,t={}){return this.sendJson(`POST`,`${e}/reject`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async sendSolutionDeactivationRequest(e,t={}){return this.sendJson(`POST`,`${e}/send_deactivation_request`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getMigrationIntentDetails(e,t){return this.sendJson(`GET`,`${e}${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async listWabaSolutions(e=this.config.WA_BUSINESS_ACCOUNT_ID,t){return this.sendJson(`GET`,`${e}/solutions${this.toQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async setSolutionMigrationIntent(e,t){return this.sendJson(`POST`,`${e}/set_solution_migration_intent`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}};function I(e){let t={type:`HEADER`,format:e.format};return e.text&&(t.text=e.text),e.example&&(t.example=e.example),t}function L(e){let t={type:`BODY`,text:e.text};return e.example&&(t.example=e.example),t}function R(e){return{type:`FOOTER`,text:e.text}}function z(e){let t=[];if(e.phone_number&&t.push({type:`PHONE_NUMBER`,text:e.phone_number.text,phone_number:e.phone_number.phone_number}),e.url){let n={type:`URL`,text:e.url.text,url:e.url.url};e.url.example&&(n.example=[e.url.example]),t.push(n)}if(e.quick_reply&&e.quick_reply.forEach(e=>{t.push({type:`QUICK_REPLY`,text:e.text})}),e.copy_code&&t.push({type:`COPY_CODE`,example:e.copy_code.example}),e.flow){let n={type:`FLOW`,text:e.flow.text};e.flow.flow_id&&(n.flow_id=e.flow.flow_id),e.flow.flow_name&&(n.flow_name=e.flow.flow_name),e.flow.flow_json&&(n.flow_json=e.flow.flow_json),e.flow.flow_action&&(n.flow_action=e.flow.flow_action),e.flow.navigate_screen&&(n.navigate_screen=e.flow.navigate_screen),t.push(n)}return e.mpm&&t.push({type:`MPM`}),e.otp&&t.push({type:`OTP`}),e.spm&&t.push({type:`SPM`}),t.length>0?[{type:`BUTTONS`,buttons:t}]:[]}function Tt(e){return e.map(e=>{switch(e.type){case`text`:return e.value;case`currency`:return e.fallback_value;case`date_time`:return e.fallback_value;case`image`:case`video`:case`document`:return e.handle||e.link||``;case`location`:return e.name||``;case`product`:return e.product_retailer_id;default:return``}})}function Et(e){let t=[];if(e.header&&t.push(I(e.header)),e.body&&t.push(L(e.body)),e.footer&&t.push(R(e.footer)),e.buttons&&t.push(...z(e.buttons)),e.carousel){let n=[];e.carousel.cards.forEach((e,t)=>{if(e.image||e.video||e.product){let t=e.image?`IMAGE`:e.video?`VIDEO`:`DOCUMENT`,r=e.image||e.video||e.product||``;n.push({type:`HEADER`,format:t,example:{header_handle:[r]}})}e.body&&n.push({type:`BODY`,text:e.body,example:e.bodyParameters?{body_text:[Tt(e.bodyParameters)]}:void 0}),e.buttons&&n.push(...z(e.buttons))}),t.push(...n)}return e.limitedTimeOffer&&t.push({type:`LIMITED_TIME_OFFER`,limited_time_offer:{expiration_time_ms:e.limitedTimeOffer.expiration_time_ms}}),{name:e.name,language:e.language,category:e.category,components:t.length>0?t:void 0}}function Dt(e){let t=[],n=`*{{1}}* is your verification code.`;return e.add_security_recommendation&&(n+=` For your security, do not share this code.`),e.code_expiration_minutes&&(n+=` This code expires in ${e.code_expiration_minutes} minutes.`),t.push({type:`BODY`,text:n,example:{body_text:[[`123456`]]}}),t.push({type:`BUTTONS`,buttons:[{type:`OTP`}]}),{name:e.name,language:e.language,category:`AUTHENTICATION`,components:t}}function Ot(e){let t=[],n=`Your security code is *{{1}}*.`;return e.add_security_recommendation&&(n+=` Do not share this code with anyone.`),e.code_expiration_minutes&&(n+=` This code expires in ${e.code_expiration_minutes} minutes.`),t.push({type:`BODY`,text:n,example:{body_text:[[`ABCD1234`]]}}),e.copy_code_button&&t.push({type:`BUTTONS`,buttons:[{type:`COPY_CODE`,example:`ABCD1234`}]}),{name:e.name,language:e.language,category:`AUTHENTICATION`,components:t}}function kt(e){let t=[];return e.header&&t.push(I({...e.header,format:`TEXT`})),t.push(L(e.body)),e.footer&&t.push(R(e.footer)),t.push({type:`BUTTONS`,buttons:[{type:`CATALOG`,action:{thumbnail_product_retailer_id:e.thumbnail_product_retailer_id}}]}),{name:e.name,language:e.language,category:`MARKETING`,components:t}}function At(e){let t=[];return e.header&&t.push(I({...e.header,format:`TEXT`})),t.push(L(e.body)),e.footer&&t.push(R(e.footer)),t.push({type:`BUTTONS`,buttons:[{type:`COPY_CODE`,example:e.coupon_code}]}),{name:e.name,language:e.language,category:`MARKETING`,components:t}}function jt(e){let t=[];return t.push({type:`LIMITED_TIME_OFFER`,limited_time_offer:{expiration_time_ms:e.expiration_time_ms}}),e.header&&t.push(I({...e.header,format:`TEXT`})),t.push(L(e.body)),e.footer&&t.push(R(e.footer)),{name:e.name,language:e.language,category:`MARKETING`,components:t}}function Mt(e){let t=[],n=[];return e.cards.forEach((e,t)=>{let r=[];r.push({type:`HEADER`,format:e.header.format,example:e.header.example}),r.push(L(e.body)),e.buttons&&r.push(...z(e.buttons)),n.push({card_index:t,components:r})}),t.push({type:`CAROUSEL`,cards:n}),{name:e.name,language:e.language,category:`MARKETING`,components:t}}function Nt(e){let t=[];return e.header&&t.push(I({...e.header,format:`TEXT`})),t.push(L(e.body)),e.footer&&t.push(R(e.footer)),t.push({type:`BUTTONS`,buttons:[{type:`MPM`,action:{thumbnail_product_retailer_id:e.thumbnail_product_retailer_id,sections:e.sections}}]}),{name:e.name,language:e.language,category:`MARKETING`,components:t}}function Pt(e){let t=[];e.header&&t.push(I({...e.header,format:`TEXT`})),t.push(L(e.body)),e.footer&&t.push(R(e.footer));let n=e.cards.map((e,t)=>({card_index:t,components:[{type:`HEADER`,format:`PRODUCT`,example:{header_handle:[e.product_retailer_id]}}]}));return t.push({type:`CAROUSEL`,cards:n}),{name:e.name,language:e.language,category:`MARKETING`,components:t}}function Ft(e){let t=[];return e.header&&t.push(I({...e.header,format:`TEXT`})),t.push(L(e.body)),e.footer&&t.push(R(e.footer)),t.push({type:`BUTTONS`,buttons:[{type:`SPM`,action:{product_retailer_id:e.product_retailer_id}}]}),{name:e.name,language:e.language,category:`MARKETING`,components:t}}var It=class extends c{endpoint=`message_templates`;async getTemplate(e){return this.sendJson(`GET`,`${e}`,this.config.REQUEST_TIMEOUT,null)}async updateTemplate(e,t){return this.sendJson(`POST`,`${e}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getTemplates(e){return this.sendJson(`GET`,`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${v(e??{})}`,this.config.REQUEST_TIMEOUT,null)}async createTemplate(e){return this.sendJson(`POST`,`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async deleteTemplate(e){return this.sendJson(`DELETE`,`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${v(e)}`,this.config.REQUEST_TIMEOUT,null)}};const Lt=2e3;var Rt=class extends c{endpoint=`thread_control`;async pass(e){return this.send(`pass`,e)}async release(e){return this.send(`release`,e)}async take(e){return this.send(`take`,e)}async send(e,t){let n=!!t?.to;if(n===!!t?.recipient)throw new j(`Exactly one of "to" or "recipient" is required for thread control.`);if(t.metadata&&t.metadata.length>Lt)throw new j(`"metadata" must be at most ${Lt} characters for thread control.`);if(e!==`pass`&&t.control_pass)throw new j(`"control_pass" is only supported for the pass action.`);let r={messaging_product:s,...n?{to:t.to}:{recipient:t.recipient},action:e,...t.metadata!==void 0&&{metadata:t.metadata},...t.control_pass&&{control_pass:t.control_pass}};return await this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(r))}},zt=class extends c{async setTwoStepVerificationCode(e){let t={pin:e};return this.sendJson(`POST`,`${this.config.WA_PHONE_NUMBER_ID}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}},Bt=class extends c{toQuery(e){return e?v({fields:Array.isArray(e.fields)?e.fields.join(`,`):e.fields,filtering:Array.isArray(e.filtering)?JSON.stringify(e.filtering):e.filtering,sort:e.sort,limit:e.limit,after:e.after,before:e.before}):``}fieldsQuery(e){let t=Array.isArray(e)?e.join(`,`):e;return t?v({fields:t}):``}async getWabaAccount(e){let t=F(e)?.replace(/,/g,`%2C`);return this.sendJson(`GET`,`${this.config.WA_BUSINESS_ACCOUNT_ID}${t}`,this.config.REQUEST_TIMEOUT,null)}async updateWabaAccount(e){return this.sendJson(`POST`,`${this.config.WA_BUSINESS_ACCOUNT_ID}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getWabaActivities(e){return this.sendJson(`GET`,`${this.config.WA_BUSINESS_ACCOUNT_ID}/activities${this.toQuery(e)}`,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:e,verify_token:t}){let n={override_callback_uri:e,verify_token:t};return this.sendJson(`POST`,`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,JSON.stringify(n))}async unsubscribeFromWaba(){return this.sendJson(`DELETE`,`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,null)}async getAssignedUsers(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){return this.sendJson(`GET`,`${t}/assigned_users${this.toQuery(e)}`,this.config.REQUEST_TIMEOUT,null)}async addAssignedUser(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){let n={user:e.user,tasks:e.tasks};return this.sendUrlEncodedForm(`POST`,`${t}/assigned_users`,this.config.REQUEST_TIMEOUT,n)}async removeAssignedUser(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){return this.sendUrlEncodedForm(`DELETE`,`${t}/assigned_users`,this.config.REQUEST_TIMEOUT,{user:e.user})}async getInProgressOnBehalfRequests(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){return this.sendJson(`GET`,`${t}/in_progress_onbehalf_request${this.toQuery(e)}`,this.config.REQUEST_TIMEOUT,null)}async getOBOMobilityIntent(e,t){return this.sendJson(`GET`,`${e}${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async createOBOMobilityIntent(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){return this.sendJson(`POST`,`${t}/obo_mobility_intent`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async setOBOMobilityIntent(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){return this.sendJson(`POST`,`${t}/set_obo_mobility_intent`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getWabaSchedules(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){return this.sendJson(`GET`,`${t}/schedules${this.toQuery(e)}`,this.config.REQUEST_TIMEOUT,null)}async createWabaSchedule(e,t=this.config.WA_BUSINESS_ACCOUNT_ID){return this.sendJson(`POST`,`${t}/schedules`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getWhatsAppBusinessBotDetails(e,t){return this.sendJson(`GET`,`${e}${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async getWhatsAppBusinessProfileDetails(e,t){return this.sendJson(`GET`,`${e}${this.fieldsQuery(t)}`,this.config.REQUEST_TIMEOUT,null)}async updateWhatsAppBusinessProfile(e,t){return this.sendJson(`POST`,e,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}};let Vt=function(e){return e.Approved=`APPROVED`,e.Active=`ACTIVE`,e.Inactive=`INACTIVE`,e.Disabled=`DISABLED`,e}({}),Ht=function(e){return e.Blocked=`BLOCKED`,e.Limited=`LIMITED`,e.Available=`AVAILABLE`,e}({}),Ut=function(e){return e.Approved=`APPROVED`,e.Active=`ACTIVE`,e.Inactive=`INACTIVE`,e.Disabled=`DISABLED`,e}({}),Wt=function(e){return e.Verified=`verified`,e.PendingSubmission=`pending_submission`,e.Unverified=`unverified`,e.Rejected=`rejected`,e}({});var B=class{name;debug;constructor(e,t=!1){this.name=e,this.debug=t}formatData(e){return e.map(e=>typeof e==`object`?t(e,{depth:null,colors:!0}):e).join(` `)}log(...e){if(this.debug){let t=`[ ${Date.now()} ]`;this.name&&(t+=` - ${this.name}`),console.log(t,`: `,this.formatData(e))}}error(...e){let t=`[ ${Date.now()} ] - ERROR`;this.name&&(t+=` - ${this.name}`),console.error(t,`: `,this.formatData(e))}warn(...e){if(this.debug){let t=`[ ${Date.now()} ] - WARN`;this.name&&(t+=` - ${this.name}`),console.warn(t,`: `,this.formatData(e))}}info(...e){if(this.debug){let t=`[ ${Date.now()} ] - INFO`;this.name&&(t+=` - ${this.name}`),console.info(t,`: `,this.formatData(e))}}};const Gt=new B(`UTILS`,process.env.DEBUG===`true`||!1),Kt=e=>{if(!process.env.CLOUD_API_ACCESS_TOKEN&&!e?.accessToken)throw Gt.log(`Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined.`),Error(`Missing WhatsApp access token.`)},qt=e=>(Kt(e),{M4D_APP_ID:e?.appId||process.env.M4D_APP_ID||``,M4D_APP_SECRET:e?.appSecret||process.env.M4D_APP_SECRET||``,WA_PHONE_NUMBER_ID:e?.phoneNumberId||(process.env.WA_PHONE_NUMBER_ID?Number(process.env.WA_PHONE_NUMBER_ID):0),WA_BUSINESS_ACCOUNT_ID:e?.businessAcctId||process.env.WA_BUSINESS_ACCOUNT_ID||``,CLOUD_API_VERSION:e?.apiVersion||process.env.CLOUD_API_VERSION||`v23.0`,CLOUD_API_ACCESS_TOKEN:e?.accessToken||process.env.CLOUD_API_ACCESS_TOKEN||``,WEBHOOK_ENDPOINT:e?.webhookEndpoint||process.env.WEBHOOK_ENDPOINT||``,WEBHOOK_VERIFICATION_TOKEN:e?.webhookVerificationToken||process.env.WEBHOOK_VERIFICATION_TOKEN||``,LISTENER_PORT:e?.listenerPort||parseInt(process.env.LISTENER_PORT||``,10)||3e3,MAX_RETRIES_AFTER_WAIT:e?.maxRetriesAfterWait||parseInt(process.env.MAX_RETRIES_AFTER_WAIT||``,10)||30,REQUEST_TIMEOUT:e?.requestTimeout||parseInt(process.env.REQUEST_TIMEOUT||``,10)||2e4,DEBUG:e?.debug||process.env.DEBUG===`true`,FLOW_API_PRIVATE_PEM:e?.privatePem||process.env.FLOW_API_PRIVATE_PEM||``,FLOW_API_PASSPHRASE:e?.passphrase||process.env.FLOW_API_PASSPHRASE||``,retry:e?.retry});function Jt(e){let t=[[`App ID`,e.M4D_APP_ID||`Not Set`],[`Phone Number ID`,e.WA_PHONE_NUMBER_ID?.toString()||`Not Set`],[`Business Account ID`,e.WA_BUSINESS_ACCOUNT_ID||`Not Set`],[`API Version`,e.CLOUD_API_VERSION||`Not Set`],[`Access Token`,e.CLOUD_API_ACCESS_TOKEN?`${e.CLOUD_API_ACCESS_TOKEN.substring(0,20)}...`:`Not Set`],[`Webhook Endpoint`,e.WEBHOOK_ENDPOINT||`Not Set`],[`Webhook Verification Token`,e.WEBHOOK_VERIFICATION_TOKEN?`${e.WEBHOOK_VERIFICATION_TOKEN.substring(0,10)}...`:`Not Set`],[`Listener Port`,e.LISTENER_PORT?.toString()||`Not Set`],[`Debug Mode`,e.DEBUG?`Enabled`:`Disabled`],[`Max Retries`,e.MAX_RETRIES_AFTER_WAIT?.toString()||`Not Set`],[`Request Timeout`,e.REQUEST_TIMEOUT?`${e.REQUEST_TIMEOUT}ms`:`Not Set`],[`Private PEM`,e.FLOW_API_PRIVATE_PEM?`Configured`:`Not Set`],[`Passphrase`,e.FLOW_API_PASSPHRASE?`Configured`:`Not Set`]],n=Math.max(...t.map(([e])=>e?.length||0)),r=Math.max(...t.map(([,e])=>e?.length||0)),i=Math.max(n,20),a=Math.max(r,30),o=`┌${`─`.repeat(i+2)}┬${`─`.repeat(a+2)}┐`,s=`├${`─`.repeat(i+2)}┼${`─`.repeat(a+2)}┤`,c=`└${`─`.repeat(i+2)}┴${`─`.repeat(a+2)}┘`;return[o,`│ ${`Configuration`.padEnd(i)} │ ${`Value`.padEnd(a)} │`,s,...t.map(([e,t])=>`│ ${e?.padEnd(i)} │ ${t?.padEnd(a)} │`),c].join(`
|
|
2
|
+
`)}const V=new B(`FLOW_ENCRYPTION_UTILS`,process.env.DEBUG===`true`);function Yt(){if(!r||typeof r.generateKeyPairSync!=`function`){let e=Error(`This utility requires Node.js environment with crypto module. It cannot be used in browser or edge runtime environments.`);throw V.error(`Environment validation failed:`,e),e}if(typeof window<`u`){let e=Error(`This utility cannot run in a browser environment. Please use it in a Node.js server environment only.`);throw V.error(`Browser environment detected:`,e),e}if(process.versions?.node){let e=process.versions.node.split(`.`).map(Number),t=e[0]??0,n=e[1]??0;if(t<10||t===10&&n<12){let e=Error(`Node.js version ${process.versions.node} is not supported. Please upgrade to Node.js 10.12.0 or higher.`);throw V.error(`Node.js version check failed:`,e),e}}}function Xt(e){V.info(`[generateEncryption] Starting key pair generation`),Yt();let t=e||process.env.FLOW_API_PASSPHRASE;if(!t||t.trim().length===0){let e=Error(`Passphrase is empty. Please provide a passphrase as parameter or set FLOW_API_PASSPHRASE environment variable.`);throw V.error(`[generateEncryption] Passphrase validation failed:`,e),e}t.length<8&&V.warn(`[generateEncryption] Passphrase is shorter than 8 characters. Consider using a longer passphrase for better security.`);try{V.info(`[generateEncryption] Generating 2048-bit RSA key pair`);let e=r.generateKeyPairSync(`rsa`,{modulusLength:2048,publicKeyEncoding:{type:`spki`,format:`pem`},privateKeyEncoding:{type:`pkcs8`,format:`pem`,cipher:`aes-256-cbc`,passphrase:t}});return V.info(`[generateEncryption] Key pair generated successfully`),{passphrase:t,privateKey:e.privateKey,publicKey:e.publicKey}}catch(e){let t=e instanceof Error?e.message:String(e),n=Error(`Failed to generate key pair: ${t}`);throw V.error(`[generateEncryption] Key generation failed:`,n),n}}function Zt(e,t){if(V.info(`[decryptFlowRequest] Starting Flow request decryption`),!t.FLOW_API_PRIVATE_PEM||t.FLOW_API_PRIVATE_PEM.trim()===``){let e=Error(`Missing FLOW_API_PRIVATE_PEM. Please set the FLOW_API_PRIVATE_PEM environment variable or pass privatePem via config.`);throw V.error(`[decryptFlowRequest] Configuration error:`,e),e}if(!t.FLOW_API_PASSPHRASE||t.FLOW_API_PASSPHRASE.trim()===``){let e=Error(`Missing FLOW_API_PASSPHRASE. Please set the FLOW_API_PASSPHRASE environment variable or pass passphrase via config.`);throw V.error(`[decryptFlowRequest] Configuration error:`,e),e}V.info(`[decryptFlowRequest] Configuration validated`);let{encrypted_aes_key:n,encrypted_flow_data:i,initial_vector:a}=e;if(!n||!i||!a)throw V.error(`[decryptFlowRequest] Missing required encryption properties in request body`),Error(`Missing required encryption properties`);V.info(`[decryptFlowRequest] Request body validated`);let o=t.FLOW_API_PRIVATE_PEM;o.includes(`\\n`)&&(o=o.replace(/\\n/g,`
|
|
3
3
|
`));let s=t.FLOW_API_PASSPHRASE,c=o.includes(`-----BEGIN RSA PRIVATE KEY-----`),l=o.includes(`-----BEGIN PRIVATE KEY-----`)||o.includes(`-----BEGIN ENCRYPTED PRIVATE KEY-----`);V.info(`[decryptFlowRequest] Loading private key`,{format:l?`PKCS#8`:c?`PKCS#1`:`Unknown`});let u;try{u=s?r.createPrivateKey({key:o,format:`pem`,passphrase:s}):r.createPrivateKey(o),V.info(`[decryptFlowRequest] Private key loaded successfully`)}catch(e){if(V.error(`[decryptFlowRequest] Failed to load private key (first attempt):`,{error:e instanceof Error?e.message:e,hasPassphrase:!!s,format:l?`PKCS#8`:c?`PKCS#1`:`Unknown`}),c&&s)try{V.info(`[decryptFlowRequest] Attempting to convert PKCS#1 to PKCS#8 format`);let e=r.createPrivateKey({key:o,format:`pem`,passphrase:s}).export({type:`pkcs8`,format:`pem`,cipher:`aes-256-cbc`,passphrase:s});u=r.createPrivateKey({key:e,format:`pem`,passphrase:s}),V.info(`[decryptFlowRequest] Successfully converted PKCS#1 to PKCS#8 and loaded private key`)}catch(t){V.error(`[decryptFlowRequest] Failed to convert PKCS#1 to PKCS#8:`,{error:t instanceof Error?t.message:t});let n=`Failed to parse private key. Error: ${e instanceof Error?e.message:e}`;throw n+=`
|
|
4
4
|
|
|
5
5
|
Your key is in PKCS#1 format with unsupported encryption (DES-EDE3-CBC).`,n+=`
|
|
@@ -10,12 +10,12 @@ Your key is in PKCS#1 format (-----BEGIN RSA PRIVATE KEY-----).`,t+=`
|
|
|
10
10
|
Please convert it to PKCS#8 format using:`,t+=`
|
|
11
11
|
openssl pkcs8 -topk8 -inform PEM -outform PEM -in old_key.pem -out new_key.pem`):l||(t+=`
|
|
12
12
|
|
|
13
|
-
Your key format is not recognized. Please ensure it is in PKCS#8 format.`),Error(t)}}let d;try{V.info(`[decryptFlowRequest] Decrypting AES key with RSA private key`),d=r.privateDecrypt({key:u,padding:r.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:`sha256`},Buffer.from(n,`base64`)),V.info(`[decryptFlowRequest] AES key decrypted successfully`)}catch(e){throw V.error(`[decryptFlowRequest] Failed to decrypt AES key:`,e),Error(`Failed to decrypt the request. Please verify your private key.`)}let f=Buffer.from(i,`base64`),p=Buffer.from(a,`base64`),m=f.subarray(0,-16),h=f.subarray(-16);V.info(`[decryptFlowRequest] Decrypting flow data with AES-128-GCM`);let g=r.createDecipheriv(`aes-128-gcm`,d,p);g.setAuthTag(h);let _=Buffer.concat([g.update(m),g.final()]).toString(`utf-8`);return V.info(`[decryptFlowRequest] Flow request decrypted successfully`),{decryptedBody:JSON.parse(_),aesKeyBuffer:d,initialVectorBuffer:p}}function
|
|
13
|
+
Your key format is not recognized. Please ensure it is in PKCS#8 format.`),Error(t)}}let d;try{V.info(`[decryptFlowRequest] Decrypting AES key with RSA private key`),d=r.privateDecrypt({key:u,padding:r.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:`sha256`},Buffer.from(n,`base64`)),V.info(`[decryptFlowRequest] AES key decrypted successfully`)}catch(e){throw V.error(`[decryptFlowRequest] Failed to decrypt AES key:`,e),Error(`Failed to decrypt the request. Please verify your private key.`)}let f=Buffer.from(i,`base64`),p=Buffer.from(a,`base64`),m=f.subarray(0,-16),h=f.subarray(-16);V.info(`[decryptFlowRequest] Decrypting flow data with AES-128-GCM`);let g=r.createDecipheriv(`aes-128-gcm`,d,p);g.setAuthTag(h);let _=Buffer.concat([g.update(m),g.final()]).toString(`utf-8`);return V.info(`[decryptFlowRequest] Flow request decrypted successfully`),{decryptedBody:JSON.parse(_),aesKeyBuffer:d,initialVectorBuffer:p}}function Qt(e,t,n){V.info(`[encryptFlowResponse] Starting Flow response encryption`);let i=[];for(let e of Array.from(n.entries()))i.push(~e[1]);try{V.info(`[encryptFlowResponse] Encrypting response with AES-128-GCM`);let n=r.createCipheriv(`aes-128-gcm`,t,Buffer.from(i)),a=Buffer.concat([n.update(JSON.stringify(e||{}),`utf-8`),n.final(),n.getAuthTag()]).toString(`base64`);return V.info(`[encryptFlowResponse] Flow response encrypted successfully`),a}catch(e){throw V.error(`[encryptFlowResponse] Response encryption failed:`,e),Error(`Failed to encrypt response. Internal server error.`)}}const $t=new B(`HttpsClient`,process.env.DEBUG===`true`);var en=class{agent;constructor(){this.agent=new i({keepAlive:!0})}clearSockets(){return this.agent.destroy(),!0}async sendRequest(e,t,n,r,i,a){let o=`https://${e}/${t}`,s=new AbortController,c=setTimeout(()=>s.abort(),i);try{let e=await fetch(o,{method:n,headers:r,body:a,signal:s.signal});return $t.log(`${n} : ${o} - ${JSON.stringify(e)}`),clearTimeout(c),new tn(e)}catch(e){throw $t.error(`${n} : ${o} - ${JSON.stringify(e)}`),e}}},tn=class{res;respStatusCode;respHeaders;constructor(e){this.res=e,this.respStatusCode=e.status,this.respHeaders=Object.fromEntries(e.headers.entries())}statusCode(){return this.respStatusCode}headers(){return this.respHeaders}rawResponse(){return this.res}async json(){try{return await this.res.json()}catch(e){let t=Error(`Failed to parse response body to JSON: ${e.message}`);throw t.cause=e,t}}};const H=new B(`REQUESTER`,process.env.DEBUG===`true`);function nn(e){return new Promise(t=>setTimeout(t,e))}var rn=class{client;accessToken;phoneNumberId;businessAcctId;apiVersion;userAgent;host;protocol=`https:`;retryConfig;constructor(e,t,n,r,i,a){this.client=new en,this.host=`graph.facebook.com`,this.apiVersion=this.normalizeApiVersion(e),this.phoneNumberId=t,this.accessToken=n,this.businessAcctId=r,this.userAgent=i,this.retryConfig=a}buildHeader(e,t){let n={Authorization:`Bearer ${this.accessToken}`,"User-Agent":this.userAgent};return e!==`multipart/form-data`&&(n[`Content-Type`]=e),t&&Object.assign(n,t),n}buildCAPIPath(e){return`${this.apiVersion}/${e}`}normalizeApiVersion(e){if(!e)return`v23.0`;let t=e.trim();return/^v\d+\.\d+$/.test(t)?t:/^\d+\.\d+$/.test(t)?`v${t}`:/^v\d+$/.test(t)?`${t}.0`:/^\d+$/.test(t)?`v${t}.0`:t}buildRequestTarget(e){if(/^https?:\/\//.test(e)){let t=new URL(e),n=`${t.pathname}${t.search}`.replace(/^\//,``);return{host:t.host,path:n,displayUrl:t.toString()}}let t=this.buildCAPIPath(e.replace(/^\//,``));return{host:this.host,path:t,displayUrl:`${this.protocol.toLowerCase()}//${this.host}/${t}`}}async sendRequest(e,t,n,r,i=`application/json`,a){let o=this.retryConfig?.maxAttempts??3,s=this.retryConfig?.initialDelayMs??1e3,c=this.retryConfig?.backoff??`exponential`,l=i;r instanceof FormData?l=`multipart/form-data`:typeof r==`string`&&r.startsWith(`<?xml`)&&(l=`application/xml`);let u=this.buildRequestTarget(t);H.log(`${e} : ${u.displayUrl} (${l})`);for(let t=1;t<=o;t++)try{let t=e===`POST`||e===`PUT`||e===`DELETE`,i=await this.client.sendRequest(u.host,u.path,e,this.buildHeader(l,a),n,t?r:void 0);if(!i.rawResponse().ok){let e=null;try{e=await i.json()}catch{e=null}throw A(nt(e,i.statusCode()).error,i.statusCode())}return i}catch(e){if(e instanceof C&&t<o){let e=c===`exponential`?s*2**(t-1):s;H.log(`Throttled (attempt ${t}/${o}). Retrying in ${e}ms...`),await nn(e);continue}throw e instanceof b?e:M(e)?A(e.error):new Ge(e instanceof Error?e.message:`Network error occurred`,e)}throw new C(`Max retry attempts exceeded`,{message:`Max retry attempts exceeded`,type:`ThrottlingError`,code:130429,fbtrace_id:``},429)}async getJson(e,t,n,r,i){return await(await this.sendRequest(e,t,n,r,`application/json`,i)).json()}async sendFormData(e,t,n,r,i){return await(await this.sendRequest(e,t,n,r,`multipart/form-data`,i)).json()}updateTimeout(e){H.log(`Timeout updated to ${e}ms`)}updateAccessToken(e){this.accessToken=e,H.log(`Access token updated`)}async sendUrlEncodedForm(e,t,n,r,i){let a=new URLSearchParams;for(let[e,t]of Object.entries(r))if(Array.isArray(t))for(let n of t)a.append(e,n);else a.append(e,t);let o=a.toString();return await(await this.sendRequest(e,t,n,o,`application/x-www-form-urlencoded`,i)).json()}};function an(){process.env.NODE_ENV===`test`||process.env.VITEST===`true`||typeof global<`u`&&global.__VITEST__||console.log(`\x1B[36m%s\x1B[0m`,`
|
|
14
14
|
██████╗ ██╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ██████╗ ██╗
|
|
15
15
|
██╔════╝ ██║ ██╔═══██╗ ██║ ██║ ██╔══██╗ ██╔══██╗ ██╔══██╗ ██║
|
|
16
16
|
██║ ██║ ██║ ██║ ██║ ██║ ██║ ██║ ███████║ ██████╔╝ ██║
|
|
17
17
|
██║ ██║ ██║ ██║ ██║ ██║ ██║ ██║ ██╔══██║ ██╔═══╝ ██║
|
|
18
18
|
╚██████╗ ███████╗ ╚██████╔╝ ╚██████╔╝ ██████╔╝ ██║ ██║ ██║ ██║
|
|
19
19
|
╚═════╝ ╚══════╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝
|
|
20
|
-
`)}function rn(){try{let e=o(__dirname,`../../package.json`);return JSON.parse(a(e,`utf-8`)).version}catch{return`unknown`}}function an(){return`WhatsApp-Nodejs-SDK/${rn()} (Node.js ${process.version})`}const U=new B(`WHATSAPP`,process.env.DEBUG===`true`);var on=class{config;requester;blockUsers;business;calling;commerce;contactBook;groups;marketingMessages;messageHistory;messages;media;payments;phoneNumbers;solutions;twoStepVerification;flows;businessProfile;templates;encryption;qrCode;registration;waba;constructor(e){nn(),this.config=Gt(e),this.requester=new tn(this.config.CLOUD_API_VERSION,this.config.WA_PHONE_NUMBER_ID,this.config.CLOUD_API_ACCESS_TOKEN,this.config.WA_BUSINESS_ACCOUNT_ID,this.getUserAgent(),this.config.retry),this.blockUsers=new it(this.config,this.requester),this.business=new at(this.config,this.requester),this.calling=new ot(this.config,this.requester),this.commerce=new st(this.config,this.requester),this.contactBook=new ct(this.config,this.requester),this.groups=new ht(this.config,this.requester),this.marketingMessages=new gt(this.config,this.requester),this.messageHistory=new vt(this.config,this.requester),this.messages=new P(this.config,this.requester),this.media=new _t(this.config,this.requester),this.payments=new yt(this.config,this.requester),this.phoneNumbers=new bt(this.config,this.requester),this.solutions=new wt(this.config,this.requester),this.twoStepVerification=new Lt(this.config,this.requester),this.flows=new ut(this.config,this.requester),this.businessProfile=new xt(this.config,this.requester),this.templates=new It(this.config,this.requester),this.encryption=new lt(this.config,this.requester),this.qrCode=new St(this.config,this.requester),this.registration=new Ct(this.config,this.requester),this.waba=new Rt(this.config,this.requester),U.log(`\n${Kt(this.config)}`)}updateTimeout(e){this.config.REQUEST_TIMEOUT=e,this.requester.updateTimeout(e),U.log(`Timeout updated to ${e}ms`)}updateSenderNumberId(e){this.config.WA_PHONE_NUMBER_ID=e,U.log(`Sender number ID updated to ${e}`)}updateAccessToken(e){this.config.CLOUD_API_ACCESS_TOKEN=e,this.requester.updateAccessToken(e),U.log(`Access token updated`)}version(){return rn()}static get Enums(){return l}getUserAgent(){return an()}generateEncryption(e){return Jt(e||this.config.FLOW_API_PASSPHRASE)}};function sn(e){return typeof e==`object`&&!!e}function W(e){return typeof e==`string`}const cn=[`data_exchange`,`INIT`,`BACK`],ln=[`data_exchange`,`INIT`];function un(e){if(!(`flow_token`in e&&W(e.flow_token)&&`action`in e))return!1;let{action:t,version:n,screen:r,data:i}=e,a=n===`3.0`,o=cn.includes(t),s=r===void 0||W(r)&&r!==`SUCCESS`,c=t===`data_exchange`||sn(i);return a&&o&&s&&c}function dn(e){if(!(`flow_token`in e&&W(e.flow_token)&&`action`in e))return!1;let{action:t,screen:n,data:r}=e,i=ln.includes(t),a=W(n),o=sn(r)&&`error_key`in r&&W(r.error)&&`error_message`in r&&W(r.error_message);return i&&a&&o}function fn(e){return`action`in e&&e.action===`ping`}const G=new B(`WEBHOOK_UTILS`,process.env.DEBUG===`true`);async function pn(e,t,n){try{let r=await e.text(),i=JSON.parse(r),a={headers:e.headers,rawBody:r,method:e.method,url:e.url};if(n.rawHandler){let{rawHandler:e,rawHandlerFields:r}=n,o=i;if(r&&r.length>0){let e={...o,entry:o.entry.map(e=>({...e,changes:e.changes.filter(e=>r.includes(e.field))})).filter(e=>e.changes.length>0)};o=e.entry.length===0?null:e}o&&await e(t,o,a)}if(i.object!==`whatsapp_business_account`){let e=`Received webhook for non-WhatsApp event`;return G.warn(e),new Response(JSON.stringify({error:e}),{status:404})}let o=[];for(let e of i.entry)try{let r=e.changes;for(let i of r)i.field===`messages`?await bn(e.id,i.value,t,n,a):i.field===`account_update`?await q(e.id,i,n.accountUpdateHandler,t,a):i.field===`account_review_update`?await q(e.id,i,n.accountReviewUpdateHandler,t,a):i.field===`account_alerts`?await q(e.id,i,n.accountAlertsHandler,t,a):i.field===`business_capability_update`?await q(e.id,i,n.businessCapabilityUpdateHandler,t,a):i.field===`phone_number_name_update`?await q(e.id,i,n.phoneNumberNameUpdateHandler,t,a):i.field===`phone_number_quality_update`?await q(e.id,i,n.phoneNumberQualityUpdateHandler,t,a):i.field===`message_template_status_update`?await q(e.id,i,n.messageTemplateStatusUpdateHandler,t,a):i.field===`template_category_update`?await q(e.id,i,n.templateCategoryUpdateHandler,t,a):i.field===`message_template_quality_update`?await q(e.id,i,n.messageTemplateQualityUpdateHandler,t,a):i.field===`flows`?await q(e.id,i,n.flowsHandler,t,a):i.field===`security`?await q(e.id,i,n.securityHandler,t,a):i.field===`history`?await q(e.id,i,n.historyHandler,t,a):i.field===`smb_message_echoes`?await q(e.id,i,n.smbMessageEchoesHandler,t,a):i.field===`smb_app_state_sync`?await q(e.id,i,n.smbAppStateSyncHandler,t,a):i.field===`account_settings_update`?await q(e.id,i,n.accountSettingsUpdateHandler,t,a):i.field===`automatic_events`?await q(e.id,i,n.automaticEventsHandler,t,a):i.field===`business_status_update`?await q(e.id,i,n.businessStatusUpdateHandler,t,a):i.field===`calls`?await q(e.id,i,n.callsHandler,t,a):i.field===`group_lifecycle_update`?await q(e.id,i,n.groupLifecycleUpdateHandler,t,a):i.field===`group_participants_update`?await q(e.id,i,n.groupParticipantsUpdateHandler,t,a):i.field===`group_settings_update`?await q(e.id,i,n.groupSettingsUpdateHandler,t,a):i.field===`group_status_update`?await q(e.id,i,n.groupStatusUpdateHandler,t,a):i.field===`message_echoes`?await q(e.id,i,n.messageEchoesHandler,t,a):i.field===`message_template_components_update`?await q(e.id,i,n.messageTemplateComponentsUpdateHandler,t,a):i.field===`messaging_handovers`?await q(e.id,i,n.messagingHandoversHandler,t,a):i.field===`partner_solutions`?await q(e.id,i,n.partnerSolutionsHandler,t,a):i.field===`payment_configuration_update`?await q(e.id,i,n.paymentConfigurationUpdateHandler,t,a):i.field===`standby`?await q(e.id,i,n.standbyHandler,t,a):i.field===`template_correct_category_detection`?await q(e.id,i,n.templateCorrectCategoryDetectionHandler,t,a):i.field===`tracking_events`?await q(e.id,i,n.trackingEventsHandler,t,a):i.field===`user_preferences`?await q(e.id,i,n.userPreferencesHandler,t,a):G.warn(`Unhandled webhook field: ${i.field}`)}catch(t){let n=`Error processing webhook: ${t}`;G.error(n,{entry:e,error:t}),o.push(n)}return new Response(o.length>0?JSON.stringify({errors:o}):null,{status:200})}catch(e){return G.error(`Error processing webhook:`,e),new Response(JSON.stringify({error:`Internal Server Error`}),{status:500})}}function mn(){return{version:`3.0`,data:{status:`active`}}}function hn(){return{data:{acknowledged:!0}}}async function gn(e,t,n,r){try{let i=await e.text(),a={headers:e.headers,rawBody:i,method:e.method,url:e.url};if(!_n(i,e.headers.get(`x-hub-signature-256`),t.WEBHOOK_VERIFICATION_TOKEN||``))return G.warn(`Invalid request signature`),new Response(JSON.stringify({error:`Unauthorized`}),{status:401});let{decryptedBody:o,aesKeyBuffer:s,initialVectorBuffer:c}=Yt(JSON.parse(i),t),l=fn(o),u=dn(o),d=un(o),f;f=l?`ping`:u?`error`:d?`data_exchange`:`*`;let p=r.get(f);if(!p){if(f===`ping`)p=()=>mn();else if(f===`error`)p=()=>hn();else if(p=r.get(`*`),!p)return G.warn(`No handler registered for flow type:`,{flowType:f,action:o.action}),new Response(JSON.stringify({error:`Handler not found`}),{status:404})}let m=await p(n,o,a);if(u){G.warn(`Flow error notification received`,{error:o.data});let e=m||hn();return new Response(JSON.stringify(e),{status:200,headers:{"Content-Type":`application/json`}})}if(l||d){let e=Xt(m,s,c);return new Response(e,{status:200,headers:{"Content-Type":`text/plain`}})}return G.warn(`Unknown flow request type:`,o),new Response(JSON.stringify({error:`Unknown request type`}),{status:400})}catch(e){return G.error(`Error handling flow request:`,e),new Response(JSON.stringify({error:`Internal server error`}),{status:500})}}function _n(e,t,n){if(!t)return G.warn(`Missing signature in request`),!1;let i=r.createHmac(`sha256`,n).update(e).digest(`hex`);return r.timingSafeEqual(Buffer.from(t.replace(`sha256=`,``)),Buffer.from(i))}function vn(e,t){return`${e[`x-forwarded-proto`]||`http`}://${e.host||`localhost`}${t||`/`}`}function yn(e){return e.id?e.id:(e.type===`interactive`||e.type===`button`)&&`context`in e&&e.context?.id?e.context.id:``}async function bn(e,t,n,r,i){let a=t.metadata,o=e,s=a.display_phone_number,c=a.phone_number_id;if(`statuses`in t&&t.statuses){let e=t;for(let t of e.statuses){let e={wabaId:o,phoneNumberId:c,displayPhoneNumber:s,status:t};await xn(r.statusHandler,n,e,i)}return}if(`messages`in t&&t.messages){let e=t,a=e.contacts?.[0]?.profile?.name||``;for(let t of e.messages){let e={wabaId:o,phoneNumberId:c,displayPhoneNumber:s,profileName:a,message:t,messageId:yn(t)},l=t.type;await K(r.preProcessHandler,n,e,i,`pre-process`),await K(r.messageHandlers.get(l),n,e,i,l),await K(r.postProcessHandler,n,e,i,`post-process`)}}}async function K(e,t,n,r,i){if(e)try{await e(t,n,r)}catch(e){G.error(`Error in ${i} handler:`,{error:e,messageId:n.messageId})}}async function xn(e,t,n,r){if(e)try{await e(t,n,r)}catch(e){G.error(`Error in status handler:`,{error:e,statusId:n.status.id})}}async function q(e,t,n,r,i){if(n)try{await n(r,{wabaId:e,value:t.value},i)}catch(n){G.error(`Error in ${t.field} handler:`,{error:n,wabaId:e})}}const J=new B(`WEBHOOK_PROCESSOR`,process.env.DEBUG===`true`);var Y=class{config;client;messageHandlers=new Map;statusHandler=void 0;preProcessHandler=void 0;postProcessHandler=void 0;rawHandler=void 0;flowHandlers=new Map;accountUpdateHandler=void 0;accountReviewUpdateHandler=void 0;accountAlertsHandler=void 0;businessCapabilityUpdateHandler=void 0;phoneNumberNameUpdateHandler=void 0;phoneNumberQualityUpdateHandler=void 0;messageTemplateStatusUpdateHandler=void 0;templateCategoryUpdateHandler=void 0;messageTemplateQualityUpdateHandler=void 0;flowsHandler=void 0;securityHandler=void 0;historyHandler=void 0;smbMessageEchoesHandler=void 0;smbAppStateSyncHandler=void 0;accountSettingsUpdateHandler=void 0;automaticEventsHandler=void 0;businessStatusUpdateHandler=void 0;callsHandler=void 0;groupLifecycleUpdateHandler=void 0;groupParticipantsUpdateHandler=void 0;groupSettingsUpdateHandler=void 0;groupStatusUpdateHandler=void 0;messageEchoesHandler=void 0;messageTemplateComponentsUpdateHandler=void 0;messagingHandoversHandler=void 0;partnerSolutionsHandler=void 0;paymentConfigurationUpdateHandler=void 0;standbyHandler=void 0;templateCorrectCategoryDetectionHandler=void 0;trackingEventsHandler=void 0;userPreferencesHandler=void 0;constructor(e){this.config=Gt(e),this.client=new on(e),J.log(`WebhookProcessor instantiated`)}async processVerification(e,t,n){return e===`subscribe`&&t===this.config.WEBHOOK_VERIFICATION_TOKEN?{status:200,body:n||``,headers:{"Content-Type":`text/plain`}}:{status:403,body:JSON.stringify({error:`Forbidden`}),headers:{"Content-Type":`application/json`}}}async processWebhook(e){try{let t=await pn(e,this.client,{messageHandlers:this.messageHandlers,statusHandler:this.statusHandler,preProcessHandler:this.preProcessHandler,postProcessHandler:this.postProcessHandler,rawHandler:this.rawHandler?.handler,rawHandlerFields:this.rawHandler?.fields,accountUpdateHandler:this.accountUpdateHandler,accountReviewUpdateHandler:this.accountReviewUpdateHandler,accountAlertsHandler:this.accountAlertsHandler,businessCapabilityUpdateHandler:this.businessCapabilityUpdateHandler,phoneNumberNameUpdateHandler:this.phoneNumberNameUpdateHandler,phoneNumberQualityUpdateHandler:this.phoneNumberQualityUpdateHandler,messageTemplateStatusUpdateHandler:this.messageTemplateStatusUpdateHandler,templateCategoryUpdateHandler:this.templateCategoryUpdateHandler,messageTemplateQualityUpdateHandler:this.messageTemplateQualityUpdateHandler,flowsHandler:this.flowsHandler,securityHandler:this.securityHandler,historyHandler:this.historyHandler,smbMessageEchoesHandler:this.smbMessageEchoesHandler,smbAppStateSyncHandler:this.smbAppStateSyncHandler,accountSettingsUpdateHandler:this.accountSettingsUpdateHandler,automaticEventsHandler:this.automaticEventsHandler,businessStatusUpdateHandler:this.businessStatusUpdateHandler,callsHandler:this.callsHandler,groupLifecycleUpdateHandler:this.groupLifecycleUpdateHandler,groupParticipantsUpdateHandler:this.groupParticipantsUpdateHandler,groupSettingsUpdateHandler:this.groupSettingsUpdateHandler,groupStatusUpdateHandler:this.groupStatusUpdateHandler,messageEchoesHandler:this.messageEchoesHandler,messageTemplateComponentsUpdateHandler:this.messageTemplateComponentsUpdateHandler,messagingHandoversHandler:this.messagingHandoversHandler,partnerSolutionsHandler:this.partnerSolutionsHandler,paymentConfigurationUpdateHandler:this.paymentConfigurationUpdateHandler,standbyHandler:this.standbyHandler,templateCorrectCategoryDetectionHandler:this.templateCorrectCategoryDetectionHandler,trackingEventsHandler:this.trackingEventsHandler,userPreferencesHandler:this.userPreferencesHandler}),n=await t.text(),r=t.headers.get(`content-type`)||`application/json`;return{status:t.status,body:n,headers:{"Content-Type":r}}}catch(e){return J.log(`Error processing webhook: ${e}`),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}async processFlow(e){try{let t=await gn(e,this.config,this.client,this.flowHandlers),n=await t.text(),r=t.headers.get(`content-type`)||`text/plain`;return{status:t.status,body:n,headers:{"Content-Type":r}}}catch(e){return J.log(`Error processing flow: ${e}`),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}onMessage(e,t){if(e===`statuses`)throw Error(`MessageTypesEnum.Statuses is deprecated. Use onStatus(handler) instead of onMessage(MessageTypesEnum.Statuses, handler)`);this.messageHandlers.set(e,t),J.log(`Registered message handler for ${e}`)}onStatus(e){this.statusHandler=e,J.log(`Registered status handler`)}onMessagePreProcess(e){this.preProcessHandler=e,J.log(`Registered pre-process handler`)}onMessagePostProcess(e){this.postProcessHandler=e,J.log(`Registered post-process handler`)}onRaw(e,t){this.rawHandler={handler:e,fields:t},J.log(`Registered raw webhook handler${t?` for fields: ${t.join(`, `)}`:``}`)}onFlow(e,t){this.flowHandlers.set(e,t),J.log(`Registered flow handler for ${e}`)}onText(e){this.messageHandlers.set(`text`,e),J.log(`Registered text message handler`)}onImage(e){this.messageHandlers.set(`image`,e),J.log(`Registered image message handler`)}onVideo(e){this.messageHandlers.set(`video`,e),J.log(`Registered video message handler`)}onAudio(e){this.messageHandlers.set(`audio`,e),J.log(`Registered audio message handler`)}onDocument(e){this.messageHandlers.set(`document`,e),J.log(`Registered document message handler`)}onSticker(e){this.messageHandlers.set(`sticker`,e),J.log(`Registered sticker message handler`)}onInteractive(e){this.messageHandlers.set(`interactive`,e),J.log(`Registered interactive message handler`)}onButton(e){this.messageHandlers.set(`button`,e),J.log(`Registered button message handler`)}onLocation(e){this.messageHandlers.set(`location`,e),J.log(`Registered location message handler`)}onContacts(e){this.messageHandlers.set(`contacts`,e),J.log(`Registered contacts message handler`)}onReaction(e){this.messageHandlers.set(`reaction`,e),J.log(`Registered reaction message handler`)}onOrder(e){this.messageHandlers.set(`order`,e),J.log(`Registered order message handler`)}onSystem(e){this.messageHandlers.set(`system`,e),J.log(`Registered system message handler`)}onAccountUpdate(e){this.accountUpdateHandler=e,J.log(`Registered account_update handler`)}onAccountReviewUpdate(e){this.accountReviewUpdateHandler=e,J.log(`Registered account_review_update handler`)}onAccountAlerts(e){this.accountAlertsHandler=e,J.log(`Registered account_alerts handler`)}onBusinessCapabilityUpdate(e){this.businessCapabilityUpdateHandler=e,J.log(`Registered business_capability_update handler`)}onPhoneNumberNameUpdate(e){this.phoneNumberNameUpdateHandler=e,J.log(`Registered phone_number_name_update handler`)}onPhoneNumberQualityUpdate(e){this.phoneNumberQualityUpdateHandler=e,J.log(`Registered phone_number_quality_update handler`)}onMessageTemplateStatusUpdate(e){this.messageTemplateStatusUpdateHandler=e,J.log(`Registered message_template_status_update handler`)}onTemplateCategoryUpdate(e){this.templateCategoryUpdateHandler=e,J.log(`Registered template_category_update handler`)}onMessageTemplateQualityUpdate(e){this.messageTemplateQualityUpdateHandler=e,J.log(`Registered message_template_quality_update handler`)}onFlows(e){this.flowsHandler=e,J.log(`Registered flows handler`)}onSecurity(e){this.securityHandler=e,J.log(`Registered security handler`)}onHistory(e){this.historyHandler=e,J.log(`Registered history handler`)}onSmbMessageEchoes(e){this.smbMessageEchoesHandler=e,J.log(`Registered smb_message_echoes handler`)}onSmbAppStateSync(e){this.smbAppStateSyncHandler=e,J.log(`Registered smb_app_state_sync handler`)}onAccountSettingsUpdate(e){this.accountSettingsUpdateHandler=e,J.log(`Registered account_settings_update handler`)}onAutomaticEvents(e){this.automaticEventsHandler=e,J.log(`Registered automatic_events handler`)}onBusinessStatusUpdate(e){this.businessStatusUpdateHandler=e,J.log(`Registered business_status_update handler`)}onCalls(e){this.callsHandler=e,J.log(`Registered calls handler`)}onGroupLifecycleUpdate(e){this.groupLifecycleUpdateHandler=e,J.log(`Registered group_lifecycle_update handler`)}onGroupParticipantsUpdate(e){this.groupParticipantsUpdateHandler=e,J.log(`Registered group_participants_update handler`)}onGroupSettingsUpdate(e){this.groupSettingsUpdateHandler=e,J.log(`Registered group_settings_update handler`)}onGroupStatusUpdate(e){this.groupStatusUpdateHandler=e,J.log(`Registered group_status_update handler`)}onMessageEchoes(e){this.messageEchoesHandler=e,J.log(`Registered message_echoes handler`)}onMessageTemplateComponentsUpdate(e){this.messageTemplateComponentsUpdateHandler=e,J.log(`Registered message_template_components_update handler`)}onMessagingHandovers(e){this.messagingHandoversHandler=e,J.log(`Registered messaging_handovers handler`)}onPartnerSolutions(e){this.partnerSolutionsHandler=e,J.log(`Registered partner_solutions handler`)}onPaymentConfigurationUpdate(e){this.paymentConfigurationUpdateHandler=e,J.log(`Registered payment_configuration_update handler`)}onStandby(e){this.standbyHandler=e,J.log(`Registered standby handler`)}onTemplateCorrectCategoryDetection(e){this.templateCorrectCategoryDetectionHandler=e,J.log(`Registered template_correct_category_detection handler`)}onTrackingEvents(e){this.trackingEventsHandler=e,J.log(`Registered tracking_events handler`)}onUserPreferences(e){this.userPreferencesHandler=e,J.log(`Registered user_preferences handler`)}offMessage(e){this.messageHandlers.delete(e),J.log(`Removed message handler for ${e}`)}offMessagePreProcess(){this.preProcessHandler=void 0,J.log(`Removed pre-process handler`)}offMessagePostProcess(){this.postProcessHandler=void 0,J.log(`Removed post-process handler`)}offStatus(){this.statusHandler=void 0,J.log(`Removed status handler`)}offRaw(){this.rawHandler=void 0,J.log(`Removed raw webhook handler`)}offFlow(e){this.flowHandlers.delete(e),J.log(`Removed flow handler for ${e}`)}removeAllHandlers(){this.messageHandlers.clear(),this.statusHandler=void 0,this.preProcessHandler=void 0,this.postProcessHandler=void 0,this.rawHandler=void 0,this.flowHandlers.clear(),this.accountUpdateHandler=void 0,this.accountReviewUpdateHandler=void 0,this.accountAlertsHandler=void 0,this.businessCapabilityUpdateHandler=void 0,this.phoneNumberNameUpdateHandler=void 0,this.phoneNumberQualityUpdateHandler=void 0,this.messageTemplateStatusUpdateHandler=void 0,this.templateCategoryUpdateHandler=void 0,this.messageTemplateQualityUpdateHandler=void 0,this.flowsHandler=void 0,this.securityHandler=void 0,this.historyHandler=void 0,this.smbMessageEchoesHandler=void 0,this.smbAppStateSyncHandler=void 0,this.accountSettingsUpdateHandler=void 0,this.automaticEventsHandler=void 0,this.businessStatusUpdateHandler=void 0,this.callsHandler=void 0,this.groupLifecycleUpdateHandler=void 0,this.groupParticipantsUpdateHandler=void 0,this.groupSettingsUpdateHandler=void 0,this.groupStatusUpdateHandler=void 0,this.messageEchoesHandler=void 0,this.messageTemplateComponentsUpdateHandler=void 0,this.messagingHandoversHandler=void 0,this.partnerSolutionsHandler=void 0,this.paymentConfigurationUpdateHandler=void 0,this.standbyHandler=void 0,this.templateCorrectCategoryDetectionHandler=void 0,this.trackingEventsHandler=void 0,this.userPreferencesHandler=void 0,J.log(`Removed all handlers`)}getClient(){return this.client}getConfig(){return this.config}},Sn=class{processor;constructor(e){this.processor=new Y(e)}async processVerification(e,t,n){return await this.processor.processVerification(e,t,n)}async processWebhook(e){return await this.processor.processWebhook(e)}async processFlow(e){return await this.processor.processFlow(e)}constructFullUrl(e,t=``){return vn(e,t)}applyHeaders(e,t){t.setHeader&&Object.entries(e.headers).forEach(([e,n])=>{t.setHeader?.(e,n)})}async autoRoute(e,t,...n){switch(e.method?.toUpperCase()){case`GET`:return await this.handleGet(e,t,...n);case`POST`:return await this.handlePost(e,t,...n);default:if(t.status&&t.json)return t.status(405).json({error:`Method Not Allowed`});throw Error(`Method Not Allowed`)}}get webhookProcessor(){return this.processor}},Cn=class extends Sn{async handleGet(e,t,n){try{let{"hub.mode":n,"hub.verify_token":r,"hub.challenge":i}=e.query,a=await this.processVerification(n||null,r||null,i||null);return this.applyHeaders(a,t),t.status(a.status).send(a.body),a}catch(e){return n(e),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}async handlePost(e,t,n){try{let n=this.constructFullUrl(e.headers,e.url),r=e.rawBody??(e.method===`POST`?JSON.stringify(e.body):void 0),i=new globalThis.Request(n,{method:e.method,headers:e.headers,body:r}),a=await this.processWebhook(i);return this.applyHeaders(a,t),t.status(a.status).send(a.body),a}catch(e){return n(e),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}async handleFlow(e,t,n){try{let n=this.constructFullUrl(e.headers,e.url),r=e.rawBody??(e.method===`POST`?JSON.stringify(e.body):void 0),i=new globalThis.Request(n,{method:e.method,headers:e.headers,body:r}),a=await this.processFlow(i);return this.applyHeaders(a,t),t.status(a.status).send(a.body),a}catch(e){return n(e),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}getHandlers(){return{GET:(e,t,n)=>this.handleGet(e,t,n),POST:(e,t,n)=>this.handlePost(e,t,n),webhook:(e,t,n)=>this.autoRoute(e,t,n),flow:(e,t,n)=>this.handleFlow(e,t,n),processor:this.webhookProcessor}}};const X=new Map;function wn(e){return`express:${e.phoneNumberId??`default`}`}function Tn(e){let t=wn(e),n=X.get(t);if(n)return n;let r=new Cn(e),i={...r.getHandlers(),destroy:()=>{r.webhookProcessor.removeAllHandlers(),X.delete(t)}};return X.set(t,i),i}const Z=new Map;function En(e){return`nextjs-app:${e.phoneNumberId??`default`}`}function Dn(e){let t=En(e),n=Z.get(t);if(n)return n;let r=new Y(e),i={GET:async e=>{try{let{searchParams:t}=new URL(e.url),n=t.get(`hub.mode`),i=t.get(`hub.verify_token`),a=t.get(`hub.challenge`),o=await r.processVerification(n,i,a);return new Response(o.body,{status:o.status,headers:o.headers})}catch(e){return console.error(`Webhook verification error:`,e),new Response(`Internal Server Error`,{status:500})}},POST:async e=>{try{let t=await r.processWebhook(e);return new Response(t.body,{status:t.status,headers:t.headers})}catch(e){return console.error(`Webhook processing error:`,e),new Response(`Internal Server Error`,{status:500})}},webhook:{GET:async e=>{try{let{searchParams:t}=new URL(e.url),n=t.get(`hub.mode`),i=t.get(`hub.verify_token`),a=t.get(`hub.challenge`),o=await r.processVerification(n,i,a);return new Response(o.body,{status:o.status,headers:o.headers})}catch(e){return console.error(`Webhook verification error:`,e),new Response(`Internal Server Error`,{status:500})}},POST:async e=>{try{let t=await r.processWebhook(e);return new Response(t.body,{status:t.status,headers:t.headers})}catch(e){return console.error(`Webhook processing error:`,e),new Response(`Internal Server Error`,{status:500})}}},flow:{GET:async e=>{try{let t=await r.processFlow(e);return new Response(t.body,{status:t.status,headers:t.headers})}catch(e){return console.error(`Flow GET error:`,e),new Response(JSON.stringify({error:`Internal Server Error`}),{status:500,headers:{"Content-Type":`application/json`}})}},POST:async e=>{try{let t=await r.processFlow(e);return new Response(t.body,{status:t.status,headers:t.headers})}catch(e){return console.error(`Flow POST error:`,e),new Response(JSON.stringify({error:`Internal Server Error`}),{status:500,headers:{"Content-Type":`application/json`}})}}},processor:r,destroy:()=>{r.removeAllHandlers(),Z.delete(t)}};return Z.set(t,i),i}var On=class extends Sn{async parseRequestBody(e,t=!1){if(e.method===`POST`&&!e.body){let n=[];if(typeof e[Symbol.asyncIterator]==`function`){for await(let t of e)n.push(t);let r=Buffer.concat(n).toString();if(t&&(e.rawBody=r),r.trim())try{e.body=JSON.parse(r)}catch{throw Error(`Invalid JSON in request body`)}else e.body={}}}}async handleGet(e,t){try{let{"hub.mode":n,"hub.verify_token":r,"hub.challenge":i}=e.query,a=await this.processVerification(n||null,r||null,i||null);return this.applyHeaders(a,t),t.status(a.status).send(a.body),a}catch(e){return console.error(`Webhook verification error:`,e),t.status(500).json({error:`Internal Server Error`}),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}async handlePost(e,t){try{await this.parseRequestBody(e,!0)}catch(e){return console.error(`Webhook processing error:`,e),e instanceof Error&&e.message===`Invalid JSON in request body`?(t.status(400).json({error:`Invalid JSON`}),{status:400,body:JSON.stringify({error:`Invalid JSON`}),headers:{"Content-Type":`application/json`}}):(t.status(500).json({error:`Internal Server Error`}),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}})}try{let n=this.constructFullUrl(e.headers,e.url),r=e.rawBody??(e.method===`POST`?JSON.stringify(e.body):void 0),i=new Request(n,{method:`POST`,headers:e.headers,body:r}),a=await this.processWebhook(i);return this.applyHeaders(a,t),t.status(a.status).send(a.body),a}catch(e){return console.error(`Webhook processing error:`,e),t.status(500).json({error:`Internal Server Error`}),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}async handleFlow(e,t){try{await this.parseRequestBody(e,!0)}catch(e){return console.error(`Flow body parsing error:`,e),e instanceof Error&&e.message===`Invalid JSON in request body`?(t.status(400).json({error:`Invalid JSON`}),{status:400,body:JSON.stringify({error:`Invalid JSON`}),headers:{"Content-Type":`application/json`}}):(t.status(500).json({error:`Internal Server Error`}),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}})}try{let n=this.constructFullUrl(e.headers,e.url),r=e.rawBody??(e.method===`POST`?JSON.stringify(e.body):void 0),i=new Request(n,{method:e.method,headers:e.headers,body:r}),a=await this.processFlow(i);return this.applyHeaders(a,t),t.status(a.status).send(a.body),a}catch(e){return console.error(`Flow error:`,e),t.status(500).json({error:`Internal Server Error`}),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}getHandlers(){return{GET:(e,t)=>this.handleGet(e,t),POST:(e,t)=>this.handlePost(e,t),webhook:(e,t)=>this.autoRoute(e,t),flow:(e,t)=>this.handleFlow(e,t),processor:this.webhookProcessor}}};const Q=new Map;function kn(e){return`nextjs-page:${e.phoneNumberId??`default`}`}function An(e){let t=kn(e),n=Q.get(t);if(n)return n;let r=new On(e),i={...r.getHandlers(),destroy:()=>{r.webhookProcessor.removeAllHandlers(),Q.delete(t)}};return Q.set(t,i),i}function jn(e){switch(e.type){case`text`:return e.text.body;case`image`:return e.image.caption||`[Image]`;case`video`:return e.video.caption||`[Video]`;case`audio`:return e.audio.voice?`[Voice Message]`:`[Audio]`;case`document`:return e.document.caption||e.document.filename||`[Document]`;case`sticker`:return e.sticker.animated?`[Animated Sticker]`:`[Sticker]`;case`interactive`:{let t=e.interactive;return t.type===`button_reply`?t.button_reply.title:t.type===`list_reply`?t.list_reply.title:t.type===`nfm_reply`?t.nfm_reply.body||t.nfm_reply.name||`[Form Reply]`:`[Interactive]`}case`button`:return e.button.text;case`location`:return e.location.name||e.location.address||`📍 ${e.location.latitude}, ${e.location.longitude}`;case`contacts`:{let t=e.contacts.map(e=>e.name.formatted_name);return t.length===1?`👤 ${t[0]}`:`👤 ${t.length} contacts`}case`reaction`:return e.reaction.emoji||`[Reaction removed]`;case`order`:{let t=e.order.product_items.length;return`🛒 Order: ${t} item${t>1?`s`:``}`}case`system`:return e.system.body;case`unsupported`:return`[Unsupported message]`;default:return`[${e.type}]`}}const Mn=(e,t)=>n.createHmac(`sha256`,t).update(e,`utf-8`).digest(`hex`);function Nn(e){return e.type===`text`}function Pn(e){return e.type===`image`}function Fn(e){return e.type===`video`}function In(e){return e.type===`audio`}function Ln(e){return e.type===`document`}function Rn(e){return e.type===`sticker`}function $(e){return e.type===`interactive`}function zn(e){return e.type===`button`}function Bn(e){return e.type===`location`}function Vn(e){return e.type===`contacts`}function Hn(e){return e.type===`reaction`}function Un(e){return e.type===`order`}function Wn(e){return e.type===`system`}function Gn(e){return $(e)&&e.interactive.type===`button_reply`}function Kn(e){return $(e)&&e.interactive.type===`list_reply`}function qn(e){return $(e)&&e.interactive.type===`nfm_reply`}function Jn(e){return Pn(e)?{id:e.image.id,mimeType:e.image.mime_type,sha256:e.image.sha256,caption:e.image.caption}:Fn(e)?{id:e.video.id,mimeType:e.video.mime_type,sha256:e.video.sha256,caption:e.video.caption}:In(e)?{id:e.audio.id,mimeType:e.audio.mime_type,sha256:e.audio.sha256,voice:e.audio.voice}:Ln(e)?{id:e.document.id,mimeType:e.document.mime_type,sha256:e.document.sha256,caption:e.document.caption,filename:e.document.filename}:Rn(e)?{id:e.sticker.id,mimeType:e.sticker.mime_type,sha256:e.sticker.sha256,animated:e.sticker.animated}:null}function Yn(e){return $(e)?e.interactive.type===`button_reply`?{type:`button_reply`,id:e.interactive.button_reply.id,title:e.interactive.button_reply.title}:e.interactive.type===`list_reply`?{type:`list_reply`,id:e.interactive.list_reply.id,title:e.interactive.list_reply.title,description:e.interactive.list_reply.description}:e.interactive.type===`nfm_reply`?{type:`nfm_reply`,id:e.interactive.nfm_reply.name,title:e.interactive.nfm_reply.body,responseJson:e.interactive.nfm_reply.response_json}:null:null}function Xn(e){return Bn(e)?{latitude:e.location.latitude,longitude:e.location.longitude,name:e.location.name,address:e.location.address,url:e.location.url}:null}function Zn(e){return Vn(e)?e.contacts.map(e=>({formattedName:e.name.formatted_name,firstName:e.name.first_name,lastName:e.name.last_name,phones:e.phones?.map(e=>e.phone)||[],emails:e.emails?.map(e=>e.email)||[]})):[]}function Qn(e){return Hn(e)?{messageId:e.reaction.message_id,emoji:e.reaction.emoji||null}:null}function $n(e){return Un(e)?{catalogId:e.order.catalog_id,text:e.order.text,items:e.order.product_items.map(e=>({productId:e.product_retailer_id,quantity:e.quantity,price:e.item_price,currency:e.currency}))}:null}const er={Authentication:`AUTHENTICATION`,Marketing:`MARKETING`,Utility:`UTILITY`},tr={Authentication:`authentication`,Service:`service`,Utility:`utility`},nr={Approved:`APPROVED`,Pending:`PENDING`,Rejected:`REJECTED`},rr={Get:`GET`,Post:`POST`,Put:`PUT`,Delete:`DELETE`},ir={Audio:`audio`,Contacts:`contacts`,Document:`document`,Image:`image`,Interactive:`interactive`,Location:`location`,Reaction:`reaction`,Sticker:`sticker`,Template:`template`,Text:`text`,Video:`video`,Button:`button`,Order:`order`,System:`system`,Unsupported:`unsupported`,Unknown:`unknown`,Statuses:`statuses`,All:`*`},ar={Action:`ACTION`,CouponCode:`COUPON_CODE`,Currency:`CURRENCY`,DateTime:`DATE_TIME`,Document:`DOCUMENT`,ExpirationTimeMs:`EXPIRATION_TIME_MS`,Image:`IMAGE`,LimitedTimeOffer:`LIMITED_TIME_OFFER`,Location:`LOCATION`,OrderStatus:`ORDER_STATUS`,Payload:`PAYLOAD`,Product:`PRODUCT`,Text:`TEXT`,TtlMinutes:`TTL_MINUTES`,Video:`VIDEO`,WebviewInteraction:`WEBVIEW_INTERACTION`,WebviewPresentation:`WEBVIEW_PRESENTATION`},or={Button:`button`,List:`list`,Product:`product`,ProductList:`product_list`,CtaUrl:`cta_url`,Carousel:`carousel`,LocationRequest:`location_request_message`,AddressMessage:`address_message`,Flow:`flow`,VoiceCall:`voice_call`},sr={First:1,Second:2,Third:3,Fourth:4,Fifth:5},cr={Catalog:`CATALOG`,CopyCode:`COPY_CODE`,Flow:`FLOW`,Mpm:`MPM`,OrderDetails:`ORDER_DETAILS`,QuickReply:`QUICK_REPLY`,Reminder:`REMINDER`,Url:`URL`,VoiceCall:`VOICE_CALL`},lr={Header:`HEADER`,Body:`BODY`,Button:`BUTTON`,Footer:`FOOTER`},ur={BusinessInitiated:`business_initiated`,CustomerInitiated:`customer_initiated`,ReferralConversion:`referral_conversion`},dr={Delivered:`delivered`,Read:`read`,Sent:`sent`},fr={Mp4:`video/mp4`,Threegp:`video/3gp`},pr={Webp:`image/webp`},mr={Jpeg:`image/jpeg`,Png:`image/png`},hr={Text:`text/plain`,Pdf:`application/pdf`,Ppt:`application/vnd.ms-powerpoint`,Word:`application/msword`,Excel:`application/vnd.ms-excel`,OpenDoc:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,OpenPres:`application/vnd.openxmlformats-officedocument.presentationml.presentation`,OpenSheet:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`},gr={Aac:`audio/aac`,Mp4:`audio/mp4`,Mpeg:`audio/mpeg`,Amr:`audio/amr`,Ogg:`audio/ogg`},_r={Audio:`audio`,Button:`button`,Document:`document`,Text:`text`,Image:`image`,Interactive:`interactive`,Order:`order`,Sticker:`sticker`,System:`system`,Unknown:`unknown`,Video:`video`},vr={CustomerChangedNumber:`customer_changed_number`,CustomerIdentityChanged:`customer_identity_changed`,UserChangedNumber:`user_changed_number`,UserIdentityChanged:`user_identity_changed`,UserChangedUserId:`user_changed_user_id`},yr={Ad:`ad`,Post:`post`},br={Sms:`SMS`,Voice:`VOICE`},xr={Afrikaans:`af`,Albanian:`sq`,Arabic:`ar`,Azerbaijani:`az`,Bengali:`bn`,Bulgarian:`bg`,Catalan:`ca`,Chinese_CHN:`zh_CN`,Chinese_HKG:`zh_HK`,Chinese_TAI:`zh_TW`,Croatian:`hr`,Czech:`cs`,Danish:`da`,Dutch:`nl`,English:`en`,English_UK:`en_GB`,English_US:`en_US`,Estonian:`et`,Filipino:`fil`,Finnish:`fi`,French:`fr`,Georgian:`ka`,German:`de`,Greek:`el`,Gujarati:`gu`,Hausa:`ha`,Hebrew:`he`,Hindi:`hi`,Hungarian:`hu`,Indonesian:`id`,Irish:`ga`,Italian:`it`,Japanese:`ja`,Kannada:`kn`,Kazakh:`kk`,Kinyarwanda:`rw_RW`,Korean:`ko`,Kyrgyz_Kyrgyzstan:`ky_KG`,Lao:`lo`,Latvian:`lv`,Lithuanian:`lt`,Macedonian:`mk`,Malay:`ms`,Malayalam:`ml`,Marathi:`mr`,Norwegian:`nb`,Persian:`fa`,Polish:`pl`,Portuguese_BR:`pt_BR`,Portuguese_POR:`pt_PT`,Punjabi:`pa`,Romanian:`ro`,Russian:`ru`,Serbian:`sr`,Slovak:`sk`,Slovenian:`sl`,Spanish:`es`,Spanish_ARG:`es_AR`,Spanish_SPA:`es_ES`,Spanish_MEX:`es_MX`,Swahili:`sw`,Swedish:`sv`,Tamil:`ta`,Telugu:`te`,Thai:`th`,Turkish:`tr`,Ukrainian:`uk`,Urdu:`ur`,Uzbek:`uz`,Vietnamese:`vi`,Zulu:`zu`},Sr={AU:`AU`,ID:`ID`,IN:`IN`,JP:`JP`,SG:`SG`,KR:`KR`,DE:`DE`,CH:`CH`,GB:`GB`,BR:`BR`,BH:`BH`,ZA:`ZA`,AE:`AE`,CA:`CA`};export{be as AUTHORIZATION_ERROR_CODES,gr as AudioMediaTypes,le as AudioMediaTypesEnum,Te as BLOCK_USER_ERROR_CODES,it as BlockUsersApi,at as BusinessApi,xt as BusinessProfileApi,_e as BusinessVerticalEnum,sr as ButtonPosition,_ as ButtonPositionEnum,Ee as CALLING_ERROR_CODES,ot as CallingApi,er as Category,u as CategoryEnum,st as CommerceApi,lr as ComponentType,te as ComponentTypesEnum,ct as ContactBookApi,ur as ConversationTypes,re as ConversationTypesEnum,he as CurrencyCodesEnum,Sr as DataLocalizationRegion,ge as DataLocalizationRegionEnum,hr as DocumentMediaTypes,ce as DocumentMediaTypesEnum,lt as EncryptionApi,we as FLOW_ERROR_CODES,pt as FlowActionEnum,ut as FlowApi,ft as FlowCategoryEnum,dt as FlowStatusEnum,mt as FlowTypeEnum,De as GROUP_ERROR_CODES,ht as GroupsApi,rr as HttpMethods,p as HttpMethodsEnum,Se as INTEGRITY_ERROR_CODES,mr as ImageMediaTypes,se as ImageMediaTypesEnum,or as InteractiveTypes,g as InteractiveTypesEnum,xr as Languages,me as LanguagesEnum,B as Logger,gt as MarketingMessagesApi,_t as MediaApi,P as MessageApi,P as MessagesApi,tr as MessageCategory,d as MessageCategoryEnum,vt as MessageHistoryApi,ir as MessageTypes,m as MessageTypesEnum,ar as ParametersTypes,h as ParametersTypesEnum,yt as PaymentsApi,bt as PhoneNumberApi,St as QrCodeApi,yr as ReferralSourceTypes,fe as ReferralSourceTypesEnum,Ct as RegistrationApi,br as RequestCodeMethods,pe as RequestCodeMethodsEnum,Ce as SEND_MESSAGE_ERROR_CODES,wt as SolutionsApi,dr as Status,ie as StatusEnum,pr as StickerMediaTypes,oe as StickerMediaTypesEnum,cr as SubType,ee as SubTypeEnum,vr as SystemChangeTypes,de as SystemChangeTypesEnum,xe as THROTTLING_ERROR_CODES,It as TemplateApi,nr as TemplateStatus,f as TemplateStatusEnum,Lt as TwoStepVerificationApi,fr as VideoMediaTypes,ae as VideoMediaTypesEnum,ve as WHATSAPP_ERROR_CODES,zt as WabaAccountReviewStatus,Vt as WabaAccountStatus,Rt as WabaApi,Ht as WabaBusinessVerificationStatus,ne as WabaConfigEnum,Bt as WabaHealthStatusCanSendMessage,Y as WebhookProcessor,_r as WebhookTypes,ue as WebhookTypesEnum,on as WhatsApp,x as WhatsAppApiError,S as WhatsAppAuthorizationError,D as WhatsAppBlockUserError,O as WhatsAppCallingError,b as WhatsAppError,E as WhatsAppFlowError,k as WhatsAppGroupError,w as WhatsAppIntegrityError,Ge as WhatsAppNetworkError,T as WhatsAppSendMessageError,C as WhatsAppThrottlingError,Ke as WhatsAppUnknownError,j as WhatsAppValidationError,F as buildFieldsQueryString,vn as constructFullUrl,Ot as createAuthenticationTemplate,kt as createCatalogTemplate,At as createCouponTemplate,jt as createLimitedTimeOfferTemplate,Nt as createMPMTemplate,Mt as createMediaCardCarouselTemplate,Dt as createOTPTemplate,Pt as createProductCardCarouselTemplate,Ft as createSPMTemplate,Et as createTemplate,A as createWhatsAppApiError,Yt as decryptFlowRequest,Xt as encryptFlowResponse,Tn as expressWebhookHandler,jn as extractMessageText,Kt as formatConfigTable,Jt as generateEncryption,Mn as generateXHub256Sig,Zn as getContactsInfo,Yn as getInteractiveReply,Xn as getLocationInfo,Jn as getMediaInfo,$n as getOrderInfo,Qn as getReactionInfo,y as isApiPermissionErrorCode,In as isAudioMessage,Le as isAuthorizationErrorCode,He as isBlockUserErrorCode,zn as isButtonMessage,Gn as isButtonReply,Ue as isCallingErrorCode,Vn as isContactsMessage,Ln as isDocumentMessage,un as isFlowDataExchangeRequest,Ve as isFlowErrorCode,dn as isFlowErrorRequest,fn as isFlowPingRequest,We as isGroupErrorCode,Pn as isImageMessage,ze as isIntegrityErrorCode,$ as isInteractiveMessage,Kn as isListReply,Bn as isLocationMessage,M as isMetaError,qn as isNfmReply,Un as isOrderMessage,Hn as isReactionMessage,Be as isSendMessageErrorCode,Rn as isStickerMessage,Wn as isSystemMessage,Nn as isTextMessage,Re as isThrottlingErrorCode,Fn as isVideoMessage,qe as isWhatsAppApiErrorResponse,Je as isWhatsAppAuthorizationError,$e as isWhatsAppBlockUserError,et as isWhatsAppCallingError,Ie as isWhatsAppErrorCode,Qe as isWhatsAppFlowError,tt as isWhatsAppGroupError,Xe as isWhatsAppIntegrityError,Ze as isWhatsAppSendMessageError,Ye as isWhatsAppThrottlingError,Dn as nextjsAppWebhookHandler,An as nextjsPagesWebhookHandler,nt as normalizeMetaError,v as objectToQueryString,gn as processFlowRequest,pn as processWebhookMessages};
|
|
20
|
+
`)}function on(){try{let e=o(__dirname,`../../package.json`);return JSON.parse(a(e,`utf-8`)).version}catch{return`unknown`}}function sn(){return`WhatsApp-Nodejs-SDK/${on()} (Node.js ${process.version})`}const U=new B(`WHATSAPP`,process.env.DEBUG===`true`);var cn=class{config;requester;blockUsers;business;calling;commerce;contactBook;groups;marketingMessages;messageHistory;messages;media;payments;phoneNumbers;solutions;threadControl;twoStepVerification;flows;businessProfile;templates;encryption;qrCode;registration;waba;constructor(e){an(),this.config=qt(e),this.requester=new rn(this.config.CLOUD_API_VERSION,this.config.WA_PHONE_NUMBER_ID,this.config.CLOUD_API_ACCESS_TOKEN,this.config.WA_BUSINESS_ACCOUNT_ID,this.getUserAgent(),this.config.retry),this.blockUsers=new it(this.config,this.requester),this.business=new at(this.config,this.requester),this.calling=new ot(this.config,this.requester),this.commerce=new st(this.config,this.requester),this.contactBook=new ct(this.config,this.requester),this.groups=new ht(this.config,this.requester),this.marketingMessages=new gt(this.config,this.requester),this.messageHistory=new vt(this.config,this.requester),this.messages=new P(this.config,this.requester),this.media=new _t(this.config,this.requester),this.payments=new yt(this.config,this.requester),this.phoneNumbers=new bt(this.config,this.requester),this.solutions=new wt(this.config,this.requester),this.threadControl=new Rt(this.config,this.requester),this.twoStepVerification=new zt(this.config,this.requester),this.flows=new ut(this.config,this.requester),this.businessProfile=new xt(this.config,this.requester),this.templates=new It(this.config,this.requester),this.encryption=new lt(this.config,this.requester),this.qrCode=new St(this.config,this.requester),this.registration=new Ct(this.config,this.requester),this.waba=new Bt(this.config,this.requester),U.log(`\n${Jt(this.config)}`)}updateTimeout(e){this.config.REQUEST_TIMEOUT=e,this.requester.updateTimeout(e),U.log(`Timeout updated to ${e}ms`)}updateSenderNumberId(e){this.config.WA_PHONE_NUMBER_ID=e,U.log(`Sender number ID updated to ${e}`)}updateAccessToken(e){this.config.CLOUD_API_ACCESS_TOKEN=e,this.requester.updateAccessToken(e),U.log(`Access token updated`)}version(){return on()}static get Enums(){return l}getUserAgent(){return sn()}generateEncryption(e){return Xt(e||this.config.FLOW_API_PASSPHRASE)}};function ln(e){return typeof e==`object`&&!!e}function W(e){return typeof e==`string`}const un=[`data_exchange`,`INIT`,`BACK`],dn=[`data_exchange`,`INIT`];function fn(e){if(!(`flow_token`in e&&W(e.flow_token)&&`action`in e))return!1;let{action:t,version:n,screen:r,data:i}=e,a=n===`3.0`,o=un.includes(t),s=r===void 0||W(r)&&r!==`SUCCESS`,c=t===`data_exchange`||ln(i);return a&&o&&s&&c}function pn(e){if(!(`flow_token`in e&&W(e.flow_token)&&`action`in e))return!1;let{action:t,screen:n,data:r}=e,i=dn.includes(t),a=W(n),o=ln(r)&&`error_key`in r&&W(r.error)&&`error_message`in r&&W(r.error_message);return i&&a&&o}function mn(e){return`action`in e&&e.action===`ping`}const G=new B(`WEBHOOK_UTILS`,process.env.DEBUG===`true`);async function hn(e,t,n){try{let r=await e.text(),i=JSON.parse(r),a={headers:e.headers,rawBody:r,method:e.method,url:e.url};if(n.rawHandler){let{rawHandler:e,rawHandlerFields:r}=n,o=i;if(r&&r.length>0){let e={...o,entry:o.entry.map(e=>({...e,changes:e.changes.filter(e=>r.includes(e.field))})).filter(e=>e.changes.length>0)};o=e.entry.length===0?null:e}o&&await e(t,o,a)}if(i.object!==`whatsapp_business_account`){let e=`Received webhook for non-WhatsApp event`;return G.warn(e),new Response(JSON.stringify({error:e}),{status:404})}let o=[];for(let e of i.entry)try{let r=e.changes;for(let i of r)i.field===`messages`?await Sn(e.id,i.value,t,n,a):i.field===`account_update`?await q(e.id,i,n.accountUpdateHandler,t,a):i.field===`account_review_update`?await q(e.id,i,n.accountReviewUpdateHandler,t,a):i.field===`account_alerts`?await q(e.id,i,n.accountAlertsHandler,t,a):i.field===`business_capability_update`?await q(e.id,i,n.businessCapabilityUpdateHandler,t,a):i.field===`phone_number_name_update`?await q(e.id,i,n.phoneNumberNameUpdateHandler,t,a):i.field===`phone_number_quality_update`?await q(e.id,i,n.phoneNumberQualityUpdateHandler,t,a):i.field===`message_template_status_update`?await q(e.id,i,n.messageTemplateStatusUpdateHandler,t,a):i.field===`template_category_update`?await q(e.id,i,n.templateCategoryUpdateHandler,t,a):i.field===`message_template_quality_update`?await q(e.id,i,n.messageTemplateQualityUpdateHandler,t,a):i.field===`flows`?await q(e.id,i,n.flowsHandler,t,a):i.field===`security`?await q(e.id,i,n.securityHandler,t,a):i.field===`history`?await q(e.id,i,n.historyHandler,t,a):i.field===`smb_message_echoes`?await q(e.id,i,n.smbMessageEchoesHandler,t,a):i.field===`smb_app_state_sync`?await q(e.id,i,n.smbAppStateSyncHandler,t,a):i.field===`account_settings_update`?await q(e.id,i,n.accountSettingsUpdateHandler,t,a):i.field===`automatic_events`?await q(e.id,i,n.automaticEventsHandler,t,a):i.field===`business_status_update`?await q(e.id,i,n.businessStatusUpdateHandler,t,a):i.field===`business_username_updates`?await q(e.id,i,n.businessUsernameUpdatesHandler,t,a):i.field===`calls`?await q(e.id,i,n.callsHandler,t,a):i.field===`group_lifecycle_update`?await q(e.id,i,n.groupLifecycleUpdateHandler,t,a):i.field===`group_participants_update`?await q(e.id,i,n.groupParticipantsUpdateHandler,t,a):i.field===`group_settings_update`?await q(e.id,i,n.groupSettingsUpdateHandler,t,a):i.field===`group_status_update`?await q(e.id,i,n.groupStatusUpdateHandler,t,a):i.field===`message_echoes`?await q(e.id,i,n.messageEchoesHandler,t,a):i.field===`message_template_components_update`?await q(e.id,i,n.messageTemplateComponentsUpdateHandler,t,a):i.field===`messaging_handovers`?await q(e.id,i,n.messagingHandoversHandler,t,a):i.field===`partner_solutions`?await q(e.id,i,n.partnerSolutionsHandler,t,a):i.field===`payment_configuration_update`?await q(e.id,i,n.paymentConfigurationUpdateHandler,t,a):i.field===`standby`?await q(e.id,i,n.standbyHandler,t,a):i.field===`template_correct_category_detection`?await q(e.id,i,n.templateCorrectCategoryDetectionHandler,t,a):i.field===`tracking_events`?await q(e.id,i,n.trackingEventsHandler,t,a):i.field===`user_preferences`?await q(e.id,i,n.userPreferencesHandler,t,a):G.warn(`Unhandled webhook field: ${i.field}`)}catch(t){let n=`Error processing webhook: ${t}`;G.error(n,{entry:e,error:t}),o.push(n)}return new Response(o.length>0?JSON.stringify({errors:o}):null,{status:200})}catch(e){return G.error(`Error processing webhook:`,e),new Response(JSON.stringify({error:`Internal Server Error`}),{status:500})}}function gn(){return{version:`3.0`,data:{status:`active`}}}function _n(){return{data:{acknowledged:!0}}}async function vn(e,t,n,r){try{let i=await e.text(),a={headers:e.headers,rawBody:i,method:e.method,url:e.url};if(!yn(i,e.headers.get(`x-hub-signature-256`),t.WEBHOOK_VERIFICATION_TOKEN||``))return G.warn(`Invalid request signature`),new Response(JSON.stringify({error:`Unauthorized`}),{status:401});let{decryptedBody:o,aesKeyBuffer:s,initialVectorBuffer:c}=Zt(JSON.parse(i),t),l=mn(o),u=pn(o),d=fn(o),f;f=l?`ping`:u?`error`:d?`data_exchange`:`*`;let p=r.get(f);if(!p){if(f===`ping`)p=()=>gn();else if(f===`error`)p=()=>_n();else if(p=r.get(`*`),!p)return G.warn(`No handler registered for flow type:`,{flowType:f,action:o.action}),new Response(JSON.stringify({error:`Handler not found`}),{status:404})}let m=await p(n,o,a);if(u){G.warn(`Flow error notification received`,{error:o.data});let e=m||_n();return new Response(JSON.stringify(e),{status:200,headers:{"Content-Type":`application/json`}})}if(l||d){let e=Qt(m,s,c);return new Response(e,{status:200,headers:{"Content-Type":`text/plain`}})}return G.warn(`Unknown flow request type:`,o),new Response(JSON.stringify({error:`Unknown request type`}),{status:400})}catch(e){return G.error(`Error handling flow request:`,e),new Response(JSON.stringify({error:`Internal server error`}),{status:500})}}function yn(e,t,n){if(!t)return G.warn(`Missing signature in request`),!1;let i=r.createHmac(`sha256`,n).update(e).digest(`hex`);return r.timingSafeEqual(Buffer.from(t.replace(`sha256=`,``)),Buffer.from(i))}function bn(e,t){return`${e[`x-forwarded-proto`]||`http`}://${e.host||`localhost`}${t||`/`}`}function xn(e){return e.id?e.id:(e.type===`interactive`||e.type===`button`)&&`context`in e&&e.context?.id?e.context.id:``}async function Sn(e,t,n,r,i){let a=t.metadata,o=e,s=a.display_phone_number,c=a.phone_number_id;if(`statuses`in t&&t.statuses){let e=t;for(let t of e.statuses){let e={wabaId:o,phoneNumberId:c,displayPhoneNumber:s,status:t};await Cn(r.statusHandler,n,e,i)}return}if(`messages`in t&&t.messages){let e=t,a=e.contacts?.[0]?.profile?.name||``;for(let t of e.messages){let l={wabaId:o,phoneNumberId:c,displayPhoneNumber:s,profileName:a,message:t,messageId:xn(t),...e.conversation_context&&{conversationContext:e.conversation_context}},u=t.type;await K(r.preProcessHandler,n,l,i,`pre-process`),await K(r.messageHandlers.get(u),n,l,i,u),await K(r.postProcessHandler,n,l,i,`post-process`)}}}async function K(e,t,n,r,i){if(e)try{await e(t,n,r)}catch(e){G.error(`Error in ${i} handler:`,{error:e,messageId:n.messageId})}}async function Cn(e,t,n,r){if(e)try{await e(t,n,r)}catch(e){G.error(`Error in status handler:`,{error:e,statusId:n.status.id})}}async function q(e,t,n,r,i){if(n)try{await n(r,{wabaId:e,value:t.value},i)}catch(n){G.error(`Error in ${t.field} handler:`,{error:n,wabaId:e})}}const J=new B(`WEBHOOK_PROCESSOR`,process.env.DEBUG===`true`);var Y=class{config;client;messageHandlers=new Map;statusHandler=void 0;preProcessHandler=void 0;postProcessHandler=void 0;rawHandler=void 0;flowHandlers=new Map;accountUpdateHandler=void 0;accountReviewUpdateHandler=void 0;accountAlertsHandler=void 0;businessCapabilityUpdateHandler=void 0;phoneNumberNameUpdateHandler=void 0;phoneNumberQualityUpdateHandler=void 0;messageTemplateStatusUpdateHandler=void 0;templateCategoryUpdateHandler=void 0;messageTemplateQualityUpdateHandler=void 0;flowsHandler=void 0;securityHandler=void 0;historyHandler=void 0;smbMessageEchoesHandler=void 0;smbAppStateSyncHandler=void 0;accountSettingsUpdateHandler=void 0;automaticEventsHandler=void 0;businessStatusUpdateHandler=void 0;businessUsernameUpdatesHandler=void 0;callsHandler=void 0;groupLifecycleUpdateHandler=void 0;groupParticipantsUpdateHandler=void 0;groupSettingsUpdateHandler=void 0;groupStatusUpdateHandler=void 0;messageEchoesHandler=void 0;messageTemplateComponentsUpdateHandler=void 0;messagingHandoversHandler=void 0;partnerSolutionsHandler=void 0;paymentConfigurationUpdateHandler=void 0;standbyHandler=void 0;templateCorrectCategoryDetectionHandler=void 0;trackingEventsHandler=void 0;userPreferencesHandler=void 0;constructor(e){this.config=qt(e),this.client=new cn(e),J.log(`WebhookProcessor instantiated`)}async processVerification(e,t,n){return e===`subscribe`&&t===this.config.WEBHOOK_VERIFICATION_TOKEN?{status:200,body:n||``,headers:{"Content-Type":`text/plain`}}:{status:403,body:JSON.stringify({error:`Forbidden`}),headers:{"Content-Type":`application/json`}}}async processWebhook(e){try{let t=await hn(e,this.client,{messageHandlers:this.messageHandlers,statusHandler:this.statusHandler,preProcessHandler:this.preProcessHandler,postProcessHandler:this.postProcessHandler,rawHandler:this.rawHandler?.handler,rawHandlerFields:this.rawHandler?.fields,accountUpdateHandler:this.accountUpdateHandler,accountReviewUpdateHandler:this.accountReviewUpdateHandler,accountAlertsHandler:this.accountAlertsHandler,businessCapabilityUpdateHandler:this.businessCapabilityUpdateHandler,phoneNumberNameUpdateHandler:this.phoneNumberNameUpdateHandler,phoneNumberQualityUpdateHandler:this.phoneNumberQualityUpdateHandler,messageTemplateStatusUpdateHandler:this.messageTemplateStatusUpdateHandler,templateCategoryUpdateHandler:this.templateCategoryUpdateHandler,messageTemplateQualityUpdateHandler:this.messageTemplateQualityUpdateHandler,flowsHandler:this.flowsHandler,securityHandler:this.securityHandler,historyHandler:this.historyHandler,smbMessageEchoesHandler:this.smbMessageEchoesHandler,smbAppStateSyncHandler:this.smbAppStateSyncHandler,accountSettingsUpdateHandler:this.accountSettingsUpdateHandler,automaticEventsHandler:this.automaticEventsHandler,businessStatusUpdateHandler:this.businessStatusUpdateHandler,businessUsernameUpdatesHandler:this.businessUsernameUpdatesHandler,callsHandler:this.callsHandler,groupLifecycleUpdateHandler:this.groupLifecycleUpdateHandler,groupParticipantsUpdateHandler:this.groupParticipantsUpdateHandler,groupSettingsUpdateHandler:this.groupSettingsUpdateHandler,groupStatusUpdateHandler:this.groupStatusUpdateHandler,messageEchoesHandler:this.messageEchoesHandler,messageTemplateComponentsUpdateHandler:this.messageTemplateComponentsUpdateHandler,messagingHandoversHandler:this.messagingHandoversHandler,partnerSolutionsHandler:this.partnerSolutionsHandler,paymentConfigurationUpdateHandler:this.paymentConfigurationUpdateHandler,standbyHandler:this.standbyHandler,templateCorrectCategoryDetectionHandler:this.templateCorrectCategoryDetectionHandler,trackingEventsHandler:this.trackingEventsHandler,userPreferencesHandler:this.userPreferencesHandler}),n=await t.text(),r=t.headers.get(`content-type`)||`application/json`;return{status:t.status,body:n,headers:{"Content-Type":r}}}catch(e){return J.log(`Error processing webhook: ${e}`),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}async processFlow(e){try{let t=await vn(e,this.config,this.client,this.flowHandlers),n=await t.text(),r=t.headers.get(`content-type`)||`text/plain`;return{status:t.status,body:n,headers:{"Content-Type":r}}}catch(e){return J.log(`Error processing flow: ${e}`),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}onMessage(e,t){if(e===`statuses`)throw Error(`MessageTypesEnum.Statuses is deprecated. Use onStatus(handler) instead of onMessage(MessageTypesEnum.Statuses, handler)`);this.messageHandlers.set(e,t),J.log(`Registered message handler for ${e}`)}onStatus(e){this.statusHandler=e,J.log(`Registered status handler`)}onMessagePreProcess(e){this.preProcessHandler=e,J.log(`Registered pre-process handler`)}onMessagePostProcess(e){this.postProcessHandler=e,J.log(`Registered post-process handler`)}onRaw(e,t){this.rawHandler={handler:e,fields:t},J.log(`Registered raw webhook handler${t?` for fields: ${t.join(`, `)}`:``}`)}onFlow(e,t){this.flowHandlers.set(e,t),J.log(`Registered flow handler for ${e}`)}onText(e){this.messageHandlers.set(`text`,e),J.log(`Registered text message handler`)}onImage(e){this.messageHandlers.set(`image`,e),J.log(`Registered image message handler`)}onVideo(e){this.messageHandlers.set(`video`,e),J.log(`Registered video message handler`)}onAudio(e){this.messageHandlers.set(`audio`,e),J.log(`Registered audio message handler`)}onDocument(e){this.messageHandlers.set(`document`,e),J.log(`Registered document message handler`)}onSticker(e){this.messageHandlers.set(`sticker`,e),J.log(`Registered sticker message handler`)}onInteractive(e){this.messageHandlers.set(`interactive`,e),J.log(`Registered interactive message handler`)}onButton(e){this.messageHandlers.set(`button`,e),J.log(`Registered button message handler`)}onLocation(e){this.messageHandlers.set(`location`,e),J.log(`Registered location message handler`)}onContacts(e){this.messageHandlers.set(`contacts`,e),J.log(`Registered contacts message handler`)}onReaction(e){this.messageHandlers.set(`reaction`,e),J.log(`Registered reaction message handler`)}onOrder(e){this.messageHandlers.set(`order`,e),J.log(`Registered order message handler`)}onSystem(e){this.messageHandlers.set(`system`,e),J.log(`Registered system message handler`)}onAccountUpdate(e){this.accountUpdateHandler=e,J.log(`Registered account_update handler`)}onAccountReviewUpdate(e){this.accountReviewUpdateHandler=e,J.log(`Registered account_review_update handler`)}onAccountAlerts(e){this.accountAlertsHandler=e,J.log(`Registered account_alerts handler`)}onBusinessCapabilityUpdate(e){this.businessCapabilityUpdateHandler=e,J.log(`Registered business_capability_update handler`)}onPhoneNumberNameUpdate(e){this.phoneNumberNameUpdateHandler=e,J.log(`Registered phone_number_name_update handler`)}onPhoneNumberQualityUpdate(e){this.phoneNumberQualityUpdateHandler=e,J.log(`Registered phone_number_quality_update handler`)}onMessageTemplateStatusUpdate(e){this.messageTemplateStatusUpdateHandler=e,J.log(`Registered message_template_status_update handler`)}onTemplateCategoryUpdate(e){this.templateCategoryUpdateHandler=e,J.log(`Registered template_category_update handler`)}onMessageTemplateQualityUpdate(e){this.messageTemplateQualityUpdateHandler=e,J.log(`Registered message_template_quality_update handler`)}onFlows(e){this.flowsHandler=e,J.log(`Registered flows handler`)}onSecurity(e){this.securityHandler=e,J.log(`Registered security handler`)}onHistory(e){this.historyHandler=e,J.log(`Registered history handler`)}onSmbMessageEchoes(e){this.smbMessageEchoesHandler=e,J.log(`Registered smb_message_echoes handler`)}onSmbAppStateSync(e){this.smbAppStateSyncHandler=e,J.log(`Registered smb_app_state_sync handler`)}onAccountSettingsUpdate(e){this.accountSettingsUpdateHandler=e,J.log(`Registered account_settings_update handler`)}onAutomaticEvents(e){this.automaticEventsHandler=e,J.log(`Registered automatic_events handler`)}onBusinessStatusUpdate(e){this.businessStatusUpdateHandler=e,J.log(`Registered business_status_update handler`)}onBusinessUsernameUpdates(e){this.businessUsernameUpdatesHandler=e,J.log(`Registered business_username_updates handler`)}onCalls(e){this.callsHandler=e,J.log(`Registered calls handler`)}onGroupLifecycleUpdate(e){this.groupLifecycleUpdateHandler=e,J.log(`Registered group_lifecycle_update handler`)}onGroupParticipantsUpdate(e){this.groupParticipantsUpdateHandler=e,J.log(`Registered group_participants_update handler`)}onGroupSettingsUpdate(e){this.groupSettingsUpdateHandler=e,J.log(`Registered group_settings_update handler`)}onGroupStatusUpdate(e){this.groupStatusUpdateHandler=e,J.log(`Registered group_status_update handler`)}onMessageEchoes(e){this.messageEchoesHandler=e,J.log(`Registered message_echoes handler`)}onMessageTemplateComponentsUpdate(e){this.messageTemplateComponentsUpdateHandler=e,J.log(`Registered message_template_components_update handler`)}onMessagingHandovers(e){this.messagingHandoversHandler=e,J.log(`Registered messaging_handovers handler`)}onPartnerSolutions(e){this.partnerSolutionsHandler=e,J.log(`Registered partner_solutions handler`)}onPaymentConfigurationUpdate(e){this.paymentConfigurationUpdateHandler=e,J.log(`Registered payment_configuration_update handler`)}onStandby(e){this.standbyHandler=e,J.log(`Registered standby handler`)}onTemplateCorrectCategoryDetection(e){this.templateCorrectCategoryDetectionHandler=e,J.log(`Registered template_correct_category_detection handler`)}onTrackingEvents(e){this.trackingEventsHandler=e,J.log(`Registered tracking_events handler`)}onUserPreferences(e){this.userPreferencesHandler=e,J.log(`Registered user_preferences handler`)}offMessage(e){this.messageHandlers.delete(e),J.log(`Removed message handler for ${e}`)}offMessagePreProcess(){this.preProcessHandler=void 0,J.log(`Removed pre-process handler`)}offMessagePostProcess(){this.postProcessHandler=void 0,J.log(`Removed post-process handler`)}offStatus(){this.statusHandler=void 0,J.log(`Removed status handler`)}offRaw(){this.rawHandler=void 0,J.log(`Removed raw webhook handler`)}offFlow(e){this.flowHandlers.delete(e),J.log(`Removed flow handler for ${e}`)}removeAllHandlers(){this.messageHandlers.clear(),this.statusHandler=void 0,this.preProcessHandler=void 0,this.postProcessHandler=void 0,this.rawHandler=void 0,this.flowHandlers.clear(),this.accountUpdateHandler=void 0,this.accountReviewUpdateHandler=void 0,this.accountAlertsHandler=void 0,this.businessCapabilityUpdateHandler=void 0,this.phoneNumberNameUpdateHandler=void 0,this.phoneNumberQualityUpdateHandler=void 0,this.messageTemplateStatusUpdateHandler=void 0,this.templateCategoryUpdateHandler=void 0,this.messageTemplateQualityUpdateHandler=void 0,this.flowsHandler=void 0,this.securityHandler=void 0,this.historyHandler=void 0,this.smbMessageEchoesHandler=void 0,this.smbAppStateSyncHandler=void 0,this.accountSettingsUpdateHandler=void 0,this.automaticEventsHandler=void 0,this.businessStatusUpdateHandler=void 0,this.businessUsernameUpdatesHandler=void 0,this.callsHandler=void 0,this.groupLifecycleUpdateHandler=void 0,this.groupParticipantsUpdateHandler=void 0,this.groupSettingsUpdateHandler=void 0,this.groupStatusUpdateHandler=void 0,this.messageEchoesHandler=void 0,this.messageTemplateComponentsUpdateHandler=void 0,this.messagingHandoversHandler=void 0,this.partnerSolutionsHandler=void 0,this.paymentConfigurationUpdateHandler=void 0,this.standbyHandler=void 0,this.templateCorrectCategoryDetectionHandler=void 0,this.trackingEventsHandler=void 0,this.userPreferencesHandler=void 0,J.log(`Removed all handlers`)}getClient(){return this.client}getConfig(){return this.config}},wn=class{processor;constructor(e){this.processor=new Y(e)}async processVerification(e,t,n){return await this.processor.processVerification(e,t,n)}async processWebhook(e){return await this.processor.processWebhook(e)}async processFlow(e){return await this.processor.processFlow(e)}constructFullUrl(e,t=``){return bn(e,t)}applyHeaders(e,t){t.setHeader&&Object.entries(e.headers).forEach(([e,n])=>{t.setHeader?.(e,n)})}async autoRoute(e,t,...n){switch(e.method?.toUpperCase()){case`GET`:return await this.handleGet(e,t,...n);case`POST`:return await this.handlePost(e,t,...n);default:if(t.status&&t.json)return t.status(405).json({error:`Method Not Allowed`});throw Error(`Method Not Allowed`)}}get webhookProcessor(){return this.processor}},Tn=class extends wn{async handleGet(e,t,n){try{let{"hub.mode":n,"hub.verify_token":r,"hub.challenge":i}=e.query,a=await this.processVerification(n||null,r||null,i||null);return this.applyHeaders(a,t),t.status(a.status).send(a.body),a}catch(e){return n(e),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}async handlePost(e,t,n){try{let n=this.constructFullUrl(e.headers,e.url),r=e.rawBody??(e.method===`POST`?JSON.stringify(e.body):void 0),i=new globalThis.Request(n,{method:e.method,headers:e.headers,body:r}),a=await this.processWebhook(i);return this.applyHeaders(a,t),t.status(a.status).send(a.body),a}catch(e){return n(e),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}async handleFlow(e,t,n){try{let n=this.constructFullUrl(e.headers,e.url),r=e.rawBody??(e.method===`POST`?JSON.stringify(e.body):void 0),i=new globalThis.Request(n,{method:e.method,headers:e.headers,body:r}),a=await this.processFlow(i);return this.applyHeaders(a,t),t.status(a.status).send(a.body),a}catch(e){return n(e),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}getHandlers(){return{GET:(e,t,n)=>this.handleGet(e,t,n),POST:(e,t,n)=>this.handlePost(e,t,n),webhook:(e,t,n)=>this.autoRoute(e,t,n),flow:(e,t,n)=>this.handleFlow(e,t,n),processor:this.webhookProcessor}}};const X=new Map;function En(e){return`express:${e.phoneNumberId??`default`}`}function Dn(e){let t=En(e),n=X.get(t);if(n)return n;let r=new Tn(e),i={...r.getHandlers(),destroy:()=>{r.webhookProcessor.removeAllHandlers(),X.delete(t)}};return X.set(t,i),i}const Z=new Map;function On(e){return`nextjs-app:${e.phoneNumberId??`default`}`}function kn(e){let t=On(e),n=Z.get(t);if(n)return n;let r=new Y(e),i={GET:async e=>{try{let{searchParams:t}=new URL(e.url),n=t.get(`hub.mode`),i=t.get(`hub.verify_token`),a=t.get(`hub.challenge`),o=await r.processVerification(n,i,a);return new Response(o.body,{status:o.status,headers:o.headers})}catch(e){return console.error(`Webhook verification error:`,e),new Response(`Internal Server Error`,{status:500})}},POST:async e=>{try{let t=await r.processWebhook(e);return new Response(t.body,{status:t.status,headers:t.headers})}catch(e){return console.error(`Webhook processing error:`,e),new Response(`Internal Server Error`,{status:500})}},webhook:{GET:async e=>{try{let{searchParams:t}=new URL(e.url),n=t.get(`hub.mode`),i=t.get(`hub.verify_token`),a=t.get(`hub.challenge`),o=await r.processVerification(n,i,a);return new Response(o.body,{status:o.status,headers:o.headers})}catch(e){return console.error(`Webhook verification error:`,e),new Response(`Internal Server Error`,{status:500})}},POST:async e=>{try{let t=await r.processWebhook(e);return new Response(t.body,{status:t.status,headers:t.headers})}catch(e){return console.error(`Webhook processing error:`,e),new Response(`Internal Server Error`,{status:500})}}},flow:{GET:async e=>{try{let t=await r.processFlow(e);return new Response(t.body,{status:t.status,headers:t.headers})}catch(e){return console.error(`Flow GET error:`,e),new Response(JSON.stringify({error:`Internal Server Error`}),{status:500,headers:{"Content-Type":`application/json`}})}},POST:async e=>{try{let t=await r.processFlow(e);return new Response(t.body,{status:t.status,headers:t.headers})}catch(e){return console.error(`Flow POST error:`,e),new Response(JSON.stringify({error:`Internal Server Error`}),{status:500,headers:{"Content-Type":`application/json`}})}}},processor:r,destroy:()=>{r.removeAllHandlers(),Z.delete(t)}};return Z.set(t,i),i}var An=class extends wn{async parseRequestBody(e,t=!1){if(e.method===`POST`&&!e.body){let n=[];if(typeof e[Symbol.asyncIterator]==`function`){for await(let t of e)n.push(t);let r=Buffer.concat(n).toString();if(t&&(e.rawBody=r),r.trim())try{e.body=JSON.parse(r)}catch{throw Error(`Invalid JSON in request body`)}else e.body={}}}}async handleGet(e,t){try{let{"hub.mode":n,"hub.verify_token":r,"hub.challenge":i}=e.query,a=await this.processVerification(n||null,r||null,i||null);return this.applyHeaders(a,t),t.status(a.status).send(a.body),a}catch(e){return console.error(`Webhook verification error:`,e),t.status(500).json({error:`Internal Server Error`}),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}async handlePost(e,t){try{await this.parseRequestBody(e,!0)}catch(e){return console.error(`Webhook processing error:`,e),e instanceof Error&&e.message===`Invalid JSON in request body`?(t.status(400).json({error:`Invalid JSON`}),{status:400,body:JSON.stringify({error:`Invalid JSON`}),headers:{"Content-Type":`application/json`}}):(t.status(500).json({error:`Internal Server Error`}),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}})}try{let n=this.constructFullUrl(e.headers,e.url),r=e.rawBody??(e.method===`POST`?JSON.stringify(e.body):void 0),i=new Request(n,{method:`POST`,headers:e.headers,body:r}),a=await this.processWebhook(i);return this.applyHeaders(a,t),t.status(a.status).send(a.body),a}catch(e){return console.error(`Webhook processing error:`,e),t.status(500).json({error:`Internal Server Error`}),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}async handleFlow(e,t){try{await this.parseRequestBody(e,!0)}catch(e){return console.error(`Flow body parsing error:`,e),e instanceof Error&&e.message===`Invalid JSON in request body`?(t.status(400).json({error:`Invalid JSON`}),{status:400,body:JSON.stringify({error:`Invalid JSON`}),headers:{"Content-Type":`application/json`}}):(t.status(500).json({error:`Internal Server Error`}),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}})}try{let n=this.constructFullUrl(e.headers,e.url),r=e.rawBody??(e.method===`POST`?JSON.stringify(e.body):void 0),i=new Request(n,{method:e.method,headers:e.headers,body:r}),a=await this.processFlow(i);return this.applyHeaders(a,t),t.status(a.status).send(a.body),a}catch(e){return console.error(`Flow error:`,e),t.status(500).json({error:`Internal Server Error`}),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}getHandlers(){return{GET:(e,t)=>this.handleGet(e,t),POST:(e,t)=>this.handlePost(e,t),webhook:(e,t)=>this.autoRoute(e,t),flow:(e,t)=>this.handleFlow(e,t),processor:this.webhookProcessor}}};const Q=new Map;function jn(e){return`nextjs-page:${e.phoneNumberId??`default`}`}function Mn(e){let t=jn(e),n=Q.get(t);if(n)return n;let r=new An(e),i={...r.getHandlers(),destroy:()=>{r.webhookProcessor.removeAllHandlers(),Q.delete(t)}};return Q.set(t,i),i}function Nn(e){switch(e.type){case`text`:return e.text.body;case`image`:return e.image.caption||`[Image]`;case`video`:return e.video.caption||`[Video]`;case`audio`:return e.audio.voice?`[Voice Message]`:`[Audio]`;case`document`:return e.document.caption||e.document.filename||`[Document]`;case`sticker`:return e.sticker.animated?`[Animated Sticker]`:`[Sticker]`;case`interactive`:{let t=e.interactive;return t.type===`button_reply`?t.button_reply.title:t.type===`list_reply`?t.list_reply.title:t.type===`nfm_reply`?t.nfm_reply.body||t.nfm_reply.name||`[Form Reply]`:`[Interactive]`}case`button`:return e.button.text;case`location`:return e.location.name||e.location.address||`📍 ${e.location.latitude}, ${e.location.longitude}`;case`contacts`:{let t=e.contacts.map(e=>e.name.formatted_name);return t.length===1?`👤 ${t[0]}`:`👤 ${t.length} contacts`}case`reaction`:return e.reaction.emoji||`[Reaction removed]`;case`order`:{let t=e.order.product_items.length;return`🛒 Order: ${t} item${t>1?`s`:``}`}case`system`:return e.system.body;case`unsupported`:return`[Unsupported message]`;default:return`[${e.type}]`}}const Pn=(e,t)=>n.createHmac(`sha256`,t).update(e,`utf-8`).digest(`hex`);function Fn(e){return e.type===`text`}function In(e){return e.type===`image`}function Ln(e){return e.type===`video`}function Rn(e){return e.type===`audio`}function zn(e){return e.type===`document`}function Bn(e){return e.type===`sticker`}function $(e){return e.type===`interactive`}function Vn(e){return e.type===`button`}function Hn(e){return e.type===`location`}function Un(e){return e.type===`contacts`}function Wn(e){return e.type===`reaction`}function Gn(e){return e.type===`order`}function Kn(e){return e.type===`system`}function qn(e){return $(e)&&e.interactive.type===`button_reply`}function Jn(e){return $(e)&&e.interactive.type===`list_reply`}function Yn(e){return $(e)&&e.interactive.type===`nfm_reply`}function Xn(e){return In(e)?{id:e.image.id,mimeType:e.image.mime_type,sha256:e.image.sha256,caption:e.image.caption}:Ln(e)?{id:e.video.id,mimeType:e.video.mime_type,sha256:e.video.sha256,caption:e.video.caption}:Rn(e)?{id:e.audio.id,mimeType:e.audio.mime_type,sha256:e.audio.sha256,voice:e.audio.voice}:zn(e)?{id:e.document.id,mimeType:e.document.mime_type,sha256:e.document.sha256,caption:e.document.caption,filename:e.document.filename}:Bn(e)?{id:e.sticker.id,mimeType:e.sticker.mime_type,sha256:e.sticker.sha256,animated:e.sticker.animated}:null}function Zn(e){return $(e)?e.interactive.type===`button_reply`?{type:`button_reply`,id:e.interactive.button_reply.id,title:e.interactive.button_reply.title}:e.interactive.type===`list_reply`?{type:`list_reply`,id:e.interactive.list_reply.id,title:e.interactive.list_reply.title,description:e.interactive.list_reply.description}:e.interactive.type===`nfm_reply`?{type:`nfm_reply`,id:e.interactive.nfm_reply.name,title:e.interactive.nfm_reply.body,responseJson:e.interactive.nfm_reply.response_json}:null:null}function Qn(e){return Hn(e)?{latitude:e.location.latitude,longitude:e.location.longitude,name:e.location.name,address:e.location.address,url:e.location.url}:null}function $n(e){return Un(e)?e.contacts.map(e=>({formattedName:e.name.formatted_name,firstName:e.name.first_name,lastName:e.name.last_name,phones:e.phones?.map(e=>e.phone)||[],emails:e.emails?.map(e=>e.email)||[]})):[]}function er(e){return Wn(e)?{messageId:e.reaction.message_id,emoji:e.reaction.emoji||null}:null}function tr(e){return Gn(e)?{catalogId:e.order.catalog_id,text:e.order.text,items:e.order.product_items.map(e=>({productId:e.product_retailer_id,quantity:e.quantity,price:e.item_price,currency:e.currency}))}:null}const nr={Authentication:`AUTHENTICATION`,Marketing:`MARKETING`,Utility:`UTILITY`},rr={Authentication:`authentication`,Service:`service`,Utility:`utility`},ir={Approved:`APPROVED`,Pending:`PENDING`,Rejected:`REJECTED`},ar={Get:`GET`,Post:`POST`,Put:`PUT`,Delete:`DELETE`},or={Audio:`audio`,Contacts:`contacts`,Document:`document`,Image:`image`,Interactive:`interactive`,Location:`location`,Reaction:`reaction`,Sticker:`sticker`,Template:`template`,Text:`text`,Video:`video`,Button:`button`,Order:`order`,System:`system`,Unsupported:`unsupported`,Unknown:`unknown`,Statuses:`statuses`,All:`*`},sr={Action:`ACTION`,CouponCode:`COUPON_CODE`,Currency:`CURRENCY`,DateTime:`DATE_TIME`,Document:`DOCUMENT`,ExpirationTimeMs:`EXPIRATION_TIME_MS`,Image:`IMAGE`,LimitedTimeOffer:`LIMITED_TIME_OFFER`,Location:`LOCATION`,OrderStatus:`ORDER_STATUS`,Payload:`PAYLOAD`,Product:`PRODUCT`,Text:`TEXT`,TtlMinutes:`TTL_MINUTES`,Video:`VIDEO`,WebviewInteraction:`WEBVIEW_INTERACTION`,WebviewPresentation:`WEBVIEW_PRESENTATION`},cr={Button:`button`,List:`list`,Product:`product`,ProductList:`product_list`,CtaUrl:`cta_url`,Carousel:`carousel`,LocationRequest:`location_request_message`,AddressMessage:`address_message`,Flow:`flow`,VoiceCall:`voice_call`},lr={First:1,Second:2,Third:3,Fourth:4,Fifth:5},ur={Catalog:`CATALOG`,CopyCode:`COPY_CODE`,Flow:`FLOW`,Mpm:`MPM`,OrderDetails:`ORDER_DETAILS`,QuickReply:`QUICK_REPLY`,Reminder:`REMINDER`,Url:`URL`,VoiceCall:`VOICE_CALL`},dr={Header:`HEADER`,Body:`BODY`,Button:`BUTTON`,Footer:`FOOTER`},fr={BusinessInitiated:`business_initiated`,CustomerInitiated:`customer_initiated`,ReferralConversion:`referral_conversion`},pr={Delivered:`delivered`,Read:`read`,Sent:`sent`},mr={Mp4:`video/mp4`,Threegp:`video/3gp`},hr={Webp:`image/webp`},gr={Jpeg:`image/jpeg`,Png:`image/png`},_r={Text:`text/plain`,Pdf:`application/pdf`,Ppt:`application/vnd.ms-powerpoint`,Word:`application/msword`,Excel:`application/vnd.ms-excel`,OpenDoc:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,OpenPres:`application/vnd.openxmlformats-officedocument.presentationml.presentation`,OpenSheet:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`},vr={Aac:`audio/aac`,Mp4:`audio/mp4`,Mpeg:`audio/mpeg`,Amr:`audio/amr`,Ogg:`audio/ogg`},yr={Audio:`audio`,Button:`button`,Document:`document`,Text:`text`,Image:`image`,Interactive:`interactive`,Order:`order`,Sticker:`sticker`,System:`system`,Unknown:`unknown`,Video:`video`},br={CustomerChangedNumber:`customer_changed_number`,CustomerIdentityChanged:`customer_identity_changed`,UserChangedNumber:`user_changed_number`,UserIdentityChanged:`user_identity_changed`,UserChangedUserId:`user_changed_user_id`},xr={Ad:`ad`,Post:`post`},Sr={Sms:`SMS`,Voice:`VOICE`},Cr={Afrikaans:`af`,Albanian:`sq`,Arabic:`ar`,Azerbaijani:`az`,Bengali:`bn`,Bulgarian:`bg`,Catalan:`ca`,Chinese_CHN:`zh_CN`,Chinese_HKG:`zh_HK`,Chinese_TAI:`zh_TW`,Croatian:`hr`,Czech:`cs`,Danish:`da`,Dutch:`nl`,English:`en`,English_UK:`en_GB`,English_US:`en_US`,Estonian:`et`,Filipino:`fil`,Finnish:`fi`,French:`fr`,Georgian:`ka`,German:`de`,Greek:`el`,Gujarati:`gu`,Hausa:`ha`,Hebrew:`he`,Hindi:`hi`,Hungarian:`hu`,Indonesian:`id`,Irish:`ga`,Italian:`it`,Japanese:`ja`,Kannada:`kn`,Kazakh:`kk`,Kinyarwanda:`rw_RW`,Korean:`ko`,Kyrgyz_Kyrgyzstan:`ky_KG`,Lao:`lo`,Latvian:`lv`,Lithuanian:`lt`,Macedonian:`mk`,Malay:`ms`,Malayalam:`ml`,Marathi:`mr`,Norwegian:`nb`,Persian:`fa`,Polish:`pl`,Portuguese_BR:`pt_BR`,Portuguese_POR:`pt_PT`,Punjabi:`pa`,Romanian:`ro`,Russian:`ru`,Serbian:`sr`,Slovak:`sk`,Slovenian:`sl`,Spanish:`es`,Spanish_ARG:`es_AR`,Spanish_SPA:`es_ES`,Spanish_MEX:`es_MX`,Swahili:`sw`,Swedish:`sv`,Tamil:`ta`,Telugu:`te`,Thai:`th`,Turkish:`tr`,Ukrainian:`uk`,Urdu:`ur`,Uzbek:`uz`,Vietnamese:`vi`,Zulu:`zu`},wr={AU:`AU`,ID:`ID`,IN:`IN`,JP:`JP`,SG:`SG`,KR:`KR`,DE:`DE`,CH:`CH`,GB:`GB`,BR:`BR`,BH:`BH`,ZA:`ZA`,AE:`AE`,CA:`CA`};export{be as AUTHORIZATION_ERROR_CODES,vr as AudioMediaTypes,le as AudioMediaTypesEnum,Te as BLOCK_USER_ERROR_CODES,it as BlockUsersApi,at as BusinessApi,xt as BusinessProfileApi,_e as BusinessVerticalEnum,lr as ButtonPosition,_ as ButtonPositionEnum,Ee as CALLING_ERROR_CODES,ot as CallingApi,nr as Category,u as CategoryEnum,st as CommerceApi,dr as ComponentType,te as ComponentTypesEnum,ct as ContactBookApi,fr as ConversationTypes,re as ConversationTypesEnum,he as CurrencyCodesEnum,wr as DataLocalizationRegion,ge as DataLocalizationRegionEnum,_r as DocumentMediaTypes,ce as DocumentMediaTypesEnum,lt as EncryptionApi,we as FLOW_ERROR_CODES,pt as FlowActionEnum,ut as FlowApi,ft as FlowCategoryEnum,dt as FlowStatusEnum,mt as FlowTypeEnum,De as GROUP_ERROR_CODES,ht as GroupsApi,ar as HttpMethods,p as HttpMethodsEnum,Se as INTEGRITY_ERROR_CODES,gr as ImageMediaTypes,se as ImageMediaTypesEnum,cr as InteractiveTypes,g as InteractiveTypesEnum,Cr as Languages,me as LanguagesEnum,B as Logger,gt as MarketingMessagesApi,_t as MediaApi,P as MessageApi,P as MessagesApi,rr as MessageCategory,d as MessageCategoryEnum,vt as MessageHistoryApi,or as MessageTypes,m as MessageTypesEnum,sr as ParametersTypes,h as ParametersTypesEnum,yt as PaymentsApi,bt as PhoneNumberApi,St as QrCodeApi,xr as ReferralSourceTypes,fe as ReferralSourceTypesEnum,Ct as RegistrationApi,Sr as RequestCodeMethods,pe as RequestCodeMethodsEnum,Ce as SEND_MESSAGE_ERROR_CODES,wt as SolutionsApi,pr as Status,ie as StatusEnum,hr as StickerMediaTypes,oe as StickerMediaTypesEnum,ur as SubType,ee as SubTypeEnum,br as SystemChangeTypes,de as SystemChangeTypesEnum,xe as THROTTLING_ERROR_CODES,It as TemplateApi,ir as TemplateStatus,f as TemplateStatusEnum,Rt as ThreadControlApi,zt as TwoStepVerificationApi,mr as VideoMediaTypes,ae as VideoMediaTypesEnum,ve as WHATSAPP_ERROR_CODES,Vt as WabaAccountReviewStatus,Ut as WabaAccountStatus,Bt as WabaApi,Wt as WabaBusinessVerificationStatus,ne as WabaConfigEnum,Ht as WabaHealthStatusCanSendMessage,Y as WebhookProcessor,yr as WebhookTypes,ue as WebhookTypesEnum,cn as WhatsApp,x as WhatsAppApiError,S as WhatsAppAuthorizationError,D as WhatsAppBlockUserError,O as WhatsAppCallingError,b as WhatsAppError,E as WhatsAppFlowError,k as WhatsAppGroupError,w as WhatsAppIntegrityError,Ge as WhatsAppNetworkError,T as WhatsAppSendMessageError,C as WhatsAppThrottlingError,Ke as WhatsAppUnknownError,j as WhatsAppValidationError,F as buildFieldsQueryString,bn as constructFullUrl,Ot as createAuthenticationTemplate,kt as createCatalogTemplate,At as createCouponTemplate,jt as createLimitedTimeOfferTemplate,Nt as createMPMTemplate,Mt as createMediaCardCarouselTemplate,Dt as createOTPTemplate,Pt as createProductCardCarouselTemplate,Ft as createSPMTemplate,Et as createTemplate,A as createWhatsAppApiError,Zt as decryptFlowRequest,Qt as encryptFlowResponse,Dn as expressWebhookHandler,Nn as extractMessageText,Jt as formatConfigTable,Xt as generateEncryption,Pn as generateXHub256Sig,$n as getContactsInfo,Zn as getInteractiveReply,Qn as getLocationInfo,Xn as getMediaInfo,tr as getOrderInfo,er as getReactionInfo,y as isApiPermissionErrorCode,Rn as isAudioMessage,Le as isAuthorizationErrorCode,He as isBlockUserErrorCode,Vn as isButtonMessage,qn as isButtonReply,Ue as isCallingErrorCode,Un as isContactsMessage,zn as isDocumentMessage,fn as isFlowDataExchangeRequest,Ve as isFlowErrorCode,pn as isFlowErrorRequest,mn as isFlowPingRequest,We as isGroupErrorCode,In as isImageMessage,ze as isIntegrityErrorCode,$ as isInteractiveMessage,Jn as isListReply,Hn as isLocationMessage,M as isMetaError,Yn as isNfmReply,Gn as isOrderMessage,Wn as isReactionMessage,Be as isSendMessageErrorCode,Bn as isStickerMessage,Kn as isSystemMessage,Fn as isTextMessage,Re as isThrottlingErrorCode,Ln as isVideoMessage,qe as isWhatsAppApiErrorResponse,Je as isWhatsAppAuthorizationError,$e as isWhatsAppBlockUserError,et as isWhatsAppCallingError,Ie as isWhatsAppErrorCode,Qe as isWhatsAppFlowError,tt as isWhatsAppGroupError,Xe as isWhatsAppIntegrityError,Ze as isWhatsAppSendMessageError,Ye as isWhatsAppThrottlingError,kn as nextjsAppWebhookHandler,Mn as nextjsPagesWebhookHandler,nt as normalizeMetaError,v as objectToQueryString,vn as processFlowRequest,hn as processWebhookMessages};
|
|
21
21
|
//# sourceMappingURL=index.mjs.map
|