@warriorteam/messenger-sdk
Version:
TypeScript SDK for Facebook Messenger Platform API with Conversations support
3 lines • 28.4 kB
JavaScript
var re="v23.0",ie="https://graph.facebook.com";var E={MESSAGES:"/me/messages",MESSAGE_ATTACHMENTS:"/me/message_attachments",MODERATE_CONVERSATIONS:"/me/moderate_conversations"},C={TEXT_MESSAGE_MAX_CHARS:2e3},He={IMAGE_MAX_SIZE:8*1024*1024,OTHER_MAX_SIZE:25*1024*1024,VIDEO_TIMEOUT:75,OTHER_TIMEOUT:10},c={GENERIC_ELEMENTS_MAX:10,GENERIC_TITLE_MAX_CHARS:80,GENERIC_SUBTITLE_MAX_CHARS:80,BUTTON_TEXT_MAX_CHARS:640,BUTTONS_MAX_COUNT:3,BUTTON_TITLE_MAX_CHARS:20,POSTBACK_PAYLOAD_MAX_CHARS:1e3,MEDIA_ELEMENTS_COUNT:1,MEDIA_BUTTONS_MAX_COUNT:3};var h=class extends Error{code;type;subcode;fbtrace_id;statusCode;response;constructor(e,s,o){super(e.message),this.name="MessengerAPIError",this.code=e.code,this.type=e.type,this.subcode=e.error_subcode,this.fbtrace_id=e.fbtrace_id,this.statusCode=s,this.response=o;}},y=class extends Error{cause;constructor(e,s){super(e),this.name="MessengerNetworkError",this.cause=s;}},T=class extends Error{timeout;constructor(e){super(`Request timed out after ${e}ms`),this.name="MessengerTimeoutError",this.timeout=e;}},d=class extends Error{constructor(e){super(e),this.name="MessengerConfigError";}};var O=class{config;constructor(e){this.config={accessToken:e.accessToken,version:e.version,baseUrl:e.baseUrl||ie,timeout:e.timeout||3e4,maxRetries:e.maxRetries||3};}async request(e){let s=this.buildUrl(e.path,e.query,e.accessToken),o;for(let a=0;a<=this.config.maxRetries;a++)try{let n=await this.makeRequest(s,e);return await this.handleResponse(n)}catch(n){if(o=n,n instanceof h&&n.statusCode>=400&&n.statusCode<500||a===this.config.maxRetries)throw n;await this.delay(1e3*(a+1));}throw o||new Error("Unknown error occurred")}buildUrl(e,s,o){let a=new URL(`${this.config.baseUrl}/${this.config.version}${e}`),n=o||this.config.accessToken;if(!n)throw new Error("Access token is required. Provide it in constructor or method options.");return a.searchParams.append("access_token",n),s&&Object.entries(s).forEach(([b,p])=>{a.searchParams.append(b,String(p));}),a.toString()}async makeRequest(e,s){let o=new AbortController,a=setTimeout(()=>o.abort(),this.config.timeout);try{let n={method:s.method,headers:{"Content-Type":"application/json"},signal:o.signal};return s.body&&(n.body=JSON.stringify(s.body)),await fetch(e,n)}catch(n){throw n instanceof Error?n.name==="AbortError"?new T(this.config.timeout):new y(`Network request failed: ${n.message}`,n):n}finally{clearTimeout(a);}}async handleResponse(e){let o=e.headers.get("content-type")?.includes("application/json");if(!e.ok)if(o){let a=await e.json();throw new h(a.error,e.status,a)}else {let a=await e.text();throw new h({message:a||`HTTP ${e.status} ${e.statusText}`,type:"http_error",code:e.status,fbtrace_id:""},e.status,a)}return o?await e.json():await e.text()}delay(e){return new Promise(s=>setTimeout(s,e))}};var M=class extends Error{constructor(e){super(e),this.name="MessageValidationError";}};function ce(t){if(!t||t.trim()==="")throw new M("Text message cannot be empty");if(t.length>C.TEXT_MESSAGE_MAX_CHARS)throw new M(`Text message cannot exceed ${C.TEXT_MESSAGE_MAX_CHARS} characters`)}var k=class{constructor(e){this.httpClient=e;}async message(e,s){return e.message?.text&&ce(e.message.text),this.httpClient.request({method:"POST",path:E.MESSAGES,body:e,accessToken:s?.accessToken})}async action(e,s,o){let a={recipient:{id:e},messaging_type:"RESPONSE",sender_action:s};return o?.payload&&(a.payload=o.payload),this.httpClient.request({method:"POST",path:E.MESSAGES,body:a,accessToken:o?.accessToken})}async typingOn(e,s){return this.action(e,"typing_on",s)}async typingOff(e,s){return this.action(e,"typing_off",s)}async markSeen(e,s){return this.action(e,"mark_seen",s)}async setTyping(e,s,o){return s?this.typingOn(e,o):this.typingOff(e,o)}async markRead(e,s){return this.markSeen(e,s)}async addReaction(e,s,o){return this.action(e,"react",{...o,payload:{message_id:s.messageId,reaction:s.emoji}})}async removeReaction(e,s,o){return this.action(e,"unreact",{...o,payload:{message_id:s}})}async attachment(e,s){return this.message({recipient:e.recipient,messaging_type:e.messaging_type??"RESPONSE",message:{attachment:{type:e.type,payload:{attachment_id:e.attachment_id}}}},s)}async attachmentFromUrl(e,s){return this.message({recipient:e.recipient,messaging_type:e.messaging_type??"RESPONSE",message:{attachment:{type:e.type,payload:{url:e.url}}}},s)}};var P=class{constructor(e){this.httpClient=e;}async upload(e,s){let o={message:{attachment:{type:e.type,payload:{url:e.url,is_reusable:e.is_reusable??true}}}};return this.httpClient.request({method:"POST",path:E.MESSAGE_ATTACHMENTS,body:o,accessToken:s?.accessToken})}};var S=class{constructor(e){this.httpClient=e;}async moderate(e,s){return this.httpClient.request({method:"POST",path:E.MODERATE_CONVERSATIONS,body:e,accessToken:s?.accessToken})}async blockUser(e,s){let o=Array.isArray(e)?e.map(a=>({id:a})):[{id:e}];return this.moderate({user_ids:o,actions:["block_user"]},s)}async unblockUser(e,s){let o=Array.isArray(e)?e.map(a=>({id:a})):[{id:e}];return this.moderate({user_ids:o,actions:["unblock_user"]},s)}async banUser(e,s){let o=Array.isArray(e)?e.map(a=>({id:a})):[{id:e}];return this.moderate({user_ids:o,actions:["ban_user"]},s)}async unbanUser(e,s){let o=Array.isArray(e)?e.map(a=>({id:a})):[{id:e}];return this.moderate({user_ids:o,actions:["unban_user"]},s)}async moveToSpam(e,s){let o=Array.isArray(e)?e.map(a=>({id:a})):[{id:e}];return this.moderate({user_ids:o,actions:["move_to_spam"]},s)}async blockAndSpam(e,s){let o=Array.isArray(e)?e.map(a=>({id:a})):[{id:e}];return this.moderate({user_ids:o,actions:["block_user","move_to_spam"]},s)}};var i=class extends Error{constructor(e){super(e),this.name="TemplateValidationError";}};function de(t){if(t.length===0)throw new i("Generic template must have at least 1 element");if(t.length>c.GENERIC_ELEMENTS_MAX)throw new i(`Generic template cannot have more than ${c.GENERIC_ELEMENTS_MAX} elements`);t.forEach((e,s)=>{$e(e,s);});}function $e(t,e){if(!t.title||t.title.trim()==="")throw new i(`Element ${e}: title is required`);if(t.title.length>c.GENERIC_TITLE_MAX_CHARS)throw new i(`Element ${e}: title cannot exceed ${c.GENERIC_TITLE_MAX_CHARS} characters`);if(t.subtitle&&t.subtitle.length>c.GENERIC_SUBTITLE_MAX_CHARS)throw new i(`Element ${e}: subtitle cannot exceed ${c.GENERIC_SUBTITLE_MAX_CHARS} characters`);if(t.image_url&&!_(t.image_url))throw new i(`Element ${e}: image_url must be HTTPS`);if(t.buttons&&V(t.buttons,`Element ${e}`),!!!(t.subtitle||t.image_url||t.default_action||t.buttons&&t.buttons.length>0))throw new i(`Element ${e}: must have at least one additional property beyond title`)}function pe(t,e){if(!t||t.trim()==="")throw new i("Button template text is required");if(t.length>c.BUTTON_TEXT_MAX_CHARS)throw new i(`Button template text cannot exceed ${c.BUTTON_TEXT_MAX_CHARS} characters`);if(e.length===0)throw new i("Button template must have at least 1 button");V(e,"Button template");}function ge(t){if(!t.media_type)throw new i("Media template element must have media_type");if(!t.url&&!t.attachment_id)throw new i("Media template element must have either url or attachment_id");if(t.url&&t.attachment_id)throw new i("Media template element cannot have both url and attachment_id");if(t.url&&!_(t.url))throw new i("Media template url must be HTTPS");if(t.buttons){if(t.buttons.length>c.MEDIA_BUTTONS_MAX_COUNT)throw new i(`Media template cannot have more than ${c.MEDIA_BUTTONS_MAX_COUNT} buttons`);V(t.buttons,"Media template");}}function V(t,e){if(t.length>c.BUTTONS_MAX_COUNT)throw new i(`${e} cannot have more than ${c.BUTTONS_MAX_COUNT} buttons`);t.forEach((s,o)=>{Ke(s,`${e} button ${o}`);});}function Ke(t,e){if(!t.type)throw new i(`${e}: type is required`);if(t.type!=="account_unlink"&&(!t.title||t.title.trim()===""))throw new i(`${e}: title is required for ${t.type} buttons`);if(t.title&&t.title.length>c.BUTTON_TITLE_MAX_CHARS)throw new i(`${e}: title cannot exceed ${c.BUTTON_TITLE_MAX_CHARS} characters`);switch(t.type){case "web_url":if(!t.url)throw new i(`${e}: url is required for web_url buttons`);if(!_(t.url))throw new i(`${e}: url must be HTTPS for web_url buttons`);break;case "postback":if(!t.payload)throw new i(`${e}: payload is required for postback buttons`);if(t.payload.length>c.POSTBACK_PAYLOAD_MAX_CHARS)throw new i(`${e}: payload cannot exceed ${c.POSTBACK_PAYLOAD_MAX_CHARS} characters`);break;case "phone_number":if(!t.payload)throw new i(`${e}: payload is required for phone_number buttons`);if(!t.payload.startsWith("+"))throw new i(`${e}: phone_number payload must start with + (e.g., +1234567890)`);break;case "game_play":break;case "account_link":if(!t.url)throw new i(`${e}: url is required for account_link buttons`);if(!_(t.url))throw new i(`${e}: url must be HTTPS for account_link buttons`);break;}if(t.type==="web_url"&&t.messenger_extensions&&t.fallback_url&&!_(t.fallback_url))throw new i(`${e}: fallback_url must be HTTPS`)}function _(t){try{return new URL(t).protocol==="https:"}catch{return false}}var A=class{constructor(e){this.httpClient=e;}async generic(e,s){de(e.elements);let o={template_type:"generic",elements:e.elements,image_aspect_ratio:e.image_aspect_ratio},a={recipient:e.recipient,messaging_type:e.messaging_type||"UPDATE",message:{attachment:{type:"template",payload:o}},notification_type:e.notification_type,tag:e.tag};return this.httpClient.request({method:"POST",path:E.MESSAGES,body:a,accessToken:s?.accessToken})}async button(e,s){pe(e.text,e.buttons);let o={template_type:"button",text:e.text,buttons:e.buttons},a={recipient:e.recipient,messaging_type:e.messaging_type||"UPDATE",message:{attachment:{type:"template",payload:o}},notification_type:e.notification_type,tag:e.tag};return this.httpClient.request({method:"POST",path:E.MESSAGES,body:a,accessToken:s?.accessToken})}async media(e,s){ge(e.element);let o={template_type:"media",elements:[e.element]},a={recipient:e.recipient,messaging_type:e.messaging_type||"UPDATE",message:{attachment:{type:"template",payload:o}},notification_type:e.notification_type,tag:e.tag};return this.httpClient.request({method:"POST",path:E.MESSAGES,body:a,accessToken:s?.accessToken})}async product(e,s){let o={template_type:"product",elements:e.elements},a={recipient:e.recipient,messaging_type:e.messaging_type||"UPDATE",message:{attachment:{type:"template",payload:o}},notification_type:e.notification_type,tag:e.tag};return this.httpClient.request({method:"POST",path:E.MESSAGES,body:a,accessToken:s?.accessToken})}};var R=class{constructor(e){this.httpClient=e;}async get(e,s){let{psid:o,fields:a=["first_name","last_name"]}=e,n=new URLSearchParams({fields:a.join(",")});return this.httpClient.request({method:"GET",path:`/${o}?${n.toString()}`,body:void 0,accessToken:s?.accessToken})}async getBasic(e,s){return this.get({psid:e,fields:["first_name","last_name","profile_pic"]},s)}async getFull(e,s){return this.get({psid:e,fields:["id","name","first_name","last_name","profile_pic","locale","timezone","gender"]},s)}async getName(e,s){return this.get({psid:e,fields:["first_name","last_name"]},s)}async getProfilePicture(e,s){return this.get({psid:e,fields:["profile_pic"]},s)}};var v=class{constructor(e){this.httpClient=e;}async list(e,s,o){if(!e)throw new d("Page ID is required");let a={};return s?.platform&&(a.platform=s.platform),s?.user_id&&(a.user_id=s.user_id),s?.folder&&(a.folder=s.folder),s?.limit&&(a.limit=s.limit.toString()),s?.after&&(a.after=s.after),s?.before&&(a.before=s.before),this.httpClient.request({method:"GET",path:`/${e}/conversations`,query:a,accessToken:o?.accessToken})}async get(e,s,o){if(!e)throw new d("Conversation ID is required");let a={};return s?.fields&&s.fields.length>0&&(a.fields=s.fields.join(",")),s?.limit&&(a.limit=s.limit.toString()),s?.after&&(a.after=s.after),s?.before&&(a.before=s.before),this.httpClient.request({method:"GET",path:`/${e}`,query:a,accessToken:o?.accessToken})}async getMessages(e,s,o){if(!e)throw new d("Conversation ID is required");let a={fields:"messages"};s?.limit&&(a.limit=s.limit.toString()),s?.after&&(a.after=s.after),s?.before&&(a.before=s.before);let n=await this.httpClient.request({method:"GET",path:`/${e}`,query:a,accessToken:o?.accessToken});return {data:n.messages?.data||[],paging:n.messages?.paging}}async getMessage(e,s,o){if(!e)throw new d("Message ID is required");let a={};return s?.fields&&s.fields.length>0?a.fields=s.fields.join(","):a.fields="id,created_time,from,to,message,attachments,reactions,reply_to",this.httpClient.request({method:"GET",path:`/${e}`,query:a,accessToken:o?.accessToken})}async getRecentMessages(e,s){let a=(await this.getMessages(e,{limit:20},s)).data.map(n=>this.getMessage(n.id,void 0,s));return Promise.all(a)}async findByUser(e,s,o,a){let n=await this.list(e,{platform:o,user_id:s},a);return n.data&&n.data.length>0&&n.data[0]?n.data[0].id:null}};var w=class{send;attachments;moderation;templates;profile;conversations;httpClient;constructor(e={}){this.validateConfig(e);let s={accessToken:e.accessToken,version:e.version||re,baseUrl:e.baseUrl,timeout:e.timeout,maxRetries:e.maxRetries};this.httpClient=new O(s),this.send=new k(this.httpClient),this.attachments=new P(this.httpClient),this.moderation=new S(this.httpClient),this.templates=new A(this.httpClient),this.profile=new R(this.httpClient),this.conversations=new v(this.httpClient);}validateConfig(e){if(e.accessToken!==void 0&&(typeof e.accessToken!="string"||e.accessToken.trim()===""))throw new d("Access token must be a non-empty string");if(e.version&&typeof e.version!="string")throw new d("API version must be a string");if(e.timeout&&(typeof e.timeout!="number"||e.timeout<=0))throw new d("Timeout must be a positive number");if(e.maxRetries&&(typeof e.maxRetries!="number"||e.maxRetries<0))throw new d("Max retries must be a non-negative number")}};var x=(l=>(l.MESSAGE="message",l.MESSAGE_ECHO="message_echo",l.MESSAGE_EDIT="message_edit",l.MESSAGE_REACTION="reaction",l.MESSAGE_READ="read",l.MESSAGING_FEEDBACK="messaging_feedback",l.MESSAGING_POSTBACK="postback",l.FEED="feed",l.VIDEOS="videos",l.LIVE_VIDEOS="live_videos",l))(x||{});function Ye(t){return typeof t.id=="string"&&t.id.length>0}function Ee(t){let e=[];if(t.object==="page"&&Array.isArray(t.entry))for(let s of t.entry)Array.isArray(s.messaging)&&e.push(...s.messaging);return e}function me(t){let e=[];if(t.object==="page"&&Array.isArray(t.entry))for(let s of t.entry)Array.isArray(s.changes)&&e.push(...s.changes);return e}function W(t){let e=Ye(t.sender);return {senderId:t.sender.id,userRef:t.sender.user_ref,recipientId:t.recipient.id,timestamp:t.timestamp,isIdentifiedUser:e,eventDate:new Date(t.timestamp)}}function le(t){let e=new Set;if(t.object==="page"&&Array.isArray(t.entry)){for(let s of t.entry)if(Array.isArray(s.changes)){for(let o of s.changes)if(o&&typeof o=="object"&&"field"in o)switch(o.field){case "feed":e.add("feed");break;case "videos":e.add("videos");break;case "live_videos":e.add("live_videos");break}}}return Array.from(e)}function Qe(t){return t&&typeof t=="object"&&"message_edit"in t}function ze(t){return {...W(t),messageId:t.message_edit.mid,updatedText:t.message_edit.text,editCount:t.message_edit.num_edit}}var Ze={MAX_EDITS:5,EVENT_TYPE:"message_edit"};var U=(m=>(m.LIKE="like",m.DISLIKE="dislike",m.LOVE="love",m.SAD="sad",m.ANGRY="angry",m.WOW="wow",m.SMILE="smile",m.OTHER="other",m))(U||{}),G=(s=>(s.REACT="react",s.UNREACT="unreact",s))(G||{});function Je(t){return t&&typeof t=="object"&&"read"in t}function et(t){return {senderId:t.sender.id,recipientId:t.recipient.id,watermarkTimestamp:t.read.watermark,readTimestamp:t.timestamp,watermarkDate:new Date(t.read.watermark),readDate:new Date(t.timestamp)}}function ue(t,e){return t<=e}function he(t,e){return t.filter(s=>ue(s.timestamp,e))}function tt(t,e){return he(t,e).length}var st={EVENT_TYPE:"message_reads",READ_PROPERTY:"read"};function ot(t){return t&&typeof t=="object"&&"postback"in t}function fe(t){return t.postback&&"referral"in t.postback&&t.postback.referral!=null}function be(t){return t&&typeof t.id=="string"&&t.id.length>0}function at(t){let e=fe(t),s=be(t.sender);return {payload:t.postback.payload,senderId:t.sender.id,userRef:t.sender.user_ref,recipientId:t.recipient.id,buttonTitle:t.postback.title,messageId:t.postback.mid,timestamp:t.timestamp,referralContext:e?{ref:t.postback.referral.ref,source:t.postback.referral.source,type:t.postback.referral.type}:void 0,isReferred:e,isIdentifiedUser:s}}var nt={GET_STARTED:"GET_STARTED",MAIN_MENU:"MAIN_MENU",HELP:"HELP",SUPPORT:"SUPPORT",CONTACT:"CONTACT",CONTACT_SALES:"CONTACT_SALES",CONTACT_SUPPORT:"CONTACT_SUPPORT",BACK:"BACK",NEXT:"NEXT",CANCEL:"CANCEL",SETTINGS:"SETTINGS",PREFERENCES:"PREFERENCES"},rt={MAX_PAYLOAD_LENGTH:1e3,EVENT_TYPE:"postback",REFERRAL_SOURCES:{SHORTLINK:"SHORTLINK",ADS:"ADS",MESSENGER_CODE:"MESSENGER_CODE"},REFERRAL_TYPES:{OPEN_THREAD:"OPEN_THREAD"}};var F=(o=>(o.CSAT="csat",o.NPS="nps",o.CES="ces",o))(F||{}),B=(o=>(o.ONE_TO_FIVE="one_to_five",o.FIVE_STARS="five_stars",o.FIVE_EMOJIS="five_emojis",o))(B||{}),H=(e=>(e.ZERO_TO_TEN="zero_to_ten",e))(H||{}),q=(e=>(e.ONE_TO_SEVEN="one_to_seven",e))(q||{}),j=(e=>(e.FREE_FORM="free_form",e))(j||{});function it(t){return t&&typeof t=="object"&&"messaging_feedback"in t}function ct(t){let e=[];return t.messaging_feedback.feedback_screens.forEach(s=>{Object.entries(s.questions).forEach(([o,a])=>{e.push({questionId:o,feedbackType:a.type,score:parseInt(a.payload,10),textFeedback:a.follow_up?.payload,screenId:s.screen_id});});}),{senderId:t.sender.id,recipientId:t.recipient.id,submissionTimestamp:t.timestamp,screenCount:t.messaging_feedback.feedback_screens.length,allResponses:e}}function dt(t){let e=new Map;return t.messaging_feedback.feedback_screens.forEach(s=>{Object.values(s.questions).forEach(o=>{let a=parseInt(o.payload,10),n=e.get(o.type)||[];e.set(o.type,[...n,a]);});}),e}function pt(t){let e=[];return t.messaging_feedback.feedback_screens.forEach(s=>{Object.values(s.questions).forEach(o=>{o.follow_up?.payload&&e.push(o.follow_up.payload);});}),e}var f={MAX_TEXT_FEEDBACK_LENGTH:400,SCORE_RANGES:{csat:{min:1,max:5},nps:{min:0,max:10},ces:{min:1,max:7}},TEMPLATE_EXPIRY:{MIN_DAYS:1,MAX_DAYS:7,DEFAULT_DAYS:1},QUESTION_ID:{MAX_LENGTH:80,VALID_PATTERN:/^[a-zA-Z0-9_]+$/},TEMPLATE_LIMITS:{MAX_TITLES:1,MAX_SCORING_COMPONENTS:1},EVENT_TYPE:"messaging_feedback"};function gt(t,e){let s=f.SCORE_RANGES[t];return Number.isInteger(e)&&e>=s.min&&e<=s.max}function Et(t){return t.length<=f.QUESTION_ID.MAX_LENGTH&&f.QUESTION_ID.VALID_PATTERN.test(t)}function mt(t){return t.length<=f.MAX_TEXT_FEEDBACK_LENGTH}var X=(r=>(r.ALBUM="album",r.ADDRESS="address",r.COMMENT="comment",r.CONNECTION="connection",r.COUPON="coupon",r.EVENT="event",r.EXPERIENCE="experience",r.GROUP="group",r.GROUP_MESSAGE="group_message",r.INTEREST="interest",r.LINK="link",r.MENTION="mention",r.MILESTONE="milestone",r.NOTE="note",r.PAGE="page",r.PICTURE="picture",r.PLATFORM_STORY="platform-story",r.PHOTO="photo",r.PHOTO_ALBUM="photo-album",r.POST="post",r.PROFILE="profile",r.QUESTION="question",r.RATING="rating",r.REACTION="reaction",r.RELATIONSHIP_STATUS="relationship-status",r.SHARE="share",r.STATUS="status",r.STORY="story",r.TIMELINE_COVER="timeline cover",r.TAG="tag",r.VIDEO="video",r))(X||{}),$=(g=>(g.ADD="add",g.BLOCK="block",g.EDIT="edit",g.EDITED="edited",g.DELETE="delete",g.FOLLOW="follow",g.HIDE="hide",g.MUTE="mute",g.REMOVE="remove",g.UNBLOCK="unblock",g.UNHIDE="unhide",g.UPDATE="update",g))($||{});function lt(t){return t&&typeof t=="object"&&t.field==="feed"}function ye(t){return t.verb==="add"&&t.item==="post"}function Te(t){return t.item==="comment"}function Me(t){return t.item==="photo"||t.item==="photo-album"}function ke(t){return t.item==="video"}function Pe(t){return t.item==="reaction"}function ut(t){return typeof t.message=="string"&&t.message.length>0}function ht(t,e,s){let{value:o}=s;return {pageId:t,timestamp:e,eventDate:new Date(e),sender:o.from,postId:o.post_id,commentId:o.comment_id,verb:o.verb,item:o.item,message:o.message,isPostCreated:ye(o),isComment:Te(o),isPhoto:Me(o),isVideo:ke(o),isReaction:Pe(o)}}function ft(t){let e=[];return t.photo&&e.push({url:t.photo,id:t.photo_id}),t.photos&&Array.isArray(t.photos)&&e.push(...t.photos.map((s,o)=>({url:s,id:t.photo_ids?.[o]}))),e}var Se={FIELD_NAME:"feed",MAX_PAGE_LIKES_FOR_NOTIFICATIONS:1e4};var I=(o=>(o.PROCESSING="processing",o.READY="ready",o.ERROR="error",o))(I||{});function _e(t){return t&&typeof t=="object"&&t.field==="videos"}function K(t){return t.status.video_status==="processing"}function Y(t){return t.status.video_status==="ready"}function Q(t){return t.status.video_status==="error"}function Ae(t,e,s){let{value:o}=s;return {pageId:t,timestamp:e,eventDate:new Date(e),videoId:o.id,status:o.status.video_status,isProcessing:K(o),isReady:Y(o),hasError:Q(o)}}function Re(t,e){return t==="processing"&&e==="ready"}function ve(t,e){return t==="processing"&&e==="error"}var xe={FIELD_NAME:"videos",STATUSES:Object.values(I)};var D=(u=>(u.LIVE="LIVE",u.LIVE_STOPPED="LIVE_STOPPED",u.PROCESSING="PROCESSING",u.SCHEDULED_CANCELED="SCHEDULED_CANCELED",u.SCHEDULED_EXPIRED="SCHEDULED_EXPIRED",u.SCHEDULED_LIVE="SCHEDULED_LIVE",u.SCHEDULED_UNPUBLISHED="SCHEDULED_UNPUBLISHED",u.UNPUBLISHED="UNPUBLISHED",u.VOD="VOD",u))(D||{});function Ce(t){return t&&typeof t=="object"&&t.field==="live_videos"}function z(t){return t.status==="LIVE"}function Z(t){return t.status==="SCHEDULED_UNPUBLISHED"||t.status==="SCHEDULED_LIVE"}function J(t){return t.status==="PROCESSING"}function ee(t){return t.status==="LIVE_STOPPED"||t.status==="SCHEDULED_CANCELED"||t.status==="SCHEDULED_EXPIRED"}function te(t){return t.status==="VOD"}function Oe(t,e,s){let{value:o}=s;return {pageId:t,timestamp:e,eventDate:new Date(e),videoId:o.id,status:o.status,isLive:z(o),isScheduled:Z(o),isProcessing:J(o),hasEnded:ee(o),isVODReady:te(o)}}function We(t,e){return t!=="LIVE"&&e==="LIVE"}function Ie(t,e){return t==="LIVE"&&(e==="LIVE_STOPPED"||e==="SCHEDULED_CANCELED"||e==="SCHEDULED_EXPIRED")}var De={FIELD_NAME:"live_videos",STATUSES:Object.values(D)};var se=(p=>(p.AUDIO="audio",p.FILE="file",p.IMAGE="image",p.VIDEO="video",p.FALLBACK="fallback",p.REEL="reel",p.IG_REEL="ig_reel",p))(se||{}),oe=(o=>(o.OPEN_THREAD="OPEN_THREAD",o.PRODUCT="product",o.ADS="ads",o))(oe||{}),ae=(n=>(n.MESSENGER_CODE="MESSENGER_CODE",n.DISCOVER_TAB="DISCOVER_TAB",n.ADS="ADS",n.SHORTLINK="SHORTLINK",n.CUSTOMER_CHAT_PLUGIN="CUSTOMER_CHAT_PLUGIN",n))(ae||{});function bt(t){return t&&typeof t=="object"&&"message"in t}function yt(t){return typeof t.text=="string"&&t.text.length>0}function N(t){return Array.isArray(t.attachments)&&t.attachments.length>0}function Ne(t){return t.quick_reply!==void 0}function Le(t){return t.reply_to!==void 0}function Ve(t){return t.referral!==void 0}function we(t,e){return t.type===e}function Tt(t){let{message:e}=t;return {...W(t),messageId:e.mid,text:e.text,hasAttachments:N(e),isQuickReply:Ne(e),isReply:Le(e),hasReferral:Ve(e),quickReplyPayload:e.quick_reply?.payload,repliedToMessageId:e.reply_to?.mid}}function Mt(t,e){return N(t)?t.attachments.filter(s=>we(s,e)):[]}function kt(t){return N(t)?t.attachments.map(e=>e.payload.url):[]}var Pt={MAX_TEXT_LENGTH:2e3,MAX_QUICK_REPLY_PAYLOAD_LENGTH:1e3,MAX_REFERRAL_REF_LENGTH:250,EVENT_TYPE:"message"},St={image:["image/jpeg","image/png","image/gif","image/webp"],video:["video/mp4","video/avi","video/quicktime","video/webm"],audio:["audio/mpeg","audio/mp4","audio/wav","audio/ogg"],file:["application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","text/plain"]};function L(t){return !t||typeof t!="object"?null:"type"in t&&Object.values(x).includes(t.type)?t.type:"message"in t&&t.message&&typeof t.message=="object"&&t.message.is_echo===true?"message_echo":"message"in t?"message":"message_edit"in t?"message_edit":"reaction"in t?"reaction":"read"in t?"read":"messaging_feedback"in t?"messaging_feedback":"postback"in t?"postback":null}function Ue(t){let e=new Set;if(t.object==="page"&&Array.isArray(t.entry)){for(let s of t.entry)if(Array.isArray(s.messaging))for(let o of s.messaging){let a=L(o);a&&e.add(a);}}return Array.from(e)}function ne(t){return Ee(t)}function _t(t){let e=L(t);return e?"type"in t?t:{...t,type:e}:null}async function Ge(t,e){let s=ne(t);for(let o of s){let a=_t(o);if(!a){e.onUnknown&&await e.onUnknown(o);continue}switch(a.type){case "message":e.onMessage&&await e.onMessage(a);break;case "message_echo":e.onMessageEcho&&await e.onMessageEcho(a);break;case "message_edit":e.onMessageEdit&&await e.onMessageEdit(a);break;case "reaction":e.onMessageReaction&&await e.onMessageReaction(a);break;case "read":e.onMessageRead&&await e.onMessageRead(a);break;case "messaging_feedback":e.onMessagingFeedback&&await e.onMessagingFeedback(a);break;case "postback":e.onMessagingPostback&&await e.onMessagingPostback(a);break;default:let n=a;e.onUnknown&&await e.onUnknown(n);break}}}function Fe(t,e){return t["hub.mode"]==="subscribe"&&t["hub.verify_token"]===e?t["hub.challenge"]:null}async function Be(t,e,s){if(!e)return {isValid:false,error:"Missing X-Hub-Signature-256 header"};if(!e.startsWith("sha256="))return {isValid:false,error:"Invalid signature format. Expected sha256= prefix"};if(!s)return {isValid:false,error:"App secret is required for signature verification"};try{if(typeof Buffer>"u")return {isValid:!1,error:"Signature verification is only supported in Node.js environments"};let o=await import('crypto'),a=e.substring(7),n=o.createHmac("sha256",s).update(t).digest("hex"),b=Buffer.from(a,"hex"),p=Buffer.from(n,"hex");if(b.length!==p.length)return {isValid:!1,error:"Signature length mismatch"};let m=o.timingSafeEqual(b,p);return {isValid:m,error:m?void 0:"Signature verification failed"}}catch(o){return {isValid:false,error:`Signature verification error: ${o instanceof Error?o.message:"Unknown error"}`}}}
export{He as ATTACHMENT_LIMITS,St as ATTACHMENT_MIME_TYPES,P as AttachmentsAPI,q as CESDisplayOption,nt as COMMON_POSTBACK_PAYLOADS,B as CSATDisplayOption,v as ConversationsAPI,Se as FEED_CONSTANTS,$ as FeedActionVerb,X as FeedItemType,F as FeedbackType,j as FollowUpType,De as LIVE_VIDEO_CONSTANTS,D as LiveVideoStatus,Pt as MESSAGE_CONSTANTS,Ze as MESSAGE_EDIT_CONSTANTS,C as MESSAGE_LIMITS,st as MESSAGE_READS_CONSTANTS,f as MESSAGING_FEEDBACK_CONSTANTS,G as MessageReactionAction,U as MessageReactionType,ae as MessageReferralSource,oe as MessageReferralType,M as MessageValidationError,w as Messenger,h as MessengerAPIError,d as MessengerConfigError,y as MessengerNetworkError,T as MessengerTimeoutError,S as ModerationAPI,H as NPSDisplayOption,rt as POSTBACK_CONSTANTS,R as ProfileAPI,k as SendAPI,c as TEMPLATE_LIMITS,i as TemplateValidationError,A as TemplatesAPI,xe as VIDEO_CONSTANTS,I as VideoStatus,se as WebhookAttachmentType,x as WebhookEventType,ht as extractFeedContext,Oe as extractLiveVideoContext,Tt as extractMessageContext,ze as extractMessageEditContext,et as extractMessageReadsContext,ct as extractMessagingFeedbackContext,me as extractPageEvents,ft as extractPhotos,at as extractPostbackContext,pt as extractTextFeedback,Ae as extractVideoContext,ne as extractWebhookEvents,kt as getAttachmentUrls,Mt as getAttachmentsByType,dt as getFeedbackScoresByType,le as getPageWebhookEventTypes,tt as getReadMessageCount,he as getReadMessages,L as getWebhookEventType,Ue as getWebhookPayloadEventTypes,N as hasAttachments,ee as hasEnded,ut as hasMessage,Ne as hasQuickReply,Ve as hasReferral,fe as hasReferralData,we as isAttachmentType,Te as isComment,Re as isCompletingEncoding,ve as isEncodingFailed,Ie as isEndingLive,lt as isFeedEvent,ke as isFeedVideo,We as isGoingLive,be as isIdentifiedSender,z as isLive,Ce as isLiveVideoEvent,J as isLiveVideoProcessing,Qe as isMessageEditEvent,bt as isMessageEvent,ue as isMessageRead,Je as isMessageReadsEvent,it as isMessagingFeedbackEvent,ot as isMessagingPostbackEvent,Me as isPhoto,ye as isPostCreated,Pe as isReaction,Le as isReplyMessage,Z as isScheduled,yt as isTextMessage,te as isVODReady,gt as isValidFeedbackScore,Et as isValidQuestionId,mt as isValidTextFeedback,_e as isVideoEvent,K as isVideoProcessing,Y as isVideoReady,Ge as processWebhookEvents,Be as verifyWebhookSignature,Fe as verifyWebhookSubscription,Q as videoHasError};//# sourceMappingURL=index.js.map
//# sourceMappingURL=index.js.map