meta-cloud-api 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,12 +1,21 @@
1
- import{__export as e}from"./chunk-CTAAG5j7.js";import{inspect as t}from"util";import{Agent as n}from"https";import{readFileSync as r}from"fs";import{join as i}from"path";import*as a from"crypto";import o from"crypto";var s=e({AudioMediaTypesEnum:()=>S,BusinessVerticalEnum:()=>oe,ButtonPositionEnum:()=>m,CategoryEnum:()=>c,ComponentTypesEnum:()=>g,ConversationTypesEnum:()=>ee,CurrencyCodesEnum:()=>ie,DataLocalizationRegionEnum:()=>ae,DocumentMediaTypesEnum:()=>x,HttpMethodsEnum:()=>u,ImageMediaTypesEnum:()=>b,InteractiveTypesEnum:()=>p,LanguagesEnum:()=>T,MessageTypesEnum:()=>d,ParametersTypesEnum:()=>f,ReferralSourceTypesEnum:()=>ne,RequestCodeMethodsEnum:()=>re,StatusEnum:()=>te,StickerMediaTypesEnum:()=>y,SubTypeEnum:()=>h,SystemChangeTypesEnum:()=>w,TemplateStatusEnum:()=>l,VideoMediaTypesEnum:()=>v,WabaConfigEnum:()=>_,WebhookTypesEnum:()=>C});let c=function(e){return e.Authentication=`AUTHENTICATION`,e.Marketing=`MARKETING`,e.Utility=`UTILITY`,e}({}),l=function(e){return e.Approved=`APPROVED`,e.Pending=`PENDING`,e.Rejected=`REJECTED`,e}({}),u=function(e){return e.Get=`GET`,e.Post=`POST`,e.Put=`PUT`,e.Delete=`DELETE`,e}({}),d=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}({}),f=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}({}),p=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}({}),m=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}({}),h=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}({}),g=function(e){return e.Header=`HEADER`,e.Body=`BODY`,e.Button=`BUTTON`,e.Footer=`FOOTER`,e}({}),_=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}({}),v=function(e){return e.Mp4=`video/mp4`,e.Threegp=`video/3gp`,e}({}),y=function(e){return e.Webp=`image/webp`,e}({}),b=function(e){return e.Jpeg=`image/jpeg`,e.Png=`image/png`,e}({}),x=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}({}),S=function(e){return e.Aac=`audio/aac`,e.Mp4=`audio/mp4`,e.Mpeg=`audio/mpeg`,e.Amr=`audio/amr`,e.Ogg=`audio/ogg`,e}({}),C=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}({}),w=function(e){return e.CustomerChangedNumber=`customer_changed_number`,e.CustomerIdentityChanged=`customer_identity_changed`,e}({}),ne=function(e){return e.Ad=`ad`,e.Post=`post`,e}({}),re=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}({}),ie=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.XO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`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}({}),ae=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}({}),oe=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}formatData(e){return e.map(e=>typeof e==`object`?t(e,{depth:null,colors:!0}):e).join(` `)}log(...e){if(this.debug){let t=`[ ${Date.now()} ]`;this.name&&(t+=` - ${this.name}`),console.log(t,`: `,this.formatData(e))}}error(...e){let t=`[ ${Date.now()} ] - ERROR`;this.name&&(t+=` - ${this.name}`),console.error(t,`: `,this.formatData(e))}warn(...e){if(this.debug){let t=`[ ${Date.now()} ] - WARN`;this.name&&(t+=` - ${this.name}`),console.warn(t,`: `,this.formatData(e))}}info(...e){if(this.debug){let t=`[ ${Date.now()} ] - INFO`;this.name&&(t+=` - ${this.name}`),console.info(t,`: `,this.formatData(e))}}};const se=new E(`UTILS`,process.env.DEBUG===`true`||!1),ce=e=>{if(!process.env[_.AccessToken]&&!e?.accessToken)throw se.log(`Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined.`),Error(`Missing WhatsApp access token.`)},le=e=>(ce(e),{[_.AppId]:e?.appId||process.env.M4D_APP_ID||``,[_.AppSecret]:e?.appSecret||process.env.M4D_APP_SECRET||``,[_.PhoneNumberId]:e?.phoneNumberId||Number(process.env.WA_PHONE_NUMBER_ID),[_.BusinessAcctId]:e?.businessAcctId||process.env.WA_BUSINESS_ACCOUNT_ID||``,[_.APIVersion]:e?.apiVersion||process.env.CLOUD_API_VERSION||``,[_.AccessToken]:e?.accessToken||process.env.CLOUD_API_ACCESS_TOKEN||``,[_.WebhookEndpoint]:e?.webhookEndpoint||process.env.WEBHOOK_ENDPOINT||``,[_.WebhookVerificationToken]:e?.webhookVerificationToken||process.env.WEBHOOK_VERIFICATION_TOKEN||``,[_.ListenerPort]:e?.listenerPort||parseInt(process.env.LISTENER_PORT||``)||3e3,[_.MaxRetriesAfterWait]:e?.maxRetriesAfterWait||parseInt(process.env.MAX_RETRIES_AFTER_WAIT||``)||30,[_.RequestTimeout]:e?.requestTimeout||parseInt(process.env.REQUEST_TIMEOUT||``)||2e4,[_.Debug]:e?.debug||process.env.DEBUG===`true`,[_.PrivatePem]:e?.privatePem||process.env.FLOW_API_PRIVATE_PEM||``,[_.Passphrase]:e?.passphrase||process.env.FLOW_API_PASSPHRASE||``});function ue(e){let t=[[`App ID`,e[_.AppId]||`Not Set`],[`Phone Number ID`,e[_.PhoneNumberId]?.toString()||`Not Set`],[`Business Account ID`,e[_.BusinessAcctId]||`Not Set`],[`API Version`,e[_.APIVersion]||`Not Set`],[`Access Token`,e[_.AccessToken]?`${e[_.AccessToken].substring(0,20)}...`:`Not Set`],[`Webhook Endpoint`,e[_.WebhookEndpoint]||`Not Set`],[`Webhook Verification Token`,e[_.WebhookVerificationToken]?`${e[_.WebhookVerificationToken].substring(0,10)}...`:`Not Set`],[`Listener Port`,e[_.ListenerPort]?.toString()||`Not Set`],[`Debug Mode`,e[_.Debug]?`Enabled`:`Disabled`],[`Max Retries`,e[_.MaxRetriesAfterWait]?.toString()||`Not Set`],[`Request Timeout`,e[_.RequestTimeout]?`${e[_.RequestTimeout]}ms`:`Not Set`],[`Private PEM`,e[_.PrivatePem]?`Configured`:`Not Set`],[`Passphrase`,e[_.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 de(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 fe=new E(`HttpsClient`,process.env.DEBUG===`true`);var pe=class{agent;constructor(){this.agent=new n({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 fe.log(`${n} : ${o} - ${JSON.stringify(e)}`),clearTimeout(c),new me(e)}catch(e){throw fe.error(`${n} : ${o} - ${JSON.stringify(e)}`),e}}},me=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 he=new E(`REQUESTER`,process.env.DEBUG===`true`);var ge=class{client;accessToken;phoneNumberId;businessAcctId;apiVersion;userAgent;host;protocol=`https:`;constructor(e,t,n,r,i){this.client=new pe,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)}`;he.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 de(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 de(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 _e(){try{let e=i(__dirname,`../../package.json`);return JSON.parse(r(e,`utf-8`)).version}catch{return`unknown`}}function ve(){let e=_e(),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(u.Get,`${this.config[_.PhoneNumberId]}/${this.endpoint}`,this.config[_.RequestTimeout],null)}async setEncryptionPublicKey(e){let t=new FormData;return t.append(`business_public_key`,e),this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/${this.endpoint}`,this.config[_.RequestTimeout],t)}},k=class extends D{constructor(e,t){super(e,t)}async listFlows(e){return this.sendJson(u.Get,`/${e}/flows`,this.config[_.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(u.Post,`/${e}/flows`,this.config[_.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(u.Get,`/${e}${i}`,this.config[_.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(u.Post,`/${e}`,this.config[_.RequestTimeout],JSON.stringify(n))}async deleteFlow(e){return this.sendJson(u.Delete,`/${e}`,this.config[_.RequestTimeout],null)}async listAssets(e){return this.sendJson(u.Get,`/${e}/assets`,this.config[_.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(u.Post,`/${e}/assets`,this.config[_.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(u.Post,`/${e}/publish`,this.config[_.RequestTimeout],JSON.stringify({}))}async deprecateFlow(e){return this.sendJson(u.Post,`/${e}/deprecate`,this.config[_.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(u.Post,`/${e}/migrate_flows`,this.config[_.RequestTimeout],JSON.stringify(n))}};let ye=function(e){return e.Draft=`DRAFT`,e.Published=`PUBLISHED`,e.Throttled=`THROTTLED`,e.Blocked=`BLOCKED`,e.Deprecated=`DEPRECATED`,e}({}),be=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(u.Get,`${e}`,this.config[_.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(u.Post,`${this.config[_.PhoneNumberId]}/${this.endpoint}`,this.config[_.RequestTimeout],n)}async deleteMedia(e,t){return this.sendJson(u.Delete,`${e}`,this.config[_.RequestTimeout],null)}async downloadMedia(e){return this.sendJson(u.Get,e,this.config[_.RequestTimeout],null)}},N=class extends D{commonMethod=u.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[_.PhoneNumberId]}/${this.commonEndpoint}`,this.config[_.RequestTimeout],e)}async audio(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.Audio,t,n,r)))}async contacts(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.Contacts,t,n,r)))}async document(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.Document,t,n,r)))}async image(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.Image,t,n,r)))}async interactive(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.Interactive,t,n,r)))}async location(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.Location,t,n,r)))}async sticker(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.Sticker,t,n,r)))}async template(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.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(d.Text,a,n,r)))}async video(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.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(d.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}},xe=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}},Se=class{static createButtonMessage(e,t,n){let r=new I().setType(p.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(p.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(p.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}},Ce=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}},we=class extends R{},Te=class extends R{},Ee=class extends R{setCaption(e){throw Error(`Audio messages do not support captions`)}},De=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}},Oe=class extends R{setCaption(e){throw Error(`Sticker messages do not support captions`)}},ke=class{static createImageWithCaption(e,t,n=!1){let r=new we;return n?r.setId(e):r.setLink(e),r.setCaption(t).build()}static createVideoWithCaption(e,t,n=!1){let r=new Te;return n?r.setId(e):r.setLink(e),r.setCaption(t).build()}static createDocument(e,t,n,r=!1){let i=new De;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 Ee;return t?n.setId(e):n.setLink(e),n.build()}static createSticker(e,t=!1){let n=new Oe;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}},Ae=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 je(e){return Object.values(T).includes(e)}function Me(e){return Object.values(m).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(!je(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:g.Header,parameters:e.map(e=>{if(typeof e!=`string`)throw Error(`All parameters must be strings`);return{type:f.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:g.Header,parameters:[{type:f.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:g.Body,parameters:e.map(e=>{if(typeof e!=`string`)throw Error(`All parameters must be strings`);return{type:f.Text,text:e}})};return this.template.components||(this.template.components=[]),this.template.components.push(t),this}addFooter(){let e={type:g.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`||!Me(e.index))throw Error(`Button index must be a valid ButtonPositionEnum value: ${e.index}`);let t=e.type===`quick_reply`?h.QuickReply:h.Url,n={type:g.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:f.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:f.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:f.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:f.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}},Ne=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}},Pe=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 Fe=class extends D{endpoint=`phone_numbers`;constructor(e,t){super(e,t)}async getPhoneNumberById(e){let t=e?H({fields:e}):``;return this.sendJson(u.Get,`${this.config[_.PhoneNumberId]}${t}`,this.config[_.RequestTimeout],null)}async getPhoneNumbers(){return this.sendJson(u.Get,`${this.config[_.BusinessAcctId]}/${this.endpoint}`,this.config[_.RequestTimeout],null)}async requestVerificationCode(e){return this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/request_code`,this.config[_.RequestTimeout],JSON.stringify(e))}async verifyCode(e){return this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/verify_code`,this.config[_.RequestTimeout],JSON.stringify(e))}};function Ie(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 Le=class extends D{endpoint=`whatsapp_business_profile`;constructor(e,t){super(e,t)}async getBusinessProfile(e){return this.sendJson(u.Get,`${this.config[_.PhoneNumberId]}/${this.endpoint}${Ie(e)}`,this.config[_.RequestTimeout],null)}async updateBusinessProfile(e){return this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/${this.endpoint}`,this.config[_.RequestTimeout],JSON.stringify(e))}async createUploadSession(e,t,n){let r=H({file_length:e,file_type:t,file_name:n});return this.sendJson(u.Post,`app/uploads/${r}`,this.config[_.RequestTimeout],null)}async uploadMedia(e,t){return this.sendJson(u.Post,`${e}`,this.config[_.RequestTimeout],t)}async getUploadHandle(e){return this.sendJson(u.Get,`${e}`,this.config[_.RequestTimeout],null)}},Re=class extends D{endpoint=`message_qrdls`;constructor(e,t){super(e,t)}async createQrCode(e){return this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/${this.endpoint}`,this.config[_.RequestTimeout],JSON.stringify(e))}async getQrCodes(){return this.sendJson(u.Get,`${this.config[_.PhoneNumberId]}/${this.endpoint}`,this.config[_.RequestTimeout],null)}async getQrCode(e){return this.sendJson(u.Get,`${this.config[_.PhoneNumberId]}/${this.endpoint}/${e}`,this.config[_.RequestTimeout],null)}async updateQrCode(e){return this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/${this.endpoint}`,this.config[_.RequestTimeout],JSON.stringify(e))}async deleteQrCode(e){return this.sendJson(u.Delete,`${this.config[_.PhoneNumberId]}/${this.endpoint}/${e}`,this.config[_.RequestTimeout],null)}},ze=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(u.Post,`${this.config[_.PhoneNumberId]}/register`,this.config[_.RequestTimeout],JSON.stringify(n))}async deregister(){return this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/deregister`,this.config[_.RequestTimeout],null)}},Be=class extends D{endpoint=`message_templates`;constructor(e,t){super(e,t)}async getTemplate(e){return this.sendJson(u.Get,`${e}`,this.config[_.RequestTimeout],null)}async updateTemplate(e,t){return this.sendJson(u.Post,`${e}`,this.config[_.RequestTimeout],JSON.stringify(t))}async getTemplates(e){return this.sendJson(u.Get,`${this.config[_.BusinessAcctId]}/${this.endpoint}${H(e??{})}`,this.config[_.RequestTimeout],null)}async createTemplate(e){return this.sendJson(u.Post,`${this.config[_.BusinessAcctId]}/${this.endpoint}`,this.config[_.RequestTimeout],JSON.stringify(e))}async deleteTemplate(e){return this.sendJson(u.Delete,`${this.config[_.BusinessAcctId]}/${this.endpoint}${H(e)}`,this.config[_.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 Ve(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 He(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:[Ve(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 Ue(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:c.Authentication,components:t}}function We(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:c.Authentication,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:`CATALOG`,action:{thumbnail_product_retailer_id:e.thumbnail_product_retailer_id}}]}),{name:e.name,language:e.language,category:c.Marketing,components:t}}function Ke(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:c.Marketing,components:t}}function qe(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:c.Marketing,components:t}}function Je(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:c.Marketing,components:t}}function Ye(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:c.Marketing,components:t}}function Xe(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:c.Marketing,components:t}}function Ze(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:c.Marketing,components:t}}var Qe=class extends D{constructor(e,t){super(e,t)}async setTwoStepVerificationCode(e){let t={pin:e};return this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}`,this.config[_.RequestTimeout],JSON.stringify(t))}},$e=class extends D{constructor(e,t){super(e,t)}async getWabaAccount(e){let t=Ie(e)?.replace(/,/g,`%2C`);return this.sendJson(u.Get,`${this.config[_.BusinessAcctId]}${t}`,this.config[_.RequestTimeout],null)}async getAllWabaSubscriptions(){return this.sendJson(u.Get,`${this.config[_.BusinessAcctId]}/subscribed_apps`,this.config[_.RequestTimeout],null)}async updateWabaSubscription({override_callback_uri:e,verify_token:t}){let n={override_callback_uri:e,verify_token:t};return this.sendJson(u.Post,`${this.config[_.BusinessAcctId]}/subscribed_apps`,this.config[_.RequestTimeout],JSON.stringify(n))}async unsubscribeFromWaba(){return this.sendJson(u.Delete,`${this.config[_.BusinessAcctId]}/subscribed_apps`,this.config[_.RequestTimeout],null)}};function et(){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{inspect as t}from"util";import{Agent as n}from"https";import{readFileSync as r}from"fs";import{join as i}from"path";import*as a from"crypto";import o from"crypto";var s=e({AudioMediaTypesEnum:()=>x,BusinessVerticalEnum:()=>se,ButtonPositionEnum:()=>m,CategoryEnum:()=>c,ComponentTypesEnum:()=>g,ConversationTypesEnum:()=>ee,CurrencyCodesEnum:()=>ae,DataLocalizationRegionEnum:()=>oe,DocumentMediaTypesEnum:()=>b,HttpMethodsEnum:()=>u,ImageMediaTypesEnum:()=>y,InteractiveTypesEnum:()=>p,LanguagesEnum:()=>w,MessageTypesEnum:()=>d,ParametersTypesEnum:()=>f,ReferralSourceTypesEnum:()=>re,RequestCodeMethodsEnum:()=>ie,StatusEnum:()=>te,StickerMediaTypesEnum:()=>v,SubTypeEnum:()=>h,SystemChangeTypesEnum:()=>C,TemplateStatusEnum:()=>l,VideoMediaTypesEnum:()=>ne,WabaConfigEnum:()=>_,WebhookTypesEnum:()=>S});let c=function(e){return e.Authentication=`AUTHENTICATION`,e.Marketing=`MARKETING`,e.Utility=`UTILITY`,e}({}),l=function(e){return e.Approved=`APPROVED`,e.Pending=`PENDING`,e.Rejected=`REJECTED`,e}({}),u=function(e){return e.Get=`GET`,e.Post=`POST`,e.Put=`PUT`,e.Delete=`DELETE`,e}({}),d=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}({}),f=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}({}),p=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}({}),m=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}({}),h=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}({}),g=function(e){return e.Header=`HEADER`,e.Body=`BODY`,e.Button=`BUTTON`,e.Footer=`FOOTER`,e}({}),_=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}({}),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}({}),re=function(e){return e.Ad=`ad`,e.Post=`post`,e}({}),ie=function(e){return e.Sms=`SMS`,e.Voice=`VOICE`,e}({}),w=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=`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ERY`,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 T=class{name;debug;constructor(e,t=!1){this.name=e,this.debug=t}formatData(e){return e.map(e=>typeof e==`object`?t(e,{depth:null,colors:!0}):e).join(` `)}log(...e){if(this.debug){let t=`[ ${Date.now()} ]`;this.name&&(t+=` - ${this.name}`),console.log(t,`: `,this.formatData(e))}}error(...e){let t=`[ ${Date.now()} ] - ERROR`;this.name&&(t+=` - ${this.name}`),console.error(t,`: `,this.formatData(e))}warn(...e){if(this.debug){let t=`[ ${Date.now()} ] - WARN`;this.name&&(t+=` - ${this.name}`),console.warn(t,`: `,this.formatData(e))}}info(...e){if(this.debug){let t=`[ ${Date.now()} ] - INFO`;this.name&&(t+=` - ${this.name}`),console.info(t,`: `,this.formatData(e))}}};const ce=new T(`UTILS`,process.env.DEBUG===`true`||!1),le=e=>{if(!process.env[_.AccessToken]&&!e?.accessToken)throw ce.log(`Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined.`),Error(`Missing WhatsApp access token.`)},ue=e=>(le(e),{[_.AppId]:e?.appId||process.env.M4D_APP_ID||``,[_.AppSecret]:e?.appSecret||process.env.M4D_APP_SECRET||``,[_.PhoneNumberId]:e?.phoneNumberId||Number(process.env.WA_PHONE_NUMBER_ID),[_.BusinessAcctId]:e?.businessAcctId||process.env.WA_BUSINESS_ACCOUNT_ID||``,[_.APIVersion]:e?.apiVersion||process.env.CLOUD_API_VERSION||``,[_.AccessToken]:e?.accessToken||process.env.CLOUD_API_ACCESS_TOKEN||``,[_.WebhookEndpoint]:e?.webhookEndpoint||process.env.WEBHOOK_ENDPOINT||``,[_.WebhookVerificationToken]:e?.webhookVerificationToken||process.env.WEBHOOK_VERIFICATION_TOKEN||``,[_.ListenerPort]:e?.listenerPort||parseInt(process.env.LISTENER_PORT||``)||3e3,[_.MaxRetriesAfterWait]:e?.maxRetriesAfterWait||parseInt(process.env.MAX_RETRIES_AFTER_WAIT||``)||30,[_.RequestTimeout]:e?.requestTimeout||parseInt(process.env.REQUEST_TIMEOUT||``)||2e4,[_.Debug]:e?.debug||process.env.DEBUG===`true`,[_.PrivatePem]:e?.privatePem||process.env.FLOW_API_PRIVATE_PEM||``,[_.Passphrase]:e?.passphrase||process.env.FLOW_API_PASSPHRASE||``});function de(e){let t=[[`App ID`,e[_.AppId]||`Not Set`],[`Phone Number ID`,e[_.PhoneNumberId]?.toString()||`Not Set`],[`Business Account ID`,e[_.BusinessAcctId]||`Not Set`],[`API Version`,e[_.APIVersion]||`Not Set`],[`Access Token`,e[_.AccessToken]?`${e[_.AccessToken].substring(0,20)}...`:`Not Set`],[`Webhook Endpoint`,e[_.WebhookEndpoint]||`Not Set`],[`Webhook Verification Token`,e[_.WebhookVerificationToken]?`${e[_.WebhookVerificationToken].substring(0,10)}...`:`Not Set`],[`Listener Port`,e[_.ListenerPort]?.toString()||`Not Set`],[`Debug Mode`,e[_.Debug]?`Enabled`:`Disabled`],[`Max Retries`,e[_.MaxRetriesAfterWait]?.toString()||`Not Set`],[`Request Timeout`,e[_.RequestTimeout]?`${e[_.RequestTimeout]}ms`:`Not Set`],[`Private PEM`,e[_.PrivatePem]?`Configured`:`Not Set`],[`Passphrase`,e[_.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 fe(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 pe=new T(`HttpsClient`,process.env.DEBUG===`true`);var me=class{agent;constructor(){this.agent=new n({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 pe.log(`${n} : ${o} - ${JSON.stringify(e)}`),clearTimeout(c),new he(e)}catch(e){throw pe.error(`${n} : ${o} - ${JSON.stringify(e)}`),e}}},he=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 ge=new T(`REQUESTER`,process.env.DEBUG===`true`);var _e=class{client;accessToken;phoneNumberId;businessAcctId;apiVersion;userAgent;host;protocol=`https:`;constructor(e,t,n,r,i){this.client=new me,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)}`;ge.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 fe(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 fe(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 ve(){try{let e=i(__dirname,`../../package.json`);return JSON.parse(r(e,`utf-8`)).version}catch{return`unknown`}}function ye(){let e=ve(),t=process.version;return`WhatsApp-Nodejs-SDK/${e} (Node.js ${t})`}var E=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)}},D=class extends E{endpoint=`whatsapp_business_encryption`;constructor(e,t){super(e,t)}async getEncryptionPublicKey(){return this.sendJson(u.Get,`${this.config[_.PhoneNumberId]}/${this.endpoint}`,this.config[_.RequestTimeout],null)}async setEncryptionPublicKey(e){let t=new FormData;return t.append(`business_public_key`,e),this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/${this.endpoint}`,this.config[_.RequestTimeout],t)}},O=class extends E{constructor(e,t){super(e,t)}async listFlows(e){return this.sendJson(u.Get,`/${e}/flows`,this.config[_.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(u.Post,`/${e}/flows`,this.config[_.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(u.Get,`/${e}${i}`,this.config[_.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(u.Post,`/${e}`,this.config[_.RequestTimeout],JSON.stringify(n))}async deleteFlow(e){return this.sendJson(u.Delete,`/${e}`,this.config[_.RequestTimeout],null)}async listAssets(e){return this.sendJson(u.Get,`/${e}/assets`,this.config[_.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(u.Post,`/${e}/assets`,this.config[_.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(u.Post,`/${e}/publish`,this.config[_.RequestTimeout],JSON.stringify({}))}async deprecateFlow(e){return this.sendJson(u.Post,`/${e}/deprecate`,this.config[_.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(u.Post,`/${e}/migrate_flows`,this.config[_.RequestTimeout],JSON.stringify(n))}};let be=function(e){return e.Draft=`DRAFT`,e.Published=`PUBLISHED`,e.Throttled=`THROTTLED`,e.Blocked=`BLOCKED`,e.Deprecated=`DEPRECATED`,e}({}),xe=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}({}),k=function(e){return e.INIT=`INIT`,e.BACK=`BACK`,e.DATA_EXCHANGE=`data_exchange`,e}({}),A=function(e){return e.Ping=`ping`,e.Change=`data_exchange`,e.Error=`error`,e.All=`*`,e}({});var j=class extends E{endpoint=`media`;constructor(e,t){super(e,t)}async getMediaById(e,t){return this.sendJson(u.Get,`${e}`,this.config[_.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(u.Post,`${this.config[_.PhoneNumberId]}/${this.endpoint}`,this.config[_.RequestTimeout],n)}async deleteMedia(e,t){return this.sendJson(u.Delete,`${e}`,this.config[_.RequestTimeout],null)}async downloadMedia(e){return this.sendJson(u.Get,e,this.config[_.RequestTimeout],null)}},M=class extends E{commonMethod=u.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[_.PhoneNumberId]}/${this.commonEndpoint}`,this.config[_.RequestTimeout],e)}async audio(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.Audio,t,n,r)))}async contacts(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.Contacts,t,n,r)))}async document(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.Document,t,n,r)))}async image(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.Image,t,n,r)))}async interactive(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.Interactive,t,n,r)))}async location(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.Location,t,n,r)))}async sticker(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.Sticker,t,n,r)))}async template(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.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(d.Text,a,n,r)))}async video(e){let{body:t,to:n,replyMessageId:r}=e;return this.send(JSON.stringify(this.bodyBuilder(d.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(d.Reaction,t,e.to)))}},N=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}},Se=class{static createSimpleContact(e,t){return new N().setSimpleName(e).addPhone(t).build()}static createBusinessContact(e,t,n,r,i,a){return new N().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 N().setSimpleName(e,t).addPhone(n,`MOBILE`);return r&&a.addEmail(r,`HOME`),i&&a.setBirthday(i.year,i.month,i.day),a.build()}};function P(e){return!(`name`in e)}var F=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 P(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 P(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 P(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}},Ce=class{static createButtonMessage(e,t,n){let r=new F().setType(p.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 F().setType(p.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 P(o)&&(o.button=t),a}static createCTAUrlMessage(e,t,n,r){let i=new F().setType(p.CtaUrl).setBody(e).setCTAUrl(t,n);return r?.headerText&&i.setTextHeader(r.headerText),r?.footerText&&i.setFooter(r.footerText),i.build()}},I=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}},we=class{static createSimpleLocation(e,t){return new I().setCoordinates(e,t).build()}static createNamedLocation(e,t,n,r){return new I().setCoordinates(e,t).setName(n).setAddress(r).build()}static createBusinessLocation(e,t,n,r){return new I().setCoordinates(e,t).setName(n).setAddress(r).build()}},L=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}},Te=class extends L{},R=class extends L{},Ee=class extends L{setCaption(e){throw Error(`Audio messages do not support captions`)}},De=class extends L{setFilename(e){if(!e||typeof e!=`string`)throw Error(`Filename must be a non-empty string`);return this.media.filename=e,this}},Oe=class extends L{setCaption(e){throw Error(`Sticker messages do not support captions`)}},ke=class{static createImageWithCaption(e,t,n=!1){let r=new Te;return n?r.setId(e):r.setLink(e),r.setCaption(t).build()}static createVideoWithCaption(e,t,n=!1){let r=new R;return n?r.setId(e):r.setLink(e),r.setCaption(t).build()}static createDocument(e,t,n,r=!1){let i=new De;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 Ee;return t?n.setId(e):n.setLink(e),n.build()}static createSticker(e,t=!1){let n=new Oe;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}},Ae=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 je(e){return Object.values(w).includes(e)}function Me(e){return Object.values(m).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(!je(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:g.Header,parameters:e.map(e=>{if(typeof e!=`string`)throw Error(`All parameters must be strings`);return{type:f.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:g.Header,parameters:[{type:f.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:g.Body,parameters:e.map(e=>{if(typeof e!=`string`)throw Error(`All parameters must be strings`);return{type:f.Text,text:e}})};return this.template.components||(this.template.components=[]),this.template.components.push(t),this}addFooter(){let e={type:g.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`||!Me(e.index))throw Error(`Button index must be a valid ButtonPositionEnum value: ${e.index}`);let t=e.type===`quick_reply`?h.QuickReply:h.Url,n={type:g.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:f.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:f.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:f.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:f.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}},Ne=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}},Pe=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 Fe=class extends E{endpoint=`phone_numbers`;constructor(e,t){super(e,t)}async getPhoneNumberById(e){let t=e?H({fields:e}):``;return this.sendJson(u.Get,`${this.config[_.PhoneNumberId]}${t}`,this.config[_.RequestTimeout],null)}async getPhoneNumbers(){return this.sendJson(u.Get,`${this.config[_.BusinessAcctId]}/${this.endpoint}`,this.config[_.RequestTimeout],null)}async requestVerificationCode(e){return this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/request_code`,this.config[_.RequestTimeout],JSON.stringify(e))}async verifyCode(e){return this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/verify_code`,this.config[_.RequestTimeout],JSON.stringify(e))}};function Ie(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 Le=class extends E{endpoint=`whatsapp_business_profile`;constructor(e,t){super(e,t)}async getBusinessProfile(e){return this.sendJson(u.Get,`${this.config[_.PhoneNumberId]}/${this.endpoint}${Ie(e)}`,this.config[_.RequestTimeout],null)}async updateBusinessProfile(e){return this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/${this.endpoint}`,this.config[_.RequestTimeout],JSON.stringify(e))}async createUploadSession(e,t,n){let r=H({file_length:e,file_type:t,file_name:n});return this.sendJson(u.Post,`app/uploads/${r}`,this.config[_.RequestTimeout],null)}async uploadMedia(e,t){return this.sendJson(u.Post,`${e}`,this.config[_.RequestTimeout],t)}async getUploadHandle(e){return this.sendJson(u.Get,`${e}`,this.config[_.RequestTimeout],null)}},Re=class extends E{endpoint=`message_qrdls`;constructor(e,t){super(e,t)}async createQrCode(e){return this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/${this.endpoint}`,this.config[_.RequestTimeout],JSON.stringify(e))}async getQrCodes(){return this.sendJson(u.Get,`${this.config[_.PhoneNumberId]}/${this.endpoint}`,this.config[_.RequestTimeout],null)}async getQrCode(e){return this.sendJson(u.Get,`${this.config[_.PhoneNumberId]}/${this.endpoint}/${e}`,this.config[_.RequestTimeout],null)}async updateQrCode(e){return this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/${this.endpoint}`,this.config[_.RequestTimeout],JSON.stringify(e))}async deleteQrCode(e){return this.sendJson(u.Delete,`${this.config[_.PhoneNumberId]}/${this.endpoint}/${e}`,this.config[_.RequestTimeout],null)}},ze=class extends E{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(u.Post,`${this.config[_.PhoneNumberId]}/register`,this.config[_.RequestTimeout],JSON.stringify(n))}async deregister(){return this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}/deregister`,this.config[_.RequestTimeout],null)}},Be=class extends E{endpoint=`message_templates`;constructor(e,t){super(e,t)}async getTemplate(e){return this.sendJson(u.Get,`${e}`,this.config[_.RequestTimeout],null)}async updateTemplate(e,t){return this.sendJson(u.Post,`${e}`,this.config[_.RequestTimeout],JSON.stringify(t))}async getTemplates(e){return this.sendJson(u.Get,`${this.config[_.BusinessAcctId]}/${this.endpoint}${H(e??{})}`,this.config[_.RequestTimeout],null)}async createTemplate(e){return this.sendJson(u.Post,`${this.config[_.BusinessAcctId]}/${this.endpoint}`,this.config[_.RequestTimeout],JSON.stringify(e))}async deleteTemplate(e){return this.sendJson(u.Delete,`${this.config[_.BusinessAcctId]}/${this.endpoint}${H(e)}`,this.config[_.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 Ve(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 He(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:[Ve(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 Ue(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:c.Authentication,components:t}}function We(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:c.Authentication,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:`CATALOG`,action:{thumbnail_product_retailer_id:e.thumbnail_product_retailer_id}}]}),{name:e.name,language:e.language,category:c.Marketing,components:t}}function Ke(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:c.Marketing,components:t}}function qe(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:c.Marketing,components:t}}function Je(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:c.Marketing,components:t}}function Ye(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:c.Marketing,components:t}}function Xe(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:c.Marketing,components:t}}function Ze(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:c.Marketing,components:t}}var Qe=class extends E{constructor(e,t){super(e,t)}async setTwoStepVerificationCode(e){let t={pin:e};return this.sendJson(u.Post,`${this.config[_.PhoneNumberId]}`,this.config[_.RequestTimeout],JSON.stringify(t))}},$e=class extends E{constructor(e,t){super(e,t)}async getWabaAccount(e){let t=Ie(e)?.replace(/,/g,`%2C`);return this.sendJson(u.Get,`${this.config[_.BusinessAcctId]}${t}`,this.config[_.RequestTimeout],null)}async getAllWabaSubscriptions(){return this.sendJson(u.Get,`${this.config[_.BusinessAcctId]}/subscribed_apps`,this.config[_.RequestTimeout],null)}async updateWabaSubscription({override_callback_uri:e,verify_token:t}){let n={override_callback_uri:e,verify_token:t};return this.sendJson(u.Post,`${this.config[_.BusinessAcctId]}/subscribed_apps`,this.config[_.RequestTimeout],JSON.stringify(n))}async unsubscribeFromWaba(){return this.sendJson(u.Delete,`${this.config[_.BusinessAcctId]}/subscribed_apps`,this.config[_.RequestTimeout],null)}};function et(){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 q=new E(`WHATSAPP`,process.env.DEBUG===`true`);var tt=class{config;requester;messages;media;phoneNumbers;twoStepVerification;flows;businessProfile;templates;encryption;qrCode;registration;waba;constructor(e){et(),this.config=le(e),this.requester=new ge(this.config[_.APIVersion],this.config[_.PhoneNumberId],this.config[_.AccessToken],this.config[_.BusinessAcctId],this.getUserAgent()),this.messages=new N(this.config,this.requester),this.media=new M(this.config,this.requester),this.phoneNumbers=new Fe(this.config,this.requester),this.twoStepVerification=new Qe(this.config,this.requester),this.flows=new k(this.config,this.requester),this.businessProfile=new Le(this.config,this.requester),this.templates=new Be(this.config,this.requester),this.encryption=new O(this.config,this.requester),this.qrCode=new Re(this.config,this.requester),this.registration=new ze(this.config,this.requester),this.waba=new $e(this.config,this.requester),q.log(`
10
- `+ue(this.config))}updateTimeout(e){this.config[_.RequestTimeout]=e,`updateTimeout`in this.requester&&this.requester.updateTimeout(e),q.log(`Timeout updated to ${e}ms`)}updateSenderNumberId(e){this.config[_.PhoneNumberId]=e,q.log(`Sender number ID updated to ${e}`)}updateAccessToken(e){this.config[_.AccessToken]=e,`updateAccessToken`in this.requester&&this.requester.updateAccessToken(e),q.log(`Access token updated`)}version(){return _e()}static get Enums(){return s}getUserAgent(){return ve()}};function nt(e){return typeof e==`object`&&!!e}function J(e){return typeof e==`string`}const rt=[A.DATA_EXCHANGE,A.INIT,A.BACK],it=[A.DATA_EXCHANGE,A.INIT];function at(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=rt.includes(t),s=r===void 0||J(r)&&r!==`SUCCESS`,c=t===A.DATA_EXCHANGE||nt(i);return a&&o&&s&&c}function ot(e){if(!(`flow_token`in e&&J(e.flow_token)&&`action`in e))return!1;let{action:t,screen:n,data:r}=e,i=it.includes(t),a=J(n),o=nt(r)&&`error_key`in r&&J(r.error)&&`error_message`in r&&J(r.error_message);return i&&a&&o}function st(e){return`action`in e&&e.action===`ping`}const Y=new E(`WEBHOOK_UTILS`,process.env.DEBUG===`true`);async function X(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 dt(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 ct(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}),!lt(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}=ft(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(st(s))return Y.info(`Handling flow ping request`),new Response(JSON.stringify({version:`3.0`,data:{status:`active`}}),{status:200});if(ot(s))return Y.warn(`Flow error request received:`,s),new Response(null,{status:200});if(at(s)){Y.info(`Processing flow data exchange request`);let e=await c(n,s);Y.info(`Flow handler result:`,e);let t=pt(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 lt(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=o.createHmac(`sha256`,n).update(e).digest(`hex`);return Y.info(`Signature verification:`,{received:t.replace(`sha256=`,``),expected:r}),o.timingSafeEqual(Buffer.from(t.replace(`sha256=`,``)),Buffer.from(r))}function ut(e,t){let n=e[`x-forwarded-proto`]||`http`,r=e.host||`localhost`;return`${n}://${r}${t||`/`}`}async function dt(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:d.Statuses,phoneNumberId:c,displayPhoneNumber:s,profileName:l,statuses:t.statuses[0],originalData:i};Y.info(`Processing status:`,e),await Z(r.messageHandlers.get(d.Statuses),n,e,d.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 d.Text:i.text=t.text;break;case d.Image:i.image=t.image;break;case d.Video:i.video=t.video;break;case d.Audio:i.audio=t.audio;break;case d.Document:i.document=t.document;break;case d.Sticker:i.sticker=t.sticker;break;case d.Location:i.location=t.location;break;case d.Contacts:i.contacts=t.contacts;break;case d.Interactive:i.interactive=t.interactive;break;case d.Button:i.button=t.button;break;case d.Order:i.order=t.order;break;case d.System:i.system=t.system;break;case d.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 ft(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 a=t.FLOW_API_PRIVATE_PEM.replace(/\\n/g,`
11
- `),s=t.FLOW_API_PASSPHRASE,c=o.createPrivateKey({key:a,passphrase:s}),l;try{Y.info(`Decrypting AES key`),l=o.privateDecrypt({key:c,padding:o.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=o.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 pt(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=o.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=le(e),this.client=new tt(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 X(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 ct(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}},mt=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 ut(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}},ht=class extends mt{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 gt(e){return new ht(e).getHandlers()}var _t=class extends mt{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 vt(e){return new _t(e).getHandlers()}function yt(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 bt=(e,t)=>a.createHmac(`sha256`,t).update(e,`utf-8`).digest(`hex`);let xt=function(e){return e.Approved=`APPROVED`,e.Active=`ACTIVE`,e.Inactive=`INACTIVE`,e.Disabled=`DISABLED`,e}({}),St=function(e){return e.Blocked=`BLOCKED`,e.Limited=`LIMITED`,e.Available=`AVAILABLE`,e}({}),Ct=function(e){return e.Approved=`APPROVED`,e.Active=`ACTIVE`,e.Inactive=`INACTIVE`,e.Disabled=`DISABLED`,e}({}),wt=function(e){return e.Verified=`verified`,e.PendingSubmission=`pending_submission`,e.Unverified=`unverified`,e.Rejected=`rejected`,e}({});export{S as AudioMediaTypesEnum,Ee as AudioMessageBuilder,Le as BusinessProfileApi,oe as BusinessVerticalEnum,m as ButtonPositionEnum,c as CategoryEnum,g as ComponentTypesEnum,P as ContactMessageBuilder,xe as ContactMessageFactory,ee as ConversationTypesEnum,ie as CurrencyCodesEnum,ae as DataLocalizationRegionEnum,x as DocumentMediaTypesEnum,De as DocumentMessageBuilder,O as EncryptionApi,A as FlowActionEnum,k as FlowApi,be as FlowCategoryEnum,ye as FlowStatusEnum,j as FlowTypeEnum,u as HttpMethodsEnum,b as ImageMediaTypesEnum,we as ImageMessageBuilder,I as InteractiveMessageBuilder,Se as InteractiveMessageFactory,p as InteractiveTypesEnum,T as LanguagesEnum,L as LocationMessageBuilder,Ce as LocationMessageFactory,M as MediaApi,ke as MediaMessageFactory,N as MessageApi,N as MessagesApi,d as MessageTypesEnum,f as ParametersTypesEnum,Fe as PhoneNumberApi,Re as QrCodeApi,z as ReactionMessageBuilder,Ae as ReactionMessageFactory,ne as ReferralSourceTypesEnum,ze as RegistrationApi,re as RequestCodeMethodsEnum,te as StatusEnum,y as StickerMediaTypesEnum,Oe as StickerMessageBuilder,h as SubTypeEnum,w as SystemChangeTypesEnum,Be as TemplateApi,B as TemplateMessageBuilder,Ne as TemplateMessageFactory,l as TemplateStatusEnum,V as TextMessageBuilder,Pe as TextMessageFactory,Qe as TwoStepVerificationApi,v as VideoMediaTypesEnum,Te as VideoMessageBuilder,xt as WabaAccountReviewStatus,Ct as WabaAccountStatus,$e as WabaApi,wt as WabaBusinessVerificationStatus,_ as WabaConfigEnum,St as WabaHealthStatusCanSendMessage,$ as WebhookProcessor,C as WebhookTypesEnum,tt as WhatsApp,ut as constructFullUrl,We as createAuthenticationTemplate,Ge as createCatalogTemplate,Ke as createCouponTemplate,qe as createLimitedTimeOfferTemplate,Ye as createMPMTemplate,Je as createMediaCardCarouselTemplate,Ue as createOTPTemplate,Xe as createProductCardCarouselTemplate,Ze as createSPMTemplate,He as createTemplate,gt as expressWebhookHandler,bt as generateXHub256Sig,yt as nextjsAppWebhookHandler,vt as nextjsWebhookHandler,ct as processFlowRequest,X as processWebhookMessages};
9
+ `)}const q=new T(`WHATSAPP`,process.env.DEBUG===`true`);var tt=class{config;requester;messages;media;phoneNumbers;twoStepVerification;flows;businessProfile;templates;encryption;qrCode;registration;waba;constructor(e){et(),this.config=ue(e),this.requester=new _e(this.config[_.APIVersion],this.config[_.PhoneNumberId],this.config[_.AccessToken],this.config[_.BusinessAcctId],this.getUserAgent()),this.messages=new M(this.config,this.requester),this.media=new j(this.config,this.requester),this.phoneNumbers=new Fe(this.config,this.requester),this.twoStepVerification=new Qe(this.config,this.requester),this.flows=new O(this.config,this.requester),this.businessProfile=new Le(this.config,this.requester),this.templates=new Be(this.config,this.requester),this.encryption=new D(this.config,this.requester),this.qrCode=new Re(this.config,this.requester),this.registration=new ze(this.config,this.requester),this.waba=new $e(this.config,this.requester),q.log(`
10
+ `+de(this.config))}updateTimeout(e){this.config[_.RequestTimeout]=e,`updateTimeout`in this.requester&&this.requester.updateTimeout(e),q.log(`Timeout updated to ${e}ms`)}updateSenderNumberId(e){this.config[_.PhoneNumberId]=e,q.log(`Sender number ID updated to ${e}`)}updateAccessToken(e){this.config[_.AccessToken]=e,`updateAccessToken`in this.requester&&this.requester.updateAccessToken(e),q.log(`Access token updated`)}version(){return ve()}static get Enums(){return s}getUserAgent(){return ye()}};function nt(e){return typeof e==`object`&&!!e}function J(e){return typeof e==`string`}const rt=[k.DATA_EXCHANGE,k.INIT,k.BACK],it=[k.DATA_EXCHANGE,k.INIT];function at(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=rt.includes(t),s=r===void 0||J(r)&&r!==`SUCCESS`,c=t===k.DATA_EXCHANGE||nt(i);return a&&o&&s&&c}function ot(e){if(!(`flow_token`in e&&J(e.flow_token)&&`action`in e))return!1;let{action:t,screen:n,data:r}=e,i=it.includes(t),a=J(n),o=nt(r)&&`error_key`in r&&J(r.error)&&`error_message`in r&&J(r.error_message);return i&&a&&o}function st(e){return`action`in e&&e.action===`ping`}const Y=new T(`WEBHOOK_UTILS`,process.env.DEBUG===`true`);async function ct(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 pt(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})}}function lt(){return{version:`3.0`,data:{status:`active`}}}function X(){return{data:{acknowledged:!0}}}async function ut(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}),!dt(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,aesKeyBuffer:c,initialVectorBuffer:l}=mt(o,t);Y.info(`Decrypted flow request:`,s);let u=st(s),d=ot(s),f=at(s),p=u?A.Ping:d?A.Error:f?A.Change:A.All,m=r.get(p);if(!m){if(p===A.Ping)Y.info(`No Ping handler registered, using default`),m=()=>lt();else if(p===A.Error)Y.info(`No Error handler registered, using default`),m=()=>X();else if(m=r.get(A.All),!m)return Y.warn(`No handler registered for flow type:`,{flowType:p,action:s.action}),new Response(JSON.stringify({error:`Handler not found`}),{status:404})}let h=await m(n,s);if(Y.info(`Flow handler result:`,h),d){Y.warn(`Flow error notification received`,{error:s.data});let e=h||X();return new Response(JSON.stringify(e),{status:200,headers:{"Content-Type":`application/json`}})}if(u||f){let e=u?`PING`:`DATA_EXCHANGE`;Y.info(`Processing flow ${e.toLowerCase()} response`);let t=ht(h,c,l);return Y.info(`Encrypted flow response generated`),new Response(t,{status:200,headers:{"Content-Type":`text/plain`}})}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 dt(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=o.createHmac(`sha256`,n).update(e).digest(`hex`);return Y.info(`Signature verification:`,{received:t.replace(`sha256=`,``),expected:r}),o.timingSafeEqual(Buffer.from(t.replace(`sha256=`,``)),Buffer.from(r))}function ft(e,t){let n=e[`x-forwarded-proto`]||`http`,r=e.host||`localhost`;return`${n}://${r}${t||`/`}`}async function pt(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:d.Statuses,phoneNumberId:c,displayPhoneNumber:s,profileName:l,statuses:t.statuses[0],originalData:i};Y.info(`Processing status:`,e),await Z(r.messageHandlers.get(d.Statuses),n,e,d.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 d.Text:i.text=t.text;break;case d.Image:i.image=t.image;break;case d.Video:i.video=t.video;break;case d.Audio:i.audio=t.audio;break;case d.Document:i.document=t.document;break;case d.Sticker:i.sticker=t.sticker;break;case d.Location:i.location=t.location;break;case d.Contacts:i.contacts=t.contacts;break;case d.Interactive:i.interactive=t.interactive;break;case d.Button:i.button=t.button;break;case d.Order:i.order=t.order;break;case d.System:i.system=t.system;break;case d.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 mt(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 a=t.FLOW_API_PRIVATE_PEM;a.includes(`\\n`)&&(a=a.replace(/\\n/g,`
11
+ `));let s=t.FLOW_API_PASSPHRASE,c=a.includes(`-----BEGIN RSA PRIVATE KEY-----`),l=a.includes(`-----BEGIN PRIVATE KEY-----`)||a.includes(`-----BEGIN ENCRYPTED PRIVATE KEY-----`);Y.info(`Private key format check:`,{isPKCS1:c,isPKCS8:l,hasBeginMarker:a.includes(`-----BEGIN`),hasEndMarker:a.includes(`-----END`),length:a.length,firstLine:a.split(`
12
+ `)[0]});let u;try{u=s?o.createPrivateKey({key:a,format:`pem`,passphrase:s}):o.createPrivateKey(a)}catch(e){Y.error(`Failed to create private key:`,{error:e instanceof Error?e.message:e,pemPreview:a.substring(0,100)+`...`,hasPassphrase:!!s,isPKCS1:c,isPKCS8:l});let t=`Failed to parse private key. Error: ${e instanceof Error?e.message:e}`;throw c?(t+=`
13
+
14
+ Your key is in PKCS#1 format (-----BEGIN RSA PRIVATE KEY-----).`,t+=`
15
+ Please convert it to PKCS#8 format using:`,t+=`
16
+ openssl pkcs8 -topk8 -inform PEM -outform PEM -in old_key.pem -out new_key.pem`,t+=`
17
+
18
+ Or ensure your key uses a supported encryption algorithm (not DES-EDE3-CBC).`):l||(t+=`
19
+
20
+ Your key format is not recognized. Please ensure it is in PKCS#8 format.`),Error(t)}let d;try{Y.info(`Decrypting AES key`),d=o.privateDecrypt({key:u,padding:o.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 f=Buffer.from(r,`base64`),p=Buffer.from(i,`base64`),m=f.subarray(0,-16),h=f.subarray(-16);Y.info(`Decrypting flow data`);let g=o.createDecipheriv(`aes-128-gcm`,d,p);g.setAuthTag(h);let _=Buffer.concat([g.update(m),g.final()]).toString(`utf-8`);return Y.info(`Flow request decryption complete`),{decryptedBody:JSON.parse(_),aesKeyBuffer:d,initialVectorBuffer:p}}function ht(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=o.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 T(`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=ue(e),this.client=new tt(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 ct(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 ut(e,this.config,this.client,this.flowHandlers),n=await t.text(),r=t.headers.get(`content-type`)||`text/plain`;return{status:t.status,body:n,headers:{"Content-Type":r}}}catch(e){return 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}},gt=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 ft(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}},_t=class extends gt{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),a}catch(e){throw n(e),e}}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),i}catch(e){throw n(e),e}}async handleFlow(e,t,n){try{let n=this.constructFullUrl(e.headers,e.url),r=e.rawBody||(e.method===`POST`?JSON.stringify(e.body):void 0),i=new globalThis.Request(n,{method:e.method,headers:e.headers,body:r}),a=await this.processFlow(i);return this.applyHeaders(a,t),t.status(a.status).send(a.body),a}catch(e){throw n(e),e}}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 vt(e){return new _t(e).getHandlers()}var yt=class extends gt{constructor(e){super(e)}async parseRequestBody(e,t=!1){if(e.method===`POST`&&!e.body){let n=[];if(typeof e[Symbol.asyncIterator]==`function`){for await(let t of e)n.push(t);let r=Buffer.concat(n).toString();if(t&&(e.rawBody=r),r.trim())try{e.body=JSON.parse(r)}catch{throw Error(`Invalid JSON in request body`)}else e.body={}}}}async handleGet(e,t){try{let{"hub.mode":n,"hub.verify_token":r,"hub.challenge":i}=e.query,a=await this.processVerification(n||null,r||null,i||null);return this.applyHeaders(a,t),t.status(a.status).send(a.body),a}catch(e){throw console.error(`Webhook verification error:`,e),t.status(500).json({error:`Internal Server Error`}),e}}async handlePost(e,t){try{await this.parseRequestBody(e)}catch(e){throw console.error(`Webhook processing error:`,e),e instanceof Error&&e.message===`Invalid JSON in request body`?(t.status(400).json({error:`Invalid JSON`}),e):(t.status(500).json({error:`Internal Server Error`}),e)}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),i}catch(e){throw console.error(`Webhook processing error:`,e),t.status(500).json({error:`Internal Server Error`}),e}}async handleFlow(e,t){try{await this.parseRequestBody(e,!0)}catch(e){throw console.error(`Flow body parsing error:`,e),e instanceof Error&&e.message===`Invalid JSON in request body`?(t.status(400).json({error:`Invalid JSON`}),e):(t.status(500).json({error:`Internal Server Error`}),e)}try{let n=this.constructFullUrl(e.headers,e.url),r=e.rawBody||(e.method===`POST`?JSON.stringify(e.body):void 0),i=new Request(n,{method:e.method,headers:e.headers,body:r}),a=await this.processFlow(i);return this.applyHeaders(a,t),t.status(a.status).send(a.body),a}catch(e){throw console.error(`Flow error:`,e),t.status(500).json({error:`Internal Server Error`}),e}}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 bt(e){return new yt(e).getHandlers()}function xt(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 new Response(n.body,{status:n.status,headers:n.headers})}catch(e){return console.error(`Flow GET error:`,e),new Response(JSON.stringify({error:`Internal Server Error`}),{status:500,headers:{"Content-Type":`application/json`}})}},POST:async e=>{try{let n=await t.processFlow(e);return new Response(n.body,{status:n.status,headers:n.headers})}catch(e){return console.error(`Flow POST error:`,e),new Response(JSON.stringify({error:`Internal Server Error`}),{status:500,headers:{"Content-Type":`application/json`}})}}},processor:t}}const St=(e,t)=>a.createHmac(`sha256`,t).update(e,`utf-8`).digest(`hex`);let Ct=function(e){return e.Approved=`APPROVED`,e.Active=`ACTIVE`,e.Inactive=`INACTIVE`,e.Disabled=`DISABLED`,e}({}),wt=function(e){return e.Blocked=`BLOCKED`,e.Limited=`LIMITED`,e.Available=`AVAILABLE`,e}({}),Tt=function(e){return e.Approved=`APPROVED`,e.Active=`ACTIVE`,e.Inactive=`INACTIVE`,e.Disabled=`DISABLED`,e}({}),Et=function(e){return e.Verified=`verified`,e.PendingSubmission=`pending_submission`,e.Unverified=`unverified`,e.Rejected=`rejected`,e}({});export{x as AudioMediaTypesEnum,Ee as AudioMessageBuilder,Le as BusinessProfileApi,se as BusinessVerticalEnum,m as ButtonPositionEnum,c as CategoryEnum,g as ComponentTypesEnum,N as ContactMessageBuilder,Se as ContactMessageFactory,ee as ConversationTypesEnum,ae as CurrencyCodesEnum,oe as DataLocalizationRegionEnum,b as DocumentMediaTypesEnum,De as DocumentMessageBuilder,D as EncryptionApi,k as FlowActionEnum,O as FlowApi,xe as FlowCategoryEnum,be as FlowStatusEnum,A as FlowTypeEnum,u as HttpMethodsEnum,y as ImageMediaTypesEnum,Te as ImageMessageBuilder,F as InteractiveMessageBuilder,Ce as InteractiveMessageFactory,p as InteractiveTypesEnum,w as LanguagesEnum,I as LocationMessageBuilder,we as LocationMessageFactory,j as MediaApi,ke as MediaMessageFactory,M as MessageApi,M as MessagesApi,d as MessageTypesEnum,f as ParametersTypesEnum,Fe as PhoneNumberApi,Re as QrCodeApi,z as ReactionMessageBuilder,Ae as ReactionMessageFactory,re as ReferralSourceTypesEnum,ze as RegistrationApi,ie as RequestCodeMethodsEnum,te as StatusEnum,v as StickerMediaTypesEnum,Oe as StickerMessageBuilder,h as SubTypeEnum,C as SystemChangeTypesEnum,Be as TemplateApi,B as TemplateMessageBuilder,Ne as TemplateMessageFactory,l as TemplateStatusEnum,V as TextMessageBuilder,Pe as TextMessageFactory,Qe as TwoStepVerificationApi,ne as VideoMediaTypesEnum,R as VideoMessageBuilder,Ct as WabaAccountReviewStatus,Tt as WabaAccountStatus,$e as WabaApi,Et as WabaBusinessVerificationStatus,_ as WabaConfigEnum,wt as WabaHealthStatusCanSendMessage,$ as WebhookProcessor,S as WebhookTypesEnum,tt as WhatsApp,ft as constructFullUrl,We as createAuthenticationTemplate,Ge as createCatalogTemplate,Ke as createCouponTemplate,X as createFlowErrorResponse,lt as createFlowPingResponse,qe as createLimitedTimeOfferTemplate,Ye as createMPMTemplate,Je as createMediaCardCarouselTemplate,Ue as createOTPTemplate,Xe as createProductCardCarouselTemplate,Ze as createSPMTemplate,He as createTemplate,vt as expressWebhookHandler,St as generateXHub256Sig,xt as nextjsAppWebhookHandler,bt as nextjsPagesWebhookHandler,ut as processFlowRequest,ct as processWebhookMessages};
12
21
  //# sourceMappingURL=index.js.map