meta-cloud-api 1.1.9 → 1.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,12 +1,12 @@
1
- import{__export as e}from"./chunk-CTAAG5j7.js";import{Agent as t}from"https";import{readFileSync as n}from"fs";import{join as r}from"path";import*as i from"crypto";import a from"crypto";var o=e({AudioMediaTypesEnum:()=>oe,BusinessVerticalEnum:()=>pe,ButtonPositionEnum:()=>p,CategoryEnum:()=>s,ComponentTypesEnum:()=>h,ConversationTypesEnum:()=>ee,CurrencyCodesEnum:()=>de,DataLocalizationRegionEnum:()=>fe,DocumentMediaTypesEnum:()=>ae,HttpMethodsEnum:()=>l,ImageMediaTypesEnum:()=>ie,InteractiveTypesEnum:()=>f,LanguagesEnum:()=>_,MessageTypesEnum:()=>u,ParametersTypesEnum:()=>d,ReferralSourceTypesEnum:()=>le,RequestCodeMethodsEnum:()=>ue,StatusEnum:()=>te,StickerMediaTypesEnum:()=>re,SubTypeEnum:()=>m,SystemChangeTypesEnum:()=>ce,TemplateStatusEnum:()=>c,VideoMediaTypesEnum:()=>ne,WabaConfigEnum:()=>g,WebhookTypesEnum:()=>se});let s=function(e){return e.Authentication=`AUTHENTICATION`,e.Marketing=`MARKETING`,e.Utility=`UTILITY`,e}({}),c=function(e){return e.Approved=`APPROVED`,e.Pending=`PENDING`,e.Rejected=`REJECTED`,e}({}),l=function(e){return e.Get=`GET`,e.Post=`POST`,e.Put=`PUT`,e.Delete=`DELETE`,e}({}),u=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.Unknown=`unknown`,e.Statuses=`statuses`,e[`*`]=`*`,e}({}),d=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}({}),f=function(e){return e.Button=`button`,e.List=`list`,e.Product=`product`,e.ProductList=`product_list`,e.CtaUrl=`cta_url`,e.LocationRequest=`location_request_message`,e.AddressMessage=`address_message`,e.Flow=`flow`,e}({}),p=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}({}),m=function(e){return e.Catalog=`CATALOG`,e.CopyCode=`COPY_CODE`,e.Flow=`FLOW`,e.Mpm=`MPM`,e.OrderDetails=`ORDER_DETAILS`,e.QuickReply=`QUICK_REPLY`,e.Reminder=`REMINDER`,e.Url=`URL`,e.VoiceCall=`VOICE_CALL`,e}({}),h=function(e){return e.Header=`HEADER`,e.Body=`BODY`,e.Button=`BUTTON`,e.Footer=`FOOTER`,e}({}),g=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}({}),ee=function(e){return e.BusinessInitiated=`business_initiated`,e.CustomerInitiated=`customer_initiated`,e.ReferralConversion=`referral_conversion`,e}({}),te=function(e){return e.Delivered=`delivered`,e.Read=`read`,e.Sent=`sent`,e}({}),ne=function(e){return e.Mp4=`video/mp4`,e.Threegp=`video/3gp`,e}({}),re=function(e){return e.Webp=`image/webp`,e}({}),ie=function(e){return e.Jpeg=`image/jpeg`,e.Png=`image/png`,e}({}),ae=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}({}),oe=function(e){return e.Aac=`audio/aac`,e.Mp4=`audio/mp4`,e.Mpeg=`audio/mpeg`,e.Amr=`audio/amr`,e.Ogg=`audio/ogg`,e}({}),se=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}({}),ce=function(e){return e.CustomerChangedNumber=`customer_changed_number`,e.CustomerIdentityChanged=`customer_identity_changed`,e}({}),le=function(e){return e.Ad=`ad`,e.Post=`post`,e}({}),ue=function(e){return e.Sms=`SMS`,e.Voice=`VOICE`,e}({}),_=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}({}),de=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}({}),fe=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}({}),pe=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}({});var v=class{name;debug;constructor(e,t=!1){this.name=e,this.debug=t}log(...e){if(this.debug){let t=`[ ${Date.now()} ]`;this.name&&(t+=` - ${this.name}`),console.log.apply(console,[t,`: `,...e])}}error(...e){let t=`[ ${Date.now()} ] - ERROR`;this.name&&(t+=` - ${this.name}`),console.error.apply(console,[t,`: `,...e])}warn(...e){let t=`[ ${Date.now()} ] - WARN`;this.name&&(t+=` - ${this.name}`),console.warn.apply(console,[t,`: `,...e])}info(...e){let t=`[ ${Date.now()} ] - INFO`;this.name&&(t+=` - ${this.name}`),console.info.apply(console,[t,`: `,...e])}};const me=new v(`UTILS`,process.env.DEBUG===`true`||!1),he=e=>{if(!process.env[g.AccessToken]&&!e?.accessToken)throw me.log(`Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined.`),Error(`Missing WhatsApp access token.`)},ge=e=>(he(e),{[g.AppId]:e?.appId||process.env.M4D_APP_ID||``,[g.AppSecret]:e?.appSecret||process.env.M4D_APP_SECRET||``,[g.PhoneNumberId]:e?.phoneNumberId||Number(process.env.WA_PHONE_NUMBER_ID),[g.BusinessAcctId]:e?.businessAcctId||process.env.WA_BUSINESS_ACCOUNT_ID||``,[g.APIVersion]:e?.apiVersion||process.env.CLOUD_API_VERSION||``,[g.AccessToken]:e?.accessToken||process.env.CLOUD_API_ACCESS_TOKEN||``,[g.WebhookEndpoint]:e?.webhookEndpoint||process.env.WEBHOOK_ENDPOINT||``,[g.WebhookVerificationToken]:e?.webhookVerificationToken||process.env.WEBHOOK_VERIFICATION_TOKEN||``,[g.ListenerPort]:e?.listenerPort||parseInt(process.env.LISTENER_PORT||``)||3e3,[g.MaxRetriesAfterWait]:e?.maxRetriesAfterWait||parseInt(process.env.MAX_RETRIES_AFTER_WAIT||``)||30,[g.RequestTimeout]:e?.requestTimeout||parseInt(process.env.REQUEST_TIMEOUT||``)||2e4,[g.Debug]:e?.debug||process.env.DEBUG===`true`,[g.PrivatePem]:e?.privatePem||process.env.FLOW_API_PRIVATE_PEM||``,[g.Passphrase]:e?.passphrase||process.env.FLOW_API_PASSPHRASE||``});function _e(e){let t=[[`App ID`,e[g.AppId]||`Not Set`],[`Phone Number ID`,e[g.PhoneNumberId]?.toString()||`Not Set`],[`Business Account ID`,e[g.BusinessAcctId]||`Not Set`],[`API Version`,e[g.APIVersion]||`Not Set`],[`Access Token`,e[g.AccessToken]?`${e[g.AccessToken].substring(0,20)}...`:`Not Set`],[`Webhook Endpoint`,e[g.WebhookEndpoint]||`Not Set`],[`Webhook Verification Token`,e[g.WebhookVerificationToken]?`${e[g.WebhookVerificationToken].substring(0,10)}...`:`Not Set`],[`Listener Port`,e[g.ListenerPort]?.toString()||`Not Set`],[`Debug Mode`,e[g.Debug]?`Enabled`:`Disabled`],[`Max Retries`,e[g.MaxRetriesAfterWait]?.toString()||`Not Set`],[`Request Timeout`,e[g.RequestTimeout]?`${e[g.RequestTimeout]}ms`:`Not Set`],[`Private PEM`,e[g.PrivatePem]?`Configured`:`Not Set`],[`Passphrase`,e[g.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)}┘`,l=`│ ${`Configuration`.padEnd(i)} │ ${`Value`.padEnd(a)} │`,u=t.map(([e,t])=>`│ ${e?.padEnd(i)} │ ${t?.padEnd(a)} │`);return[o,l,s,...u,c].join(`
2
- `)}function ve(e){return typeof e==`object`&&!!e&&`error`in e&&typeof e.error==`object`&&e.error!=null&&`message`in e.error&&typeof e.error.message==`string`&&`type`in e.error&&typeof e.error.type==`string`&&`code`in e.error&&typeof e.error.code==`number`&&`fbtrace_id`in e.error&&typeof e.error.fbtrace_id==`string`&&(!(`error_data`in e.error)||typeof e.error.error_data==`object`&&e.error.error_data!=null&&`messaging_product`in e.error.error_data&&e.error.error_data.messaging_product===`whatsapp`&&`details`in e.error.error_data&&typeof e.error.error_data.details==`string`)&&(!(`error_subcode`in e.error)||typeof e.error.error_subcode==`number`)}const ye=new v(`HttpsClient`,process.env.DEBUG===`true`||!1);var be=class{agent;constructor(){this.agent=new t({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 ye.log(`${n} : ${o} - ${JSON.stringify(e)}`),clearTimeout(c),new xe(e)}catch(e){throw ye.error(`${n} : ${o} - ${JSON.stringify(e)}`),e}}},xe=class{res;respStatusCode;respHeaders;constructor(e){this.res=e,this.respStatusCode=e.status,this.respHeaders=Object.fromEntries(e.headers.entries())}statusCode(){return this.respStatusCode}headers(){return this.respHeaders}rawResponse(){return this.res}async json(){try{return await this.res.json()}catch(e){throw Error(`Failed to parse response body to JSON: `+e.message)}}};const Se=new v(`REQUESTER`,process.env.DEBUG===`true`||!1);var Ce=class{client;accessToken;phoneNumberId;businessAcctId;apiVersion;userAgent;host;protocol=`https:`;constructor(e,t,n,r,i){this.client=new be,this.host=`graph.facebook.com`,this.apiVersion=e||`22`,this.phoneNumberId=t,this.accessToken=n,this.businessAcctId=r,this.userAgent=i}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`v${this.apiVersion}.0/${e}`}async sendRequest(e,t,n,r,i=`application/json`,a){let o=i;r instanceof FormData?o=`multipart/form-data`:typeof r==`string`&&r.startsWith(`<?xml`)&&(o=`application/xml`);let s=`${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(t)}`;Se.log(`${e} : ${s} (${o})`);try{let i=await this.client.sendRequest(this.host,this.buildCAPIPath(t),e,this.buildHeader(o,a),n,e===`POST`||e===`PUT`?r:void 0);if(!i.rawResponse().ok){let e=await i.json();throw ve(e)?e:{name:`MetaError`,message:`Unknown error occurred`,error:{message:e.message||`Unknown error occurred`,type:`UnknownError`,code:i.statusCode(),fbtrace_id:``}}}return i}catch(e){throw ve(e)?e:{name:`MetaError`,message:e instanceof Error?e.message:`Network error occurred`,error:{message:e instanceof Error?e.message:`Network error occurred`,type:`NetworkError`,code:500,fbtrace_id:``}}}}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()}async sendUrlEncodedForm(e,t,n,r,i){let a=new URLSearchParams(r).toString();return await(await this.sendRequest(e,t,n,a,`application/x-www-form-urlencoded`,i)).json()}};function y(){try{let e=r(__dirname,`../../package.json`);return JSON.parse(n(e,`utf-8`)).version}catch{return`unknown`}}function we(){let e=y(),t=process.version;return`WhatsApp-Nodejs-SDK/${e} (Node.js ${t})`}var b=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)}},x=class extends b{endpoint=`whatsapp_business_encryption`;constructor(e,t){super(e,t)}async getEncryptionPublicKey(){return this.sendJson(l.Get,`${this.config[g.PhoneNumberId]}/${this.endpoint}`,this.config[g.RequestTimeout],null)}async setEncryptionPublicKey(e){let t=new FormData;return t.append(`business_public_key`,e),this.sendJson(l.Post,`${this.config[g.PhoneNumberId]}/${this.endpoint}`,this.config[g.RequestTimeout],t)}},S=class extends b{constructor(e,t){super(e,t)}async listFlows(e){return this.sendJson(l.Get,`/${e}/flows`,this.config[g.RequestTimeout],null)}async createFlow(e,t){let n={name:t.name,categories:t.categories,...t.endpoint_uri&&{endpoint_uri:t.endpoint_uri},...t.clone_flow_id&&{clone_flow_id:t.clone_flow_id},...t.flow_json&&{flow_json:t.flow_json},...t.publish!==void 0&&{publish:t.publish}};return this.sendJson(l.Post,`/${e}/flows`,this.config[g.RequestTimeout],JSON.stringify(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(l.Get,`/${e}${i}`,this.config[g.RequestTimeout],null)}async getFlowPreview(e,t=!1){let n=`preview.invalidate(${t})`;return this.getFlow(e,n)}async updateFlowMetadata(e,t){let n={...t.name&&{name:t.name},...t.categories&&{categories:t.categories},...t.endpoint_uri&&{endpoint_uri:t.endpoint_uri},...t.application_id&&{application_id:t.application_id}};return this.sendJson(l.Post,`/${e}`,this.config[g.RequestTimeout],JSON.stringify(n))}async deleteFlow(e){return this.sendJson(l.Delete,`/${e}`,this.config[g.RequestTimeout],null)}async listAssets(e){return this.sendJson(l.Get,`/${e}/assets`,this.config[g.RequestTimeout],null)}async updateFlowJson(e,t){let n=new FormData,r;if(t.file instanceof Buffer)r=new globalThis.Blob([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(l.Post,`/${e}/assets`,this.config[g.RequestTimeout],n)}async validateFlowJson(e,t){try{let n=await this.updateFlowJson(e,{file:t}),r=!n.validation_errors||n.validation_errors.length===0;return{...n,valid:r}}catch(e){throw e}}async publishFlow(e){return this.sendJson(l.Post,`/${e}/publish`,this.config[g.RequestTimeout],JSON.stringify({}))}async deprecateFlow(e){return this.sendJson(l.Post,`/${e}/deprecate`,this.config[g.RequestTimeout],JSON.stringify({}))}async migrateFlows(e,t){let n={source_waba_id:t.source_waba_id,...t.source_flow_names&&{source_flow_names:t.source_flow_names}};return this.sendJson(l.Post,`/${e}/migrate_flows`,this.config[g.RequestTimeout],JSON.stringify(n))}};let C=function(e){return e.INIT=`INIT`,e.BACK=`BACK`,e.DATA_EXCHANGE=`data_exchange`,e}({}),w=function(e){return e.Ping=`ping`,e.Change=`data_exchange`,e.Error=`error`,e.All=`*`,e}({});var T=class extends b{endpoint=`media`;constructor(e,t){super(e,t)}async getMediaById(e,t){return this.sendJson(l.Get,`${e}`,this.config[g.RequestTimeout],null)}async uploadMedia(e,t=`whatsapp`){let n=new FormData;return n.append(`file`,e),n.append(`messaging_product`,t),n.append(`type`,e.type),this.sendJson(l.Post,`${this.config[g.PhoneNumberId]}/${this.endpoint}`,this.config[g.RequestTimeout],n)}async deleteMedia(e,t){return this.sendJson(l.Delete,`${e}`,this.config[g.RequestTimeout],null)}async downloadMedia(e){return this.sendJson(l.Get,e,this.config[g.RequestTimeout],null)}},E=class extends b{commonMethod=l.Post;commonEndpoint=`messages`;constructor(e,t){super(e,t)}bodyBuilder(e,t,n,r){let i={messaging_product:`whatsapp`,recipient_type:`individual`,to:n,type:e,[e]:t};return r&&(i.context={message_id:r}),i}send(e){return this.sendJson(this.commonMethod,`${this.config[g.PhoneNumberId]}/${this.commonEndpoint}`,this.config[g.RequestTimeout],e)}async audio(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(u.Audio,t,n,r)))}async contacts(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(u.Contacts,t,n,r)))}async document(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(u.Document,t,n,r)))}async image(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(u.Image,t,n,r)))}async interactive(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(u.Interactive,t,n,r)))}async location(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(u.Location,t,n,r)))}async sticker(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(u.Sticker,t,n,r)))}async template(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(u.Template,t,n,r)))}async text(e){let{body:t,to:n,replyMessageId:r,previewUrl:i}=e,a=typeof t==`string`?{body:t,preview_url:i??!0}:{...t,preview_url:i??t.preview_url??!0};return this.send(JSON.stringify(this.bodyBuilder(u.Text,a,n,r)))}async video(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(u.Video,t,n,r)))}async status(e){let t={messaging_product:`whatsapp`,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){return this.status({status:`read`,messageId:e.messageId,typingIndicator:{type:`text`}})}async interactiveList(e){return this.interactive(e)}async interactiveCtaUrl(e){return this.interactive(e)}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 reaction(e){let t={message_id:e.messageId,emoji:e.emoji};return this.send(JSON.stringify(this.bodyBuilder(u.Reaction,t,e.to)))}},D=class{contact={};setName(e){if(!e||typeof e!=`object`)throw Error(`Name must be an object`);return this.contact.name=e,this}setSimpleName(e,t){if(!e||typeof e!=`string`)throw Error(`First name must be a non-empty string`);let n={formatted_name:t?`${e} ${t}`:e,first_name:e};return t&&(n.last_name=t),this.setName(n)}setFullName(e,t,n,r,i){if(!e||typeof e!=`string`)throw Error(`First name must be a non-empty string`);let a={formatted_name:[i,e,n,t,r].filter(Boolean).join(` `),first_name:e};return t&&(a.last_name=t),n&&(a.middle_name=n),r&&(a.suffix=r),i&&(a.prefix=i),this.setName(a)}addPhone(e,t,n){if(!e||typeof e!=`string`)throw Error(`Phone number must be a non-empty string`);let r={phone:`PHONE_NUMBER`};return t&&(r.type=t),n&&(r.wa_id=n),this.contact.phones||(this.contact.phones=[]),this.contact.phones.push(r),this}addEmail(e,t){if(!e||typeof e!=`string`)throw Error(`Email must be a non-empty string`);if(!e.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/))throw Error(`Invalid email format`);let n={email:e};return t&&(n.type=t),this.contact.emails||(this.contact.emails=[]),this.contact.emails.push(n),this}addAddress(e){if(!e||typeof e!=`object`)throw Error(`Address must be an object`);return this.contact.addresses||(this.contact.addresses=[]),this.contact.addresses.push(e),this}addSimpleAddress(e,t,n,r){let i={street:e,city:t,country:n};return r&&(i.type=r),this.addAddress(i)}setOrganization(e,t,n){let r={};return e&&(r.company=e),t&&(r.department=t),n&&(r.title=n),this.contact.org=r,this}addUrl(e,t){if(!e||typeof e!=`string`)throw Error(`URL must be a non-empty string`);let n={url:e};return t&&(n.type=t),this.contact.urls||(this.contact.urls=[]),this.contact.urls.push(n),this}setBirthday(e,t,n){let r=t.toString().padStart(2,`0`),i=n.toString().padStart(2,`0`);return this.contact.birthday=`${e}-${r}-${i}`,this}build(){if(!this.contact.name)throw Error(`Contact name is required`);return this.contact}reset(){return this.contact={},this}},Te=class{static createSimpleContact(e,t){return new D().setSimpleName(e).addPhone(t).build()}static createBusinessContact(e,t,n,r,i,a){return new D().setSimpleName(e,t).setOrganization(n,void 0,r).addPhone(i,`WORK`).addEmail(a,`WORK`).build()}static createPersonalContact(e,t,n,r,i){let a=new D().setSimpleName(e,t).addPhone(n,`MOBILE`);return r&&a.addEmail(r,`HOME`),i&&a.setBirthday(i.year,i.month,i.day),a.build()}};function O(e){return!(`name`in e)}var k=class{message={};setType(e){return this.message.type=e,this}setBody(e){return this.message.body={text:e},this}setFooter(e){return this.message.footer={text:e},this}setTextHeader(e){return this.message.header={type:`text`,text:e},this}setImageHeader(e){return this.message.header={type:`image`,image:{link:e}},this}addReplyButtons(e){this.message.action||(this.message.action={});let t=this.message.action;return O(t)&&(t.buttons=e.map(e=>({type:`reply`,reply:{id:e.id,title:e.title}}))),this}addListSections(e){this.message.action||(this.message.action={});let t=this.message.action;return O(t)&&(t.sections=e.map(e=>({title:e.title,rows:e.rows}))),this}setListButtonText(e){this.message.action||(this.message.action={});let t=this.message.action;return O(t)&&(t.button=e),this}setCTAUrl(e,t){return this.message.action={name:`cta_url`,parameters:{display_text:e,url:t}},this}build(){if(!this.message.type)throw Error(`Interactive message type is required`);if(!this.message.body)throw Error(`Interactive message body is required`);if(!this.message.action)throw Error(`Interactive message action is required`);return this.message}reset(){return this.message={},this}},Ee=class{static createButtonMessage(e,t,n){let r=new k().setType(f.Button).setBody(e).addReplyButtons(t);return n?.headerText&&r.setTextHeader(n.headerText),n?.footerText&&r.setFooter(n.footerText),r.build()}static createListMessage(e,t,n,r){let i=new k().setType(f.List).setBody(e).addListSections(n);r?.headerText&&i.setTextHeader(r.headerText),r?.footerText&&i.setFooter(r.footerText);let a=i.build(),o=a.action;return O(o)&&(o.button=t),a}static createCTAUrlMessage(e,t,n,r){let i=new k().setType(f.CtaUrl).setBody(e).setCTAUrl(t,n);return r?.headerText&&i.setTextHeader(r.headerText),r?.footerText&&i.setFooter(r.footerText),i.build()}},A=class{location={};setLatitude(e){if(typeof e!=`number`||e<-90||e>90)throw Error(`Latitude must be a number between -90 and 90`);return this.location.latitude=e,this}setLongitude(e){if(typeof e!=`number`||e<-180||e>180)throw Error(`Longitude must be a number between -180 and 180`);return this.location.longitude=e,this}setCoordinates(e,t){return this.setLatitude(e).setLongitude(t)}setName(e){if(e&&typeof e!=`string`)throw Error(`Location name must be a string`);return this.location.name=e,this}setAddress(e){if(e&&typeof e!=`string`)throw Error(`Location address must be a string`);return this.location.address=e,this}build(){if(this.location.latitude===void 0)throw Error(`Latitude is required`);if(this.location.longitude===void 0)throw Error(`Longitude is required`);return this.location}reset(){return this.location={},this}},De=class{static createSimpleLocation(e,t){return new A().setCoordinates(e,t).build()}static createNamedLocation(e,t,n,r){return new A().setCoordinates(e,t).setName(n).setAddress(r).build()}static createBusinessLocation(e,t,n,r){return new A().setCoordinates(e,t).setName(n).setAddress(r).build()}},j=class{media={};setId(e){if(!e||typeof e!=`string`)throw Error(`Media ID must be a non-empty string`);return this.media.id=e,this}setLink(e){if(!e||typeof e!=`string`)throw Error(`Media URL must be a non-empty string`);if(!e.match(/^https?:\/\//))throw Error(`Media URL must be a valid HTTP/HTTPS URL`);return this.media.link=e,this}setCaption(e){if(e&&typeof e!=`string`)throw Error(`Caption must be a string`);return this.media.caption=e,this}build(){if(!this.media.id&&!this.media.link)throw Error(`Either media ID or link is required`);return this.media}reset(){return this.media={},this}},M=class extends j{},N=class extends j{},P=class extends j{setCaption(e){throw Error(`Audio messages do not support captions`)}},F=class extends j{setFilename(e){if(!e||typeof e!=`string`)throw Error(`Filename must be a non-empty string`);return this.media.filename=e,this}},I=class extends j{setCaption(e){throw Error(`Sticker messages do not support captions`)}},Oe=class{static createImageWithCaption(e,t,n=!1){let r=new M;return n?r.setId(e):r.setLink(e),r.setCaption(t).build()}static createVideoWithCaption(e,t,n=!1){let r=new N;return n?r.setId(e):r.setLink(e),r.setCaption(t).build()}static createDocument(e,t,n,r=!1){let i=new F;return r?i.setId(e):i.setLink(e),i.setFilename(t),n&&i.setCaption(n),i.build()}static createAudio(e,t=!1){let n=new P;return t?n.setId(e):n.setLink(e),n.build()}static createSticker(e,t=!1){let n=new I;return t?n.setId(e):n.setLink(e),n.build()}},L=class{reaction={};setMessageId(e){if(!e||typeof e!=`string`)throw Error(`Message ID must be a non-empty string`);return this.reaction.message_id=e,this}setEmoji(e){if(!e||typeof e!=`string`)throw Error(`Emoji must be a non-empty string`);if(e.length>4)throw Error(`Please provide a single emoji character`);return this.reaction.emoji=e,this}removeReaction(){return this.reaction.emoji=``,this}build(){if(!this.reaction.message_id)throw Error(`Message ID is required`);if(this.reaction.emoji===void 0)throw Error(`Emoji is required (use empty string to remove reaction)`);return this.reaction}reset(){return this.reaction={},this}},ke=class{static createLike(e){return new L().setMessageId(e).setEmoji(`👍`).build()}static createHeart(e){return new L().setMessageId(e).setEmoji(`❤️`).build()}static createLaugh(e){return new L().setMessageId(e).setEmoji(`😂`).build()}static createWow(e){return new L().setMessageId(e).setEmoji(`😮`).build()}static createSad(e){return new L().setMessageId(e).setEmoji(`😢`).build()}static createAngry(e){return new L().setMessageId(e).setEmoji(`😠`).build()}static removeReaction(e){return new L().setMessageId(e).removeReaction().build()}};function Ae(e){return Object.values(_).includes(e)}function je(e){return Object.values(p).includes(e)}var R=class{template={components:[]};setName(e){if(!e||e.trim().length===0)throw Error(`Template name cannot be empty`);return this.template.name=e,this}setLanguage(e){if(!Ae(e))throw Error(`Invalid language code: ${e}. Must be a valid LanguagesEnum value.`);return this.template.language={policy:`deterministic`,code:e},this}addTextHeader(e){if(!Array.isArray(e))throw Error(`Parameters must be an array`);let t={type:h.Header,parameters:e.map(e=>{if(typeof e!=`string`)throw Error(`All parameters must be strings`);return{type:d.Text,text:e}})};return this.template.components||(this.template.components=[]),this.template.components.push(t),this}addImageHeader(e){if(!e||typeof e!=`string`)throw Error(`Image URL must be a non-empty string`);let t={type:h.Header,parameters:[{type:d.Image,image:{link:e}}]};return this.template.components||(this.template.components=[]),this.template.components.push(t),this}addBody(e){if(!Array.isArray(e))throw Error(`Parameters must be an array`);let t={type:h.Body,parameters:e.map(e=>{if(typeof e!=`string`)throw Error(`All parameters must be strings`);return{type:d.Text,text:e}})};return this.template.components||(this.template.components=[]),this.template.components.push(t),this}addFooter(){let e={type:h.Footer};return this.template.components||(this.template.components=[]),this.template.components.push(e),this}addButtons(e){if(!Array.isArray(e))throw Error(`Buttons must be an array`);return e.forEach(e=>{if(typeof e.index!=`number`||!je(e.index))throw Error(`Button index must be a valid ButtonPositionEnum value: ${e.index}`);let t=e.type===`quick_reply`?m.QuickReply:m.Url,n={type:h.Button,sub_type:t,index:e.index};if(e.parameters&&e.parameters.length>0){if(!Array.isArray(e.parameters))throw Error(`Button parameters must be an array`);e.type===`quick_reply`?n.parameters=e.parameters.map(e=>{if(typeof e!=`string`)throw Error(`All button parameters must be strings`);return{type:d.Payload,payload:e}}):e.type===`url`&&(n.parameters=e.parameters.map(e=>{if(typeof e!=`string`)throw Error(`All button parameters must be strings`);return{type:d.Text,text:e}}))}this.template.components||(this.template.components=[]),this.template.components.push(n)}),this}addCurrencyParameter(e,t,n){if(!e||typeof e!=`string`)throw Error(`Fallback value must be a non-empty string`);if(!t||typeof t!=`string`)throw Error(`Currency code must be a non-empty string`);if(typeof n!=`number`||n<0)throw Error(`Amount must be a non-negative number`);return{type:d.Currency,currency:{fallback_value:e,code:t,amount_1000:n*1e3}}}addDateTimeParameter(e,t){if(!e||typeof e!=`string`)throw Error(`Fallback value must be a non-empty string`);if(typeof t!=`number`||t<=0)throw Error(`Timestamp must be a positive number`);return{type:d.DateTime,date_time:{fallback_value:e,timestamp:t}}}build(){if(!this.template.name)throw Error(`Template name is required`);if(!this.template.language)throw Error(`Template language is required`);return this.template}reset(){return this.template={components:[]},this}},Me=class{static createSimpleTextTemplate(e,t,n){if(!e||!t||!Array.isArray(n))throw Error(`Invalid parameters for simple text template`);return new R().setName(e).setLanguage(t).addBody(n).build()}static createCompleteTemplate(e,t,n){if(!e||!t||!n.bodyParameters)throw Error(`Invalid parameters for complete template`);let r=new R().setName(e).setLanguage(t).addBody(n.bodyParameters);return n.headerParameters?r.addTextHeader(n.headerParameters):n.headerImage&&r.addImageHeader(n.headerImage),n.buttons&&r.addButtons(n.buttons),r.build()}static createOrderConfirmationTemplate(e,t,n,r,i){if(!e||!t||!n||typeof r!=`number`||!i)throw Error(`Invalid parameters for order confirmation template`);return new R().setName(`order_confirmation`).setLanguage(e).addBody([t,n,r.toString(),i]).addButtons([{index:0,type:`quick_reply`},{index:1,type:`url`,parameters:[n]}]).build()}},z=class{textMessage={};setBody(e){if(!e||typeof e!=`string`)throw Error(`Message body must be a non-empty string`);return this.textMessage.body=e,this}setPreviewUrl(e=!0){return this.textMessage.preview_url=e,this}build(){if(!this.textMessage.body)throw Error(`Message body is required`);return this.textMessage}reset(){return this.textMessage={},this}},Ne=class{static createSimpleText(e){return new z().setBody(e).build()}static createTextWithPreview(e){return new z().setBody(e).setPreviewUrl(!0).build()}static createNotification(e,t){return new z().setBody(`*${e}*\n\n${t}`).build()}};const B=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(`&`)}`:``};var V=class extends b{endpoint=`phone_numbers`;constructor(e,t){super(e,t)}async getPhoneNumberById(e){let t=e?B({fields:e}):``;return this.sendJson(l.Get,`${this.config[g.PhoneNumberId]}${t}`,this.config[g.RequestTimeout],null)}async getPhoneNumbers(){return this.sendJson(l.Get,`${this.config[g.BusinessAcctId]}/${this.endpoint}`,this.config[g.RequestTimeout],null)}async requestVerificationCode(e){return this.sendJson(l.Post,`${this.config[g.PhoneNumberId]}/request_code`,this.config[g.RequestTimeout],JSON.stringify(e))}async verifyCode(e){return this.sendJson(l.Post,`${this.config[g.PhoneNumberId]}/verify_code`,this.config[g.RequestTimeout],JSON.stringify(e))}};function Pe(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 Fe=class extends b{endpoint=`whatsapp_business_profile`;constructor(e,t){super(e,t)}async getBusinessProfile(e){return this.sendJson(l.Get,`${this.config[g.PhoneNumberId]}/${this.endpoint}${Pe(e)}`,this.config[g.RequestTimeout],null)}async updateBusinessProfile(e){return this.sendJson(l.Post,`${this.config[g.PhoneNumberId]}/${this.endpoint}`,this.config[g.RequestTimeout],JSON.stringify(e))}async createUploadSession(e,t,n){let r=B({file_length:e,file_type:t,file_name:n});return this.sendJson(l.Post,`app/uploads/${r}`,this.config[g.RequestTimeout],null)}async uploadMedia(e,t){return this.sendJson(l.Post,`${e}`,this.config[g.RequestTimeout],t)}async getUploadHandle(e){return this.sendJson(l.Get,`${e}`,this.config[g.RequestTimeout],null)}},Ie=class extends b{endpoint=`message_qrdls`;constructor(e,t){super(e,t)}async createQrCode(e){return this.sendJson(l.Post,`${this.config[g.PhoneNumberId]}/${this.endpoint}`,this.config[g.RequestTimeout],JSON.stringify(e))}async getQrCodes(){return this.sendJson(l.Get,`${this.config[g.PhoneNumberId]}/${this.endpoint}`,this.config[g.RequestTimeout],null)}async getQrCode(e){return this.sendJson(l.Get,`${this.config[g.PhoneNumberId]}/${this.endpoint}/${e}`,this.config[g.RequestTimeout],null)}async updateQrCode(e){return this.sendJson(l.Post,`${this.config[g.PhoneNumberId]}/${this.endpoint}`,this.config[g.RequestTimeout],JSON.stringify(e))}async deleteQrCode(e){return this.sendJson(l.Delete,`${this.config[g.PhoneNumberId]}/${this.endpoint}/${e}`,this.config[g.RequestTimeout],null)}},Le=class extends b{constructor(e,t){super(e,t)}async register(e,t){let n={messaging_product:`whatsapp`,pin:e,...t&&{data_localization_region:t}};return this.sendJson(l.Post,`${this.config[g.PhoneNumberId]}/register`,this.config[g.RequestTimeout],JSON.stringify(n))}async deregister(){return this.sendJson(l.Post,`${this.config[g.PhoneNumberId]}/deregister`,this.config[g.RequestTimeout],null)}},Re=class extends b{endpoint=`message_templates`;constructor(e,t){super(e,t)}async getTemplate(e){return this.sendJson(l.Get,`${e}`,this.config[g.RequestTimeout],null)}async updateTemplate(e,t){return this.sendJson(l.Post,`${e}`,this.config[g.RequestTimeout],JSON.stringify(t))}async getTemplates(e){return this.sendJson(l.Get,`${this.config[g.BusinessAcctId]}/${this.endpoint}${B(e??{})}`,this.config[g.RequestTimeout],null)}async createTemplate(e){return this.sendJson(l.Post,`${this.config[g.BusinessAcctId]}/${this.endpoint}`,this.config[g.RequestTimeout],JSON.stringify(e))}async deleteTemplate(e){return this.sendJson(l.Delete,`${this.config[g.BusinessAcctId]}/${this.endpoint}${B(e)}`,this.config[g.RequestTimeout],null)}};function H(e){let t={type:`HEADER`,format:e.format};return e.text&&(t.text=e.text),e.example&&(t.example=e.example),t}function U(e){let t={type:`BODY`,text:e.text};return e.example&&(t.example=e.example),t}function W(e){return{type:`FOOTER`,text:e.text}}function G(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 ze(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 Be(e){let t=[];if(e.header&&t.push(H(e.header)),e.body&&t.push(U(e.body)),e.footer&&t.push(W(e.footer)),e.buttons&&t.push(...G(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:[ze(e.bodyParameters)]}:void 0}),e.buttons&&n.push(...G(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 Ve(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:s.Authentication,components:t}}function He(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:s.Authentication,components:t}}function Ue(e){let t=[];return e.header&&t.push(H({...e.header,format:`TEXT`})),t.push(U(e.body)),e.footer&&t.push(W(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:s.Marketing,components:t}}function We(e){let t=[];return e.header&&t.push(H({...e.header,format:`TEXT`})),t.push(U(e.body)),e.footer&&t.push(W(e.footer)),t.push({type:`BUTTONS`,buttons:[{type:`COPY_CODE`,example:e.coupon_code}]}),{name:e.name,language:e.language,category:s.Marketing,components:t}}function Ge(e){let t=[];return t.push({type:`LIMITED_TIME_OFFER`,limited_time_offer:{expiration_time_ms:e.expiration_time_ms}}),e.header&&t.push(H({...e.header,format:`TEXT`})),t.push(U(e.body)),e.footer&&t.push(W(e.footer)),{name:e.name,language:e.language,category:s.Marketing,components:t}}function Ke(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(U(e.body)),e.buttons&&r.push(...G(e.buttons)),n.push({card_index:t,components:r})}),t.push({type:`CAROUSEL`,cards:n}),{name:e.name,language:e.language,category:s.Marketing,components:t}}function qe(e){let t=[];return e.header&&t.push(H({...e.header,format:`TEXT`})),t.push(U(e.body)),e.footer&&t.push(W(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:s.Marketing,components:t}}function Je(e){let t=[];e.header&&t.push(H({...e.header,format:`TEXT`})),t.push(U(e.body)),e.footer&&t.push(W(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:s.Marketing,components:t}}function Ye(e){let t=[];return e.header&&t.push(H({...e.header,format:`TEXT`})),t.push(U(e.body)),e.footer&&t.push(W(e.footer)),t.push({type:`BUTTONS`,buttons:[{type:`SPM`,action:{product_retailer_id:e.product_retailer_id}}]}),{name:e.name,language:e.language,category:s.Marketing,components:t}}var Xe=class extends b{constructor(e,t){super(e,t)}async setTwoStepVerificationCode(e){let t={pin:e};return this.sendJson(l.Post,`${this.config[g.PhoneNumberId]}`,this.config[g.RequestTimeout],JSON.stringify(t))}},Ze=class extends b{constructor(e,t){super(e,t)}async getWabaAccount(e){let t=Pe(e)?.replace(/,/g,`%2C`);return this.sendJson(l.Get,`${this.config[g.BusinessAcctId]}${t}`,this.config[g.RequestTimeout],null)}async getAllWabaSubscriptions(){return this.sendJson(l.Get,`${this.config[g.BusinessAcctId]}/subscribed_apps`,this.config[g.RequestTimeout],null)}async updateWabaSubscription({override_callback_uri:e,verify_token:t}){let n={override_callback_uri:e,verify_token:t};return this.sendJson(l.Post,`${this.config[g.BusinessAcctId]}/subscribed_apps`,this.config[g.RequestTimeout],JSON.stringify(n))}async unsubscribeFromWaba(){return this.sendJson(l.Delete,`${this.config[g.BusinessAcctId]}/subscribed_apps`,this.config[g.RequestTimeout],null)}};function Qe(){process.env.NODE_ENV===`test`||process.env.VITEST===`true`||typeof global<`u`&&global.__VITEST__||console.log(`\x1B[36m%s\x1B[0m`,`
1
+ import{__export as e}from"./chunk-CTAAG5j7.js";import{Agent as t}from"https";import{readFileSync as n}from"fs";import{join as r}from"path";import*as i from"crypto";import a from"crypto";var o=e({AudioMediaTypesEnum:()=>x,BusinessVerticalEnum:()=>ae,ButtonPositionEnum:()=>p,CategoryEnum:()=>s,ComponentTypesEnum:()=>h,ConversationTypesEnum:()=>ee,CurrencyCodesEnum:()=>re,DataLocalizationRegionEnum:()=>ie,DocumentMediaTypesEnum:()=>b,HttpMethodsEnum:()=>l,ImageMediaTypesEnum:()=>y,InteractiveTypesEnum:()=>f,LanguagesEnum:()=>T,MessageTypesEnum:()=>u,ParametersTypesEnum:()=>d,ReferralSourceTypesEnum:()=>w,RequestCodeMethodsEnum:()=>ne,StatusEnum:()=>te,StickerMediaTypesEnum:()=>v,SubTypeEnum:()=>m,SystemChangeTypesEnum:()=>C,TemplateStatusEnum:()=>c,VideoMediaTypesEnum:()=>_,WabaConfigEnum:()=>g,WebhookTypesEnum:()=>S});let s=function(e){return e.Authentication=`AUTHENTICATION`,e.Marketing=`MARKETING`,e.Utility=`UTILITY`,e}({}),c=function(e){return e.Approved=`APPROVED`,e.Pending=`PENDING`,e.Rejected=`REJECTED`,e}({}),l=function(e){return e.Get=`GET`,e.Post=`POST`,e.Put=`PUT`,e.Delete=`DELETE`,e}({}),u=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.Unknown=`unknown`,e.Statuses=`statuses`,e[`*`]=`*`,e}({}),d=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}({}),f=function(e){return e.Button=`button`,e.List=`list`,e.Product=`product`,e.ProductList=`product_list`,e.CtaUrl=`cta_url`,e.LocationRequest=`location_request_message`,e.AddressMessage=`address_message`,e.Flow=`flow`,e}({}),p=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}({}),m=function(e){return e.Catalog=`CATALOG`,e.CopyCode=`COPY_CODE`,e.Flow=`FLOW`,e.Mpm=`MPM`,e.OrderDetails=`ORDER_DETAILS`,e.QuickReply=`QUICK_REPLY`,e.Reminder=`REMINDER`,e.Url=`URL`,e.VoiceCall=`VOICE_CALL`,e}({}),h=function(e){return e.Header=`HEADER`,e.Body=`BODY`,e.Button=`BUTTON`,e.Footer=`FOOTER`,e}({}),g=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}({}),ee=function(e){return e.BusinessInitiated=`business_initiated`,e.CustomerInitiated=`customer_initiated`,e.ReferralConversion=`referral_conversion`,e}({}),te=function(e){return e.Delivered=`delivered`,e.Read=`read`,e.Sent=`sent`,e}({}),_=function(e){return e.Mp4=`video/mp4`,e.Threegp=`video/3gp`,e}({}),v=function(e){return e.Webp=`image/webp`,e}({}),y=function(e){return e.Jpeg=`image/jpeg`,e.Png=`image/png`,e}({}),b=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}({}),x=function(e){return e.Aac=`audio/aac`,e.Mp4=`audio/mp4`,e.Mpeg=`audio/mpeg`,e.Amr=`audio/amr`,e.Ogg=`audio/ogg`,e}({}),S=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}({}),C=function(e){return e.CustomerChangedNumber=`customer_changed_number`,e.CustomerIdentityChanged=`customer_identity_changed`,e}({}),w=function(e){return e.Ad=`ad`,e.Post=`post`,e}({}),ne=function(e){return e.Sms=`SMS`,e.Voice=`VOICE`,e}({}),T=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}({}),re=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}({}),ie=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}({}),ae=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}({});var E=class{name;debug;constructor(e,t=!1){this.name=e,this.debug=t}log(...e){if(this.debug){let t=`[ ${Date.now()} ]`;this.name&&(t+=` - ${this.name}`),console.log.apply(console,[t,`: `,...e])}}error(...e){let t=`[ ${Date.now()} ] - ERROR`;this.name&&(t+=` - ${this.name}`),console.error.apply(console,[t,`: `,...e])}warn(...e){let t=`[ ${Date.now()} ] - WARN`;this.name&&(t+=` - ${this.name}`),console.warn.apply(console,[t,`: `,...e])}info(...e){let t=`[ ${Date.now()} ] - INFO`;this.name&&(t+=` - ${this.name}`),console.info.apply(console,[t,`: `,...e])}};const oe=new E(`UTILS`,process.env.DEBUG===`true`||!1),se=e=>{if(!process.env[g.AccessToken]&&!e?.accessToken)throw oe.log(`Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined.`),Error(`Missing WhatsApp access token.`)},ce=e=>(se(e),{[g.AppId]:e?.appId||process.env.M4D_APP_ID||``,[g.AppSecret]:e?.appSecret||process.env.M4D_APP_SECRET||``,[g.PhoneNumberId]:e?.phoneNumberId||Number(process.env.WA_PHONE_NUMBER_ID),[g.BusinessAcctId]:e?.businessAcctId||process.env.WA_BUSINESS_ACCOUNT_ID||``,[g.APIVersion]:e?.apiVersion||process.env.CLOUD_API_VERSION||``,[g.AccessToken]:e?.accessToken||process.env.CLOUD_API_ACCESS_TOKEN||``,[g.WebhookEndpoint]:e?.webhookEndpoint||process.env.WEBHOOK_ENDPOINT||``,[g.WebhookVerificationToken]:e?.webhookVerificationToken||process.env.WEBHOOK_VERIFICATION_TOKEN||``,[g.ListenerPort]:e?.listenerPort||parseInt(process.env.LISTENER_PORT||``)||3e3,[g.MaxRetriesAfterWait]:e?.maxRetriesAfterWait||parseInt(process.env.MAX_RETRIES_AFTER_WAIT||``)||30,[g.RequestTimeout]:e?.requestTimeout||parseInt(process.env.REQUEST_TIMEOUT||``)||2e4,[g.Debug]:e?.debug||process.env.DEBUG===`true`,[g.PrivatePem]:e?.privatePem||process.env.FLOW_API_PRIVATE_PEM||``,[g.Passphrase]:e?.passphrase||process.env.FLOW_API_PASSPHRASE||``});function le(e){let t=[[`App ID`,e[g.AppId]||`Not Set`],[`Phone Number ID`,e[g.PhoneNumberId]?.toString()||`Not Set`],[`Business Account ID`,e[g.BusinessAcctId]||`Not Set`],[`API Version`,e[g.APIVersion]||`Not Set`],[`Access Token`,e[g.AccessToken]?`${e[g.AccessToken].substring(0,20)}...`:`Not Set`],[`Webhook Endpoint`,e[g.WebhookEndpoint]||`Not Set`],[`Webhook Verification Token`,e[g.WebhookVerificationToken]?`${e[g.WebhookVerificationToken].substring(0,10)}...`:`Not Set`],[`Listener Port`,e[g.ListenerPort]?.toString()||`Not Set`],[`Debug Mode`,e[g.Debug]?`Enabled`:`Disabled`],[`Max Retries`,e[g.MaxRetriesAfterWait]?.toString()||`Not Set`],[`Request Timeout`,e[g.RequestTimeout]?`${e[g.RequestTimeout]}ms`:`Not Set`],[`Private PEM`,e[g.PrivatePem]?`Configured`:`Not Set`],[`Passphrase`,e[g.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)}┘`,l=`│ ${`Configuration`.padEnd(i)} │ ${`Value`.padEnd(a)} │`,u=t.map(([e,t])=>`│ ${e?.padEnd(i)} │ ${t?.padEnd(a)} │`);return[o,l,s,...u,c].join(`
2
+ `)}function ue(e){return typeof e==`object`&&!!e&&`error`in e&&typeof e.error==`object`&&e.error!=null&&`message`in e.error&&typeof e.error.message==`string`&&`type`in e.error&&typeof e.error.type==`string`&&`code`in e.error&&typeof e.error.code==`number`&&`fbtrace_id`in e.error&&typeof e.error.fbtrace_id==`string`&&(!(`error_data`in e.error)||typeof e.error.error_data==`object`&&e.error.error_data!=null&&`messaging_product`in e.error.error_data&&e.error.error_data.messaging_product===`whatsapp`&&`details`in e.error.error_data&&typeof e.error.error_data.details==`string`)&&(!(`error_subcode`in e.error)||typeof e.error.error_subcode==`number`)}const de=new E(`HttpsClient`,process.env.DEBUG===`true`||!1);var fe=class{agent;constructor(){this.agent=new t({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 de.log(`${n} : ${o} - ${JSON.stringify(e)}`),clearTimeout(c),new pe(e)}catch(e){throw de.error(`${n} : ${o} - ${JSON.stringify(e)}`),e}}},pe=class{res;respStatusCode;respHeaders;constructor(e){this.res=e,this.respStatusCode=e.status,this.respHeaders=Object.fromEntries(e.headers.entries())}statusCode(){return this.respStatusCode}headers(){return this.respHeaders}rawResponse(){return this.res}async json(){try{return await this.res.json()}catch(e){throw Error(`Failed to parse response body to JSON: `+e.message)}}};const me=new E(`REQUESTER`,process.env.DEBUG===`true`||!1);var he=class{client;accessToken;phoneNumberId;businessAcctId;apiVersion;userAgent;host;protocol=`https:`;constructor(e,t,n,r,i){this.client=new fe,this.host=`graph.facebook.com`,this.apiVersion=e||`22`,this.phoneNumberId=t,this.accessToken=n,this.businessAcctId=r,this.userAgent=i}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`v${this.apiVersion}.0/${e}`}async sendRequest(e,t,n,r,i=`application/json`,a){let o=i;r instanceof FormData?o=`multipart/form-data`:typeof r==`string`&&r.startsWith(`<?xml`)&&(o=`application/xml`);let s=`${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(t)}`;me.log(`${e} : ${s} (${o})`);try{let i=await this.client.sendRequest(this.host,this.buildCAPIPath(t),e,this.buildHeader(o,a),n,e===`POST`||e===`PUT`?r:void 0);if(!i.rawResponse().ok){let e=await i.json();throw ue(e)?e:{name:`MetaError`,message:`Unknown error occurred`,error:{message:e.message||`Unknown error occurred`,type:`UnknownError`,code:i.statusCode(),fbtrace_id:``}}}return i}catch(e){throw ue(e)?e:{name:`MetaError`,message:e instanceof Error?e.message:`Network error occurred`,error:{message:e instanceof Error?e.message:`Network error occurred`,type:`NetworkError`,code:500,fbtrace_id:``}}}}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()}async sendUrlEncodedForm(e,t,n,r,i){let a=new URLSearchParams(r).toString();return await(await this.sendRequest(e,t,n,a,`application/x-www-form-urlencoded`,i)).json()}};function ge(){try{let e=r(__dirname,`../../package.json`);return JSON.parse(n(e,`utf-8`)).version}catch{return`unknown`}}function _e(){let e=ge(),t=process.version;return`WhatsApp-Nodejs-SDK/${e} (Node.js ${t})`}var D=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)}},O=class extends D{endpoint=`whatsapp_business_encryption`;constructor(e,t){super(e,t)}async getEncryptionPublicKey(){return this.sendJson(l.Get,`${this.config[g.PhoneNumberId]}/${this.endpoint}`,this.config[g.RequestTimeout],null)}async setEncryptionPublicKey(e){let t=new FormData;return t.append(`business_public_key`,e),this.sendJson(l.Post,`${this.config[g.PhoneNumberId]}/${this.endpoint}`,this.config[g.RequestTimeout],t)}},k=class extends D{constructor(e,t){super(e,t)}async listFlows(e){return this.sendJson(l.Get,`/${e}/flows`,this.config[g.RequestTimeout],null)}async createFlow(e,t){let n={name:t.name,categories:t.categories,...t.endpoint_uri&&{endpoint_uri:t.endpoint_uri},...t.clone_flow_id&&{clone_flow_id:t.clone_flow_id},...t.flow_json&&{flow_json:t.flow_json},...t.publish!==void 0&&{publish:t.publish}};return this.sendJson(l.Post,`/${e}/flows`,this.config[g.RequestTimeout],JSON.stringify(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(l.Get,`/${e}${i}`,this.config[g.RequestTimeout],null)}async getFlowPreview(e,t=!1){let n=`preview.invalidate(${t})`;return this.getFlow(e,n)}async updateFlowMetadata(e,t){let n={...t.name&&{name:t.name},...t.categories&&{categories:t.categories},...t.endpoint_uri&&{endpoint_uri:t.endpoint_uri},...t.application_id&&{application_id:t.application_id}};return this.sendJson(l.Post,`/${e}`,this.config[g.RequestTimeout],JSON.stringify(n))}async deleteFlow(e){return this.sendJson(l.Delete,`/${e}`,this.config[g.RequestTimeout],null)}async listAssets(e){return this.sendJson(l.Get,`/${e}/assets`,this.config[g.RequestTimeout],null)}async updateFlowJson(e,t){let n=new FormData,r;if(t.file instanceof Buffer)r=new globalThis.Blob([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(l.Post,`/${e}/assets`,this.config[g.RequestTimeout],n)}async validateFlowJson(e,t){try{let n=await this.updateFlowJson(e,{file:t}),r=!n.validation_errors||n.validation_errors.length===0;return{...n,valid:r}}catch(e){throw e}}async publishFlow(e){return this.sendJson(l.Post,`/${e}/publish`,this.config[g.RequestTimeout],JSON.stringify({}))}async deprecateFlow(e){return this.sendJson(l.Post,`/${e}/deprecate`,this.config[g.RequestTimeout],JSON.stringify({}))}async migrateFlows(e,t){let n={source_waba_id:t.source_waba_id,...t.source_flow_names&&{source_flow_names:t.source_flow_names}};return this.sendJson(l.Post,`/${e}/migrate_flows`,this.config[g.RequestTimeout],JSON.stringify(n))}};let ve=function(e){return e.Draft=`DRAFT`,e.Published=`PUBLISHED`,e.Throttled=`THROTTLED`,e.Blocked=`BLOCKED`,e.Deprecated=`DEPRECATED`,e}({}),ye=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}({}),A=function(e){return e.INIT=`INIT`,e.BACK=`BACK`,e.DATA_EXCHANGE=`data_exchange`,e}({}),j=function(e){return e.Ping=`ping`,e.Change=`data_exchange`,e.Error=`error`,e.All=`*`,e}({});var M=class extends D{endpoint=`media`;constructor(e,t){super(e,t)}async getMediaById(e,t){return this.sendJson(l.Get,`${e}`,this.config[g.RequestTimeout],null)}async uploadMedia(e,t=`whatsapp`){let n=new FormData;return n.append(`file`,e),n.append(`messaging_product`,t),n.append(`type`,e.type),this.sendJson(l.Post,`${this.config[g.PhoneNumberId]}/${this.endpoint}`,this.config[g.RequestTimeout],n)}async deleteMedia(e,t){return this.sendJson(l.Delete,`${e}`,this.config[g.RequestTimeout],null)}async downloadMedia(e){return this.sendJson(l.Get,e,this.config[g.RequestTimeout],null)}},N=class extends D{commonMethod=l.Post;commonEndpoint=`messages`;constructor(e,t){super(e,t)}bodyBuilder(e,t,n,r){let i={messaging_product:`whatsapp`,recipient_type:`individual`,to:n,type:e,[e]:t};return r&&(i.context={message_id:r}),i}send(e){return this.sendJson(this.commonMethod,`${this.config[g.PhoneNumberId]}/${this.commonEndpoint}`,this.config[g.RequestTimeout],e)}async audio(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(u.Audio,t,n,r)))}async contacts(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(u.Contacts,t,n,r)))}async document(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(u.Document,t,n,r)))}async image(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(u.Image,t,n,r)))}async interactive(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(u.Interactive,t,n,r)))}async location(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(u.Location,t,n,r)))}async sticker(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(u.Sticker,t,n,r)))}async template(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(u.Template,t,n,r)))}async text(e){let{body:t,to:n,replyMessageId:r,previewUrl:i}=e,a=typeof t==`string`?{body:t,preview_url:i??!0}:{...t,preview_url:i??t.preview_url??!0};return this.send(JSON.stringify(this.bodyBuilder(u.Text,a,n,r)))}async video(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(u.Video,t,n,r)))}async status(e){let t={messaging_product:`whatsapp`,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){return this.status({status:`read`,messageId:e.messageId,typingIndicator:{type:`text`}})}async interactiveList(e){return this.interactive(e)}async interactiveCtaUrl(e){return this.interactive(e)}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 reaction(e){let t={message_id:e.messageId,emoji:e.emoji};return this.send(JSON.stringify(this.bodyBuilder(u.Reaction,t,e.to)))}},P=class{contact={};setName(e){if(!e||typeof e!=`object`)throw Error(`Name must be an object`);return this.contact.name=e,this}setSimpleName(e,t){if(!e||typeof e!=`string`)throw Error(`First name must be a non-empty string`);let n={formatted_name:t?`${e} ${t}`:e,first_name:e};return t&&(n.last_name=t),this.setName(n)}setFullName(e,t,n,r,i){if(!e||typeof e!=`string`)throw Error(`First name must be a non-empty string`);let a={formatted_name:[i,e,n,t,r].filter(Boolean).join(` `),first_name:e};return t&&(a.last_name=t),n&&(a.middle_name=n),r&&(a.suffix=r),i&&(a.prefix=i),this.setName(a)}addPhone(e,t,n){if(!e||typeof e!=`string`)throw Error(`Phone number must be a non-empty string`);let r={phone:`PHONE_NUMBER`};return t&&(r.type=t),n&&(r.wa_id=n),this.contact.phones||(this.contact.phones=[]),this.contact.phones.push(r),this}addEmail(e,t){if(!e||typeof e!=`string`)throw Error(`Email must be a non-empty string`);if(!e.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/))throw Error(`Invalid email format`);let n={email:e};return t&&(n.type=t),this.contact.emails||(this.contact.emails=[]),this.contact.emails.push(n),this}addAddress(e){if(!e||typeof e!=`object`)throw Error(`Address must be an object`);return this.contact.addresses||(this.contact.addresses=[]),this.contact.addresses.push(e),this}addSimpleAddress(e,t,n,r){let i={street:e,city:t,country:n};return r&&(i.type=r),this.addAddress(i)}setOrganization(e,t,n){let r={};return e&&(r.company=e),t&&(r.department=t),n&&(r.title=n),this.contact.org=r,this}addUrl(e,t){if(!e||typeof e!=`string`)throw Error(`URL must be a non-empty string`);let n={url:e};return t&&(n.type=t),this.contact.urls||(this.contact.urls=[]),this.contact.urls.push(n),this}setBirthday(e,t,n){let r=t.toString().padStart(2,`0`),i=n.toString().padStart(2,`0`);return this.contact.birthday=`${e}-${r}-${i}`,this}build(){if(!this.contact.name)throw Error(`Contact name is required`);return this.contact}reset(){return this.contact={},this}},be=class{static createSimpleContact(e,t){return new P().setSimpleName(e).addPhone(t).build()}static createBusinessContact(e,t,n,r,i,a){return new P().setSimpleName(e,t).setOrganization(n,void 0,r).addPhone(i,`WORK`).addEmail(a,`WORK`).build()}static createPersonalContact(e,t,n,r,i){let a=new P().setSimpleName(e,t).addPhone(n,`MOBILE`);return r&&a.addEmail(r,`HOME`),i&&a.setBirthday(i.year,i.month,i.day),a.build()}};function F(e){return!(`name`in e)}var I=class{message={};setType(e){return this.message.type=e,this}setBody(e){return this.message.body={text:e},this}setFooter(e){return this.message.footer={text:e},this}setTextHeader(e){return this.message.header={type:`text`,text:e},this}setImageHeader(e){return this.message.header={type:`image`,image:{link:e}},this}addReplyButtons(e){this.message.action||(this.message.action={});let t=this.message.action;return F(t)&&(t.buttons=e.map(e=>({type:`reply`,reply:{id:e.id,title:e.title}}))),this}addListSections(e){this.message.action||(this.message.action={});let t=this.message.action;return F(t)&&(t.sections=e.map(e=>({title:e.title,rows:e.rows}))),this}setListButtonText(e){this.message.action||(this.message.action={});let t=this.message.action;return F(t)&&(t.button=e),this}setCTAUrl(e,t){return this.message.action={name:`cta_url`,parameters:{display_text:e,url:t}},this}build(){if(!this.message.type)throw Error(`Interactive message type is required`);if(!this.message.body)throw Error(`Interactive message body is required`);if(!this.message.action)throw Error(`Interactive message action is required`);return this.message}reset(){return this.message={},this}},xe=class{static createButtonMessage(e,t,n){let r=new I().setType(f.Button).setBody(e).addReplyButtons(t);return n?.headerText&&r.setTextHeader(n.headerText),n?.footerText&&r.setFooter(n.footerText),r.build()}static createListMessage(e,t,n,r){let i=new I().setType(f.List).setBody(e).addListSections(n);r?.headerText&&i.setTextHeader(r.headerText),r?.footerText&&i.setFooter(r.footerText);let a=i.build(),o=a.action;return F(o)&&(o.button=t),a}static createCTAUrlMessage(e,t,n,r){let i=new I().setType(f.CtaUrl).setBody(e).setCTAUrl(t,n);return r?.headerText&&i.setTextHeader(r.headerText),r?.footerText&&i.setFooter(r.footerText),i.build()}},L=class{location={};setLatitude(e){if(typeof e!=`number`||e<-90||e>90)throw Error(`Latitude must be a number between -90 and 90`);return this.location.latitude=e,this}setLongitude(e){if(typeof e!=`number`||e<-180||e>180)throw Error(`Longitude must be a number between -180 and 180`);return this.location.longitude=e,this}setCoordinates(e,t){return this.setLatitude(e).setLongitude(t)}setName(e){if(e&&typeof e!=`string`)throw Error(`Location name must be a string`);return this.location.name=e,this}setAddress(e){if(e&&typeof e!=`string`)throw Error(`Location address must be a string`);return this.location.address=e,this}build(){if(this.location.latitude===void 0)throw Error(`Latitude is required`);if(this.location.longitude===void 0)throw Error(`Longitude is required`);return this.location}reset(){return this.location={},this}},Se=class{static createSimpleLocation(e,t){return new L().setCoordinates(e,t).build()}static createNamedLocation(e,t,n,r){return new L().setCoordinates(e,t).setName(n).setAddress(r).build()}static createBusinessLocation(e,t,n,r){return new L().setCoordinates(e,t).setName(n).setAddress(r).build()}},R=class{media={};setId(e){if(!e||typeof e!=`string`)throw Error(`Media ID must be a non-empty string`);return this.media.id=e,this}setLink(e){if(!e||typeof e!=`string`)throw Error(`Media URL must be a non-empty string`);if(!e.match(/^https?:\/\//))throw Error(`Media URL must be a valid HTTP/HTTPS URL`);return this.media.link=e,this}setCaption(e){if(e&&typeof e!=`string`)throw Error(`Caption must be a string`);return this.media.caption=e,this}build(){if(!this.media.id&&!this.media.link)throw Error(`Either media ID or link is required`);return this.media}reset(){return this.media={},this}},Ce=class extends R{},we=class extends R{},Te=class extends R{setCaption(e){throw Error(`Audio messages do not support captions`)}},Ee=class extends R{setFilename(e){if(!e||typeof e!=`string`)throw Error(`Filename must be a non-empty string`);return this.media.filename=e,this}},De=class extends R{setCaption(e){throw Error(`Sticker messages do not support captions`)}},Oe=class{static createImageWithCaption(e,t,n=!1){let r=new Ce;return n?r.setId(e):r.setLink(e),r.setCaption(t).build()}static createVideoWithCaption(e,t,n=!1){let r=new we;return n?r.setId(e):r.setLink(e),r.setCaption(t).build()}static createDocument(e,t,n,r=!1){let i=new Ee;return r?i.setId(e):i.setLink(e),i.setFilename(t),n&&i.setCaption(n),i.build()}static createAudio(e,t=!1){let n=new Te;return t?n.setId(e):n.setLink(e),n.build()}static createSticker(e,t=!1){let n=new De;return t?n.setId(e):n.setLink(e),n.build()}},z=class{reaction={};setMessageId(e){if(!e||typeof e!=`string`)throw Error(`Message ID must be a non-empty string`);return this.reaction.message_id=e,this}setEmoji(e){if(!e||typeof e!=`string`)throw Error(`Emoji must be a non-empty string`);if(e.length>4)throw Error(`Please provide a single emoji character`);return this.reaction.emoji=e,this}removeReaction(){return this.reaction.emoji=``,this}build(){if(!this.reaction.message_id)throw Error(`Message ID is required`);if(this.reaction.emoji===void 0)throw Error(`Emoji is required (use empty string to remove reaction)`);return this.reaction}reset(){return this.reaction={},this}},ke=class{static createLike(e){return new z().setMessageId(e).setEmoji(`👍`).build()}static createHeart(e){return new z().setMessageId(e).setEmoji(`❤️`).build()}static createLaugh(e){return new z().setMessageId(e).setEmoji(`😂`).build()}static createWow(e){return new z().setMessageId(e).setEmoji(`😮`).build()}static createSad(e){return new z().setMessageId(e).setEmoji(`😢`).build()}static createAngry(e){return new z().setMessageId(e).setEmoji(`😠`).build()}static removeReaction(e){return new z().setMessageId(e).removeReaction().build()}};function Ae(e){return Object.values(T).includes(e)}function je(e){return Object.values(p).includes(e)}var B=class{template={components:[]};setName(e){if(!e||e.trim().length===0)throw Error(`Template name cannot be empty`);return this.template.name=e,this}setLanguage(e){if(!Ae(e))throw Error(`Invalid language code: ${e}. Must be a valid LanguagesEnum value.`);return this.template.language={policy:`deterministic`,code:e},this}addTextHeader(e){if(!Array.isArray(e))throw Error(`Parameters must be an array`);let t={type:h.Header,parameters:e.map(e=>{if(typeof e!=`string`)throw Error(`All parameters must be strings`);return{type:d.Text,text:e}})};return this.template.components||(this.template.components=[]),this.template.components.push(t),this}addImageHeader(e){if(!e||typeof e!=`string`)throw Error(`Image URL must be a non-empty string`);let t={type:h.Header,parameters:[{type:d.Image,image:{link:e}}]};return this.template.components||(this.template.components=[]),this.template.components.push(t),this}addBody(e){if(!Array.isArray(e))throw Error(`Parameters must be an array`);let t={type:h.Body,parameters:e.map(e=>{if(typeof e!=`string`)throw Error(`All parameters must be strings`);return{type:d.Text,text:e}})};return this.template.components||(this.template.components=[]),this.template.components.push(t),this}addFooter(){let e={type:h.Footer};return this.template.components||(this.template.components=[]),this.template.components.push(e),this}addButtons(e){if(!Array.isArray(e))throw Error(`Buttons must be an array`);return e.forEach(e=>{if(typeof e.index!=`number`||!je(e.index))throw Error(`Button index must be a valid ButtonPositionEnum value: ${e.index}`);let t=e.type===`quick_reply`?m.QuickReply:m.Url,n={type:h.Button,sub_type:t,index:e.index};if(e.parameters&&e.parameters.length>0){if(!Array.isArray(e.parameters))throw Error(`Button parameters must be an array`);e.type===`quick_reply`?n.parameters=e.parameters.map(e=>{if(typeof e!=`string`)throw Error(`All button parameters must be strings`);return{type:d.Payload,payload:e}}):e.type===`url`&&(n.parameters=e.parameters.map(e=>{if(typeof e!=`string`)throw Error(`All button parameters must be strings`);return{type:d.Text,text:e}}))}this.template.components||(this.template.components=[]),this.template.components.push(n)}),this}addCurrencyParameter(e,t,n){if(!e||typeof e!=`string`)throw Error(`Fallback value must be a non-empty string`);if(!t||typeof t!=`string`)throw Error(`Currency code must be a non-empty string`);if(typeof n!=`number`||n<0)throw Error(`Amount must be a non-negative number`);return{type:d.Currency,currency:{fallback_value:e,code:t,amount_1000:n*1e3}}}addDateTimeParameter(e,t){if(!e||typeof e!=`string`)throw Error(`Fallback value must be a non-empty string`);if(typeof t!=`number`||t<=0)throw Error(`Timestamp must be a positive number`);return{type:d.DateTime,date_time:{fallback_value:e,timestamp:t}}}build(){if(!this.template.name)throw Error(`Template name is required`);if(!this.template.language)throw Error(`Template language is required`);return this.template}reset(){return this.template={components:[]},this}},Me=class{static createSimpleTextTemplate(e,t,n){if(!e||!t||!Array.isArray(n))throw Error(`Invalid parameters for simple text template`);return new B().setName(e).setLanguage(t).addBody(n).build()}static createCompleteTemplate(e,t,n){if(!e||!t||!n.bodyParameters)throw Error(`Invalid parameters for complete template`);let r=new B().setName(e).setLanguage(t).addBody(n.bodyParameters);return n.headerParameters?r.addTextHeader(n.headerParameters):n.headerImage&&r.addImageHeader(n.headerImage),n.buttons&&r.addButtons(n.buttons),r.build()}static createOrderConfirmationTemplate(e,t,n,r,i){if(!e||!t||!n||typeof r!=`number`||!i)throw Error(`Invalid parameters for order confirmation template`);return new B().setName(`order_confirmation`).setLanguage(e).addBody([t,n,r.toString(),i]).addButtons([{index:0,type:`quick_reply`},{index:1,type:`url`,parameters:[n]}]).build()}},V=class{textMessage={};setBody(e){if(!e||typeof e!=`string`)throw Error(`Message body must be a non-empty string`);return this.textMessage.body=e,this}setPreviewUrl(e=!0){return this.textMessage.preview_url=e,this}build(){if(!this.textMessage.body)throw Error(`Message body is required`);return this.textMessage}reset(){return this.textMessage={},this}},Ne=class{static createSimpleText(e){return new V().setBody(e).build()}static createTextWithPreview(e){return new V().setBody(e).setPreviewUrl(!0).build()}static createNotification(e,t){return new V().setBody(`*${e}*\n\n${t}`).build()}};const H=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(`&`)}`:``};var Pe=class extends D{endpoint=`phone_numbers`;constructor(e,t){super(e,t)}async getPhoneNumberById(e){let t=e?H({fields:e}):``;return this.sendJson(l.Get,`${this.config[g.PhoneNumberId]}${t}`,this.config[g.RequestTimeout],null)}async getPhoneNumbers(){return this.sendJson(l.Get,`${this.config[g.BusinessAcctId]}/${this.endpoint}`,this.config[g.RequestTimeout],null)}async requestVerificationCode(e){return this.sendJson(l.Post,`${this.config[g.PhoneNumberId]}/request_code`,this.config[g.RequestTimeout],JSON.stringify(e))}async verifyCode(e){return this.sendJson(l.Post,`${this.config[g.PhoneNumberId]}/verify_code`,this.config[g.RequestTimeout],JSON.stringify(e))}};function Fe(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 Ie=class extends D{endpoint=`whatsapp_business_profile`;constructor(e,t){super(e,t)}async getBusinessProfile(e){return this.sendJson(l.Get,`${this.config[g.PhoneNumberId]}/${this.endpoint}${Fe(e)}`,this.config[g.RequestTimeout],null)}async updateBusinessProfile(e){return this.sendJson(l.Post,`${this.config[g.PhoneNumberId]}/${this.endpoint}`,this.config[g.RequestTimeout],JSON.stringify(e))}async createUploadSession(e,t,n){let r=H({file_length:e,file_type:t,file_name:n});return this.sendJson(l.Post,`app/uploads/${r}`,this.config[g.RequestTimeout],null)}async uploadMedia(e,t){return this.sendJson(l.Post,`${e}`,this.config[g.RequestTimeout],t)}async getUploadHandle(e){return this.sendJson(l.Get,`${e}`,this.config[g.RequestTimeout],null)}},Le=class extends D{endpoint=`message_qrdls`;constructor(e,t){super(e,t)}async createQrCode(e){return this.sendJson(l.Post,`${this.config[g.PhoneNumberId]}/${this.endpoint}`,this.config[g.RequestTimeout],JSON.stringify(e))}async getQrCodes(){return this.sendJson(l.Get,`${this.config[g.PhoneNumberId]}/${this.endpoint}`,this.config[g.RequestTimeout],null)}async getQrCode(e){return this.sendJson(l.Get,`${this.config[g.PhoneNumberId]}/${this.endpoint}/${e}`,this.config[g.RequestTimeout],null)}async updateQrCode(e){return this.sendJson(l.Post,`${this.config[g.PhoneNumberId]}/${this.endpoint}`,this.config[g.RequestTimeout],JSON.stringify(e))}async deleteQrCode(e){return this.sendJson(l.Delete,`${this.config[g.PhoneNumberId]}/${this.endpoint}/${e}`,this.config[g.RequestTimeout],null)}},Re=class extends D{constructor(e,t){super(e,t)}async register(e,t){let n={messaging_product:`whatsapp`,pin:e,...t&&{data_localization_region:t}};return this.sendJson(l.Post,`${this.config[g.PhoneNumberId]}/register`,this.config[g.RequestTimeout],JSON.stringify(n))}async deregister(){return this.sendJson(l.Post,`${this.config[g.PhoneNumberId]}/deregister`,this.config[g.RequestTimeout],null)}},ze=class extends D{endpoint=`message_templates`;constructor(e,t){super(e,t)}async getTemplate(e){return this.sendJson(l.Get,`${e}`,this.config[g.RequestTimeout],null)}async updateTemplate(e,t){return this.sendJson(l.Post,`${e}`,this.config[g.RequestTimeout],JSON.stringify(t))}async getTemplates(e){return this.sendJson(l.Get,`${this.config[g.BusinessAcctId]}/${this.endpoint}${H(e??{})}`,this.config[g.RequestTimeout],null)}async createTemplate(e){return this.sendJson(l.Post,`${this.config[g.BusinessAcctId]}/${this.endpoint}`,this.config[g.RequestTimeout],JSON.stringify(e))}async deleteTemplate(e){return this.sendJson(l.Delete,`${this.config[g.BusinessAcctId]}/${this.endpoint}${H(e)}`,this.config[g.RequestTimeout],null)}};function U(e){let t={type:`HEADER`,format:e.format};return e.text&&(t.text=e.text),e.example&&(t.example=e.example),t}function W(e){let t={type:`BODY`,text:e.text};return e.example&&(t.example=e.example),t}function G(e){return{type:`FOOTER`,text:e.text}}function K(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 Be(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 Ve(e){let t=[];if(e.header&&t.push(U(e.header)),e.body&&t.push(W(e.body)),e.footer&&t.push(G(e.footer)),e.buttons&&t.push(...K(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:[Be(e.bodyParameters)]}:void 0}),e.buttons&&n.push(...K(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 He(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:s.Authentication,components:t}}function Ue(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:s.Authentication,components:t}}function We(e){let t=[];return e.header&&t.push(U({...e.header,format:`TEXT`})),t.push(W(e.body)),e.footer&&t.push(G(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:s.Marketing,components:t}}function Ge(e){let t=[];return e.header&&t.push(U({...e.header,format:`TEXT`})),t.push(W(e.body)),e.footer&&t.push(G(e.footer)),t.push({type:`BUTTONS`,buttons:[{type:`COPY_CODE`,example:e.coupon_code}]}),{name:e.name,language:e.language,category:s.Marketing,components:t}}function Ke(e){let t=[];return t.push({type:`LIMITED_TIME_OFFER`,limited_time_offer:{expiration_time_ms:e.expiration_time_ms}}),e.header&&t.push(U({...e.header,format:`TEXT`})),t.push(W(e.body)),e.footer&&t.push(G(e.footer)),{name:e.name,language:e.language,category:s.Marketing,components:t}}function qe(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(W(e.body)),e.buttons&&r.push(...K(e.buttons)),n.push({card_index:t,components:r})}),t.push({type:`CAROUSEL`,cards:n}),{name:e.name,language:e.language,category:s.Marketing,components:t}}function Je(e){let t=[];return e.header&&t.push(U({...e.header,format:`TEXT`})),t.push(W(e.body)),e.footer&&t.push(G(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:s.Marketing,components:t}}function Ye(e){let t=[];e.header&&t.push(U({...e.header,format:`TEXT`})),t.push(W(e.body)),e.footer&&t.push(G(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:s.Marketing,components:t}}function Xe(e){let t=[];return e.header&&t.push(U({...e.header,format:`TEXT`})),t.push(W(e.body)),e.footer&&t.push(G(e.footer)),t.push({type:`BUTTONS`,buttons:[{type:`SPM`,action:{product_retailer_id:e.product_retailer_id}}]}),{name:e.name,language:e.language,category:s.Marketing,components:t}}var Ze=class extends D{constructor(e,t){super(e,t)}async setTwoStepVerificationCode(e){let t={pin:e};return this.sendJson(l.Post,`${this.config[g.PhoneNumberId]}`,this.config[g.RequestTimeout],JSON.stringify(t))}},Qe=class extends D{constructor(e,t){super(e,t)}async getWabaAccount(e){let t=Fe(e)?.replace(/,/g,`%2C`);return this.sendJson(l.Get,`${this.config[g.BusinessAcctId]}${t}`,this.config[g.RequestTimeout],null)}async getAllWabaSubscriptions(){return this.sendJson(l.Get,`${this.config[g.BusinessAcctId]}/subscribed_apps`,this.config[g.RequestTimeout],null)}async updateWabaSubscription({override_callback_uri:e,verify_token:t}){let n={override_callback_uri:e,verify_token:t};return this.sendJson(l.Post,`${this.config[g.BusinessAcctId]}/subscribed_apps`,this.config[g.RequestTimeout],JSON.stringify(n))}async unsubscribeFromWaba(){return this.sendJson(l.Delete,`${this.config[g.BusinessAcctId]}/subscribed_apps`,this.config[g.RequestTimeout],null)}};function $e(){process.env.NODE_ENV===`test`||process.env.VITEST===`true`||typeof global<`u`&&global.__VITEST__||console.log(`\x1B[36m%s\x1B[0m`,`
3
3
  ██████╗ ██╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ██████╗ ██╗
4
4
  ██╔════╝ ██║ ██╔═══██╗ ██║ ██║ ██╔══██╗ ██╔══██╗ ██╔══██╗ ██║
5
5
  ██║ ██║ ██║ ██║ ██║ ██║ ██║ ██║ ███████║ ██████╔╝ ██║
6
6
  ██║ ██║ ██║ ██║ ██║ ██║ ██║ ██║ ██╔══██║ ██╔═══╝ ██║
7
7
  ╚██████╗ ███████╗ ╚██████╔╝ ╚██████╔╝ ██████╔╝ ██║ ██║ ██║ ██║
8
8
  ╚═════╝ ╚══════╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝
9
- `)}const K=new v(`WHATSAPP`,process.env.DEBUG===`true`);var $e=class{config;requester;messages;media;phoneNumbers;twoStepVerification;flows;businessProfile;templates;encryption;qrCode;registration;waba;constructor(e){Qe(),this.config=ge(e),this.requester=new Ce(this.config[g.APIVersion],this.config[g.PhoneNumberId],this.config[g.AccessToken],this.config[g.BusinessAcctId],this.getUserAgent()),this.messages=new E(this.config,this.requester),this.media=new T(this.config,this.requester),this.phoneNumbers=new V(this.config,this.requester),this.twoStepVerification=new Xe(this.config,this.requester),this.flows=new S(this.config,this.requester),this.businessProfile=new Fe(this.config,this.requester),this.templates=new Re(this.config,this.requester),this.encryption=new x(this.config,this.requester),this.qrCode=new Ie(this.config,this.requester),this.registration=new Le(this.config,this.requester),this.waba=new Ze(this.config,this.requester),K.log(`
10
- `+_e(this.config))}updateTimeout(e){this.config[g.RequestTimeout]=e,`updateTimeout`in this.requester&&this.requester.updateTimeout(e),K.log(`Timeout updated to ${e}ms`)}updateSenderNumberId(e){this.config[g.PhoneNumberId]=e,K.log(`Sender number ID updated to ${e}`)}updateAccessToken(e){this.config[g.AccessToken]=e,`updateAccessToken`in this.requester&&this.requester.updateAccessToken(e),K.log(`Access token updated`)}version(){return y()}static get Enums(){return o}getUserAgent(){return we()}};function et(e){return typeof e==`object`&&!!e}function q(e){return typeof e==`string`}const tt=[C.DATA_EXCHANGE,C.INIT,C.BACK],nt=[C.DATA_EXCHANGE,C.INIT];function rt(e){if(!(`flow_token`in e&&q(e.flow_token)&&`action`in e))return!1;let{action:t,version:n,screen:r,data:i}=e,a=n===`3.0`,o=tt.includes(t),s=r===void 0||q(r)&&r!==`SUCCESS`,c=t===C.DATA_EXCHANGE||et(i);return a&&o&&s&&c}function it(e){if(!(`flow_token`in e&&q(e.flow_token)&&`action`in e))return!1;let{action:t,screen:n,data:r}=e,i=nt.includes(t),a=q(n),o=et(r)&&`error_key`in r&&q(r.error)&&`error_message`in r&&q(r.error_message);return i&&a&&o}function at(e){return`action`in e&&e.action===`ping`}const J=new v(`WEBHOOK_UTILS`,process.env.DEBUG===`true`);async function Y(e,t,n){try{J.info(`Processing webhook messages request`);let r=await e.json();if(J.info(`Webhook request body:`,r),r.object!==`whatsapp_business_account`){let e=`Received webhook for non-WhatsApp event`;return J.warn(e,{body:r}),new Response(JSON.stringify({error:e}),{status:404})}let i=[];for(let e of r.entry)try{J.info(`Processing webhook entry:`,{entryId:e.id});let r=e.changes;for(let i of r)i.field===`messages`&&(J.info(`Processing messages change:`,{change:i}),await lt(e.id,i.value,t,n))}catch(t){let n=`Error processing webhook: ${t}`;J.error(n,{entry:e,error:t}),i.push(n)}return J.info(`Webhook processing complete`,{errorCount:i.length}),new Response(i.length>0?JSON.stringify({errors:i}):null,{status:200})}catch(e){return J.error(`Error processing webhook:`,e),new Response(JSON.stringify({error:`Internal Server Error`}),{status:500})}}async function ot(e,t,n,r){try{J.info(`Processing flow request`);let i=await e.text(),a=e.headers.get(`x-hub-signature-256`);if(J.info(`Flow request signature:`,{signature:a}),!st(i,a,t.WEBHOOK_VERIFICATION_TOKEN||``))return J.warn(`Invalid request signature`,{signature:a}),new Response(JSON.stringify({error:`Unauthorized`}),{status:401});let o=JSON.parse(i);J.info(`Flow request data:`,o);let{decryptedBody:s}=ut(o,t);J.info(`Decrypted flow request:`,s);let c=r.get(w.All);if(!c)return J.warn(`No handler registered for flow action:`,{action:s.action}),new Response(JSON.stringify({error:`Handler not found`}),{status:404});if(at(s))return J.info(`Handling flow ping request`),new Response(JSON.stringify({version:`3.0`,data:{status:`active`}}),{status:200});if(it(s))return J.warn(`Flow error request received:`,s),new Response(null,{status:200});if(rt(s)){J.info(`Processing flow data exchange request`);let e=await c(n,s);J.info(`Flow handler result:`,e);let t=dt(e,Buffer.from(o.aes_key,`base64`),Buffer.from(o.initial_vector,`base64`));return J.info(`Encrypted flow response generated`),new Response(JSON.stringify(t),{status:200})}return J.warn(`Unknown flow request type:`,s),new Response(JSON.stringify({error:`Unknown request type`}),{status:400})}catch(e){return J.error(`Error handling flow request:`,e),new Response(JSON.stringify({error:`Internal server error`}),{status:500})}}function st(e,t,n){if(!t)return J.warn(`Missing signature in request`),!1;J.info(`Signature verification details:`,{bodyLength:e.length,verificationTokenLength:n.length,rawSignature:t,cleanedSignature:t.replace(`sha256=`,``)});let r=a.createHmac(`sha256`,n).update(e).digest(`hex`);return J.info(`Signature verification:`,{received:t.replace(`sha256=`,``),expected:r}),a.timingSafeEqual(Buffer.from(t.replace(`sha256=`,``)),Buffer.from(r))}function ct(e,t){let n=e[`x-forwarded-proto`]||`http`,r=e.host||`localhost`;return`${n}://${r}${t||`/`}`}async function lt(e,t,n,r){J.info(`Processing messages:`,{waba_id:e,value:t});let i=t.metadata,a=t.contacts,o=e,s=i?.display_phone_number||``,c=i?.phone_number_id||``,l=a?.[0]?.profile?.name||``;if(t.statuses&&t.statuses.length>0){J.info(`Processing statuses:`,{statusCount:t.statuses.length});let e=t.statuses;for(let i of e){let e={wabaId:o,id:i.id,from:i.recipient_id,timestamp:i.timestamp,type:u.Statuses,phoneNumberId:c,displayPhoneNumber:s,profileName:l,statuses:t.statuses[0],originalData:i};J.info(`Processing status:`,e),await X(r.messageHandlers.get(u.Statuses),n,e,u.Statuses)}return}if(t.messages&&t.messages.length>0){J.info(`Processing messages:`,{messageCount:t.messages.length});let e=t.messages;for(let t of e){let e=t.type;J.info(`Processing message:`,{messageType:e,messageId:t.id});let i={wabaId:o,id:t.id,from:t.from,timestamp:t.timestamp,type:t.type,phoneNumberId:c,displayPhoneNumber:s,profileName:l,originalData:t};switch(e){case u.Text:i.text=t.text;break;case u.Image:i.image=t.image;break;case u.Video:i.video=t.video;break;case u.Audio:i.audio=t.audio;break;case u.Document:i.document=t.document;break;case u.Sticker:i.sticker=t.sticker;break;case u.Location:i.location=t.location;break;case u.Contacts:i.contacts=t.contacts;break;case u.Interactive:i.interactive=t.interactive;break;case u.Button:i.button=t.button;break;case u.Order:i.order=t.order;break;case u.System:i.system=t.system;break;case u.Reaction:i.reaction=t.reaction;break;default:J.warn(`Unknown message type:`,{messageType:e});break}J.info(`Executing message handlers`),await X(r.preProcessHandler,n,i,`pre-process`),await X(r.messageHandlers.get(e),n,i,e),await X(r.postProcessHandler,n,i,`post-process`)}}}async function X(e,t,n,r){if(e)try{J.info(`Executing handler:`,{handlerType:r,messageId:n.id}),await e(t,n),J.info(`Handler execution complete:`,{handlerType:r,messageId:n.id})}catch(e){J.error(`Error in ${r} handler:`,{error:e,messageId:n.id})}else J.info(`No handler registered:`,{handlerType:r})}function ut(e,t){J.info(`Decrypting flow request`);let{encrypted_aes_key:n,encrypted_flow_data:r,initial_vector:i}=e;if(!n||!r||!i)throw J.error(`Missing required encryption properties`),Error(`Missing required encryption properties`);let o=t.FLOW_API_PRIVATE_PEM.replace(/\\n/g,`
11
- `),s=t.FLOW_API_PASSPHRASE,c=a.createPrivateKey({key:o,passphrase:s}),l;try{J.info(`Decrypting AES key`),l=a.privateDecrypt({key:c,padding:a.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:`sha256`},Buffer.from(n,`base64`))}catch(e){throw J.error(`Failed to decrypt AES key:`,e),Error(`Failed to decrypt the request. Please verify your private key.`)}let u=Buffer.from(r,`base64`),d=Buffer.from(i,`base64`),f=u.subarray(0,-16),p=u.subarray(-16);J.info(`Decrypting flow data`);let m=a.createDecipheriv(`aes-128-gcm`,l,d);m.setAuthTag(p);let h=Buffer.concat([m.update(f),m.final()]).toString(`utf-8`);return J.info(`Flow request decryption complete`),{decryptedBody:JSON.parse(h),aesKeyBuffer:l,initialVectorBuffer:d}}function dt(e,t,n){J.info(`Encrypting flow response`);let r=[];for(let e of Array.from(n.entries()))r.push(~e[1]);try{let n=a.createCipheriv(`aes-128-gcm`,t,Buffer.from(r)),i=Buffer.concat([n.update(JSON.stringify(e||{}),`utf-8`),n.final(),n.getAuthTag()]).toString(`base64`);return J.info(`Flow response encryption complete`),i}catch(e){throw J.error(`Response encryption error:`,e),Error(`Failed to encrypt response. Internal server error.`)}}const Z=new v(`WEBHOOK_PROCESSOR`,process.env.DEBUG===`true`);var Q=class{config;client;messageHandlers=new Map;preProcessHandler=void 0;postProcessHandler=void 0;flowHandlers=new Map;constructor(e){this.config=ge(e),this.client=new $e(e),Z.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 Y(e,this.client,{messageHandlers:this.messageHandlers,preProcessHandler:this.preProcessHandler,postProcessHandler:this.postProcessHandler}),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 Z.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 ot(e,this.config,this.client,this.flowHandlers),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 Z.log(`Error processing flow: ${e}`),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}onMessage(e,t){this.messageHandlers.set(e,t),Z.log(`Registered message handler for ${e}`)}onMessagePreProcess(e){this.preProcessHandler=e,Z.log(`Registered pre-process handler`)}onMessagePostProcess(e){this.postProcessHandler=e,Z.log(`Registered post-process handler`)}onFlow(e,t){this.flowHandlers.set(e,t),Z.log(`Registered flow handler for ${e}`)}getClient(){return this.client}getConfig(){return this.config}},$=class{processor;constructor(e){this.processor=new Q(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 ct(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}},ft=class extends ${constructor(e){super(e)}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)}catch(e){return n(e),t}}async handlePost(e,t,n){try{let n=this.constructFullUrl(e.headers,e.url),r=new globalThis.Request(n,{method:e.method,headers:e.headers,body:JSON.stringify(e.body)}),i=await this.processWebhook(r);return this.applyHeaders(i,t),t.status(i.status).send(i.body)}catch(e){return n(e),t}}async handleFlow(e,t,n){try{let n=this.constructFullUrl(e.headers,e.url),r=new globalThis.Request(n,{method:e.method,headers:e.headers,body:e.method===`POST`?JSON.stringify(e.body):void 0}),i=await this.processFlow(r);return this.applyHeaders(i,t),t.status(i.status).send(i.body)}catch(e){return n(e),t}}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}}};function pt(e){return new ft(e).getHandlers()}var mt=class extends ${constructor(e){super(e)}async parseRequestBody(e){if(e.method===`POST`&&!e.body){let t=[];if(typeof e[Symbol.asyncIterator]==`function`){for await(let n of e)t.push(n);let n=Buffer.concat(t).toString();if(n.trim())try{e.body=JSON.parse(n)}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)}catch(e){return console.error(`Webhook verification error:`,e),t.status(500).json({error:`Internal Server Error`})}}async handlePost(e,t){try{await this.parseRequestBody(e)}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`}):t.status(500).json({error:`Internal Server Error`})}try{let n=this.constructFullUrl(e.headers,e.url),r=new Request(n,{method:`POST`,headers:e.headers,body:JSON.stringify(e.body)}),i=await this.processWebhook(r);return this.applyHeaders(i,t),t.status(i.status).send(i.body)}catch(e){return console.error(`Webhook processing error:`,e),t.status(500).json({error:`Internal Server Error`})}}async handleFlow(e,t){try{let n=this.constructFullUrl(e.headers,e.url),r=new Request(n,{method:e.method,headers:e.headers,body:e.method===`POST`?JSON.stringify(e.body):void 0}),i=await this.processFlow(r);return this.applyHeaders(i,t),t.status(i.status).send(i.body)}catch(e){return console.error(`Flow error:`,e),t.status(500).json({error:`Internal Server Error`})}}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}}};function ht(e){return new mt(e).getHandlers()}function gt(e){let t=new Q(e);return{GET:async e=>{try{let{searchParams:n}=new URL(e.url),r=n.get(`hub.mode`),i=n.get(`hub.verify_token`),a=n.get(`hub.challenge`),o=await t.processVerification(r,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 n=await t.processWebhook(e);return new Response(n.body,{status:n.status,headers:n.headers})}catch(e){return console.error(`Webhook processing error:`,e),new Response(`Internal Server Error`,{status:500})}},webhook:{GET:async e=>{try{let{searchParams:n}=new URL(e.url),r=n.get(`hub.mode`),i=n.get(`hub.verify_token`),a=n.get(`hub.challenge`),o=await t.processVerification(r,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 n=await t.processWebhook(e);return new Response(n.body,{status:n.status,headers:n.headers})}catch(e){return console.error(`Webhook processing error:`,e),new Response(`Internal Server Error`,{status:500})}}},flow:{GET:async e=>{try{let n=await t.processFlow(e);return Response.json(n.body,{status:n.status,headers:n.headers})}catch(e){return console.error(`Flow GET error:`,e),new Response(`Internal Server Error`,{status:500})}},POST:async e=>{try{let n=await t.processFlow(e);return Response.json(n.body,{status:n.status,headers:n.headers})}catch(e){return console.error(`Flow POST error:`,e),new Response(`Internal Server Error`,{status:500})}}},processor:t}}const _t=(e,t)=>i.createHmac(`sha256`,t).update(e,`utf-8`).digest(`hex`);export{P as AudioMessageBuilder,Fe as BusinessProfileApi,D as ContactMessageBuilder,Te as ContactMessageFactory,F as DocumentMessageBuilder,x as EncryptionApi,S as FlowApi,w as FlowTypeEnum,M as ImageMessageBuilder,k as InteractiveMessageBuilder,Ee as InteractiveMessageFactory,A as LocationMessageBuilder,De as LocationMessageFactory,T as MediaApi,Oe as MediaMessageFactory,E as MessageApi,E as MessagesApi,V as PhoneNumberApi,Ie as QrCodeApi,L as ReactionMessageBuilder,ke as ReactionMessageFactory,Le as RegistrationApi,I as StickerMessageBuilder,Re as TemplateApi,R as TemplateMessageBuilder,Me as TemplateMessageFactory,z as TextMessageBuilder,Ne as TextMessageFactory,Xe as TwoStepVerificationApi,N as VideoMessageBuilder,Ze as WabaApi,Q as WebhookProcessor,$e as WhatsApp,ct as constructFullUrl,He as createAuthenticationTemplate,Ue as createCatalogTemplate,We as createCouponTemplate,Ge as createLimitedTimeOfferTemplate,qe as createMPMTemplate,Ke as createMediaCardCarouselTemplate,Ve as createOTPTemplate,Je as createProductCardCarouselTemplate,Ye as createSPMTemplate,Be as createTemplate,pt as expressWebhookHandler,_t as generateXHub256Sig,gt as nextjsAppWebhookHandler,ht as nextjsWebhookHandler,ot as processFlowRequest,Y as processWebhookMessages};
9
+ `)}const q=new E(`WHATSAPP`,process.env.DEBUG===`true`);var et=class{config;requester;messages;media;phoneNumbers;twoStepVerification;flows;businessProfile;templates;encryption;qrCode;registration;waba;constructor(e){$e(),this.config=ce(e),this.requester=new he(this.config[g.APIVersion],this.config[g.PhoneNumberId],this.config[g.AccessToken],this.config[g.BusinessAcctId],this.getUserAgent()),this.messages=new N(this.config,this.requester),this.media=new M(this.config,this.requester),this.phoneNumbers=new Pe(this.config,this.requester),this.twoStepVerification=new Ze(this.config,this.requester),this.flows=new k(this.config,this.requester),this.businessProfile=new Ie(this.config,this.requester),this.templates=new ze(this.config,this.requester),this.encryption=new O(this.config,this.requester),this.qrCode=new Le(this.config,this.requester),this.registration=new Re(this.config,this.requester),this.waba=new Qe(this.config,this.requester),q.log(`
10
+ `+le(this.config))}updateTimeout(e){this.config[g.RequestTimeout]=e,`updateTimeout`in this.requester&&this.requester.updateTimeout(e),q.log(`Timeout updated to ${e}ms`)}updateSenderNumberId(e){this.config[g.PhoneNumberId]=e,q.log(`Sender number ID updated to ${e}`)}updateAccessToken(e){this.config[g.AccessToken]=e,`updateAccessToken`in this.requester&&this.requester.updateAccessToken(e),q.log(`Access token updated`)}version(){return ge()}static get Enums(){return o}getUserAgent(){return _e()}};function tt(e){return typeof e==`object`&&!!e}function J(e){return typeof e==`string`}const nt=[A.DATA_EXCHANGE,A.INIT,A.BACK],rt=[A.DATA_EXCHANGE,A.INIT];function it(e){if(!(`flow_token`in e&&J(e.flow_token)&&`action`in e))return!1;let{action:t,version:n,screen:r,data:i}=e,a=n===`3.0`,o=nt.includes(t),s=r===void 0||J(r)&&r!==`SUCCESS`,c=t===A.DATA_EXCHANGE||tt(i);return a&&o&&s&&c}function at(e){if(!(`flow_token`in e&&J(e.flow_token)&&`action`in e))return!1;let{action:t,screen:n,data:r}=e,i=rt.includes(t),a=J(n),o=tt(r)&&`error_key`in r&&J(r.error)&&`error_message`in r&&J(r.error_message);return i&&a&&o}function ot(e){return`action`in e&&e.action===`ping`}const Y=new E(`WEBHOOK_UTILS`,process.env.DEBUG===`true`);async function st(e,t,n){try{Y.info(`Processing webhook messages request`);let r=await e.json();if(Y.info(`Webhook request body:`,r),r.object!==`whatsapp_business_account`){let e=`Received webhook for non-WhatsApp event`;return Y.warn(e,{body:r}),new Response(JSON.stringify({error:e}),{status:404})}let i=[];for(let e of r.entry)try{Y.info(`Processing webhook entry:`,{entryId:e.id});let r=e.changes;for(let i of r)i.field===`messages`&&(Y.info(`Processing messages change:`,{change:i}),await ut(e.id,i.value,t,n))}catch(t){let n=`Error processing webhook: ${t}`;Y.error(n,{entry:e,error:t}),i.push(n)}return Y.info(`Webhook processing complete`,{errorCount:i.length}),new Response(i.length>0?JSON.stringify({errors:i}):null,{status:200})}catch(e){return Y.error(`Error processing webhook:`,e),new Response(JSON.stringify({error:`Internal Server Error`}),{status:500})}}async function X(e,t,n,r){try{Y.info(`Processing flow request`);let i=await e.text(),a=e.headers.get(`x-hub-signature-256`);if(Y.info(`Flow request signature:`,{signature:a}),!ct(i,a,t.WEBHOOK_VERIFICATION_TOKEN||``))return Y.warn(`Invalid request signature`,{signature:a}),new Response(JSON.stringify({error:`Unauthorized`}),{status:401});let o=JSON.parse(i);Y.info(`Flow request data:`,o);let{decryptedBody:s}=dt(o,t);Y.info(`Decrypted flow request:`,s);let c=r.get(j.All);if(!c)return Y.warn(`No handler registered for flow action:`,{action:s.action}),new Response(JSON.stringify({error:`Handler not found`}),{status:404});if(ot(s))return Y.info(`Handling flow ping request`),new Response(JSON.stringify({version:`3.0`,data:{status:`active`}}),{status:200});if(at(s))return Y.warn(`Flow error request received:`,s),new Response(null,{status:200});if(it(s)){Y.info(`Processing flow data exchange request`);let e=await c(n,s);Y.info(`Flow handler result:`,e);let t=ft(e,Buffer.from(o.aes_key,`base64`),Buffer.from(o.initial_vector,`base64`));return Y.info(`Encrypted flow response generated`),new Response(JSON.stringify(t),{status:200})}return Y.warn(`Unknown flow request type:`,s),new Response(JSON.stringify({error:`Unknown request type`}),{status:400})}catch(e){return Y.error(`Error handling flow request:`,e),new Response(JSON.stringify({error:`Internal server error`}),{status:500})}}function ct(e,t,n){if(!t)return Y.warn(`Missing signature in request`),!1;Y.info(`Signature verification details:`,{bodyLength:e.length,verificationTokenLength:n.length,rawSignature:t,cleanedSignature:t.replace(`sha256=`,``)});let r=a.createHmac(`sha256`,n).update(e).digest(`hex`);return Y.info(`Signature verification:`,{received:t.replace(`sha256=`,``),expected:r}),a.timingSafeEqual(Buffer.from(t.replace(`sha256=`,``)),Buffer.from(r))}function lt(e,t){let n=e[`x-forwarded-proto`]||`http`,r=e.host||`localhost`;return`${n}://${r}${t||`/`}`}async function ut(e,t,n,r){Y.info(`Processing messages:`,{waba_id:e,value:t});let i=t.metadata,a=t.contacts,o=e,s=i?.display_phone_number||``,c=i?.phone_number_id||``,l=a?.[0]?.profile?.name||``;if(t.statuses&&t.statuses.length>0){Y.info(`Processing statuses:`,{statusCount:t.statuses.length});let e=t.statuses;for(let i of e){let e={wabaId:o,id:i.id,from:i.recipient_id,timestamp:i.timestamp,type:u.Statuses,phoneNumberId:c,displayPhoneNumber:s,profileName:l,statuses:t.statuses[0],originalData:i};Y.info(`Processing status:`,e),await Z(r.messageHandlers.get(u.Statuses),n,e,u.Statuses)}return}if(t.messages&&t.messages.length>0){Y.info(`Processing messages:`,{messageCount:t.messages.length});let e=t.messages;for(let t of e){let e=t.type;Y.info(`Processing message:`,{messageType:e,messageId:t.id});let i={wabaId:o,id:t.id,from:t.from,timestamp:t.timestamp,type:t.type,phoneNumberId:c,displayPhoneNumber:s,profileName:l,originalData:t};switch(e){case u.Text:i.text=t.text;break;case u.Image:i.image=t.image;break;case u.Video:i.video=t.video;break;case u.Audio:i.audio=t.audio;break;case u.Document:i.document=t.document;break;case u.Sticker:i.sticker=t.sticker;break;case u.Location:i.location=t.location;break;case u.Contacts:i.contacts=t.contacts;break;case u.Interactive:i.interactive=t.interactive;break;case u.Button:i.button=t.button;break;case u.Order:i.order=t.order;break;case u.System:i.system=t.system;break;case u.Reaction:i.reaction=t.reaction;break;default:Y.warn(`Unknown message type:`,{messageType:e});break}Y.info(`Executing message handlers`),await Z(r.preProcessHandler,n,i,`pre-process`),await Z(r.messageHandlers.get(e),n,i,e),await Z(r.postProcessHandler,n,i,`post-process`)}}}async function Z(e,t,n,r){if(e)try{Y.info(`Executing handler:`,{handlerType:r,messageId:n.id}),await e(t,n),Y.info(`Handler execution complete:`,{handlerType:r,messageId:n.id})}catch(e){Y.error(`Error in ${r} handler:`,{error:e,messageId:n.id})}else Y.info(`No handler registered:`,{handlerType:r})}function dt(e,t){Y.info(`Decrypting flow request`);let{encrypted_aes_key:n,encrypted_flow_data:r,initial_vector:i}=e;if(!n||!r||!i)throw Y.error(`Missing required encryption properties`),Error(`Missing required encryption properties`);let o=t.FLOW_API_PRIVATE_PEM.replace(/\\n/g,`
11
+ `),s=t.FLOW_API_PASSPHRASE,c=a.createPrivateKey({key:o,passphrase:s}),l;try{Y.info(`Decrypting AES key`),l=a.privateDecrypt({key:c,padding:a.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:`sha256`},Buffer.from(n,`base64`))}catch(e){throw Y.error(`Failed to decrypt AES key:`,e),Error(`Failed to decrypt the request. Please verify your private key.`)}let u=Buffer.from(r,`base64`),d=Buffer.from(i,`base64`),f=u.subarray(0,-16),p=u.subarray(-16);Y.info(`Decrypting flow data`);let m=a.createDecipheriv(`aes-128-gcm`,l,d);m.setAuthTag(p);let h=Buffer.concat([m.update(f),m.final()]).toString(`utf-8`);return Y.info(`Flow request decryption complete`),{decryptedBody:JSON.parse(h),aesKeyBuffer:l,initialVectorBuffer:d}}function ft(e,t,n){Y.info(`Encrypting flow response`);let r=[];for(let e of Array.from(n.entries()))r.push(~e[1]);try{let n=a.createCipheriv(`aes-128-gcm`,t,Buffer.from(r)),i=Buffer.concat([n.update(JSON.stringify(e||{}),`utf-8`),n.final(),n.getAuthTag()]).toString(`base64`);return Y.info(`Flow response encryption complete`),i}catch(e){throw Y.error(`Response encryption error:`,e),Error(`Failed to encrypt response. Internal server error.`)}}const Q=new E(`WEBHOOK_PROCESSOR`,process.env.DEBUG===`true`);var $=class{config;client;messageHandlers=new Map;preProcessHandler=void 0;postProcessHandler=void 0;flowHandlers=new Map;constructor(e){this.config=ce(e),this.client=new et(e),Q.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 st(e,this.client,{messageHandlers:this.messageHandlers,preProcessHandler:this.preProcessHandler,postProcessHandler:this.postProcessHandler}),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 Q.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 X(e,this.config,this.client,this.flowHandlers),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 Q.log(`Error processing flow: ${e}`),{status:500,body:JSON.stringify({error:`Internal Server Error`}),headers:{"Content-Type":`application/json`}}}}onMessage(e,t){this.messageHandlers.set(e,t),Q.log(`Registered message handler for ${e}`)}onMessagePreProcess(e){this.preProcessHandler=e,Q.log(`Registered pre-process handler`)}onMessagePostProcess(e){this.postProcessHandler=e,Q.log(`Registered post-process handler`)}onFlow(e,t){this.flowHandlers.set(e,t),Q.log(`Registered flow handler for ${e}`)}getClient(){return this.client}getConfig(){return this.config}},pt=class{processor;constructor(e){this.processor=new $(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 lt(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}},mt=class extends pt{constructor(e){super(e)}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)}catch(e){return n(e),t}}async handlePost(e,t,n){try{let n=this.constructFullUrl(e.headers,e.url),r=new globalThis.Request(n,{method:e.method,headers:e.headers,body:JSON.stringify(e.body)}),i=await this.processWebhook(r);return this.applyHeaders(i,t),t.status(i.status).send(i.body)}catch(e){return n(e),t}}async handleFlow(e,t,n){try{let n=this.constructFullUrl(e.headers,e.url),r=new globalThis.Request(n,{method:e.method,headers:e.headers,body:e.method===`POST`?JSON.stringify(e.body):void 0}),i=await this.processFlow(r);return this.applyHeaders(i,t),t.status(i.status).send(i.body)}catch(e){return n(e),t}}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}}};function ht(e){return new mt(e).getHandlers()}var gt=class extends pt{constructor(e){super(e)}async parseRequestBody(e){if(e.method===`POST`&&!e.body){let t=[];if(typeof e[Symbol.asyncIterator]==`function`){for await(let n of e)t.push(n);let n=Buffer.concat(t).toString();if(n.trim())try{e.body=JSON.parse(n)}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)}catch(e){return console.error(`Webhook verification error:`,e),t.status(500).json({error:`Internal Server Error`})}}async handlePost(e,t){try{await this.parseRequestBody(e)}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`}):t.status(500).json({error:`Internal Server Error`})}try{let n=this.constructFullUrl(e.headers,e.url),r=new Request(n,{method:`POST`,headers:e.headers,body:JSON.stringify(e.body)}),i=await this.processWebhook(r);return this.applyHeaders(i,t),t.status(i.status).send(i.body)}catch(e){return console.error(`Webhook processing error:`,e),t.status(500).json({error:`Internal Server Error`})}}async handleFlow(e,t){try{let n=this.constructFullUrl(e.headers,e.url),r=new Request(n,{method:e.method,headers:e.headers,body:e.method===`POST`?JSON.stringify(e.body):void 0}),i=await this.processFlow(r);return this.applyHeaders(i,t),t.status(i.status).send(i.body)}catch(e){return console.error(`Flow error:`,e),t.status(500).json({error:`Internal Server Error`})}}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}}};function _t(e){return new gt(e).getHandlers()}function vt(e){let t=new $(e);return{GET:async e=>{try{let{searchParams:n}=new URL(e.url),r=n.get(`hub.mode`),i=n.get(`hub.verify_token`),a=n.get(`hub.challenge`),o=await t.processVerification(r,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 n=await t.processWebhook(e);return new Response(n.body,{status:n.status,headers:n.headers})}catch(e){return console.error(`Webhook processing error:`,e),new Response(`Internal Server Error`,{status:500})}},webhook:{GET:async e=>{try{let{searchParams:n}=new URL(e.url),r=n.get(`hub.mode`),i=n.get(`hub.verify_token`),a=n.get(`hub.challenge`),o=await t.processVerification(r,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 n=await t.processWebhook(e);return new Response(n.body,{status:n.status,headers:n.headers})}catch(e){return console.error(`Webhook processing error:`,e),new Response(`Internal Server Error`,{status:500})}}},flow:{GET:async e=>{try{let n=await t.processFlow(e);return Response.json(n.body,{status:n.status,headers:n.headers})}catch(e){return console.error(`Flow GET error:`,e),new Response(`Internal Server Error`,{status:500})}},POST:async e=>{try{let n=await t.processFlow(e);return Response.json(n.body,{status:n.status,headers:n.headers})}catch(e){return console.error(`Flow POST error:`,e),new Response(`Internal Server Error`,{status:500})}}},processor:t}}const yt=(e,t)=>i.createHmac(`sha256`,t).update(e,`utf-8`).digest(`hex`);let bt=function(e){return e.Approved=`APPROVED`,e.Active=`ACTIVE`,e.Inactive=`INACTIVE`,e.Disabled=`DISABLED`,e}({}),xt=function(e){return e.Blocked=`BLOCKED`,e.Limited=`LIMITED`,e.Available=`AVAILABLE`,e}({}),St=function(e){return e.Approved=`APPROVED`,e.Active=`ACTIVE`,e.Inactive=`INACTIVE`,e.Disabled=`DISABLED`,e}({}),Ct=function(e){return e.Verified=`verified`,e.PendingSubmission=`pending_submission`,e.Unverified=`unverified`,e.Rejected=`rejected`,e}({});export{x as AudioMediaTypesEnum,Te as AudioMessageBuilder,Ie as BusinessProfileApi,ae as BusinessVerticalEnum,p as ButtonPositionEnum,s as CategoryEnum,h as ComponentTypesEnum,P as ContactMessageBuilder,be as ContactMessageFactory,ee as ConversationTypesEnum,re as CurrencyCodesEnum,ie as DataLocalizationRegionEnum,b as DocumentMediaTypesEnum,Ee as DocumentMessageBuilder,O as EncryptionApi,A as FlowActionEnum,k as FlowApi,ye as FlowCategoryEnum,ve as FlowStatusEnum,j as FlowTypeEnum,l as HttpMethodsEnum,y as ImageMediaTypesEnum,Ce as ImageMessageBuilder,I as InteractiveMessageBuilder,xe as InteractiveMessageFactory,f as InteractiveTypesEnum,T as LanguagesEnum,L as LocationMessageBuilder,Se as LocationMessageFactory,M as MediaApi,Oe as MediaMessageFactory,N as MessageApi,N as MessagesApi,u as MessageTypesEnum,d as ParametersTypesEnum,Pe as PhoneNumberApi,Le as QrCodeApi,z as ReactionMessageBuilder,ke as ReactionMessageFactory,w as ReferralSourceTypesEnum,Re as RegistrationApi,ne as RequestCodeMethodsEnum,te as StatusEnum,v as StickerMediaTypesEnum,De as StickerMessageBuilder,m as SubTypeEnum,C as SystemChangeTypesEnum,ze as TemplateApi,B as TemplateMessageBuilder,Me as TemplateMessageFactory,c as TemplateStatusEnum,V as TextMessageBuilder,Ne as TextMessageFactory,Ze as TwoStepVerificationApi,_ as VideoMediaTypesEnum,we as VideoMessageBuilder,bt as WabaAccountReviewStatus,St as WabaAccountStatus,Qe as WabaApi,Ct as WabaBusinessVerificationStatus,g as WabaConfigEnum,xt as WabaHealthStatusCanSendMessage,$ as WebhookProcessor,S as WebhookTypesEnum,et as WhatsApp,lt as constructFullUrl,Ue as createAuthenticationTemplate,We as createCatalogTemplate,Ge as createCouponTemplate,Ke as createLimitedTimeOfferTemplate,Je as createMPMTemplate,qe as createMediaCardCarouselTemplate,He as createOTPTemplate,Ye as createProductCardCarouselTemplate,Xe as createSPMTemplate,Ve as createTemplate,ht as expressWebhookHandler,yt as generateXHub256Sig,vt as nextjsAppWebhookHandler,_t as nextjsWebhookHandler,X as processFlowRequest,st as processWebhookMessages};
12
12
  //# sourceMappingURL=index.js.map