@novu/framework 2.14.0-rc.5ea799b171 → 2.14.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.
@@ -153,13 +153,13 @@ $$`:`${e}$$`},FT=e=>NT(e)%2===0?e:DT(e),UT=e=>LT(e)%2===1?`${e}$`:e,HT=(e,t,n)=>
153
153
  `);n&&r.length>0&&r.at(-1)===""&&r.pop();let i=[],a=!1,o=!1;for(let c=0;c<r.length;c++){let p=r[c].trim();if(!a&&(p.startsWith("```")||p.startsWith("~~~"))){o=!o,i.push(r[c]);continue}if(o){i.push(r[c]);continue}let d=p!==""&&(ac.test(p)||oc.test(p));if(d&&!a){let h=!1;for(let y=c;y<r.length;y++){let g=r[y].trim();if(oc.test(g)){h=!0;break}if(g===""||!ac.test(g))break}h&&(i.push("```"),a=!0)}else!d&&a&&(i.push("```"),a=!1);i.push(r[c])}a&&t&&i.push("```");let s=i.join(`
154
154
  `);return n&&(s+=`
155
155
  `),s}function hx(e){return"adapterName"in e&&!("adapter"in e)}var Kf="thread-state:";function Xf(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}var fx=new AbortController().signal;async function*mx(e,t){let n=e[Symbol.asyncIterator](),r;try{for(;!t.aborted;){let i=new Promise(s=>{r=()=>s({done:!0,value:void 0}),t.addEventListener("abort",r,{once:!0})}),a=n.next(),o=await Promise.race([a,i]);if(r&&t.removeEventListener("abort",r),o.done||t.aborted)return;yield o.value}}finally{r&&t.removeEventListener("abort",r),n.return&&n.return().catch(()=>{})}}var gx=class sc{constructor(t){Se(this,"id");Se(this,"channelId");Se(this,"isDM");Se(this,"channelVisibility");Se(this,"signal");Se(this,"_adapter");Se(this,"_adapterName");Se(this,"_stateAdapterInstance");Se(this,"_recentMessages",[]);Se(this,"_isSubscribedContext");Se(this,"_currentMessage");Se(this,"_streamingUpdateIntervalMs");Se(this,"_fallbackStreamingPlaceholderText");Se(this,"_channel");Se(this,"_threadHistory");Se(this,"_logger");Se(this,"_typingStarted",!1);var n,r,i,a,o;this.id=t.id,this.channelId=t.channelId,this.isDM=(n=t.isDM)!=null?n:!1,this.channelVisibility=(r=t.channelVisibility)!=null?r:"unknown",this.signal=(i=t.signal)!=null?i:fx,this._isSubscribedContext=(a=t.isSubscribedContext)!=null?a:!1,this._currentMessage=t.currentMessage,this._logger=t.logger,this._streamingUpdateIntervalMs=(o=t.streamingUpdateIntervalMs)!=null?o:500,this._fallbackStreamingPlaceholderText=t.fallbackStreamingPlaceholderText,hx(t)?this._adapterName=t.adapterName:(this._adapter=t.adapter,this._stateAdapterInstance=t.stateAdapter,this._threadHistory=t.threadHistory),t.initialMessage&&(this._recentMessages=[t.initialMessage])}get adapter(){if(this._adapter)return this._adapter;if(!this._adapterName)throw new Error("Thread has no adapter configured");let n=si().getAdapter(this._adapterName);if(!n)throw new Error(`Adapter "${this._adapterName}" not found in Chat singleton`);return this._adapter=n,n}get _stateAdapter(){if(this._stateAdapterInstance)return this._stateAdapterInstance;let t=si();return this._stateAdapterInstance=t.getState(),this._stateAdapterInstance}get recentMessages(){return this._recentMessages}set recentMessages(t){this._recentMessages=t}get state(){return this._stateAdapter.get(`${Kf}${this.id}`)}async setState(t,n){let r=`${Kf}${this.id}`;if(n!=null&&n.replace)await this._stateAdapter.set(r,t,oi);else{let a={...await this._stateAdapter.get(r),...t};await this._stateAdapter.set(r,a,oi)}}get channel(){if(!this._channel){let t=rm(this.adapter,this.id);this._channel=new nm({id:t,adapter:this.adapter,stateAdapter:this._stateAdapter,isDM:this.isDM,channelVisibility:this.channelVisibility,threadHistory:this._threadHistory})}return this._channel}get messages(){let t=this.adapter,n=this.id,r=this._threadHistory;return{async*[Symbol.asyncIterator](){let i,a=!1;for(;;){let o=await t.fetchMessages(n,{cursor:i,direction:"backward"}),s=[...o.messages].reverse();for(let c of s)a=!0,yield c;if(!o.nextCursor||o.messages.length===0)break;i=o.nextCursor}if(!a&&r){let o=await r.getMessages(n);for(let s=o.length-1;s>=0;s--)yield o[s]}}}}get allMessages(){let t=this.adapter,n=this.id,r=this._threadHistory;return{async*[Symbol.asyncIterator](){let i,a=!1;for(;;){let o=await t.fetchMessages(n,{limit:100,cursor:i,direction:"forward"});for(let s of o.messages)a=!0,yield s;if(!o.nextCursor||o.messages.length===0)break;i=o.nextCursor}if(!a&&r){let o=await r.getMessages(n);for(let s of o)yield s}}}}async getParticipants(){let t=new Map;this._currentMessage&&!this._currentMessage.author.isMe&&!this._currentMessage.author.isBot&&t.set(this._currentMessage.author.userId,this._currentMessage.author);for await(let n of this.allMessages)n.author.isMe||n.author.isBot||t.has(n.author.userId)||t.set(n.author.userId,n.author);return[...t.values()]}async isSubscribed(){return this._isSubscribedContext?!0:this._stateAdapter.isSubscribed(this.id)}async subscribe(){await this._stateAdapter.subscribe(this.id),this.adapter.onThreadSubscribe&&await this.adapter.onThreadSubscribe(this.id)}async unsubscribe(){await this._stateAdapter.unsubscribe(this.id)}async post(t){if(lc(t)){if(t.kind==="stream"){let a=t.getPostData(),o={...a.options.updateIntervalMs?{updateIntervalMs:a.options.updateIntervalMs}:{},...a.options.groupTasks?{taskDisplayMode:a.options.groupTasks}:{},...a.options.endWith?{stopBlocks:a.options.endWith}:{},...a.options.sessionStatus?{sessionStatus:a.options.sessionStatus}:{}};return await this.handleStream(a.stream,o),t}return await this.handlePostableObject(t),t}if(Xf(t))return this.handleStream(t);let n=t;if(Pt(t)){let a=It(t);if(!a)throw new Error("Invalid JSX element: must be a Card element");n=a}n=await this.processCallbackUrls(n);let r;try{r=await this.adapter.postMessage(this.id,n)}finally{await this.finishTyping()}let i=this.createSentMessage(r.id,n,r.threadId);return this._threadHistory&&await this._threadHistory.append(this.id,new rn(i)),i}async handlePostableObject(t){try{await Zf(t,this.adapter,this.id,(n,r)=>this.adapter.postMessage(n,r),this._logger)}finally{await this.finishTyping()}}async postEphemeral(t,n,r){let{fallbackToDM:i}=r,a=typeof t=="string"?t:t.userId,o;if(Pt(n)){let s=It(n);if(!s)throw new Error("Invalid JSX element: must be a Card element");o=s}else o=n;if(this.adapter.postEphemeral)return o=await this.processCallbackUrls(o),this.adapter.postEphemeral(this.id,a,o);if(!i)return null;if(this.adapter.openDM){let s=await this.adapter.openDM(a);o=await this.processCallbackUrls(o,{id:this.adapter.channelIdFromThreadId(s),type:"channel"});let c=await this.adapter.postMessage(s,o);return{id:c.id,threadId:s,usedFallback:!0,raw:c.raw}}return null}async reply(t,n){if(!this.adapter.reply)throw new ai("Message replies are not supported by this adapter","replies");let r=t instanceof rn?t:this.findKnownMessage(t);if(r&&r.threadId!==this.id)throw new Error("Cannot reply to a message from another thread");let i;if(Xf(n)){let c="";for await(let p of io(n))typeof p=="string"?c+=p:p.type==="markdown_text"&&(c+=p.text);i={markdown:c.trim()?c:" "}}else if(Pt(n)){let c=It(n);if(!c)throw new Error("Invalid JSX element: must be a Card element");i=c}else i=n;i=await this.processCallbackUrls(i);let a=typeof t=="string"?t:t.id,o=await this.adapter.reply(this.id,a,i),s=this.createSentMessage(o.id,i,o.threadId,r);return this._threadHistory&&await this._threadHistory.append(this.id,new rn(s)),s}findKnownMessage(t){var n;return((n=this._currentMessage)==null?void 0:n.id)===t?this._currentMessage:this._recentMessages.find(r=>r.id===t)}async processCallbackUrls(t,n={id:this.id,type:"thread"}){var r;if(typeof t=="string")return t;if("type"in t&&t.type==="card")return oo(t,this._stateAdapter,n);if("card"in t&&((r=t.card)==null?void 0:r.type)==="card"){let i=await oo(t.card,this._stateAdapter,n);if(i!==t.card)return{...t,card:i}}return t}async schedule(t,n){let r;if(Pt(t)){let i=It(t);if(!i)throw new Error("Invalid JSX element: must be a Card element");r=i}else r=t;if(r=await this.processCallbackUrls(r),!this.adapter.scheduleMessage)throw new ai("Scheduled messages are not supported by this adapter","scheduling");return this.adapter.scheduleMessage(this.id,r,n)}async handleStream(t,n){let r=mx(io(t),this.signal),i={signal:this.signal,updateIntervalMs:this._streamingUpdateIntervalMs,...n,...this._fallbackStreamingPlaceholderText!==void 0?{fallbackStreamingPlaceholderText:this._fallbackStreamingPlaceholderText}:{}};if(this._currentMessage&&(i.recipientUserId=this._currentMessage.author.userId,i.recipientTeamId=this.extractSlackRecipientTeamId(this._currentMessage.raw)),this.adapter.stream){let o="",s={[Symbol.asyncIterator]:()=>{let p=r[Symbol.asyncIterator]();return{async next(){let d=await p.next();if(!d.done){let h=d.value;typeof h=="string"?o+=h:h.type==="markdown_text"&&(o+=h.text)}return d}}}},c;try{c=await this.adapter.stream(this.id,s,i)}catch(p){throw await this.finishTyping(),p}if(c){this._typingStarted=!1;let p=this.createSentMessage(c.id,{markdown:o},c.threadId);return this._threadHistory&&await this._threadHistory.append(this.id,new rn(p)),p}}let a={[Symbol.asyncIterator]:()=>{let o=r[Symbol.asyncIterator]();return{async next(){for(;;){let s=await o.next();if(s.done)return{value:void 0,done:!0};let c=s.value;if(typeof c=="string")return{value:c,done:!1};if(c.type==="markdown_text")return{value:c.text,done:!1}}}}}};return this.fallbackStream(a,i)}extractSlackRecipientTeamId(t){var r;if(!t||typeof t!="object")return;let n=t;if(typeof n.team_id=="string"&&n.team_id)return n.team_id;if(typeof n.team=="string"&&n.team)return n.team;if(n.team&&typeof n.team=="object"&&typeof n.team.id=="string"&&n.team.id)return n.team.id;if(typeof((r=n.user)==null?void 0:r.team_id)=="string"&&n.user.team_id)return n.user.team_id}async startTyping(t){var r;let n=(r=this._currentMessage)==null?void 0:r.author.userId;if(n){await this.adapter.startTyping(this.id,t,{initiatorUserId:n}),this._typingStarted=!0;return}await this.adapter.startTyping(this.id,t),this._typingStarted=!0}async finishTyping(t="active"){var n,r;this._typingStarted&&(this._typingStarted=!1,await((r=(n=this.adapter).endTyping)==null?void 0:r.call(n,this.id,t)))}async markAsRead(t){if(!this.adapter.markAsRead)throw new ai("Read receipts are not supported by this adapter","read-receipts");let n=t!=null?t:this._currentMessage;if(!n)throw new ao("A message is required outside a message handler","MESSAGE_REQUIRED");if(typeof n!="string"&&n.threadId!==this.id)throw new ao("Cannot mark a message from another thread as read","THREAD_MISMATCH");await this.adapter.markAsRead(this.id,typeof n=="string"?n:n.id,typeof n=="string"?void 0:n)}async fallbackStream(t,n){try{return await this.runFallbackStream(t,n)}finally{await this.finishTyping(n==null?void 0:n.sessionStatus)}}async runFallbackStream(t,n){var H;let r=(H=n==null?void 0:n.updateIntervalMs)!=null?H:this._streamingUpdateIntervalMs,i=this._fallbackStreamingPlaceholderText===void 0?"...":this._fallbackStreamingPlaceholderText,a=i===null?null:await this.adapter.postMessage(this.id,i),o=this.id,s=new im,c="",p=!1,d=null,h=null;a&&(o=a.threadId||this.id,c=i!=null?i:"");let y=()=>{h=setTimeout(()=>{d=g()},r)},g=async()=>{var ne;if(p||!a)return;let ue=s.render();if(ue.trim()&&ue!==c)try{await this.adapter.editMessage(o,a.id,{markdown:ue}),c=ue}catch(ve){(ne=this._logger)==null||ne.warn("fallbackStream edit failed",ve)}p||y()};a&&y();try{for await(let ue of t)if(s.push(ue),!a){let ne=s.render();ne.trim()&&(a=await this.adapter.postMessage(this.id,{markdown:ne}),o=a.threadId||this.id,c=ne,y())}}finally{p=!0,h&&(clearTimeout(h),h=null)}d&&await d;let I=s.getText(),K=s.finish();a||(a=await this.adapter.postMessage(this.id,{markdown:I.trim()?I:" "}),o=a.threadId||this.id,c=I),K.trim()&&K!==c&&await this.adapter.editMessage(o,a.id,{markdown:I});let Z=this.createSentMessage(a.id,{markdown:I},o);return this._threadHistory&&await this._threadHistory.append(this.id,new rn(Z)),Z}async refresh(){let t=await this.adapter.fetchMessages(this.id,{limit:50});t.messages.length>0?this._recentMessages=t.messages:this._threadHistory?this._recentMessages=await this._threadHistory.getMessages(this.id,50):this._recentMessages=[]}mentionUser(t){return`<@${t}>`}toJSON(){var t,n;return{_type:"chat:Thread",id:this.id,channelId:this.channelId,channelVisibility:this.channelVisibility,currentMessage:(t=this._currentMessage)==null?void 0:t.toJSON(),isDM:this.isDM,adapterName:(n=this._adapterName)!=null?n:this.adapter.name}}static fromJSON(t,n){let r=new sc({id:t.id,adapterName:t.adapterName,channelId:t.channelId,channelVisibility:t.channelVisibility,currentMessage:t.currentMessage?rn.fromJSON(t.currentMessage):void 0,isDM:t.isDM});return n&&(r._adapter=n),r}static[lr](t){return t.toJSON()}static[cr](t){return sc.fromJSON(t)}createSentMessage(t,n,r,i){let a=this.adapter,o=r||this.id,s=this,{plainText:c,formatted:p,attachments:d}=yx(n);return{id:t,threadId:o,text:c,formatted:p,raw:null,links:[],author:{userId:"self",userName:a.userName,fullName:a.userName,isBot:!0,isMe:!0},metadata:{dateSent:new Date,edited:!1},attachments:d,replyTo:i,toJSON(){return new rn(this).toJSON()},async edit(y){let g=y;if(Pt(y)){let I=It(y);if(!I)throw new Error("Invalid JSX element: must be a Card element");g=I}return g=await s.processCallbackUrls(g),await a.editMessage(o,t,g),s.createSentMessage(t,g,o,i)},async delete(){await a.deleteMessage(o,t)},async addReaction(y){await a.addReaction(o,t,y)},async removeReaction(y){await a.removeReaction(o,t,y)}}}createSentMessageFromMessage(t){let n=this.adapter,r=this.id,i=t.id,a=this;return{id:t.id,threadId:t.threadId,text:t.text,formatted:t.formatted,raw:t.raw,author:t.author,metadata:t.metadata,attachments:t.attachments,replyTo:t.replyTo,links:t.links,isMention:t.isMention,toJSON(){return t.toJSON()},async edit(o){let s=o;if(Pt(o)){let c=It(o);if(!c)throw new Error("Invalid JSX element: must be a Card element");s=c}return s=await a.processCallbackUrls(s),await n.editMessage(r,i,s),a.createSentMessage(i,s,r,t.replyTo)},async delete(){await n.deleteMessage(r,i)},async addReaction(o){await n.addReaction(r,i,o)},async removeReaction(o){await n.removeReaction(r,i,o)}}}};function yx(e){if(typeof e=="string")return{plainText:e,formatted:nn([tn([en(e)])]),attachments:[]};if("raw"in e)return{plainText:e.raw,formatted:nn([tn([en(e.raw)])]),attachments:e.attachments||[]};if("markdown"in e){let t=Va(e.markdown);return{plainText:sr(t),formatted:t,attachments:e.attachments||[]}}if("ast"in e)return{plainText:sr(e.ast),formatted:e.ast,attachments:e.attachments||[]};if("card"in e){let t=e.fallbackText||ni(e.card);return{plainText:t,formatted:nn([tn([en(t)])]),attachments:[]}}if("type"in e&&e.type==="card"){let t=ni(e);return{plainText:t,formatted:nn([tn([en(t)])]),attachments:[]}}throw new Error("Invalid PostableMessage format")}to();var am=require("async_hooks");var p1=new am.AsyncLocalStorage;ri();cc();var lM=10080*60*1e3;var cM=3600*1e3;var uM=600*1e3,pM=1440*60*1e3;var om=new Map;function ur(e){let t=om.get(e);return t||(t=Object.freeze({name:e,toString:()=>`{{emoji:${e}}}`,toJSON:()=>`{{emoji:${e}}}`}),om.set(e,t)),t}var bx={thumbs_up:{slack:["+1","thumbsup"],gchat:"\u{1F44D}"},thumbs_down:{slack:["-1","thumbsdown"],gchat:"\u{1F44E}"},clap:{slack:"clap",gchat:"\u{1F44F}"},wave:{slack:"wave",gchat:"\u{1F44B}"},pray:{slack:"pray",gchat:"\u{1F64F}"},muscle:{slack:"muscle",gchat:"\u{1F4AA}"},ok_hand:{slack:"ok_hand",gchat:"\u{1F44C}"},point_up:{slack:"point_up",gchat:"\u{1F446}"},point_down:{slack:"point_down",gchat:"\u{1F447}"},point_left:{slack:"point_left",gchat:"\u{1F448}"},point_right:{slack:"point_right",gchat:"\u{1F449}"},raised_hands:{slack:"raised_hands",gchat:"\u{1F64C}"},shrug:{slack:"shrug",gchat:"\u{1F937}"},facepalm:{slack:"facepalm",gchat:"\u{1F926}"},heart:{slack:"heart",gchat:["\u2764\uFE0F","\u2764"]},smile:{slack:["smile","slightly_smiling_face"],gchat:"\u{1F60A}"},laugh:{slack:["laughing","satisfied","joy"],gchat:["\u{1F602}","\u{1F606}"]},thinking:{slack:"thinking_face",gchat:"\u{1F914}"},sad:{slack:["cry","sad","white_frowning_face"],gchat:"\u{1F622}"},cry:{slack:"sob",gchat:"\u{1F62D}"},angry:{slack:"angry",gchat:"\u{1F620}"},love_eyes:{slack:"heart_eyes",gchat:"\u{1F60D}"},cool:{slack:"sunglasses",gchat:"\u{1F60E}"},wink:{slack:"wink",gchat:"\u{1F609}"},surprised:{slack:"open_mouth",gchat:"\u{1F62E}"},worried:{slack:"worried",gchat:"\u{1F61F}"},confused:{slack:"confused",gchat:"\u{1F615}"},neutral:{slack:"neutral_face",gchat:"\u{1F610}"},sleeping:{slack:"sleeping",gchat:"\u{1F634}"},sick:{slack:"nauseated_face",gchat:"\u{1F922}"},mind_blown:{slack:"exploding_head",gchat:"\u{1F92F}"},relieved:{slack:"relieved",gchat:"\u{1F60C}"},grimace:{slack:"grimacing",gchat:"\u{1F62C}"},rolling_eyes:{slack:"rolling_eyes",gchat:"\u{1F644}"},hug:{slack:"hugging_face",gchat:"\u{1F917}"},zany:{slack:"zany_face",gchat:"\u{1F92A}"},check:{slack:["white_check_mark","heavy_check_mark"],gchat:["\u2705","\u2714\uFE0F"]},x:{slack:["x","heavy_multiplication_x"],gchat:["\u274C","\u2716\uFE0F"]},question:{slack:"question",gchat:["\u2753","?"]},exclamation:{slack:"exclamation",gchat:"\u2757"},warning:{slack:"warning",gchat:"\u26A0\uFE0F"},stop:{slack:"octagonal_sign",gchat:"\u{1F6D1}"},info:{slack:"information_source",gchat:"\u2139\uFE0F"},100:{slack:"100",gchat:"\u{1F4AF}"},fire:{slack:"fire",gchat:"\u{1F525}"},star:{slack:"star",gchat:"\u2B50"},sparkles:{slack:"sparkles",gchat:"\u2728"},lightning:{slack:"zap",gchat:"\u26A1"},boom:{slack:"boom",gchat:"\u{1F4A5}"},eyes:{slack:"eyes",gchat:"\u{1F440}"},green_circle:{slack:"large_green_circle",gchat:"\u{1F7E2}"},yellow_circle:{slack:"large_yellow_circle",gchat:"\u{1F7E1}"},red_circle:{slack:"red_circle",gchat:"\u{1F534}"},blue_circle:{slack:"large_blue_circle",gchat:"\u{1F535}"},white_circle:{slack:"white_circle",gchat:"\u26AA"},black_circle:{slack:"black_circle",gchat:"\u26AB"},rocket:{slack:"rocket",gchat:"\u{1F680}"},party:{slack:["tada","partying_face"],gchat:["\u{1F389}","\u{1F973}"]},confetti:{slack:"confetti_ball",gchat:"\u{1F38A}"},balloon:{slack:"balloon",gchat:"\u{1F388}"},gift:{slack:"gift",gchat:"\u{1F381}"},trophy:{slack:"trophy",gchat:"\u{1F3C6}"},medal:{slack:"first_place_medal",gchat:"\u{1F947}"},lightbulb:{slack:"bulb",gchat:"\u{1F4A1}"},gear:{slack:"gear",gchat:"\u2699\uFE0F"},wrench:{slack:"wrench",gchat:"\u{1F527}"},hammer:{slack:"hammer",gchat:"\u{1F528}"},bug:{slack:"bug",gchat:"\u{1F41B}"},link:{slack:"link",gchat:"\u{1F517}"},lock:{slack:"lock",gchat:"\u{1F512}"},unlock:{slack:"unlock",gchat:"\u{1F513}"},key:{slack:"key",gchat:"\u{1F511}"},pin:{slack:"pushpin",gchat:"\u{1F4CC}"},memo:{slack:"memo",gchat:"\u{1F4DD}"},clipboard:{slack:"clipboard",gchat:"\u{1F4CB}"},calendar:{slack:"calendar",gchat:"\u{1F4C5}"},clock:{slack:"clock1",gchat:"\u{1F550}"},hourglass:{slack:"hourglass",gchat:"\u23F3"},bell:{slack:"bell",gchat:"\u{1F514}"},megaphone:{slack:"mega",gchat:"\u{1F4E2}"},speech_bubble:{slack:"speech_balloon",gchat:"\u{1F4AC}"},email:{slack:"email",gchat:"\u{1F4E7}"},inbox:{slack:"inbox_tray",gchat:"\u{1F4E5}"},outbox:{slack:"outbox_tray",gchat:"\u{1F4E4}"},package:{slack:"package",gchat:"\u{1F4E6}"},folder:{slack:"file_folder",gchat:"\u{1F4C1}"},file:{slack:"page_facing_up",gchat:"\u{1F4C4}"},chart_up:{slack:"chart_with_upwards_trend",gchat:"\u{1F4C8}"},chart_down:{slack:"chart_with_downwards_trend",gchat:"\u{1F4C9}"},coffee:{slack:"coffee",gchat:"\u2615"},pizza:{slack:"pizza",gchat:"\u{1F355}"},beer:{slack:"beer",gchat:"\u{1F37A}"},arrow_up:{slack:"arrow_up",gchat:"\u2B06\uFE0F"},arrow_down:{slack:"arrow_down",gchat:"\u2B07\uFE0F"},arrow_left:{slack:"arrow_left",gchat:"\u2B05\uFE0F"},arrow_right:{slack:"arrow_right",gchat:"\u27A1\uFE0F"},refresh:{slack:"arrows_counterclockwise",gchat:"\u{1F504}"},sun:{slack:"sunny",gchat:"\u2600\uFE0F"},cloud:{slack:"cloud",gchat:"\u2601\uFE0F"},rain:{slack:"rain_cloud",gchat:"\u{1F327}\uFE0F"},snow:{slack:"snowflake",gchat:"\u2744\uFE0F"},rainbow:{slack:"rainbow",gchat:"\u{1F308}"}},wx=class{constructor(e){Se(this,"emojiMap");Se(this,"slackToNormalized");Se(this,"gchatToNormalized");this.emojiMap={...bx,...e},this.slackToNormalized=new Map,this.gchatToNormalized=new Map,this.buildReverseMaps()}buildReverseMaps(){for(let[e,t]of Object.entries(this.emojiMap)){let n=Array.isArray(t.slack)?t.slack:[t.slack];for(let i of n)this.slackToNormalized.set(i.toLowerCase(),e);let r=Array.isArray(t.gchat)?t.gchat:[t.gchat];for(let i of r)this.gchatToNormalized.set(i,e)}}fromSlack(e){var r;let t=e.replace(/^:|:$/g,"").toLowerCase(),n=(r=this.slackToNormalized.get(t))!=null?r:e;return ur(n)}fromGChat(e){var n;let t=(n=this.gchatToNormalized.get(e))!=null?n:e;return ur(t)}fromTeams(e){var r;let n=(r={like:"thumbs_up",heart:"heart",laugh:"laugh",surprised:"surprised",sad:"sad",angry:"angry"}[e])!=null?r:e;return ur(n)}toSlack(e){let t=typeof e=="string"?e:e.name,n=this.emojiMap[t];return n?Array.isArray(n.slack)?n.slack[0]:n.slack:t}toGChat(e){let t=typeof e=="string"?e:e.name,n=this.emojiMap[t];return n?Array.isArray(n.gchat)?n.gchat[0]:n.gchat:t}toDiscord(e){return this.toGChat(e)}matches(e,t){let n=typeof t=="string"?t:t.name,r=this.emojiMap[n];if(!r)return e===n;let i=Array.isArray(r.slack)?r.slack:[r.slack],a=Array.isArray(r.gchat)?r.gchat:[r.gchat],o=e.replace(/^:|:$/g,"").toLowerCase();return i.some(s=>s.toLowerCase()===o)||a.includes(e)}extend(e){Object.assign(this.emojiMap,e),this.buildReverseMaps()}},Sx=new wx;function Tx(e){let t=["thumbs_up","thumbs_down","clap","wave","pray","muscle","ok_hand","point_up","point_down","point_left","point_right","raised_hands","shrug","facepalm","heart","smile","laugh","thinking","sad","cry","angry","love_eyes","cool","wink","surprised","worried","confused","neutral","sleeping","sick","mind_blown","relieved","grimace","rolling_eyes","hug","zany","check","x","question","exclamation","warning","stop","info","100","fire","star","sparkles","lightning","boom","eyes","green_circle","yellow_circle","red_circle","blue_circle","white_circle","black_circle","rocket","party","confetti","balloon","gift","trophy","medal","lightbulb","gear","wrench","hammer","bug","link","lock","unlock","key","pin","memo","clipboard","calendar","clock","hourglass","bell","megaphone","speech_bubble","email","inbox","outbox","package","folder","file","chart_up","chart_down","coffee","pizza","beer","arrow_up","arrow_down","arrow_left","arrow_right","refresh","sun","cloud","rain","snow","rainbow"],n={custom:r=>ur(r)};for(let r of t)n[r]=ur(r);if(e){for(let r of Object.keys(e))n[r]=ur(r);Sx.extend(e)}return n}var dM=Tx(),li=Jr,ci=Gr,ui=Wa;var pi=ti,di=kf,hi=ei,fi=Wr,sm=Xr,lm=Qr;var mi=Vr;var gi=Kr,cm=Yr,yi=Zr;var um=Xa,pm=Ja;var dm=Za,bi=Ka,wi=Qa,Si=Ga;function pr(e){return"type"in e&&e.type==="card"}function hm(e){return typeof e=="object"&&e!==null&&e.type==="tool-approval-card"}function fm(e){if(typeof e!="object"||e===null)return!1;let t=e.type;return t==="human-ask-card"||t==="human-approve-card"||t==="human-choose-card"||t==="human-tell-card"}function uc(e,t){return(e==null?void 0:e.workflowId)===t.id}var xx=Symbol.for("chat.jsx.element"),Ax=new Set([li,ci,ui,pi,di,hi,fi,um,sm,lm,mi,gi,pm,dm,cm,bi,wi,yi,Si]);function vx(e){return typeof e=="object"&&e!==null&&"type"in e}function kx(e){return typeof e=="object"&&e!==null&&e.$$typeof===xx}async function lo(e){let t=so(e);if(t&&typeof t=="object"&&pr(t))return t;let{isJSX:n,toCardElement:r}=await Promise.resolve().then(()=>(gm(),mm));return n(t)?r(t):null}function so(e){var t;if(Array.isArray(e))return e.map(n=>so(n));if(!kx(e))return Ex(e);if(typeof e.type=="function"&&!Ax.has(e.type)){let n={...(t=e.props)!=null?t:{}};return e.children!==void 0&&(n.children=e.children),so(e.type(n))}return{...e,children:so(e.children)}}function Ex(e){return typeof e=="string"||typeof e=="number"||vx(e)?e:null}var ym=async(e,t)=>{let n=new TextEncoder,r=n.encode(e),i=n.encode(t),a=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("HMAC",a,i);return Array.from(new Uint8Array(o)).map(s=>s.toString(16).padStart(2,"0")).join("")},bm=(e,t)=>{if(typeof e!="string"||typeof t!="string"||e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e.charCodeAt(r)^t.charCodeAt(r);return n===0};var Rx=require("cross-fetch");var wm=async()=>{if(process.env.NOVU_BRIDGE_ORIGIN)return`${process.env.NOVU_BRIDGE_ORIGIN}/api/novu`;if(process.env.NEXT_PUBLIC_VERCEL_ENV==="preview"&&process.env.NEXT_PUBLIC_VERCEL_URL)return`https://${process.env.NEXT_PUBLIC_VERCEL_URL}/api/novu`;try{if(process.env.NODE_ENV==="development"||process.env.NODE_ENV==="dev"){let t=await(await fetch("http://localhost:2022/.well-known/novu")).json();return`${t.tunnelOrigin}${t.route}`}}catch(e){console.error(e)}return""};function Sm(e){return!!e&&typeof e=="object"&&"error"in e&&"message"in e&&"statusCode"in e}var co=(e,t)=>{if(!e)throw new Zi;return{post:async(n,r)=>{let i=await fetch(`${t}/v1${n}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${e}`},body:JSON.stringify(r)}),a=await i.json();if(i.ok)return a;throw Sm(a)?new ea(a.statusCode,a.error,a.message):new Xn(a)},delete:async n=>(await fetch(`${t}/v1${n}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${e}`}})).json()}};var Em=require("liquidjs");function pc(e,t){let n={...e};for(let r of Object.keys(t)){let i=t[r];i&&typeof i=="object"&&!Array.isArray(i)?n[r]=pc(n[r]||{},i):(Array.isArray(i),n[r]=i)}return n}function uo(e,t){let n=t.split(".").reduce((r,i)=>{if(r&&typeof r=="object")return r[i]},e);if(n==null)return"";if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="boolean")return String(n);if(typeof n=="object"){let r=JSON.stringify(n);return r==="{}"?"":r}return""}function Tm(e,t=2,n,r=", "){if(!Array.isArray(e)||e.length===0)return"";let i=n?e.map(s=>typeof s!="object"||!s?"":uo(s,n)):e;if(i.length===1)return i[0];if(i.length===2)return`${i[0]} and ${i[1]}`;if(t>=i.length){let s=i.slice(0,-1),c=i[i.length-1];return`${s.join(r)} and ${c}`}let a=i.slice(0,t),o=i.length-t;return`${a.join(r)} and ${o} ${o===1?"other":"others"}`}var xm=Bt(require("pluralize"),1);function Am(e,t="",n="",r="true"){if(e==null)return"";let i=0;if(Array.isArray(e)?i=e.length:typeof e=="object"?i=Object.keys(e).length:typeof e=="string"?i=+e:typeof e=="number"?i=e:i=Number(e),Number.isNaN(i)&&(i=0),i<=0)return"";let a;return n?a=i===1?t:n:a=(0,xm.default)(t,i),r==="true"?`${i} ${a}`:a}var Cx=require("liquidjs"),vm=Bt(require("pluralize"),1),_x=require("zod");var Ox="",Ix=2,Px="other",Mx=", ",Nx=" and ",Lx=", and ";function km(e,t=Ox,n=Ix,r=Px,i=Mx,a=Nx,o=Lx){if(!Array.isArray(e)||e.length===0)return"";let s=t?e.map(y=>typeof y!="object"||!y?"":uo(y,t)):e,c=s.length;if(c===1)return s[0];if(c===2)return`${s[0]}${a}${s[1]}`;if(n>=c){let y=s.slice(0,c-1),g=s[c-1];return`${y.join(i)}${o}${g}`}let p=s.slice(0,n),d=c-n,h=n===1?a:o;return`${p.join(i)}${h}${d} ${(0,vm.default)(r,d)}`}function Dx(e){return Array.isArray(e)||typeof e=="object"&&e!==null?Rm(e):typeof e=="string"?e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t"):e==null?"":String(e)}var Rm=(e,t=0)=>Array.isArray(e)||typeof e=="object"&&e!==null?JSON.stringify(e,null,t).replace(/"/g,"'").replace(/\n/g,"\\n"):e==null?"":String(e);function Cm(e){let t=new Em.Liquid({outputEscape:Dx,...e});return t.registerFilter("json",(n,r)=>Rm(n,r)),t.registerFilter("digest",Tm),t.registerFilter("toSentence",km),t.registerFilter("pluralize",Am),t}var Vn=Bt(require("chalk"),1),et={info:e=>Vn.default.blue(e),warning:e=>Vn.default.yellow(e),error:e=>Vn.default.red(e),success:e=>Vn.default.green(e),underline:e=>Vn.default.underline(e),bold:e=>Vn.default.bold(e)},lt={SUCCESS:et.success("\u2714"),ERROR:et.error("\u2717"),WARNING:et.warning("\u26A0"),INFO:et.info("\u2139"),ARROW:et.bold("\u2192"),MOCK:et.info("\u25CB"),HYDRATED:et.bold(et.info("\u2192")),STEP:et.info("\u03C3"),ACTION:et.info("\u03B1"),DURATION:et.info("\u0394"),PROVIDER:et.info("\u2699"),OUTPUT:et.info("\u21E2"),INPUT:et.info("\u21E0"),WORKFLOW:et.info("\u03C9"),STATE:et.info("\u03C3"),EXECUTE:et.info("\u03B5"),PREVIEW:et.info("\u03C1")};function po(e){return e||process.env.NOVU_API_URL||"https://api.novu.co"}function ho(e){return e||process.env.NOVU_SECRET_KEY||process.env.NOVU_API_KEY||""}var dc=Bt(require("sanitize-html"),1),Fx=["src","alt","width","height","loading","srcset","sizes","crossorigin","usemap","ismap","class","id","style","title","dir","lang"];function Ux(e){return e.toLowerCase().startsWith("on")}function Hx(e){return e.replace(/<\/([a-zA-Z][a-zA-Z0-9]*)\s*\/[^>]*>/g,"</$1>")}var $x={allowedTags:dc.default.defaults.allowedTags.concat(["style","img","html","head","body","link","meta","title"]),allowedAttributes:!1,transformTags:{"*":(e,t)=>{let n={};for(let[r,i]of Object.entries(t))Ux(r)||(n[r]=i);return{tagName:e,attribs:n}},img:(e,t)=>{let n={};for(let[r,i]of Object.entries(t))Fx.includes(r.toLowerCase())&&(n[r]=i);return{tagName:e,attribs:n}}},allowVulnerableTags:!0,parseStyleAttributes:!1,parser:{lowerCaseAttributeNames:!0}},_m=e=>{if(!e)return e;let t=Hx(e),n=/^<!DOCTYPE .*?>/,r=t.match(n),i=(0,dc.default)(t,$x);return r?r[0]+i:i},fo=e=>Object.keys(e).reduce((t,n)=>{let r=e[n];return typeof r=="string"?t[n]=_m(r):Array.isArray(r)?t[n]=r.map(i=>typeof i=="string"?_m(i):typeof i=="object"?fo(i):i):typeof r=="object"&&r!==null?t[n]=fo(r):t[n]=r,t},{});function Om(e,t=!0,n=console){t&&(n.info(`
156
- ${et.bold(et.underline("Discovered workflowId:"))} '${e.workflowId}'`),e.steps.forEach((r,i)=>{let a=i===e.steps.length-1,o=a?"\u2514":"\u251C";n.info(`${o} ${lt.STEP} Discovered stepId: '${r.stepId}' Type: '${r.type}'`),r.providers.forEach((s,c)=>{let p=c===r.providers.length-1,d=a?" ":"\u2502",h=p?"\u2514":"\u251C";n.info(`${d} ${h} ${lt.PROVIDER} Discovered provider: '${s.type}'`)})}))}var Im=require("jsonrepair");function Pm(e){let t=e.trim();return(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))&&t.length>2}var Mm="__novuJsonString";function qx(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&e[Mm]===!0}function Ti(e){if(typeof e=="string"){if(!Pm(e))return e;try{let t=JSON.parse(e);return{[Mm]:!0,value:Ti(t)}}catch{return e}}if(Array.isArray(e))return e.map(t=>Ti(t));if(e&&typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=Ti(r);return t}return e}function xi(e){if(qx(e))return JSON.stringify(xi(e.value));if(Array.isArray(e))return e.map(t=>xi(t));if(e&&typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=xi(r);return t}return e}function jx(e){try{return JSON.parse(e),e}catch{try{return(0,Im.jsonrepair)(e)}catch{return e}}}function Nm(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>typeof n=="string"?[t,Pm(n)?jx(n):n]:typeof n=="object"&&n!==null&&!Array.isArray(n)?[t,Nm(n)]:[t,n]))}function Lm(e){return!(e!=null&&e.data)||typeof e.data!="object"||Array.isArray(e.data)?e:{...e,data:Nm(e.data)}}var Fm=Bt(require("ajv"),1),Um=Bt(require("ajv-formats"),1);var Dm=e=>typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e));var mo=class extends xn{constructor(n,r){let i=r.length===1?"it":"them";super(`Tried to use a ${n} in @novu/framework without ${r.join(", ")} installed. Please install ${i} by running \`npm install ${r.join(" ")}\`.`);this.statusCode=500;this.code="MissingDependencyError"}};var go=async(e,t)=>{let n=new Set;if((await Promise.allSettled(e.map(i=>i.import))).forEach((i,a)=>{let o=e[a];i.status==="fulfilled"&&o.exports.every(c=>i.value[c]!==void 0)||n.add(o.name)}),n.size>0)throw new mo(t,Array.from(n))};var yo=class{constructor(){this.requiredImports=[];this.ajv=new Fm.default({useDefaults:!0,removeAdditional:"failing",strict:!1}),(0,Um.default)(this.ajv),this.compiledSchemas=new Map}async canHandle(t){let n=t.type==="object"||!!t.anyOf||!!t.allOf||!!t.oneOf;return n&&await go(this.requiredImports,"JSON schema"),n}async validate(t,n){let r=this.compiledSchemas.get(n);r||(r=this.ajv.compile(n),this.compiledSchemas.set(n,r));let i=Dm(t);return r(i)?{success:!0,data:i}:{success:!1,errors:r.errors.map(o=>({path:o.instancePath,message:o.message}))}}async transformToJsonSchema(t){return t}};var bo=class{constructor(){this.requiredImports=[{name:"zod",import:import("zod"),exports:["ZodType"]},{name:"zod-to-json-schema",import:import("zod-to-json-schema"),exports:["zodToJsonSchema"]}]}async canHandle(t){let n=t.safeParseAsync!==void 0;return n&&await go(this.requiredImports,"Zod schema"),n}async validate(t,n){let r=await n.safeParseAsync(t);return r.success?{success:!0,data:r.data}:{success:!1,errors:r.error.issues.map(i=>({path:`/${i.path.join("/")}`,message:i.message}))}}async transformToJsonSchema(t){let{zodToJsonSchema:n}=await import("zod-to-json-schema");return n(t)}};var wo=new bo,So=new yo,Ai=async(e,t)=>{if(await wo.canHandle(e))return wo.validate(t,e);if(await So.canHandle(e))return So.validate(t,e);throw new Error("Invalid schema")},bt=async e=>{if(await wo.canHandle(e))return wo.transformToJsonSchema(e);if(await So.canHandle(e))return So.transformToJsonSchema(e);throw new Error("Invalid schema")};function Hm(){return["development",void 0,"dev"].includes(process.env.NODE_ENV)}var dr=class{constructor(t){this.discoveredWorkflows=new Map;this.discoverWorkflowPromises=new Map;this.registeredAgents=new Map;this.version="2.14.0-rc.5ea799b171";let n=this.buildOptions(t);this.apiUrl=n.apiUrl,this.secretKey=n.secretKey,this.strictAuthentication=n.strictAuthentication,this.verbose=n.verbose,this.logger=n.logger,this.templateEngine=Cm()}buildOptions(t){let n={apiUrl:po(t==null?void 0:t.apiUrl),secretKey:ho(t==null?void 0:t.secretKey),strictAuthentication:!Hm(),verbose:Hm(),logger:console};return(t==null?void 0:t.strictAuthentication)!==void 0?n.strictAuthentication=t.strictAuthentication:process.env.NOVU_STRICT_AUTHENTICATION_ENABLED!==void 0&&(n.strictAuthentication=process.env.NOVU_STRICT_AUTHENTICATION_ENABLED==="true"),(t==null?void 0:t.verbose)!==void 0&&(n.verbose=t.verbose),(t==null?void 0:t.logger)!==void 0&&(n.logger=t.logger),n}log(...t){this.verbose&&this.logger.info(...t)}async addWorkflows(t){for(let n of t){if(this.discoveredWorkflows.has(n.id))continue;let r=this.discoverWorkflowPromises.get(n.id);if(r){await r;continue}let i=this.addWorkflow(n);this.discoverWorkflowPromises.set(n.id,i),await i}}addAgents(t){for(let n of t)this.registeredAgents.set(n.id,n)}getAgent(t){return this.registeredAgents.get(t)}async addWorkflow(t){try{let n=await t.discover();Om(n,this.verbose,this.logger),this.discoveredWorkflows.set(t.id,n)}finally{this.discoverWorkflowPromises.delete(t.id)}}healthCheck(){let t=this.getRegisteredWorkflows(),n=t.length,r=t.reduce((i,a)=>i+a.steps.length,0);return{status:"ok",sdkVersion:"2.14.0-rc.5ea799b171",frameworkVersion:"2024-06-26",discovered:{workflows:n,steps:r}}}getWorkflow(t){let n=this.discoveredWorkflows.get(t);if(n)return n;throw new Pr(t)}getStep(t,n){let i=this.getWorkflow(t).steps.find(a=>a.stepId===n);if(i)return i;throw new la(n)}getRegisteredWorkflows(){return Array.from(this.discoveredWorkflows.values())}discover(){return{workflows:this.getRegisteredWorkflows(),agents:Array.from(this.registeredAgents.keys()).map(t=>({agentId:t}))}}mock(t){try{return Pu(t)}catch(n){return this.logger.warn("Failed to mock schema, returning empty object:",n),{}}}async validate(t,n,r,i,a,o,s){let c=await Ai(n,t);if(c.success)return c.data;switch(r){case"event":this.throwInvalidEvent(i,a,c.errors);case"step":this.throwInvalidStep(o,i,a,c.errors);case"provider":this.throwInvalidProvider(o,s,i,a,c.errors);default:throw new Error(`Invalid component: '${r}'`)}}throwInvalidProvider(t,n,r,i,a){throw t?n?r==="output"?new Gi(i,t,n,a):new Error(`Invalid payload type: '${r}'`):new Error("providerId is required"):new Error("stepId is required")}throwInvalidStep(t,n,r,i){if(!t)throw new Error("stepId is required");switch(n){case"output":throw new Wi(r,t,i);case"result":throw new Yi(r,t,i);case"controls":throw new Vi(r,t,i);default:throw new Error(`Invalid payload type: '${n}'`)}}throwInvalidEvent(t,n,r){switch(t){case"controls":throw new zi(n,r);case"payload":throw new _r(n,r);default:throw new Error(`Invalid payload type: '${t}'`)}}executeStepFactory(t,n,r){return async(i,a,o)=>{if(r())return;let s=this.getStep(t.workflowId,i),c=t.action==="preview";if(!c&&i===t.stepId){let g=await this.createStepControls(s,t),I=await this.compileControls(g,t);if(await this.shouldSkip(o==null?void 0:o.skip,I))return n({options:{skip:!0},outputs:{},providers:{}}),{}}let p=this.previewStep.bind(this),d=this.executeStep.bind(this),y=await(c?p:d)(t,{...s,providers:s.providers.map(g=>{var K;let I=(K=o==null?void 0:o.providers)==null?void 0:K[g.type];if(!I)throw new ta(g.type);return{...g,resolve:I}}),resolve:a});return this.shouldSanitize({stepType:s.type,options:o})&&(y={...y,outputs:fo(y.outputs)}),i===t.stepId&&n({...y,options:{skip:!1}}),y.outputs}}shouldSanitize({stepType:t,options:n}){return(n==null?void 0:n.disableOutputSanitization)===!0?!1:["email","in_app"].includes(t)}async shouldSkip(t,n){return t?t(n):!1}async executeWorkflow(t){let i=`${{execute:"Executing",preview:"Previewing"}[t.action]||t.action} workflowId:`;this.log(`
156
+ ${et.bold(et.underline("Discovered workflowId:"))} '${e.workflowId}'`),e.steps.forEach((r,i)=>{let a=i===e.steps.length-1,o=a?"\u2514":"\u251C";n.info(`${o} ${lt.STEP} Discovered stepId: '${r.stepId}' Type: '${r.type}'`),r.providers.forEach((s,c)=>{let p=c===r.providers.length-1,d=a?" ":"\u2502",h=p?"\u2514":"\u251C";n.info(`${d} ${h} ${lt.PROVIDER} Discovered provider: '${s.type}'`)})}))}var Im=require("jsonrepair");function Pm(e){let t=e.trim();return(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))&&t.length>2}var Mm="__novuJsonString";function qx(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&e[Mm]===!0}function Ti(e){if(typeof e=="string"){if(!Pm(e))return e;try{let t=JSON.parse(e);return{[Mm]:!0,value:Ti(t)}}catch{return e}}if(Array.isArray(e))return e.map(t=>Ti(t));if(e&&typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=Ti(r);return t}return e}function xi(e){if(qx(e))return JSON.stringify(xi(e.value));if(Array.isArray(e))return e.map(t=>xi(t));if(e&&typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=xi(r);return t}return e}function jx(e){try{return JSON.parse(e),e}catch{try{return(0,Im.jsonrepair)(e)}catch{return e}}}function Nm(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>typeof n=="string"?[t,Pm(n)?jx(n):n]:typeof n=="object"&&n!==null&&!Array.isArray(n)?[t,Nm(n)]:[t,n]))}function Lm(e){return!(e!=null&&e.data)||typeof e.data!="object"||Array.isArray(e.data)?e:{...e,data:Nm(e.data)}}var Fm=Bt(require("ajv"),1),Um=Bt(require("ajv-formats"),1);var Dm=e=>typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e));var mo=class extends xn{constructor(n,r){let i=r.length===1?"it":"them";super(`Tried to use a ${n} in @novu/framework without ${r.join(", ")} installed. Please install ${i} by running \`npm install ${r.join(" ")}\`.`);this.statusCode=500;this.code="MissingDependencyError"}};var go=async(e,t)=>{let n=new Set;if((await Promise.allSettled(e.map(i=>i.import))).forEach((i,a)=>{let o=e[a];i.status==="fulfilled"&&o.exports.every(c=>i.value[c]!==void 0)||n.add(o.name)}),n.size>0)throw new mo(t,Array.from(n))};var yo=class{constructor(){this.requiredImports=[];this.ajv=new Fm.default({useDefaults:!0,removeAdditional:"failing",strict:!1}),(0,Um.default)(this.ajv),this.compiledSchemas=new Map}async canHandle(t){let n=t.type==="object"||!!t.anyOf||!!t.allOf||!!t.oneOf;return n&&await go(this.requiredImports,"JSON schema"),n}async validate(t,n){let r=this.compiledSchemas.get(n);r||(r=this.ajv.compile(n),this.compiledSchemas.set(n,r));let i=Dm(t);return r(i)?{success:!0,data:i}:{success:!1,errors:r.errors.map(o=>({path:o.instancePath,message:o.message}))}}async transformToJsonSchema(t){return t}};var bo=class{constructor(){this.requiredImports=[{name:"zod",import:import("zod"),exports:["ZodType"]},{name:"zod-to-json-schema",import:import("zod-to-json-schema"),exports:["zodToJsonSchema"]}]}async canHandle(t){let n=t.safeParseAsync!==void 0;return n&&await go(this.requiredImports,"Zod schema"),n}async validate(t,n){let r=await n.safeParseAsync(t);return r.success?{success:!0,data:r.data}:{success:!1,errors:r.error.issues.map(i=>({path:`/${i.path.join("/")}`,message:i.message}))}}async transformToJsonSchema(t){let{zodToJsonSchema:n}=await import("zod-to-json-schema");return n(t)}};var wo=new bo,So=new yo,Ai=async(e,t)=>{if(await wo.canHandle(e))return wo.validate(t,e);if(await So.canHandle(e))return So.validate(t,e);throw new Error("Invalid schema")},bt=async e=>{if(await wo.canHandle(e))return wo.transformToJsonSchema(e);if(await So.canHandle(e))return So.transformToJsonSchema(e);throw new Error("Invalid schema")};function Hm(){return["development",void 0,"dev"].includes(process.env.NODE_ENV)}var dr=class{constructor(t){this.discoveredWorkflows=new Map;this.discoverWorkflowPromises=new Map;this.registeredAgents=new Map;this.version="2.14.0";let n=this.buildOptions(t);this.apiUrl=n.apiUrl,this.secretKey=n.secretKey,this.strictAuthentication=n.strictAuthentication,this.verbose=n.verbose,this.logger=n.logger,this.templateEngine=Cm()}buildOptions(t){let n={apiUrl:po(t==null?void 0:t.apiUrl),secretKey:ho(t==null?void 0:t.secretKey),strictAuthentication:!Hm(),verbose:Hm(),logger:console};return(t==null?void 0:t.strictAuthentication)!==void 0?n.strictAuthentication=t.strictAuthentication:process.env.NOVU_STRICT_AUTHENTICATION_ENABLED!==void 0&&(n.strictAuthentication=process.env.NOVU_STRICT_AUTHENTICATION_ENABLED==="true"),(t==null?void 0:t.verbose)!==void 0&&(n.verbose=t.verbose),(t==null?void 0:t.logger)!==void 0&&(n.logger=t.logger),n}log(...t){this.verbose&&this.logger.info(...t)}async addWorkflows(t){for(let n of t){if(this.discoveredWorkflows.has(n.id))continue;let r=this.discoverWorkflowPromises.get(n.id);if(r){await r;continue}let i=this.addWorkflow(n);this.discoverWorkflowPromises.set(n.id,i),await i}}addAgents(t){for(let n of t)this.registeredAgents.set(n.id,n)}getAgent(t){return this.registeredAgents.get(t)}async addWorkflow(t){try{let n=await t.discover();Om(n,this.verbose,this.logger),this.discoveredWorkflows.set(t.id,n)}finally{this.discoverWorkflowPromises.delete(t.id)}}healthCheck(){let t=this.getRegisteredWorkflows(),n=t.length,r=t.reduce((i,a)=>i+a.steps.length,0);return{status:"ok",sdkVersion:"2.14.0",frameworkVersion:"2024-06-26",discovered:{workflows:n,steps:r}}}getWorkflow(t){let n=this.discoveredWorkflows.get(t);if(n)return n;throw new Pr(t)}getStep(t,n){let i=this.getWorkflow(t).steps.find(a=>a.stepId===n);if(i)return i;throw new la(n)}getRegisteredWorkflows(){return Array.from(this.discoveredWorkflows.values())}discover(){return{workflows:this.getRegisteredWorkflows(),agents:Array.from(this.registeredAgents.keys()).map(t=>({agentId:t}))}}mock(t){try{return Pu(t)}catch(n){return this.logger.warn("Failed to mock schema, returning empty object:",n),{}}}async validate(t,n,r,i,a,o,s){let c=await Ai(n,t);if(c.success)return c.data;switch(r){case"event":this.throwInvalidEvent(i,a,c.errors);case"step":this.throwInvalidStep(o,i,a,c.errors);case"provider":this.throwInvalidProvider(o,s,i,a,c.errors);default:throw new Error(`Invalid component: '${r}'`)}}throwInvalidProvider(t,n,r,i,a){throw t?n?r==="output"?new Gi(i,t,n,a):new Error(`Invalid payload type: '${r}'`):new Error("providerId is required"):new Error("stepId is required")}throwInvalidStep(t,n,r,i){if(!t)throw new Error("stepId is required");switch(n){case"output":throw new Wi(r,t,i);case"result":throw new Yi(r,t,i);case"controls":throw new Vi(r,t,i);default:throw new Error(`Invalid payload type: '${n}'`)}}throwInvalidEvent(t,n,r){switch(t){case"controls":throw new zi(n,r);case"payload":throw new _r(n,r);default:throw new Error(`Invalid payload type: '${t}'`)}}executeStepFactory(t,n,r){return async(i,a,o)=>{if(r())return;let s=this.getStep(t.workflowId,i),c=t.action==="preview";if(!c&&i===t.stepId){let g=await this.createStepControls(s,t),I=await this.compileControls(g,t);if(await this.shouldSkip(o==null?void 0:o.skip,I))return n({options:{skip:!0},outputs:{},providers:{}}),{}}let p=this.previewStep.bind(this),d=this.executeStep.bind(this),y=await(c?p:d)(t,{...s,providers:s.providers.map(g=>{var K;let I=(K=o==null?void 0:o.providers)==null?void 0:K[g.type];if(!I)throw new ta(g.type);return{...g,resolve:I}}),resolve:a});return this.shouldSanitize({stepType:s.type,options:o})&&(y={...y,outputs:fo(y.outputs)}),i===t.stepId&&n({...y,options:{skip:!1}}),y.outputs}}shouldSanitize({stepType:t,options:n}){return(n==null?void 0:n.disableOutputSanitization)===!0?!1:["email","in_app"].includes(t)}async shouldSkip(t,n){return t?t(n):!1}async executeWorkflow(t){let i=`${{execute:"Executing",preview:"Previewing"}[t.action]||t.action} workflowId:`;this.log(`
157
157
  ${et.bold(et.underline(i))} '${t.workflowId}'`);let a=this.getWorkflow(t.workflowId),o=process.hrtime(),s={outputs:{},providers:{},options:{skip:!1}},c,p=!1,d=new Promise(_e=>{c=_e}),h=_e=>{if(p)throw new Error("setResult can only be called once per workflow execution");c(),p=!0,s=_e},y=()=>p,g;try{if(t.action==="execute"&&!t.payload)throw new _r(t.workflowId,{message:"Event `payload` is required"});let _e=await this.createExecutionPayload(t,a),$={...t,payload:_e};await Promise.race([d,a.execute({payload:_e,env:t.env,controls:{},subscriber:t.subscriber,context:t.context,step:{email:this.executeStepFactory($,h,y),sms:this.executeStepFactory($,h,y),inApp:this.executeStepFactory($,h,y),digest:this.executeStepFactory($,h,y),delay:this.executeStepFactory($,h,y),push:this.executeStepFactory($,h,y),chat:this.executeStepFactory($,h,y),custom:this.executeStepFactory($,h,y),throttle:this.executeStepFactory($,h,y),tool:this.executeStepFactory($,h,y)}})])}catch(_e){g=_e}let I=process.hrtime(o),K=I[0],Z=I[1],H=K*1e3+Z/1e6,ue=g?lt.ERROR:lt.SUCCESS,ve={execute:"Executed",preview:"Previewed"}[t.action]||t.action;if(this.log(`${ue} ${ve} workflowId: \`${t.workflowId}\``),this.prettyPrintExecute(t,H,g),g)throw g;return{outputs:s.outputs,providers:s.providers,options:s.options,metadata:{status:"success",error:!1,duration:H}}}async createExecutionPayload(t,n){let{payload:r}=t;if(t.action==="preview"){let a=this.mock(n.payload.schema);r=Object.assign(a,r)}return await this.validate(r,n.payload.unknownSchema,"event","payload",t.workflowId)}prettyPrintExecute(t,n,r){if(!this.verbose)return;let i=r?lt.ERROR:lt.SUCCESS,o={execute:"Executed",preview:"Previewed"}[t.action]||t.action,s=r?"Failed to execute":o,c=r?et.error:et.success,p=`${i} ${s} workflowId: '${t.workflowId}`;this.logger.info(`
158
158
  ${et.bold(c(p))}'
159
159
  \u251C ${lt.STEP} stepId: '${t.stepId}'
160
160
  \u251C ${lt.ACTION} action: '${t.action}'
161
161
  \u2514 ${lt.DURATION} duration: '${n.toFixed(2)}ms'
162
- `)}async executeProviders(t,n,r,i){return n.providers.reduce(async(a,o)=>{let s=await a,c=await this.runProvider(t,n,o,r,i);return{...s,[o.type]:c}},Promise.resolve({}))}async runProvider(t,n,r,i,a){let o=t.action==="preview";if(t.stepId!==n.stepId)return o?(this.log(` ${lt.MOCK} Mocked provider: \`${r.type}\``),this.mock(r.outputs.schema)):(this.log(` ${lt.HYDRATED} Hydrated provider: \`${r.type}\``),{});try{return await this.resolveProviderOutput(t,n,r,a,i)}catch(s){if(this.log(` ${lt.ERROR} Failed to execute provider: \`${r.type}\``),o)return this.log(` ${lt.MOCK} Mocked provider: \`${r.type}\``),this.mock(r.outputs.schema);throw new na(r.type,t.action,s)}}async resolveProviderOutput(t,n,r,i,a){let o=await r.resolve({controls:i,outputs:a}),s=await this.validate(o,r.outputs.unknownSchema,"step","output",t.workflowId,n.stepId,r.type);return this.log(` ${lt.SUCCESS} Executed provider: \`${r.type}\``),{...s,_passthrough:o._passthrough}}async executeStep(t,n){if(t.stepId===n.stepId)try{let r=await this.createStepControls(n,t),i=await this.compileControls(r,t),a=await n.resolve(i),o=await this.normalizeChatCardOutput(n,a),s=await this.validate(o,n.outputs.unknownSchema,"step","output",t.workflowId,n.stepId),c=await this.executeProviders(t,n,s,i);return this.log(` ${lt.SUCCESS} Executed stepId: \`${n.stepId}\``),{outputs:s,providers:c}}catch(r){throw this.log(` ${lt.ERROR} Failed to execute stepId: \`${n.stepId}\``),Mn(r)?r:new Ir(n.stepId,t.action,r)}else try{let r=this.getStepState(t,n.stepId);if(r){let i=await this.validate(r.outputs,n.results.unknownSchema,"step","result",t.workflowId,n.stepId);return this.log(` ${lt.HYDRATED} Hydrated stepId: \`${n.stepId}\``),{outputs:i,providers:await this.executeProviders(t,n,i,{})}}else throw new Bi(t.workflowId,n.stepId)}catch(r){throw this.log(` ${lt.ERROR} Failed to hydrate stepId: \`${n.stepId}\``),r}}async normalizeChatCardOutput(t,n){if(t.type!=="chat"||(n==null?void 0:n.card)==null)return n;let r=await lo(n.card);return r?{...n,card:r}:n}async compileControls(t,n){var r;try{let i=Ti(t),a=this.preprocessTranslationPatterns(JSON.stringify(i));a=this.preprocessFilterTranslationArgs(a);let o=this.templateEngine.parse(a),s=this.getWorkflow(n.workflowId),c={workflow:{workflowId:s.workflowId,name:s.name,description:s.description,tags:s.tags,severity:s.severity},payload:n.payload,subscriber:n.subscriber,...n.actor&&{actor:n.actor},context:n.context,steps:zx(n.state),env:(r=n.env)!=null?r:{}},p=await this.templateEngine.render(o,c),d=this.postprocessTranslationMarkers(p),h=(0,$m.jsonrepair)(d),y=JSON.parse(h),g=xi(y);return Lm(g)}catch(i){throw new Ji(n.workflowId,n.stepId,i)}}preprocessTranslationPatterns(t){return t.replace(/\{\{\s*t\.([\p{L}\p{N}_.-]+)\s*\}\}/gu,"[T:$1]")}preprocessFilterTranslationArgs(t){return t.replace(/'t\.([\p{L}\p{N}_.-]+)'/gu,"'[T:$1]'")}postprocessTranslationMarkers(t){return t.replace(/\[T:([\p{L}\p{N}_.-]+)\]/gu,"{{t.$1}}")}async createStepControls(t,n){return await this.validate(n.controls,t.controls.unknownSchema,"step","controls",n.workflowId,t.stepId)}async previewStep(t,n){try{return await this.constructStepForPreview(t,n)}catch(r){throw this.log(` ${lt.ERROR} Failed to preview stepId: \`${n.stepId}\``),Mn(r)?r:new Ir(n.stepId,t.action,r)}}async constructStepForPreview(t,n){return t.stepId===n.stepId?await this.previewRequiredStep(n,t):await this.extractMockDataForPreviousSteps(t,n)}async extractMockDataForPreviousSteps(t,n){let r={},i=this.getStepState(t,n.stepId),a=this.mock(n.results.schema);return{outputs:pc(a,(i==null?void 0:i.outputs)||{}),providers:await this.executeProviders(t,n,r,{})}}async previewRequiredStep(t,n){let r=await this.createStepControls(t,n),i=await this.compileControls(r,n),a=await t.resolve(i),o=await this.normalizeChatCardOutput(t,a),s=await this.validate(o,t.outputs.unknownSchema,"step","output",n.workflowId,t.stepId);return this.log(` ${lt.MOCK} Mocked stepId: \`${t.stepId}\``),{outputs:s,providers:await this.executeProviders(n,t,s,i)}}getStepState(t,n){return t.state.find(r=>r.stepId===n)}getStepCode(t,n){return{code:this.getStep(t,n).resolve.toString()}}getWorkflowCode(t){return{code:this.getWorkflow(t).execute.toString()}}getCode(t,n){let r;if(t)n?r=this.getStepCode(t,n):r=this.getWorkflowCode(t);else throw new Pr(t);return r}};function zx(e){let t={};for(let n of e)t[n.stepId]=n.outputs;return t}var qm=Symbol.for("novu.agent.runtimeContext");var hc=(o=>(o.ON_MESSAGE="onMessage",o.ON_MESSAGE_UPDATED="onMessageUpdated",o.ON_MESSAGE_DELETED="onMessageDeleted",o.ON_ACTION="onAction",o.ON_RESOLVE="onResolve",o.ON_REACTION="onReaction",o))(hc||{});function fc(e){return typeof e=="object"&&e!==null&&"content"in e&&!("type"in e)}var hr=class{constructor(){this.__novuPendingApproval=!0}};function jm(e){return typeof e=="object"&&e!==null&&"suppress"in e&&e.suppress===!0}var Vx=5*1024*1024,Wx=5*1024*1024,Bm=32768,Yx=/^[A-Za-z0-9+/]*={0,2}$/;function ki(e,t){return e.filename?`"${e.filename}"`:`at index ${t}`}function zm(){return globalThis.Buffer}function Jx(e){var t,n,r;return(r=(n=(t=zm())==null?void 0:t.isBuffer)==null?void 0:n.call(t,e))!=null?r:!1}function Gx(e){return typeof Blob!="undefined"&&e instanceof Blob}function mc(e){let t=zm();if(t)return t.from(e).toString("base64");if(typeof btoa!="function")throw new Error("Unable to encode file data: base64 encoding is not available in this runtime.");let n="";for(let r=0;r<e.length;r+=Bm){let i=e.subarray(r,r+Bm);n+=String.fromCharCode(...i)}return btoa(n)}function Vm(e){let t=e.replace(/\s/g,""),n=t.length%4;if(!t||n===1||!Yx.test(t))return null;let r=t.endsWith("==")?2:t.endsWith("=")?1:0;return Math.floor(t.length*3/4)-r}function vi(e,t,n){if(e>Vx)throw new Error(`Invalid file ${ki(t,n)}: inline data must be 5 MB or smaller. Use a publicly-accessible URL for larger files.`)}async function Kx(e,t,n){if(typeof e=="string"){let r=Vm(e);if(r===null)throw new Error(`Invalid file ${ki(t,n)}: data must be a base64-encoded string.`);return vi(r,t,n),e}if(Jx(e))return vi(e.byteLength,t,n),e.toString("base64");if(e instanceof Uint8Array)return vi(e.byteLength,t,n),mc(e);if(e instanceof ArrayBuffer)return vi(e.byteLength,t,n),mc(new Uint8Array(e));if(Gx(e))return vi(e.size,t,n),mc(new Uint8Array(await e.arrayBuffer()));throw new Error(`Invalid file ${ki(t,n)}: data must be a base64 string, Buffer, Uint8Array, ArrayBuffer, or Blob.`)}async function Xx(e){if(!(e!=null&&e.length))return;let t=[],n=0;for(let[r,i]of e.entries()){let a=i.data,o=i.url,s=a!=null,c=o!=null;if(s===c)throw new Error(`Invalid file ${ki(i,r)}: provide exactly one of data or url.`);if(s){let p=await Kx(a,i,r),d=Vm(p);if(n+=d!=null?d:0,n>Wx)throw new Error("Invalid files: total inline data must be 5 MB or smaller. Use publicly-accessible URLs for larger files.");t.push({...i,data:p});continue}if(c&&typeof o!="string")throw new Error(`Invalid file ${ki(i,r)}: url must be a string.`);t.push(i)}return t}async function To(e,t){let n=await Xx(t);if(typeof e=="string")return n?{markdown:e,files:n}:{markdown:e};let r=await lo(e);if(r)return n?{card:r,files:n}:{card:r};throw new Error("Invalid message content \u2014 expected string or CardElement")}var Wm=1;var Qx={400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",408:"Request Timeout",409:"Conflict",422:"Unprocessable Entity",429:"Too Many Requests",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout"};function xo(e){return typeof e=="string"&&e.trim()?e:!e||typeof e!="object"?null:xo(e.message)}function Zx(e){if(!e)return null;let t;try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!="object")return null;let n=t,r=xo(n.message);if(r)return r;let i=xo(n.error);if(i)return i;let a=n.errors;return Array.isArray(a)?xo(a[0]):null}function eA(e,t){var i;let n=(i=Qx[e])!=null?i:e,r=Zx(t);return r?`Delivery failed: ${n}: ${r}`:`Delivery failed: ${n}`}var bn=class extends Error{constructor(t,n){super(t),this.name="AgentError",this.cause=n==null?void 0:n.cause,this.delivery=n==null?void 0:n.delivery}},an=class extends bn{constructor(t,n){let r={statusCode:t,responseBody:n};super(eA(t,n),{delivery:r}),this.name="AgentDeliveryError",this.statusCode=t,this.responseBody=n}};function Ei(e){return e instanceof bn?e:e instanceof Error?new bn(e.message,{cause:e}):new bn("Turn failed",{cause:e})}function tA(e){return new Promise(t=>{setTimeout(t,e)})}function nA(e){return e>=500||e===408||e===429}var Ao=class{constructor(t){this.sequence=0;this.buffer=[];this.chain=Promise.resolve();var n,r;this.runId=`run_${crypto.randomUUID()}`,this.eventsUrl=t.eventsUrl,this.secretKey=t.secretKey,this.conversationId=t.conversationId,this.agentId=t.agentId,this.turnId=t.turnId,this.fetchFn=(n=t.fetchFn)!=null?n:fetch,this.maxRetries=(r=t.maxRetries)!=null?r:3}enqueue(t){this.sequence+=1,this.buffer.push({version:Wm,conversationId:this.conversationId,agentId:this.agentId,runId:this.runId,turnId:this.turnId,sequence:this.sequence,timestamp:new Date().toISOString(),event:t})}flush(){if(this.buffer.length===0)return this.chain;let t=this.buffer;return this.buffer=[],this.chain=this.chain.then(()=>this.postBatchWithRetry(t)),this.chain}async emit(t){this.enqueue(t),await this.flush()}async postBatchWithRetry(t){let n;for(let r=1;r<=this.maxRetries;r+=1)try{await this.postBatch(t);return}catch(i){if(n=i,!rA(i))throw i;r<this.maxRetries&&await tA(250*r)}throw n}async postBatch(t){let n;try{n=await this.fetchFn(this.eventsUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${this.secretKey}`},body:JSON.stringify({events:t})})}catch(i){throw iA(i)}let r=await n.text().catch(()=>"");if(!n.ok)throw new an(n.status,r)}};function rA(e){return!(e instanceof an)||e.statusCode===0?!0:nA(e.statusCode)}function iA(e){if(e instanceof an)return e;let t=e instanceof Error?e.message:"Network request failed";return new an(0,t)}var gc="human:";function vo(e){return`${gc}${e}:approve`}function ko(e){return`${gc}${e}:deny`}function fr(e,t){return`${gc}${e}:opt:${t}`}function Ym(e){return typeof e=="string"?e:e.label}function aA(e){return typeof e=="string"?void 0:e.id}function oA(e){return typeof e=="string"?e:e.id}function Ro(e,t){let n=t==null?void 0:t.trim();if(!n)throw new Error(`ctx.${e} requires a title (string argument or card.title)`);return n}function sA(e){if(!("title"in e))return;let t=e.title;return typeof t=="string"&&t.trim()?t.trim():void 0}function Co(e){if(!e||e.length<2||e.length>10)throw new Error("ctx.choose requires between 2 and 10 options");if(e.some(t=>Ym(t).trim().length===0))throw new Error("ctx.choose options must be non-empty strings")}function _o(e){if(e.length>4)throw new Error("ctx.approve card.extraActions supports at most 4 buttons");for(let t of e){let n=aA(t);if(!Ym(t).trim())throw new Error("ctx.approve extraActions labels must be non-empty");if(n==="approve"||n==="deny")throw new Error("ctx.approve extraActions ids cannot be approve or deny")}}function lA(e){if(typeof e=="string")throw new Error("human render must return chrome (*Card()), a Card, or a chat element \u2014 not a markdown string")}function Eo(e,t=[]){if(Array.isArray(e)){for(let r of e)Eo(r,t);return t}if(!e||typeof e!="object")return t;let n=e;n.type==="button"&&typeof n.id=="string"&&n.id.trim()&&t.push({id:n.id,label:typeof n.label=="string"?n.label:""});for(let r of Object.values(n))r&&typeof r=="object"&&Eo(r,t);return t}function cA(e){return new Set(Eo(e).map(t=>t.id))}function uA(e,t){let n=fr(t,"");return e.startsWith(n)&&e.length>n.length?e.slice(n.length):e}function pA(e,t){let n=Eo(e),r=new Set(n.map(s=>s.id)),i=vo(t),a=ko(t);if(!r.has(i))throw new Error("ctx.approve render must include a button with actionIds.approve");if(!r.has(a))throw new Error("ctx.approve render must include a button with actionIds.deny");let o=n.filter(s=>s.id!==i&&s.id!==a).map(s=>({id:uA(s.id,t),label:s.label}));o.length&&_o(o)}function dA(e,t,n){if(n){Co(n);for(let i of n){let a=oA(i);if(!e.has(fr(t,a)))throw new Error(`ctx.choose render must include a button with actionIds.option('${a}')`)}return}let r=hA(e,t);if(r.length<2||r.length>10)throw new Error("ctx.choose render must include between 2 and 10 option action buttons")}function hA(e,t){let n=fr(t,"");return[...e].filter(r=>r.startsWith(n)&&r.length>n.length).map(r=>r.slice(n.length))}function Jm(e,t,n){var r;switch(Ro(e,t.title),e){case"ask":case"tell":return;case"approve":t.type==="human-approve-card"&&t.extraActions&&_o(t.extraActions);return;case"choose":Co(t.type==="human-choose-card"&&(r=t.options)!=null?r:n);return;default:return}}function Gm(e,t,n,r){switch(lA(t),Ro(e,sA(t)),e){case"ask":case"tell":return;case"approve":pA(t,n);return;case"choose":dA(cA(t),n,r);return;default:return}}function Oo(e){let t=typeof e=="string"?[e]:e,n=[],r=new Set;for(let i of t){if(typeof i!="string")throw new Error("`to` must be a subscriberId string or an array of subscriberIds");let a=i.trim();!a||r.has(a)||(r.add(a),n.push(a))}if(n.length===0)throw new Error("`to` must include at least one subscriberId");if(n.length>50)throw new Error("`to` supports at most 50 subscriberIds");return n}var Km="tool-approval";function fA(e){return e==="approve"||e==="deny"}function yc(e,t){return`${Km}:${e}:${t}`}function Xm(e){let[t,n,...r]=(e!=null?e:"").split(":"),i=r.join(":");return t!==Km||!fA(n)||!i?null:{approved:n==="approve",approvalId:i}}async function Qm(e,t,n,r,i){var d,h;let a=r!=null?r:t.id,o={approve:yc("approve",a),deny:yc("deny",a)},s=y=>({type:"tool-approval-card",...y}),c=(h=(d=n==null?void 0:n.renderApproval)==null?void 0:d.call(n,{toolCall:t,actionIds:o,approvalCard:s}))!=null?h:s(),p={approvalId:a,toolCallId:t.id,name:t.name,input:t.input,...(i==null?void 0:i.to)!==void 0?{to:i.to}:{},...i!=null&&i.from?{from:i.from}:{},...(i==null?void 0:i.ttlSeconds)!==void 0?{ttlSeconds:i.ttlSeconds}:{}};if(e.emitToolApprovalRequest(p),hm(c)){await e.replyApprovalCard(c);return}await e.reply(c)}function Io(e){return t=>({type:e,...t})}function Po(e,t){switch(e){case"ask":return{requestId:t,askCard:Io("human-ask-card")};case"approve":return{requestId:t,actionIds:{approve:vo(t),deny:ko(t)},approveCard:Io("human-approve-card")};case"choose":return{requestId:t,actionIds:{option:n=>fr(t,n)},chooseCard:Io("human-choose-card")};case"tell":return{requestId:t,tellCard:Io("human-tell-card")};default:return e}}function Sc(e){return`${e}_${crypto.randomUUID()}`}function mA(e){let{type:t,...n}=e;return n}function gA(e){if(!(!e||!("card"in e)))return e.card}function Mo(e){if(!(!e||!("render"in e)))return e.render}function yA(e){return typeof e=="object"&&e!==null&&pr(e)?e:{type:"card",children:[e]}}function bc(e){if(!(!e||!("ttlSeconds"in e)||typeof e.ttlSeconds!="number"))return e.ttlSeconds}function Zm(e){if(e.markdown!==void 0)return{markdown:e.markdown};if(e.card!==void 0)return{card:e.card};throw new Error("Invalid reply content \u2014 expected markdown or card")}function bA(e){let t="platformMessageId"in e?e.platformMessageId.trim():e.messageId.trim();if(!t)throw new Error("quoteReply requires a non-empty platform message id");return{messageId:t}}function eg(e){if(e!=null&&e.length)return e.map((t,n)=>({fileId:t.filename||`file_${n}`,name:t.filename,mediaType:t.mimeType,...t.data!==void 0?{data:typeof t.data=="string"?t.data:void 0}:{},...t.url!==void 0?{url:t.url}:{}}))}function wc(e,t){var r;let n=[];if(e.toolApprovalRequest){let i=e.toolApprovalRequest;n.push({type:"tool-approval-request",approvalId:i.approvalId,toolUseId:i.toolCallId,toolName:i.name,input:i.input,...i.ttlSeconds!==void 0?{ttlSeconds:i.ttlSeconds}:{},...i.to!==void 0?{to:i.to}:{},...i.from!==void 0?{from:i.from}:{},...t!=null&&t.deliverApprovalCard?{deliverCard:!0}:{}})}for(let i of e.toolResults)n.push({type:"tool-use-result",toolUseId:i.toolCallId,content:[{type:"text",text:String((r=i.preview)!=null?r:"")},{type:"json",value:i.output}]});for(let i of e.signals)n.push({type:"signal",signal:i});for(let i of e.addReactions)n.push({type:"channel.reaction",messageId:i.messageId,emoji:i.emojiName,op:"add"});for(let i of e.deleteMessages)n.push({type:"channel.delete",messageId:i.messageId});return e.resolve&&n.push({type:"resolve",summary:e.resolve.summary}),n}var Tc=class{constructor(t){this.outbox=t}async sendReply(t,n,r){let i=Sc("msg"),a=wc(n);return a.push({type:"message",role:"assistant",messageId:i,content:Zm(t),files:eg(t.files),...r?{quoteReply:r}:{}}),await this._emitAndFlush(a),{messageId:i,platformThreadId:""}}async sendApprovalCard(t,n){return await this._emitAndFlush(wc(n,{deliverApprovalCard:!0})),"unaddressable"}async editMessage(t,n){return await this.outbox.emit({type:"channel.edit",messageId:t,content:Zm(n),files:eg(n.files)}),{messageId:t,platformThreadId:""}}async deleteMessage(t){await this.outbox.emit({type:"channel.delete",messageId:t})}async setTyping(t){if(t==="stop"){await this.outbox.emit({type:"channel.typing",state:"off"});return}let n=typeof t=="object"&&"status"in t?t.status:void 0;await this.outbox.emit({type:"channel.typing",state:"on",status:n})}async flushSideEffects(t){await this._emitAndFlush(wc(t))}async emitCustom(t,n){await this.outbox.emit({type:"custom",name:t,data:n})}queueRunStart(){this.outbox.enqueue({type:"run-start"})}async emitRunFinish(t){await this.outbox.emit({type:"run-finish",outcome:t})}async reportTurnError(t){await this.outbox.emit({type:"run-error",message:t!=null?t:"agent handler failed"})}async _emitAndFlush(t){if(t.length!==0){for(let n of t)this.outbox.enqueue(n);await this.outbox.flush()}}},No=class{constructor(t,n,r){this.transport=r;this.editedByHandler=!1;this.messageId=t,this.platformThreadId=n}async edit(t,n){this.editedByHandler=!0;let r=await To(t,n==null?void 0:n.files),i=await this.transport.editMessage(this.messageId,r);if(!i)throw new Error("Agent edit did not return a message handle");return this.messageId=i.messageId,this.platformThreadId=i.platformThreadId,this}async delete(){await this.transport.deleteMessage(this.messageId)}},xc=class{constructor(){this.messageId="";this.platformThreadId=""}async edit(){return this}async delete(){}},tg;tg=qm;var Lo=class{constructor(t,n,r){this[tg]=!0;this._signals=[];this._toolResults=[];this._pendingToolApprovalRequest=null;this._pendingReactions=[];this._pendingDeletes=[];this._resolveSignal=null;this._pendingHumanRenders=[];var c,p,d,h,y,g;this.event=t.event,this.action=(c=t.action)!=null?c:null,this.message=t.message,this.previousMessage=(p=t.previousMessage)!=null?p:null,this.reaction=t.reaction,this.conversation=t.conversation,this.subscriber=t.subscriber,this.context=(d=t.context)!=null?d:null,this.notification=(h=t.notification)!=null?h:null,this.history=t.history,this.platform=t.platform,this.platformContext=t.platformContext,this.humanResponse=(y=t.humanResponse)!=null?y:null,this._toolApprovalConfig=r;let i=t.eventsUrl;if(!i)throw new Error("AgentBridgeRequest.eventsUrl is required");this._transport=new Tc(new Ao({eventsUrl:i,secretKey:n,conversationId:t.conversationId,agentId:t.agentId,turnId:t.deliveryId})),this._metadataState={...(g=t.conversation.metadata)!=null?g:{}};let a=this;this.metadata={get(I){return a._metadataState[I]},set(I,K){a._metadataState[I]=K,a._signals.push({type:"metadata",action:"set",key:I,value:K})},delete(I){delete a._metadataState[I],a._signals.push({type:"metadata",action:"delete",key:I})},clear(){a._metadataState={},a._signals.push({type:"metadata",action:"clear"})},get current(){return{...a._metadataState}}};let o=I=>this._transport.setTyping(I),s=(I=>o(I===void 0?{}:{status:I}));s.stop=()=>o("stop"),this.typing=s,this.toolApproval={request:async(I,K)=>(await Qm(this,I,this._toolApprovalConfig,void 0,K),new hr)}}asMessageContext(){return this}async reply(t,n){await this.materializePendingHumanRenders();let r=await To(t,n==null?void 0:n.files),i=this._drainSideEffectsSnapshot(),a=n!=null&&n.quoteReply?bA(n.quoteReply):void 0,o=await this._transport.sendReply(r,i,a);if(!o)throw new Error("Agent reply did not return a message handle");return new No(o.messageId,o.platformThreadId,this._transport)}async replyApprovalCard(t){await this.materializePendingHumanRenders();let n=this._drainSideEffectsSnapshot();return await this._transport.sendApprovalCard(t,n),new xc}createReplyHandle(t){return new No(t,"",this._transport)}async emit(t){await this._transport.emitCustom(t.name,t.data)}resolve(t){this._resolveSignal={summary:t}}trigger(t,n){this._signals.push({...n,type:"trigger",workflowId:t})}ask(t,n){let i=typeof t!="string"?t:n,a=Mo(i);return a?this.queueRendered("ask",i,a):this.queueHumanSignal("ask",t,n)}approve(t,n){let i=typeof t!="string"?t:n,a=Mo(i);return a?this.queueRendered("approve",i,a):this.queueHumanSignal("approve",t,n)}choose(t,n,r){var c;let i=typeof t!="string",a,o;i?a=t:Array.isArray(n)?(a=r,o=n):a=n;let s=Mo(a);return s?this.queueRendered("choose",a,s):i?this.queueHumanSignal("choose",t,void 0,"card"in t?(c=t.card)==null?void 0:c.options:void 0):this.queueHumanSignal("choose",t,a,o)}tell(t,n){let r=typeof t!="string",i=r?t:n,a=Mo(i);if(a)return this.queueRendered("tell",i,a);if(r)throw new Error("ctx.tell requires a title (string argument) when render is omitted");return this.queueHumanSignal("tell",t,n)}queueHumanSignal(t,n,r,i){let a=typeof n!="string",o=a?void 0:n,s=a?n:r,c=gA(s),p=Ro(t,(o==null?void 0:o.trim())||(c==null?void 0:c.title));if(t==="choose"){let I=i!=null?i:c==null?void 0:c.options;Co(I)}t==="approve"&&(c!=null&&c.extraActions)&&_o(c.extraActions);let d=Sc("hr"),h=(s==null?void 0:s.to)!==void 0?Oo(s.to):void 0,y={...c,title:p,...t==="choose"&&i?{options:i}:{}},g=bc(s);return this._signals.push({type:"human",kind:t,requestId:d,card:y,...s!=null&&s.from?{from:s.from}:{},...g!==void 0?{ttlSeconds:g}:{},...h!==void 0?{to:h}:{}}),d}queueRendered(t,n,r){let i=Sc("hr");return this._pendingHumanRenders.push(async()=>{let a=await this.invokeHumanRender(t,i,r);if(fm(a)){this.pushRenderedChrome(t,i,a,n);return}await this.pushRenderedContent(t,i,a,n)}),i}invokeHumanRender(t,n,r){switch(t){case"ask":return Promise.resolve(r(Po("ask",n)));case"approve":return Promise.resolve(r(Po("approve",n)));case"choose":return Promise.resolve(r(Po("choose",n)));case"tell":return Promise.resolve(r(Po("tell",n)));default:{let i=t;return Promise.resolve(i)}}}pushRenderedChrome(t,n,r,i){Jm(t,r);let a=mA(r),o=bc(i),s=(i==null?void 0:i.to)!==void 0?Oo(i.to):void 0,c=t==="approve"||t==="choose";this._signals.push({type:"human",kind:t,requestId:n,...c?{actionIdentifier:n}:{},card:a,...i!=null&&i.from?{from:i.from}:{},...o!==void 0?{ttlSeconds:o}:{},...s!==void 0?{to:s}:{}})}async pushRenderedContent(t,n,r,i){Gm(t,r,n);let a=await To(yA(r));if(!a.card)throw new Error("human render must return chrome (*Card()), a Card, or a chat element \u2014 not a markdown string");let o=bc(i),s=(i==null?void 0:i.to)!==void 0?Oo(i.to):void 0,c=t==="approve"||t==="choose";this._signals.push({type:"human",kind:t,requestId:n,...c?{actionIdentifier:n}:{},card:a.card,...i!=null&&i.from?{from:i.from}:{},...o!==void 0?{ttlSeconds:o}:{},...s!==void 0?{to:s}:{}})}emitToolApprovalRequest(t){if(this._pendingToolApprovalRequest)throw new Error("Only one tool approval request can be queued before the next reply");this._pendingToolApprovalRequest=t}emitToolResult(t){this._toolResults.push(t)}addReaction(t,n){this._pendingReactions.push({messageId:t,emojiName:n})}deleteMessage(t){this._pendingDeletes.push({messageId:t})}queueRunStart(){this._transport.queueRunStart()}async emitRunFinish(t){try{await this._transport.emitRunFinish(t.outcome)}catch(n){console.error("[agent] Failed to emit run finish:",n)}}async reportTurnError(t){try{await this._transport.reportTurnError(t)}catch(n){console.error("[agent] Failed to report turn error:",n)}}async flush(){if(await this.materializePendingHumanRenders(),!this._hasPendingSideEffects())return;let t=this._drainSideEffectsSnapshot();await this._transport.flushSideEffects(t)}async materializePendingHumanRenders(){let t=this._pendingHumanRenders.splice(0);for(let n of t)await n()}_hasPendingSideEffects(){return!!(this._pendingToolApprovalRequest||this._signals.length||this._toolResults.length||this._resolveSignal||this._pendingReactions.length||this._pendingDeletes.length)}_drainSideEffectsSnapshot(){let t={toolApprovalRequest:this._pendingToolApprovalRequest,signals:this._signals,toolResults:this._toolResults,addReactions:this._pendingReactions,deleteMessages:this._pendingDeletes,resolve:this._resolveSignal};return this._pendingToolApprovalRequest=null,this._signals=[],this._toolResults=[],this._pendingReactions=[],this._pendingDeletes=[],this._resolveSignal=null,t}};function wA(e){return!!(typeof e=="string"||typeof e=="object"&&e!==null&&pr(e)||typeof e=="object"&&e!==null&&("markdown"in e||"card"in e||"files"in e))}function SA(e,t){return e}var ng="tool_approval:";function TA(e){if(!(e!=null&&e.startsWith(ng)))return null;let t=e.slice(ng.length);return t.length>0?t:null}async function rg(e,t){await e.reply(t.content,{files:t.files,quoteReply:t.quoteReply})}async function Wn(e,t){if(!(t instanceof hr||t===void 0)){if(fc(t)){await rg(e,t);return}await e.reply(t)}}async function xA(e,t){return jm(t)?!0:fc(t)?(await rg(e,t),!0):wA(t)?(await e.reply(t),!0):!1}function AA(e,t){var n;for(let r of e){let i=r.toolData;if(r.type==="tool_approval_request"&&(i==null?void 0:i.approvalId)===t&&i.toolCallId)return{approvalId:i.approvalId,toolCallId:i.toolCallId,name:(n=i.toolName)!=null?n:"tool",input:i.input}}}async function ig(e){var a;let t=new Lo(e.bridge,e.secretKey,e.agent.handlers.toolApproval),{agent:n,event:r,logger:i}=e;try{t.queueRunStart(),await kA(n,r,t),await t.flush(),await t.emitRunFinish({outcome:"completed"})}catch(o){let s=Ei(o);i==null||i.error(`[agent:${n.id}] Turn failed (${r}): ${s.message}`,(a=s.cause)!=null?a:s);let c=!1;if(n.handlers.onError)try{let p=await n.handlers.onError(s,SA(t,r));c=await xA(t,p)}catch(p){i==null||i.error(`[agent:${n.id}] onError failed:`,p)}c?await t.emitRunFinish({outcome:"completed"}):await t.reportTurnError(s.message)}finally{try{await t.typing.stop(),await t.flush()}catch{}}}async function vA(e,t){var s,c,p,d,h,y;let n=TA((s=t.humanResponse)==null?void 0:s.requestId),r=Xm((c=t.action)==null?void 0:c.id),i=n!=null?n:r==null?void 0:r.approvalId,a=n?((p=t.humanResponse)==null?void 0:p.status)==="approved"&&!t.humanResponse.expired:r==null?void 0:r.approved;if(i&&a!==void 0&&e.handlers.onToolApproval){let g=AA(t.history,i),I=g?{id:g.toolCallId,name:g.name,input:g.input}:{id:i,name:""},K=t.createReplyHandle((h=(d=t.action)==null?void 0:d.sourceMessageId)!=null?h:""),Z={toolCall:I,approved:a,approvalMessage:K};e.userOnToolApproval===!1&&(await t.typing(),(y=t.action)!=null&&y.sourceMessageId&&await K.delete());let H=await e.handlers.onToolApproval(Z,t);await Wn(t,H);return}let o=t.action;o&&e.handlers.onAction&&await Wn(t,await e.handlers.onAction(o,t))}async function kA(e,t,n){switch(t){case"onMessage":{let r=n.message;r&&await Wn(n,await e.handlers.onMessage(r,n));break}case"onMessageUpdated":{let r=n.message;r&&e.handlers.onMessageUpdated&&await Wn(n,await e.handlers.onMessageUpdated(r,n));break}case"onMessageDeleted":{let r=n.message;r&&e.handlers.onMessageDeleted&&await Wn(n,await e.handlers.onMessageDeleted(r,n));break}case"onAction":{await vA(e,n);break}case"onReaction":{let r=n.reaction;r&&e.handlers.onReaction&&await Wn(n,await e.handlers.onReaction(r,n));break}case"onResolve":e.handlers.onResolve&&await Wn(n,await e.handlers.onResolve(n));break;default:throw new Nn(t,hc)}}function ag(e){let t={};for(let i of e.split(",")){let a=i.trim();if(!a)continue;let o=a.indexOf("=");if(o<=0)continue;let s=a.slice(0,o),c=a.slice(o+1);s&&c&&!(s in t)&&(t[s]=c)}let n=t.t,r=n!==void 0?Number(n):Number.NaN;return{t:Number.isFinite(r)?r:void 0,v1:t.v1}}var Do=class{constructor(t){this.handler=t.handler,this.client=t.client?t.client:new dr,this.workflows=t.workflows||[],this.agents=t.agents||[],this.http=co(this.client.secretKey,this.client.apiUrl),this.frameworkName=t.frameworkName,this.hmacEnabled=this.client.strictAuthentication,this.waitUntil=t.waitUntil,this.client.addAgents(this.agents)}createHandler(){return async(...t)=>{await this.client.addWorkflows(this.workflows);let n=await this.handler(...t),r=await this.handleAction({actions:n});return n.transformResponse(r)}}getStaticHeaders(){let t=`novu-framework:v${this.client.version}`;return{"content-type":"application/json","access-control-allow-origin":"*","access-control-allow-private-network":"true","access-control-allow-methods":"GET, POST","access-control-allow-headers":"*","access-control-max-age":"604800","novu-framework-version":"2024-06-26","novu-framework-sdk":"2.14.0-rc.5ea799b171","novu-framework-server":this.frameworkName,"user-agent":t}}createResponse(t,n){return{status:t,body:JSON.stringify(n),headers:{...this.getStaticHeaders()}}}createError(t){return{status:t.statusCode,body:JSON.stringify({message:t.message,data:t.data,code:t.code}),headers:this.getStaticHeaders()}}async handleAction({actions:t}){var h;let n=await t.url(),r=await t.method(),i=n.searchParams.get("action")||"health-check",a=n.searchParams.get("workflowId")||"",o=n.searchParams.get("stepId")||"",s=n.searchParams.get("agentId")||"",c=n.searchParams.get("event")||"",p=await t.headers("novu-signature")||"",d={};try{r==="POST"&&(d=await t.body())}catch{}try{i!=="health-check"&&await this.validateHmac(d,p);let y=this.getPostActionMap(d,a,o,i,s,c,(h=this.waitUntil)!=null?h:t.waitUntil),g=this.getGetActionMap(a,o);if(r==="POST")return await this.handlePostAction(i,y);if(r==="GET")return await this.handleGetAction(i,g);if(r==="OPTIONS")return this.createResponse(200,{})}catch(y){return this.handleError(y)}return this.createError(new Qi(r))}getPostActionMap(t,n,r,i,a,o,s){return{trigger:this.triggerAction({workflowId:n,...t}),execute:async()=>{let c=await this.client.executeWorkflow({...t,workflowId:n,stepId:r,action:i});return this.createResponse(200,c)},preview:async()=>{let c=await this.client.executeWorkflow({...t,workflowId:n,stepId:r,action:i});return this.createResponse(200,c)},"agent-event":async()=>{let c=this.client.getAgent(a);if(!c)return this.createResponse(404,{error:`Agent '${a}' not registered`});let p=ig({agent:c,event:o,bridge:t,secretKey:this.client.secretKey,logger:this.client.logger});return s?s(p):this.warnOnUnprotectedServerlessRuntime(a),this.createResponse(200,{status:"ack"})}}}warnOnUnprotectedServerlessRuntime(t){let n;try{process.env.AWS_LAMBDA_FUNCTION_NAME?n="AWS Lambda":process.env.VERCEL&&(n="Vercel")}catch{}n&&this.client.logger.warn(`[agent:${t}] Agent event acknowledged without a \`waitUntil\` primitive while running on ${n}. The runtime may freeze once the response is sent, silently dropping the rest of the agent turn. Pass \`waitUntil\` to \`serve()\` (e.g. \`serve({ agents, waitUntil })\`) to extend the invocation lifetime.`)}triggerAction(t){return async()=>{let n={name:t.workflowId,to:t.to,payload:(t==null?void 0:t.payload)||{},transactionId:t.transactionId,overrides:t.overrides||{},...t.actor&&{actor:t.actor},...t.bridgeUrl&&{bridgeUrl:t.bridgeUrl},...t.controls&&{controls:t.controls},...t.context&&{context:t.context},...t.agentId!==void 0&&{agentId:t.agentId}},r=await this.http.post("/events/trigger",n);return this.createResponse(200,r)}}getGetActionMap(t,n){return{discover:async()=>{let r=await this.client.discover();return this.createResponse(200,r)},"health-check":async()=>{let r=await this.client.healthCheck();return this.createResponse(200,r)},code:async()=>{let r=await this.client.getCode(t,n);return this.createResponse(200,r)}}}async handlePostAction(t,n){if(Object.values(Rr).includes(t)){let r=n[t];return r()}else throw new Nn(t,Rr)}async handleGetAction(t,n){if(Object.values(Hi).includes(t)){let r=n[t];return r()}else throw new Nn(t,Hi)}handleError(t){if(Mn(t))return t.statusCode>=500&&this.client.logger.error(t),this.createError(t);if(vu(t))return this.createError(t);{let n=new Xn(t);return this.client.logger.error(n),this.createError(n)}}async validateHmac(t,n){if(!this.hmacEnabled)return;if(!n)throw new ia;if(!this.client.secretKey)throw new sa;let r=ag(n);if(!r.v1||r.t===void 0)throw new aa;let i=Date.now();if(r.t<i-3e5||r.t>i+3e5)throw new oa;let a=await ym(this.client.secretKey,`${r.t}.${JSON.stringify(t)}`);if(!bm(a,r.v1))throw new ra}};function Ac(e,t){if(!e)throw new Error("agent() requires a non-empty agentId");if(!(t!=null&&t.onMessage))throw new Error(`agent('${e}') requires an onMessage handler`);return{id:e,handlers:t,userOnToolApproval:typeof t.onToolApproval=="function"}}var ae={output:{type:"object",properties:{},required:[],additionalProperties:!0}};var EA={type:"object",properties:{text:{type:"string",description:"Overrides the step body text."},effect:{type:"string",description:"iMessage expressive effect: a friendly name (confetti, fireworks, balloons, heart, lasers, celebration, sparkles, spotlight, echo, slam, loud, gentle, invisible) or a raw com.apple.\u2026 effect id."},attachments:{type:"array",items:{type:"string",format:"uri"},description:"Attachment URLs sent alongside the message."},voice:{type:"string",format:"uri",description:"Audio URL sent as a native iMessage voice note (waveform bubble)."},replyToLast:{type:"boolean",description:"Reply-thread this send to the previous message sent to this recipient."},format:{type:"string",enum:["markdown","text"],description:"Force native styled text (markdown) or plain text for the body."}},additionalProperties:!0},sg={output:EA};var RA={type:"object",properties:{webhookUrl:{type:"string",format:"uri"},text:{type:"string"},blocks:{type:"array",items:{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!0}}},additionalProperties:!0},lg={output:RA};var cg={"chat-webhook":ae,discord:ae,"google-chat":ae,getstream:ae,"grafana-on-call":ae,line:ae,mattermost:ae,msteams:ae,"novu-slack":ae,"novu-web-chat":ae,"photon-imessage":sg,"rocket-chat":ae,ryver:ae,sendblue:ae,slack:lg,"webex-messaging":ae,"whatsapp-business":ae,zulip:ae,telegram:ae};var CA={type:"object",properties:{to:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}],description:'Email address of the recipient(s). Example: "Bob bob@host.com". You can use commas to separate multiple recipients (e.g.: "test@example.com,test@example.com" or ["test@example.com", "test@example.com"]).'},from:{type:"string"},subject:{type:"string",description:"Subject of the message."},text:{type:"string",description:"Text version of the message."},html:{type:"string",description:"HTML version of the message."},message:{type:"string",description:"MIME string of the message. Make sure to use multipart/form-data to send this as a file upload."},cc:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}],description:"Same as To but for carbon copy"},bcc:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}],description:"Same as To but for blind carbon copy"},ampHtml:{type:"string"},tVersion:{type:"string"},tText:{anyOf:[{type:"string",enum:["yes","no"]},{type:"boolean"}]},oTag:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}],description:"Tag string. See Tagging for more information."},oDkim:{anyOf:[{type:"string",enum:["yes","no"]},{type:"boolean"}],description:"Enables/disabled DKIM signatures on per-message basis. Pass yes or no"},oDeliverytime:{type:"string",description:"Desired time of delivery. See Date Format. Note: Messages can be scheduled for a maximum of 3 days in the future."},oDeliverytimeOptimizePeriod:{type:"string"},oTimeZoneLocalize:{type:"string"},oTestmode:{anyOf:[{type:"string",enum:["yes","no"]},{type:"boolean"}],description:"Enables sending in test mode. Pass yes if needed. See Sending in Test Mode"},oTracking:{anyOf:[{type:"string",enum:["yes","no"]},{type:"boolean"}],description:"Toggles tracking on a per-message basis, see Tracking Messages for details. Pass yes or no."},oTrackingClicks:{anyOf:[{type:"string",enum:["yes","no","htmlonly"]},{type:"boolean"}],description:"Toggles clicks tracking on a per-message basis. Has higher priority than domain-level setting. Pass yes, no or htmlonly."},oTrackingOpens:{anyOf:[{type:"string",enum:["yes","no"]},{type:"boolean"}],description:"Toggles opens tracking on a per-message basis. Has higher priority than domain-level setting. Pass yes or no."},oRequireTls:{anyOf:[{type:"string",enum:["yes","no"]},{type:"boolean"}]},oSkipVerification:{anyOf:[{type:"string",enum:["yes","no"]},{type:"boolean"}]},recipientVariables:{type:"string"}},required:[],additionalProperties:!0},ug={output:CA};var Yn={type:"object",properties:{name:{type:"string"},email:{type:"string"}},description:'JSON object, containing 2 properties: Name and Email address of a previously validated and active sender. Including the Name property in the JSON is optional. This property is not mandatory in case you use TemplateID and you specified a From address for the template. Format : { "Email":"value", "Name":"value" }.',required:["Email"],additionalProperties:!0},_A={type:"object",properties:{contentType:{type:"string"},filename:{type:"string"},base64Content:{type:"string"}},required:["ContentType","Filename","Base64Content"],additionalProperties:!0},OA={type:"object",properties:{filename:{type:"string"},contentType:{type:"string"},contentId:{type:"string"},base64Content:{type:"string"}},required:["ContentType","Filename","Base64Content"],additionalProperties:!0},IA={type:"object",properties:{from:Yn,sender:Yn,to:{type:"array",items:Yn},cc:{type:"array",items:Yn},bcc:{type:"array",items:Yn},replyTo:Yn,subject:{type:"string"},textPart:{type:"string",description:"Content of the message, sent in Text and/or HTML format. At least one of these content types needs to be specified. When the HTML part is the only part provided, Mailjet will not generate a Text-part from the HTML version. The property can't be set when you use TemplateID"},htmlPart:{type:"string",description:"Content of the message, sent in Text and/or HTML format. At least one of these content types needs to be specified. When the HTML part is the only part provided, Mailjet will not generate a Text-part from the HTML version. The property can't be set when you use TemplateID"},templateId:{type:"number",description:"an ID for a template that is previously created and stored in Mailjet's system. It is mandatory when From and TextPart and/or HtmlPart are not provided. "},templateLanguage:{type:"boolean"},templateErrorReporting:Yn,templateErrorDeliver:{type:"boolean"},attachments:{type:"array",items:_A},inlineAttachments:{type:"array",items:OA},priority:{type:"number"},customCampaign:{type:"string"},deduplicateCampaign:{type:"boolean"},trackOpens:{type:"string",enum:["account_default","disabled","enabled"]},trackClicks:{type:"string",enum:["account_default","disabled","enabled"]},customId:{type:"string"},eventPayload:{type:"string"},urlTags:{type:"string"},headers:{type:"object",additionalProperties:!0},variables:{type:"object",additionalProperties:!0}},required:[],additionalProperties:!0},pg={output:IA};var Jt={type:"object",properties:{address:{type:"string"},name:{type:"string"}},additionalProperties:!0},Fo={type:"object",properties:{content:{type:"string"},path:{type:"string"}},additionalProperties:!0},PA={type:"object",properties:{from:{anyOf:[{type:"string"},Jt]},sender:{anyOf:[{type:"string"},Jt]},to:{anyOf:[{type:"string"},Jt,{type:"array",items:Jt}]},cc:{anyOf:[{type:"string"},Jt,{type:"array",items:Jt}]},bcc:{anyOf:[{type:"string"},Jt,{type:"array",items:Jt}]},replyTo:{anyOf:[{type:"string"},Jt,{type:"array",items:Jt}]},inReplyTo:{anyOf:[{type:"string"},Jt]},references:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},subject:{type:"string"},text:{anyOf:[{type:"string"},Fo]},html:{anyOf:[{type:"string"},Fo]},watchHtml:{anyOf:[{type:"string"},Fo]},amp:{anyOf:[{type:"string"},{type:"object",properties:{content:{type:"string"},path:{type:"string"},href:{type:"string"},encoding:{type:"string"},contentType:{type:"string"},raw:{anyOf:[{type:"string"},Fo]}}}]},icalEvent:{anyOf:[{type:"string"},{type:"object",properties:{content:{type:"string"},path:{type:"string"},method:{type:"string"},filename:{anyOf:[{type:"string"},{type:"boolean"}]},href:{type:"string"},encoding:{type:"string"}}}]},headers:{anyOf:[{type:"object",additionalProperties:!0},{type:"array",items:{type:"object",additionalProperties:!0}}]},list:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},attachments:{type:"array",items:{type:"object",properties:{content:{type:"string"},path:{type:"string"}},additionalProperties:!0}}},required:[],additionalProperties:!0},dg={output:PA};var MA={type:"object",properties:{},required:[],additionalProperties:!1},hg={output:MA};var NA={type:"object",properties:{personalizations:{type:"array",description:"An array of messages and their metadata. Each object within personalizations can be thought of as an envelope - it defines who should receive an individual message and how that message should be handled. See our [Personalizations documentation](https://sendgrid.com/docs/for-developers/sending-email/personalizations/) for examples.",uniqueItems:!1,maxItems:1e3,items:{type:"object",properties:{from:{title:"From Email Object",type:"object",properties:{email:{type:"string",format:"email",description:"The 'From' email address used to deliver the message. This address should be a verified sender in your Twilio SendGrid account."},name:{type:"string",description:"A name or title associated with the sending email address."}},required:["email"]},to:{title:"To Email Array",type:"array",items:{type:"object",properties:{email:{type:"string",format:"email",description:"The intended recipient's email address."},name:{type:"string",description:"The intended recipient's name."}},required:["email"]}},cc:{type:"array",description:"An array of recipients who will receive a copy of your email. Each object in this array must contain the recipient's email address. Each object in the array may optionally contain the recipient's name.",maxItems:1e3,items:{title:"CC BCC Email Object",type:"object",properties:{email:{type:"string",format:"email",description:"The intended recipient's email address."},name:{type:"string",description:"The intended recipient's name."}},required:["email"]}},bcc:{type:"array",description:"An array of recipients who will receive a blind carbon copy of your email. Each object in this array must contain the recipient's email address. Each object in the array may optionally contain the recipient's name.",maxItems:1e3,items:{title:"CC BCC Email Object",type:"object",properties:{email:{type:"string",format:"email",description:"The intended recipient's email address."},name:{type:"string",description:"The intended recipient's name."}},required:["email"]}},subject:{type:"string",description:"The subject of your email. See character length requirements according to [RFC 2822](http://stackoverflow.com/questions/1592291/what-is-the-email-subject-length-limit#answer-1592310).",minLength:1},headers:{type:"object",description:"A collection of JSON key/value pairs allowing you to specify handling instructions for your email. You may not overwrite the following headers: `x-sg-id`, `x-sg-eid`, `received`, `dkim-signature`, `Content-Type`, `Content-Transfer-Encoding`, `To`, `From`, `Subject`, `Reply-To`, `CC`, `BCC`"},substitutions:{type:"object",description:'Substitutions allow you to insert data without using Dynamic Transactional Templates. This field should **not** be used in combination with a Dynamic Transactional Template, which can be identified by a `templateId` starting with `d-`. This field is a collection of key/value pairs following the pattern "substitutionTag":"value to substitute". The key/value pairs must be strings. These substitutions will apply to the text and html content of the body of your email, in addition to the `subject` and `reply-to` parameters. The total collective size of your substitutions may not exceed 10,000 bytes per personalization object.',maxProperties:1e4},dynamicTemplateData:{type:"object",description:'Dynamic template data is available using Handlebars syntax in Dynamic Transactional Templates. This field should be used in combination with a Dynamic Transactional Template, which can be identified by a `templateId` starting with `d-`. This field is a collection of key/value pairs following the pattern "variable_name":"value to insert".'},customArgs:{type:"object",description:"Values that are specific to this personalization that will be carried along with the email and its activity data. Substitutions will not be made on custom arguments, so any string that is entered into this parameter will be assumed to be the custom argument that you would like to be used. This field may not exceed 10,000 bytes.",maxProperties:1e4},sendAt:{type:"integer",description:"A unix timestamp allowing you to specify when your email should be delivered. Scheduling delivery more than 72 hours in advance is forbidden."}},required:["to"]}},from:{title:"From Email Object",type:"object",properties:{email:{type:"string",format:"email",description:"The 'From' email address used to deliver the message. This address should be a verified sender in your Twilio SendGrid account."},name:{type:"string",description:"A name or title associated with the sending email address."}},required:["email"]},replyTo:{title:"Reply_to Email Object",type:"object",properties:{email:{type:"string",format:"email",description:"The email address where any replies or bounces will be returned."},name:{type:"string",description:"A name or title associated with the `replyTo` email address."}},required:["email"]},replyToList:{type:"array",description:"An array of recipients who will receive replies and/or bounces. Each object in this array must contain the recipient's email address. Each object in the array may optionally contain the recipient's name. You can either choose to use \u201CreplyTo\u201D field or \u201CreplyToList\u201D but not both.",uniqueItems:!0,maxItems:1e3,items:{type:"object",properties:{email:{type:"string",description:"The email address where any replies or bounces will be returned.",format:"email"},name:{type:"string",description:"A name or title associated with the `replyToList` email address."}},required:["email"]}},subject:{type:"string",description:"The global or 'message level' subject of your email. This may be overridden by subject lines set in personalizations.",minLength:1},content:{type:"array",description:"An array where you can specify the content of your email. You can include multiple [MIME types](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) of content, but you must specify at least one MIME type. To include more than one MIME type, add another object to the array containing the `type` and `value` parameters.",items:{type:"object",properties:{type:{type:"string",description:"The MIME type of the content you are including in your email (e.g., `\u201Ctext/plain\u201D` or `\u201Ctext/html\u201D`).",minLength:1},value:{type:"string",description:"The actual content of the specified MIME type that you are including in your email.",minLength:1}},required:["type","value"]}},attachments:{type:"array",description:"An array of objects where you can specify any attachments you want to include.",items:{type:"object",properties:{content:{type:"string",description:"The Base64 encoded content of the attachment.",minLength:1},type:{type:"string",description:"The MIME type of the content you are attaching (e.g., `\u201Ctext/plain\u201D` or `\u201Ctext/html\u201D`).",minLength:1},filename:{type:"string",description:"The attachment's filename."},disposition:{type:"string",default:"attachment",description:"The attachment's content-disposition, specifying how you would like the attachment to be displayed. For example, `\u201Cinline\u201D` results in the attached file are displayed automatically within the message while `\u201Cattachment\u201D` results in the attached file require some action to be taken before it is displayed, such as opening or downloading the file.",enum:["inline","attachment"]},contentId:{type:"string",description:"The attachment's content ID. This is used when the disposition is set to `\u201Cinline\u201D` and the attachment is an image, allowing the file to be displayed within the body of your email."}},required:["content","filename"]}},templateId:{type:"string",description:"An email template ID. A template that contains a subject and content \u2014 either text or html \u2014 will override any subject and content values specified at the personalizations or message level."},headers:{description:"An object containing key/value pairs of header names and the value to substitute for them. The key/value pairs must be strings. You must ensure these are properly encoded if they contain unicode characters. These headers cannot be one of the reserved headers.",type:"object"},categories:{type:"array",description:"An array of category names for this message. Each category name may not exceed 255 characters. ",uniqueItems:!0,maxItems:10,items:{type:"string",maxLength:255}},customArgs:{description:"Values that are specific to the entire send that will be carried along with the email and its activity data. Key/value pairs must be strings. Substitutions will not be made on custom arguments, so any string that is entered into this parameter will be assumed to be the custom argument that you would like to be used. This parameter is overridden by `customArgs` set at the personalizations level. Total `customArgs` size may not exceed 10,000 bytes.",type:"string"},sendAt:{type:"integer",description:"A unix timestamp allowing you to specify when you want your email to be delivered. This may be overridden by the `sendAt` parameter set at the personalizations level. Delivery cannot be scheduled more than 72 hours in advance. If you have the flexibility, it's better to schedule mail for off-peak times. Most emails are scheduled and sent at the top of the hour or half hour. Scheduling email to avoid peak times \u2014 for example, scheduling at 10:53 \u2014 can result in lower deferral rates due to the reduced traffic during off-peak times."},batchId:{type:"string",description:"An ID representing a batch of emails to be sent at the same time. Including a `batchId` in your request allows you include this email in that batch. It also enables you to cancel or pause the delivery of that batch. For more information, see the [Cancel Scheduled Sends API](https://sendgrid.com/docs/api-reference/)."},asm:{type:"object",description:"An object allowing you to specify how to handle unsubscribes.",properties:{groupId:{type:"integer",description:"The unsubscribe group to associate with this email."},groupsToDisplay:{type:"array",description:"An array containing the unsubscribe groups that you would like to be displayed on the unsubscribe preferences page.",maxItems:25,items:{type:"integer"}}},required:["groupId"]},ipPoolName:{type:"string",description:"The IP Pool that you would like to send this email from.",minLength:2,maxLength:64},mailSettings:{type:"object",description:"A collection of different mail settings that you can use to specify how you would like this email to be handled.",properties:{bypassListManagement:{type:"object",description:"Allows you to bypass all unsubscribe groups and suppressions to ensure that the email is delivered to every single recipient. This should only be used in emergencies when it is absolutely necessary that every recipient receives your email. This filter cannot be combined with any other bypass filters. See our [documentation](https://sendgrid.com/docs/ui/sending-email/index-suppressions/#bypass-suppressions) for more about bypass filters.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."}}},bypassSpamManagement:{type:"object",description:"Allows you to bypass the spam report list to ensure that the email is delivered to recipients. Bounce and unsubscribe lists will still be checked; addresses on these other lists will not receive the message. This filter cannot be combined with the `bypassListManagement` filter. See our [documentation](https://sendgrid.com/docs/ui/sending-email/index-suppressions/#bypass-suppressions) for more about bypass filters.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."}}},bypassBounceManagement:{type:"object",description:"Allows you to bypass the bounce list to ensure that the email is delivered to recipients. Spam report and unsubscribe lists will still be checked; addresses on these other lists will not receive the message. This filter cannot be combined with the `bypassListManagement` filter. See our [documentation](https://sendgrid.com/docs/ui/sending-email/index-suppressions/#bypass-suppressions) for more about bypass filters.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."}}},bypassUnsubscribeManagement:{type:"object",description:"Allows you to bypass the global unsubscribe list to ensure that the email is delivered to recipients. Bounce and spam report lists will still be checked; addresses on these other lists will not receive the message. This filter applies only to global unsubscribes and will not bypass group unsubscribes. This filter cannot be combined with the `bypassListManagement` filter. See our [documentation](https://sendgrid.com/docs/ui/sending-email/index-suppressions/#bypass-suppressions) for more about bypass filters.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."}}},footer:{type:"object",description:"The default footer that you would like included on every email.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."},text:{type:"string",description:"The plain text content of your footer."},html:{type:"string",description:"The HTML content of your footer."}}},sandboxMode:{type:"object",description:"Sandbox Mode allows you to send a test email to ensure that your request body is valid and formatted correctly.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."}}}}},trackingSettings:{type:"object",description:"Settings to determine how you would like to track the metrics of how your recipients interact with your email.",properties:{clickTracking:{type:"object",description:"Allows you to track if a recipient clicked a link in your email.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."},enableText:{type:"boolean",description:"Indicates if this setting should be included in the `text/plain` portion of your email."}}},openTracking:{type:"object",description:"Allows you to track if the email was opened by including a single pixel image in the body of the content. When the pixel is loaded, Twilio SendGrid can log that the email was opened.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."},substitutionTag:{type:"string",description:"Allows you to specify a substitution tag that you can insert in the body of your email at a location that you desire. This tag will be replaced by the open tracking pixel."}}},subscriptionTracking:{type:"object",description:"Allows you to insert a subscription management link at the bottom of the text and HTML bodies of your email. If you would like to specify the location of the link within your email, you may use the `substitutionTag`.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."},text:{type:"string",description:"Text to be appended to the email with the subscription tracking link. You may control where the link is by using the tag <% %>"},html:{type:"string",description:"HTML to be appended to the email with the subscription tracking link. You may control where the link is by using the tag <% %>"},substitutionTag:{type:"string",description:"A tag that will be replaced with the unsubscribe URL. for example: `[unsubscribe_url]`. If this parameter is used, it will override both the `text` and `html` parameters. The URL of the link will be placed at the substitution tag\u2019s location with no additional formatting."}}},ganalytics:{type:"object",description:"Allows you to enable tracking provided by Google Analytics.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."},utmSource:{type:"string",description:"Name of the referrer source. (e.g. Google, SomeDomain.com, or Marketing Email)"},utmMedium:{type:"string",description:"Name of the marketing medium. (e.g. Email)"},utmTerm:{type:"string",description:"Used to identify any paid keywords."},utmContent:{type:"string",description:"Used to differentiate your campaign from advertisements."},utmCampaign:{type:"string",description:"The name of the campaign."}}}}}},required:[],additionalProperties:!1},fg={output:NA};var mg={anypost:ae,braze:ae,clickatell:ae,nodemailer:dg,emailjs:ae,"email-webhook":ae,"infobip-email":ae,mailersend:ae,mailgun:ug,mailjet:pg,mailtrap:ae,mandrill:ae,netcore:ae,"novu-email":hg,outlook365:ae,plunk:ae,postmark:ae,resend:ae,sendgrid:fg,sendinblue:ae,ses:ae,sparkpost:ae};var LA={type:"object",properties:{},required:[],additionalProperties:!1},gg={output:LA};var yg={novu:gg};var bg={anyOf:[{type:"string"},{type:"object",additionalProperties:!0,properties:{name:{type:"string"},volume:{type:"number"},critical:{type:"number"}},required:["name","volume","critical"]}]},DA={type:"object",properties:{topic:{type:"string",description:"The destination topic for the notification."},id:{type:"string",description:"A UUID to identify the notification with APNS. If an id is not supplied, APNS will generate one automatically. If an error occurs the response will contain the id. This property populates the apns-id header."},expiry:{type:"number",description:"A UNIX timestamp when the notification should expire. If the notification cannot be delivered to the device, APNS will retry until it expires. An expiry of 0 indicates that the notification expires immediately, therefore no retries will be attempted."},priority:{type:"number",description:`Provide one of the following values:
162
+ `)}async executeProviders(t,n,r,i){return n.providers.reduce(async(a,o)=>{let s=await a,c=await this.runProvider(t,n,o,r,i);return{...s,[o.type]:c}},Promise.resolve({}))}async runProvider(t,n,r,i,a){let o=t.action==="preview";if(t.stepId!==n.stepId)return o?(this.log(` ${lt.MOCK} Mocked provider: \`${r.type}\``),this.mock(r.outputs.schema)):(this.log(` ${lt.HYDRATED} Hydrated provider: \`${r.type}\``),{});try{return await this.resolveProviderOutput(t,n,r,a,i)}catch(s){if(this.log(` ${lt.ERROR} Failed to execute provider: \`${r.type}\``),o)return this.log(` ${lt.MOCK} Mocked provider: \`${r.type}\``),this.mock(r.outputs.schema);throw new na(r.type,t.action,s)}}async resolveProviderOutput(t,n,r,i,a){let o=await r.resolve({controls:i,outputs:a}),s=await this.validate(o,r.outputs.unknownSchema,"step","output",t.workflowId,n.stepId,r.type);return this.log(` ${lt.SUCCESS} Executed provider: \`${r.type}\``),{...s,_passthrough:o._passthrough}}async executeStep(t,n){if(t.stepId===n.stepId)try{let r=await this.createStepControls(n,t),i=await this.compileControls(r,t),a=await n.resolve(i),o=await this.normalizeChatCardOutput(n,a),s=await this.validate(o,n.outputs.unknownSchema,"step","output",t.workflowId,n.stepId),c=await this.executeProviders(t,n,s,i);return this.log(` ${lt.SUCCESS} Executed stepId: \`${n.stepId}\``),{outputs:s,providers:c}}catch(r){throw this.log(` ${lt.ERROR} Failed to execute stepId: \`${n.stepId}\``),Mn(r)?r:new Ir(n.stepId,t.action,r)}else try{let r=this.getStepState(t,n.stepId);if(r){let i=await this.validate(r.outputs,n.results.unknownSchema,"step","result",t.workflowId,n.stepId);return this.log(` ${lt.HYDRATED} Hydrated stepId: \`${n.stepId}\``),{outputs:i,providers:await this.executeProviders(t,n,i,{})}}else throw new Bi(t.workflowId,n.stepId)}catch(r){throw this.log(` ${lt.ERROR} Failed to hydrate stepId: \`${n.stepId}\``),r}}async normalizeChatCardOutput(t,n){if(t.type!=="chat"||(n==null?void 0:n.card)==null)return n;let r=await lo(n.card);return r?{...n,card:r}:n}async compileControls(t,n){var r;try{let i=Ti(t),a=this.preprocessTranslationPatterns(JSON.stringify(i));a=this.preprocessFilterTranslationArgs(a);let o=this.templateEngine.parse(a),s=this.getWorkflow(n.workflowId),c={workflow:{workflowId:s.workflowId,name:s.name,description:s.description,tags:s.tags,severity:s.severity},payload:n.payload,subscriber:n.subscriber,...n.actor&&{actor:n.actor},context:n.context,steps:zx(n.state),env:(r=n.env)!=null?r:{}},p=await this.templateEngine.render(o,c),d=this.postprocessTranslationMarkers(p),h=(0,$m.jsonrepair)(d),y=JSON.parse(h),g=xi(y);return Lm(g)}catch(i){throw new Ji(n.workflowId,n.stepId,i)}}preprocessTranslationPatterns(t){return t.replace(/\{\{\s*t\.([\p{L}\p{N}_.-]+)\s*\}\}/gu,"[T:$1]")}preprocessFilterTranslationArgs(t){return t.replace(/'t\.([\p{L}\p{N}_.-]+)'/gu,"'[T:$1]'")}postprocessTranslationMarkers(t){return t.replace(/\[T:([\p{L}\p{N}_.-]+)\]/gu,"{{t.$1}}")}async createStepControls(t,n){return await this.validate(n.controls,t.controls.unknownSchema,"step","controls",n.workflowId,t.stepId)}async previewStep(t,n){try{return await this.constructStepForPreview(t,n)}catch(r){throw this.log(` ${lt.ERROR} Failed to preview stepId: \`${n.stepId}\``),Mn(r)?r:new Ir(n.stepId,t.action,r)}}async constructStepForPreview(t,n){return t.stepId===n.stepId?await this.previewRequiredStep(n,t):await this.extractMockDataForPreviousSteps(t,n)}async extractMockDataForPreviousSteps(t,n){let r={},i=this.getStepState(t,n.stepId),a=this.mock(n.results.schema);return{outputs:pc(a,(i==null?void 0:i.outputs)||{}),providers:await this.executeProviders(t,n,r,{})}}async previewRequiredStep(t,n){let r=await this.createStepControls(t,n),i=await this.compileControls(r,n),a=await t.resolve(i),o=await this.normalizeChatCardOutput(t,a),s=await this.validate(o,t.outputs.unknownSchema,"step","output",n.workflowId,t.stepId);return this.log(` ${lt.MOCK} Mocked stepId: \`${t.stepId}\``),{outputs:s,providers:await this.executeProviders(n,t,s,i)}}getStepState(t,n){return t.state.find(r=>r.stepId===n)}getStepCode(t,n){return{code:this.getStep(t,n).resolve.toString()}}getWorkflowCode(t){return{code:this.getWorkflow(t).execute.toString()}}getCode(t,n){let r;if(t)n?r=this.getStepCode(t,n):r=this.getWorkflowCode(t);else throw new Pr(t);return r}};function zx(e){let t={};for(let n of e)t[n.stepId]=n.outputs;return t}var qm=Symbol.for("novu.agent.runtimeContext");var hc=(o=>(o.ON_MESSAGE="onMessage",o.ON_MESSAGE_UPDATED="onMessageUpdated",o.ON_MESSAGE_DELETED="onMessageDeleted",o.ON_ACTION="onAction",o.ON_RESOLVE="onResolve",o.ON_REACTION="onReaction",o))(hc||{});function fc(e){return typeof e=="object"&&e!==null&&"content"in e&&!("type"in e)}var hr=class{constructor(){this.__novuPendingApproval=!0}};function jm(e){return typeof e=="object"&&e!==null&&"suppress"in e&&e.suppress===!0}var Vx=5*1024*1024,Wx=5*1024*1024,Bm=32768,Yx=/^[A-Za-z0-9+/]*={0,2}$/;function ki(e,t){return e.filename?`"${e.filename}"`:`at index ${t}`}function zm(){return globalThis.Buffer}function Jx(e){var t,n,r;return(r=(n=(t=zm())==null?void 0:t.isBuffer)==null?void 0:n.call(t,e))!=null?r:!1}function Gx(e){return typeof Blob!="undefined"&&e instanceof Blob}function mc(e){let t=zm();if(t)return t.from(e).toString("base64");if(typeof btoa!="function")throw new Error("Unable to encode file data: base64 encoding is not available in this runtime.");let n="";for(let r=0;r<e.length;r+=Bm){let i=e.subarray(r,r+Bm);n+=String.fromCharCode(...i)}return btoa(n)}function Vm(e){let t=e.replace(/\s/g,""),n=t.length%4;if(!t||n===1||!Yx.test(t))return null;let r=t.endsWith("==")?2:t.endsWith("=")?1:0;return Math.floor(t.length*3/4)-r}function vi(e,t,n){if(e>Vx)throw new Error(`Invalid file ${ki(t,n)}: inline data must be 5 MB or smaller. Use a publicly-accessible URL for larger files.`)}async function Kx(e,t,n){if(typeof e=="string"){let r=Vm(e);if(r===null)throw new Error(`Invalid file ${ki(t,n)}: data must be a base64-encoded string.`);return vi(r,t,n),e}if(Jx(e))return vi(e.byteLength,t,n),e.toString("base64");if(e instanceof Uint8Array)return vi(e.byteLength,t,n),mc(e);if(e instanceof ArrayBuffer)return vi(e.byteLength,t,n),mc(new Uint8Array(e));if(Gx(e))return vi(e.size,t,n),mc(new Uint8Array(await e.arrayBuffer()));throw new Error(`Invalid file ${ki(t,n)}: data must be a base64 string, Buffer, Uint8Array, ArrayBuffer, or Blob.`)}async function Xx(e){if(!(e!=null&&e.length))return;let t=[],n=0;for(let[r,i]of e.entries()){let a=i.data,o=i.url,s=a!=null,c=o!=null;if(s===c)throw new Error(`Invalid file ${ki(i,r)}: provide exactly one of data or url.`);if(s){let p=await Kx(a,i,r),d=Vm(p);if(n+=d!=null?d:0,n>Wx)throw new Error("Invalid files: total inline data must be 5 MB or smaller. Use publicly-accessible URLs for larger files.");t.push({...i,data:p});continue}if(c&&typeof o!="string")throw new Error(`Invalid file ${ki(i,r)}: url must be a string.`);t.push(i)}return t}async function To(e,t){let n=await Xx(t);if(typeof e=="string")return n?{markdown:e,files:n}:{markdown:e};let r=await lo(e);if(r)return n?{card:r,files:n}:{card:r};throw new Error("Invalid message content \u2014 expected string or CardElement")}var Wm=1;var Qx={400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",408:"Request Timeout",409:"Conflict",422:"Unprocessable Entity",429:"Too Many Requests",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout"};function xo(e){return typeof e=="string"&&e.trim()?e:!e||typeof e!="object"?null:xo(e.message)}function Zx(e){if(!e)return null;let t;try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!="object")return null;let n=t,r=xo(n.message);if(r)return r;let i=xo(n.error);if(i)return i;let a=n.errors;return Array.isArray(a)?xo(a[0]):null}function eA(e,t){var i;let n=(i=Qx[e])!=null?i:e,r=Zx(t);return r?`Delivery failed: ${n}: ${r}`:`Delivery failed: ${n}`}var bn=class extends Error{constructor(t,n){super(t),this.name="AgentError",this.cause=n==null?void 0:n.cause,this.delivery=n==null?void 0:n.delivery}},an=class extends bn{constructor(t,n){let r={statusCode:t,responseBody:n};super(eA(t,n),{delivery:r}),this.name="AgentDeliveryError",this.statusCode=t,this.responseBody=n}};function Ei(e){return e instanceof bn?e:e instanceof Error?new bn(e.message,{cause:e}):new bn("Turn failed",{cause:e})}function tA(e){return new Promise(t=>{setTimeout(t,e)})}function nA(e){return e>=500||e===408||e===429}var Ao=class{constructor(t){this.sequence=0;this.buffer=[];this.chain=Promise.resolve();var n,r;this.runId=`run_${crypto.randomUUID()}`,this.eventsUrl=t.eventsUrl,this.secretKey=t.secretKey,this.conversationId=t.conversationId,this.agentId=t.agentId,this.turnId=t.turnId,this.fetchFn=(n=t.fetchFn)!=null?n:fetch,this.maxRetries=(r=t.maxRetries)!=null?r:3}enqueue(t){this.sequence+=1,this.buffer.push({version:Wm,conversationId:this.conversationId,agentId:this.agentId,runId:this.runId,turnId:this.turnId,sequence:this.sequence,timestamp:new Date().toISOString(),event:t})}flush(){if(this.buffer.length===0)return this.chain;let t=this.buffer;return this.buffer=[],this.chain=this.chain.then(()=>this.postBatchWithRetry(t)),this.chain}async emit(t){this.enqueue(t),await this.flush()}async postBatchWithRetry(t){let n;for(let r=1;r<=this.maxRetries;r+=1)try{await this.postBatch(t);return}catch(i){if(n=i,!rA(i))throw i;r<this.maxRetries&&await tA(250*r)}throw n}async postBatch(t){let n;try{n=await this.fetchFn(this.eventsUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${this.secretKey}`},body:JSON.stringify({events:t})})}catch(i){throw iA(i)}let r=await n.text().catch(()=>"");if(!n.ok)throw new an(n.status,r)}};function rA(e){return!(e instanceof an)||e.statusCode===0?!0:nA(e.statusCode)}function iA(e){if(e instanceof an)return e;let t=e instanceof Error?e.message:"Network request failed";return new an(0,t)}var gc="human:";function vo(e){return`${gc}${e}:approve`}function ko(e){return`${gc}${e}:deny`}function fr(e,t){return`${gc}${e}:opt:${t}`}function Ym(e){return typeof e=="string"?e:e.label}function aA(e){return typeof e=="string"?void 0:e.id}function oA(e){return typeof e=="string"?e:e.id}function Ro(e,t){let n=t==null?void 0:t.trim();if(!n)throw new Error(`ctx.${e} requires a title (string argument or card.title)`);return n}function sA(e){if(!("title"in e))return;let t=e.title;return typeof t=="string"&&t.trim()?t.trim():void 0}function Co(e){if(!e||e.length<2||e.length>10)throw new Error("ctx.choose requires between 2 and 10 options");if(e.some(t=>Ym(t).trim().length===0))throw new Error("ctx.choose options must be non-empty strings")}function _o(e){if(e.length>4)throw new Error("ctx.approve card.extraActions supports at most 4 buttons");for(let t of e){let n=aA(t);if(!Ym(t).trim())throw new Error("ctx.approve extraActions labels must be non-empty");if(n==="approve"||n==="deny")throw new Error("ctx.approve extraActions ids cannot be approve or deny")}}function lA(e){if(typeof e=="string")throw new Error("human render must return chrome (*Card()), a Card, or a chat element \u2014 not a markdown string")}function Eo(e,t=[]){if(Array.isArray(e)){for(let r of e)Eo(r,t);return t}if(!e||typeof e!="object")return t;let n=e;n.type==="button"&&typeof n.id=="string"&&n.id.trim()&&t.push({id:n.id,label:typeof n.label=="string"?n.label:""});for(let r of Object.values(n))r&&typeof r=="object"&&Eo(r,t);return t}function cA(e){return new Set(Eo(e).map(t=>t.id))}function uA(e,t){let n=fr(t,"");return e.startsWith(n)&&e.length>n.length?e.slice(n.length):e}function pA(e,t){let n=Eo(e),r=new Set(n.map(s=>s.id)),i=vo(t),a=ko(t);if(!r.has(i))throw new Error("ctx.approve render must include a button with actionIds.approve");if(!r.has(a))throw new Error("ctx.approve render must include a button with actionIds.deny");let o=n.filter(s=>s.id!==i&&s.id!==a).map(s=>({id:uA(s.id,t),label:s.label}));o.length&&_o(o)}function dA(e,t,n){if(n){Co(n);for(let i of n){let a=oA(i);if(!e.has(fr(t,a)))throw new Error(`ctx.choose render must include a button with actionIds.option('${a}')`)}return}let r=hA(e,t);if(r.length<2||r.length>10)throw new Error("ctx.choose render must include between 2 and 10 option action buttons")}function hA(e,t){let n=fr(t,"");return[...e].filter(r=>r.startsWith(n)&&r.length>n.length).map(r=>r.slice(n.length))}function Jm(e,t,n){var r;switch(Ro(e,t.title),e){case"ask":case"tell":return;case"approve":t.type==="human-approve-card"&&t.extraActions&&_o(t.extraActions);return;case"choose":Co(t.type==="human-choose-card"&&(r=t.options)!=null?r:n);return;default:return}}function Gm(e,t,n,r){switch(lA(t),Ro(e,sA(t)),e){case"ask":case"tell":return;case"approve":pA(t,n);return;case"choose":dA(cA(t),n,r);return;default:return}}function Oo(e){let t=typeof e=="string"?[e]:e,n=[],r=new Set;for(let i of t){if(typeof i!="string")throw new Error("`to` must be a subscriberId string or an array of subscriberIds");let a=i.trim();!a||r.has(a)||(r.add(a),n.push(a))}if(n.length===0)throw new Error("`to` must include at least one subscriberId");if(n.length>50)throw new Error("`to` supports at most 50 subscriberIds");return n}var Km="tool-approval";function fA(e){return e==="approve"||e==="deny"}function yc(e,t){return`${Km}:${e}:${t}`}function Xm(e){let[t,n,...r]=(e!=null?e:"").split(":"),i=r.join(":");return t!==Km||!fA(n)||!i?null:{approved:n==="approve",approvalId:i}}async function Qm(e,t,n,r,i){var d,h;let a=r!=null?r:t.id,o={approve:yc("approve",a),deny:yc("deny",a)},s=y=>({type:"tool-approval-card",...y}),c=(h=(d=n==null?void 0:n.renderApproval)==null?void 0:d.call(n,{toolCall:t,actionIds:o,approvalCard:s}))!=null?h:s(),p={approvalId:a,toolCallId:t.id,name:t.name,input:t.input,...(i==null?void 0:i.to)!==void 0?{to:i.to}:{},...i!=null&&i.from?{from:i.from}:{},...(i==null?void 0:i.ttlSeconds)!==void 0?{ttlSeconds:i.ttlSeconds}:{}};if(e.emitToolApprovalRequest(p),hm(c)){await e.replyApprovalCard(c);return}await e.reply(c)}function Io(e){return t=>({type:e,...t})}function Po(e,t){switch(e){case"ask":return{requestId:t,askCard:Io("human-ask-card")};case"approve":return{requestId:t,actionIds:{approve:vo(t),deny:ko(t)},approveCard:Io("human-approve-card")};case"choose":return{requestId:t,actionIds:{option:n=>fr(t,n)},chooseCard:Io("human-choose-card")};case"tell":return{requestId:t,tellCard:Io("human-tell-card")};default:return e}}function Sc(e){return`${e}_${crypto.randomUUID()}`}function mA(e){let{type:t,...n}=e;return n}function gA(e){if(!(!e||!("card"in e)))return e.card}function Mo(e){if(!(!e||!("render"in e)))return e.render}function yA(e){return typeof e=="object"&&e!==null&&pr(e)?e:{type:"card",children:[e]}}function bc(e){if(!(!e||!("ttlSeconds"in e)||typeof e.ttlSeconds!="number"))return e.ttlSeconds}function Zm(e){if(e.markdown!==void 0)return{markdown:e.markdown};if(e.card!==void 0)return{card:e.card};throw new Error("Invalid reply content \u2014 expected markdown or card")}function bA(e){let t="platformMessageId"in e?e.platformMessageId.trim():e.messageId.trim();if(!t)throw new Error("quoteReply requires a non-empty platform message id");return{messageId:t}}function eg(e){if(e!=null&&e.length)return e.map((t,n)=>({fileId:t.filename||`file_${n}`,name:t.filename,mediaType:t.mimeType,...t.data!==void 0?{data:typeof t.data=="string"?t.data:void 0}:{},...t.url!==void 0?{url:t.url}:{}}))}function wc(e,t){var r;let n=[];if(e.toolApprovalRequest){let i=e.toolApprovalRequest;n.push({type:"tool-approval-request",approvalId:i.approvalId,toolUseId:i.toolCallId,toolName:i.name,input:i.input,...i.ttlSeconds!==void 0?{ttlSeconds:i.ttlSeconds}:{},...i.to!==void 0?{to:i.to}:{},...i.from!==void 0?{from:i.from}:{},...t!=null&&t.deliverApprovalCard?{deliverCard:!0}:{}})}for(let i of e.toolResults)n.push({type:"tool-use-result",toolUseId:i.toolCallId,content:[{type:"text",text:String((r=i.preview)!=null?r:"")},{type:"json",value:i.output}]});for(let i of e.signals)n.push({type:"signal",signal:i});for(let i of e.addReactions)n.push({type:"channel.reaction",messageId:i.messageId,emoji:i.emojiName,op:"add"});for(let i of e.deleteMessages)n.push({type:"channel.delete",messageId:i.messageId});return e.resolve&&n.push({type:"resolve",summary:e.resolve.summary}),n}var Tc=class{constructor(t){this.outbox=t}async sendReply(t,n,r){let i=Sc("msg"),a=wc(n);return a.push({type:"message",role:"assistant",messageId:i,content:Zm(t),files:eg(t.files),...r?{quoteReply:r}:{}}),await this._emitAndFlush(a),{messageId:i,platformThreadId:""}}async sendApprovalCard(t,n){return await this._emitAndFlush(wc(n,{deliverApprovalCard:!0})),"unaddressable"}async editMessage(t,n){return await this.outbox.emit({type:"channel.edit",messageId:t,content:Zm(n),files:eg(n.files)}),{messageId:t,platformThreadId:""}}async deleteMessage(t){await this.outbox.emit({type:"channel.delete",messageId:t})}async setTyping(t){if(t==="stop"){await this.outbox.emit({type:"channel.typing",state:"off"});return}let n=typeof t=="object"&&"status"in t?t.status:void 0;await this.outbox.emit({type:"channel.typing",state:"on",status:n})}async flushSideEffects(t){await this._emitAndFlush(wc(t))}async emitCustom(t,n){await this.outbox.emit({type:"custom",name:t,data:n})}queueRunStart(){this.outbox.enqueue({type:"run-start"})}async emitRunFinish(t){await this.outbox.emit({type:"run-finish",outcome:t})}async reportTurnError(t){await this.outbox.emit({type:"run-error",message:t!=null?t:"agent handler failed"})}async _emitAndFlush(t){if(t.length!==0){for(let n of t)this.outbox.enqueue(n);await this.outbox.flush()}}},No=class{constructor(t,n,r){this.transport=r;this.editedByHandler=!1;this.messageId=t,this.platformThreadId=n}async edit(t,n){this.editedByHandler=!0;let r=await To(t,n==null?void 0:n.files),i=await this.transport.editMessage(this.messageId,r);if(!i)throw new Error("Agent edit did not return a message handle");return this.messageId=i.messageId,this.platformThreadId=i.platformThreadId,this}async delete(){await this.transport.deleteMessage(this.messageId)}},xc=class{constructor(){this.messageId="";this.platformThreadId=""}async edit(){return this}async delete(){}},tg;tg=qm;var Lo=class{constructor(t,n,r){this[tg]=!0;this._signals=[];this._toolResults=[];this._pendingToolApprovalRequest=null;this._pendingReactions=[];this._pendingDeletes=[];this._resolveSignal=null;this._pendingHumanRenders=[];var c,p,d,h,y,g;this.event=t.event,this.action=(c=t.action)!=null?c:null,this.message=t.message,this.previousMessage=(p=t.previousMessage)!=null?p:null,this.reaction=t.reaction,this.conversation=t.conversation,this.subscriber=t.subscriber,this.context=(d=t.context)!=null?d:null,this.notification=(h=t.notification)!=null?h:null,this.history=t.history,this.platform=t.platform,this.platformContext=t.platformContext,this.humanResponse=(y=t.humanResponse)!=null?y:null,this._toolApprovalConfig=r;let i=t.eventsUrl;if(!i)throw new Error("AgentBridgeRequest.eventsUrl is required");this._transport=new Tc(new Ao({eventsUrl:i,secretKey:n,conversationId:t.conversationId,agentId:t.agentId,turnId:t.deliveryId})),this._metadataState={...(g=t.conversation.metadata)!=null?g:{}};let a=this;this.metadata={get(I){return a._metadataState[I]},set(I,K){a._metadataState[I]=K,a._signals.push({type:"metadata",action:"set",key:I,value:K})},delete(I){delete a._metadataState[I],a._signals.push({type:"metadata",action:"delete",key:I})},clear(){a._metadataState={},a._signals.push({type:"metadata",action:"clear"})},get current(){return{...a._metadataState}}};let o=I=>this._transport.setTyping(I),s=(I=>o(I===void 0?{}:{status:I}));s.stop=()=>o("stop"),this.typing=s,this.toolApproval={request:async(I,K)=>(await Qm(this,I,this._toolApprovalConfig,void 0,K),new hr)}}asMessageContext(){return this}async reply(t,n){await this.materializePendingHumanRenders();let r=await To(t,n==null?void 0:n.files),i=this._drainSideEffectsSnapshot(),a=n!=null&&n.quoteReply?bA(n.quoteReply):void 0,o=await this._transport.sendReply(r,i,a);if(!o)throw new Error("Agent reply did not return a message handle");return new No(o.messageId,o.platformThreadId,this._transport)}async replyApprovalCard(t){await this.materializePendingHumanRenders();let n=this._drainSideEffectsSnapshot();return await this._transport.sendApprovalCard(t,n),new xc}createReplyHandle(t){return new No(t,"",this._transport)}async emit(t){await this._transport.emitCustom(t.name,t.data)}resolve(t){this._resolveSignal={summary:t}}trigger(t,n){this._signals.push({...n,type:"trigger",workflowId:t})}ask(t,n){let i=typeof t!="string"?t:n,a=Mo(i);return a?this.queueRendered("ask",i,a):this.queueHumanSignal("ask",t,n)}approve(t,n){let i=typeof t!="string"?t:n,a=Mo(i);return a?this.queueRendered("approve",i,a):this.queueHumanSignal("approve",t,n)}choose(t,n,r){var c;let i=typeof t!="string",a,o;i?a=t:Array.isArray(n)?(a=r,o=n):a=n;let s=Mo(a);return s?this.queueRendered("choose",a,s):i?this.queueHumanSignal("choose",t,void 0,"card"in t?(c=t.card)==null?void 0:c.options:void 0):this.queueHumanSignal("choose",t,a,o)}tell(t,n){let r=typeof t!="string",i=r?t:n,a=Mo(i);if(a)return this.queueRendered("tell",i,a);if(r)throw new Error("ctx.tell requires a title (string argument) when render is omitted");return this.queueHumanSignal("tell",t,n)}queueHumanSignal(t,n,r,i){let a=typeof n!="string",o=a?void 0:n,s=a?n:r,c=gA(s),p=Ro(t,(o==null?void 0:o.trim())||(c==null?void 0:c.title));if(t==="choose"){let I=i!=null?i:c==null?void 0:c.options;Co(I)}t==="approve"&&(c!=null&&c.extraActions)&&_o(c.extraActions);let d=Sc("hr"),h=(s==null?void 0:s.to)!==void 0?Oo(s.to):void 0,y={...c,title:p,...t==="choose"&&i?{options:i}:{}},g=bc(s);return this._signals.push({type:"human",kind:t,requestId:d,card:y,...s!=null&&s.from?{from:s.from}:{},...g!==void 0?{ttlSeconds:g}:{},...h!==void 0?{to:h}:{}}),d}queueRendered(t,n,r){let i=Sc("hr");return this._pendingHumanRenders.push(async()=>{let a=await this.invokeHumanRender(t,i,r);if(fm(a)){this.pushRenderedChrome(t,i,a,n);return}await this.pushRenderedContent(t,i,a,n)}),i}invokeHumanRender(t,n,r){switch(t){case"ask":return Promise.resolve(r(Po("ask",n)));case"approve":return Promise.resolve(r(Po("approve",n)));case"choose":return Promise.resolve(r(Po("choose",n)));case"tell":return Promise.resolve(r(Po("tell",n)));default:{let i=t;return Promise.resolve(i)}}}pushRenderedChrome(t,n,r,i){Jm(t,r);let a=mA(r),o=bc(i),s=(i==null?void 0:i.to)!==void 0?Oo(i.to):void 0,c=t==="approve"||t==="choose";this._signals.push({type:"human",kind:t,requestId:n,...c?{actionIdentifier:n}:{},card:a,...i!=null&&i.from?{from:i.from}:{},...o!==void 0?{ttlSeconds:o}:{},...s!==void 0?{to:s}:{}})}async pushRenderedContent(t,n,r,i){Gm(t,r,n);let a=await To(yA(r));if(!a.card)throw new Error("human render must return chrome (*Card()), a Card, or a chat element \u2014 not a markdown string");let o=bc(i),s=(i==null?void 0:i.to)!==void 0?Oo(i.to):void 0,c=t==="approve"||t==="choose";this._signals.push({type:"human",kind:t,requestId:n,...c?{actionIdentifier:n}:{},card:a.card,...i!=null&&i.from?{from:i.from}:{},...o!==void 0?{ttlSeconds:o}:{},...s!==void 0?{to:s}:{}})}emitToolApprovalRequest(t){if(this._pendingToolApprovalRequest)throw new Error("Only one tool approval request can be queued before the next reply");this._pendingToolApprovalRequest=t}emitToolResult(t){this._toolResults.push(t)}addReaction(t,n){this._pendingReactions.push({messageId:t,emojiName:n})}deleteMessage(t){this._pendingDeletes.push({messageId:t})}queueRunStart(){this._transport.queueRunStart()}async emitRunFinish(t){try{await this._transport.emitRunFinish(t.outcome)}catch(n){console.error("[agent] Failed to emit run finish:",n)}}async reportTurnError(t){try{await this._transport.reportTurnError(t)}catch(n){console.error("[agent] Failed to report turn error:",n)}}async flush(){if(await this.materializePendingHumanRenders(),!this._hasPendingSideEffects())return;let t=this._drainSideEffectsSnapshot();await this._transport.flushSideEffects(t)}async materializePendingHumanRenders(){let t=this._pendingHumanRenders.splice(0);for(let n of t)await n()}_hasPendingSideEffects(){return!!(this._pendingToolApprovalRequest||this._signals.length||this._toolResults.length||this._resolveSignal||this._pendingReactions.length||this._pendingDeletes.length)}_drainSideEffectsSnapshot(){let t={toolApprovalRequest:this._pendingToolApprovalRequest,signals:this._signals,toolResults:this._toolResults,addReactions:this._pendingReactions,deleteMessages:this._pendingDeletes,resolve:this._resolveSignal};return this._pendingToolApprovalRequest=null,this._signals=[],this._toolResults=[],this._pendingReactions=[],this._pendingDeletes=[],this._resolveSignal=null,t}};function wA(e){return!!(typeof e=="string"||typeof e=="object"&&e!==null&&pr(e)||typeof e=="object"&&e!==null&&("markdown"in e||"card"in e||"files"in e))}function SA(e,t){return e}var ng="tool_approval:";function TA(e){if(!(e!=null&&e.startsWith(ng)))return null;let t=e.slice(ng.length);return t.length>0?t:null}async function rg(e,t){await e.reply(t.content,{files:t.files,quoteReply:t.quoteReply})}async function Wn(e,t){if(!(t instanceof hr||t===void 0)){if(fc(t)){await rg(e,t);return}await e.reply(t)}}async function xA(e,t){return jm(t)?!0:fc(t)?(await rg(e,t),!0):wA(t)?(await e.reply(t),!0):!1}function AA(e,t){var n;for(let r of e){let i=r.toolData;if(r.type==="tool_approval_request"&&(i==null?void 0:i.approvalId)===t&&i.toolCallId)return{approvalId:i.approvalId,toolCallId:i.toolCallId,name:(n=i.toolName)!=null?n:"tool",input:i.input}}}async function ig(e){var a;let t=new Lo(e.bridge,e.secretKey,e.agent.handlers.toolApproval),{agent:n,event:r,logger:i}=e;try{t.queueRunStart(),await kA(n,r,t),await t.flush(),await t.emitRunFinish({outcome:"completed"})}catch(o){let s=Ei(o);i==null||i.error(`[agent:${n.id}] Turn failed (${r}): ${s.message}`,(a=s.cause)!=null?a:s);let c=!1;if(n.handlers.onError)try{let p=await n.handlers.onError(s,SA(t,r));c=await xA(t,p)}catch(p){i==null||i.error(`[agent:${n.id}] onError failed:`,p)}c?await t.emitRunFinish({outcome:"completed"}):await t.reportTurnError(s.message)}finally{try{await t.typing.stop(),await t.flush()}catch{}}}async function vA(e,t){var s,c,p,d,h,y;let n=TA((s=t.humanResponse)==null?void 0:s.requestId),r=Xm((c=t.action)==null?void 0:c.id),i=n!=null?n:r==null?void 0:r.approvalId,a=n?((p=t.humanResponse)==null?void 0:p.status)==="approved"&&!t.humanResponse.expired:r==null?void 0:r.approved;if(i&&a!==void 0&&e.handlers.onToolApproval){let g=AA(t.history,i),I=g?{id:g.toolCallId,name:g.name,input:g.input}:{id:i,name:""},K=t.createReplyHandle((h=(d=t.action)==null?void 0:d.sourceMessageId)!=null?h:""),Z={toolCall:I,approved:a,approvalMessage:K};e.userOnToolApproval===!1&&(await t.typing(),(y=t.action)!=null&&y.sourceMessageId&&await K.delete());let H=await e.handlers.onToolApproval(Z,t);await Wn(t,H);return}let o=t.action;o&&e.handlers.onAction&&await Wn(t,await e.handlers.onAction(o,t))}async function kA(e,t,n){switch(t){case"onMessage":{let r=n.message;r&&await Wn(n,await e.handlers.onMessage(r,n));break}case"onMessageUpdated":{let r=n.message;r&&e.handlers.onMessageUpdated&&await Wn(n,await e.handlers.onMessageUpdated(r,n));break}case"onMessageDeleted":{let r=n.message;r&&e.handlers.onMessageDeleted&&await Wn(n,await e.handlers.onMessageDeleted(r,n));break}case"onAction":{await vA(e,n);break}case"onReaction":{let r=n.reaction;r&&e.handlers.onReaction&&await Wn(n,await e.handlers.onReaction(r,n));break}case"onResolve":e.handlers.onResolve&&await Wn(n,await e.handlers.onResolve(n));break;default:throw new Nn(t,hc)}}function ag(e){let t={};for(let i of e.split(",")){let a=i.trim();if(!a)continue;let o=a.indexOf("=");if(o<=0)continue;let s=a.slice(0,o),c=a.slice(o+1);s&&c&&!(s in t)&&(t[s]=c)}let n=t.t,r=n!==void 0?Number(n):Number.NaN;return{t:Number.isFinite(r)?r:void 0,v1:t.v1}}var Do=class{constructor(t){this.handler=t.handler,this.client=t.client?t.client:new dr,this.workflows=t.workflows||[],this.agents=t.agents||[],this.http=co(this.client.secretKey,this.client.apiUrl),this.frameworkName=t.frameworkName,this.hmacEnabled=this.client.strictAuthentication,this.waitUntil=t.waitUntil,this.client.addAgents(this.agents)}createHandler(){return async(...t)=>{await this.client.addWorkflows(this.workflows);let n=await this.handler(...t),r=await this.handleAction({actions:n});return n.transformResponse(r)}}getStaticHeaders(){let t=`novu-framework:v${this.client.version}`;return{"content-type":"application/json","access-control-allow-origin":"*","access-control-allow-private-network":"true","access-control-allow-methods":"GET, POST","access-control-allow-headers":"*","access-control-max-age":"604800","novu-framework-version":"2024-06-26","novu-framework-sdk":"2.14.0","novu-framework-server":this.frameworkName,"user-agent":t}}createResponse(t,n){return{status:t,body:JSON.stringify(n),headers:{...this.getStaticHeaders()}}}createError(t){return{status:t.statusCode,body:JSON.stringify({message:t.message,data:t.data,code:t.code}),headers:this.getStaticHeaders()}}async handleAction({actions:t}){var h;let n=await t.url(),r=await t.method(),i=n.searchParams.get("action")||"health-check",a=n.searchParams.get("workflowId")||"",o=n.searchParams.get("stepId")||"",s=n.searchParams.get("agentId")||"",c=n.searchParams.get("event")||"",p=await t.headers("novu-signature")||"",d={};try{r==="POST"&&(d=await t.body())}catch{}try{i!=="health-check"&&await this.validateHmac(d,p);let y=this.getPostActionMap(d,a,o,i,s,c,(h=this.waitUntil)!=null?h:t.waitUntil),g=this.getGetActionMap(a,o);if(r==="POST")return await this.handlePostAction(i,y);if(r==="GET")return await this.handleGetAction(i,g);if(r==="OPTIONS")return this.createResponse(200,{})}catch(y){return this.handleError(y)}return this.createError(new Qi(r))}getPostActionMap(t,n,r,i,a,o,s){return{trigger:this.triggerAction({workflowId:n,...t}),execute:async()=>{let c=await this.client.executeWorkflow({...t,workflowId:n,stepId:r,action:i});return this.createResponse(200,c)},preview:async()=>{let c=await this.client.executeWorkflow({...t,workflowId:n,stepId:r,action:i});return this.createResponse(200,c)},"agent-event":async()=>{let c=this.client.getAgent(a);if(!c)return this.createResponse(404,{error:`Agent '${a}' not registered`});let p=ig({agent:c,event:o,bridge:t,secretKey:this.client.secretKey,logger:this.client.logger});return s?s(p):this.warnOnUnprotectedServerlessRuntime(a),this.createResponse(200,{status:"ack"})}}}warnOnUnprotectedServerlessRuntime(t){let n;try{process.env.AWS_LAMBDA_FUNCTION_NAME?n="AWS Lambda":process.env.VERCEL&&(n="Vercel")}catch{}n&&this.client.logger.warn(`[agent:${t}] Agent event acknowledged without a \`waitUntil\` primitive while running on ${n}. The runtime may freeze once the response is sent, silently dropping the rest of the agent turn. Pass \`waitUntil\` to \`serve()\` (e.g. \`serve({ agents, waitUntil })\`) to extend the invocation lifetime.`)}triggerAction(t){return async()=>{let n={name:t.workflowId,to:t.to,payload:(t==null?void 0:t.payload)||{},transactionId:t.transactionId,overrides:t.overrides||{},...t.actor&&{actor:t.actor},...t.bridgeUrl&&{bridgeUrl:t.bridgeUrl},...t.controls&&{controls:t.controls},...t.context&&{context:t.context},...t.agentId!==void 0&&{agentId:t.agentId}},r=await this.http.post("/events/trigger",n);return this.createResponse(200,r)}}getGetActionMap(t,n){return{discover:async()=>{let r=await this.client.discover();return this.createResponse(200,r)},"health-check":async()=>{let r=await this.client.healthCheck();return this.createResponse(200,r)},code:async()=>{let r=await this.client.getCode(t,n);return this.createResponse(200,r)}}}async handlePostAction(t,n){if(Object.values(Rr).includes(t)){let r=n[t];return r()}else throw new Nn(t,Rr)}async handleGetAction(t,n){if(Object.values(Hi).includes(t)){let r=n[t];return r()}else throw new Nn(t,Hi)}handleError(t){if(Mn(t))return t.statusCode>=500&&this.client.logger.error(t),this.createError(t);if(vu(t))return this.createError(t);{let n=new Xn(t);return this.client.logger.error(n),this.createError(n)}}async validateHmac(t,n){if(!this.hmacEnabled)return;if(!n)throw new ia;if(!this.client.secretKey)throw new sa;let r=ag(n);if(!r.v1||r.t===void 0)throw new aa;let i=Date.now();if(r.t<i-3e5||r.t>i+3e5)throw new oa;let a=await ym(this.client.secretKey,`${r.t}.${JSON.stringify(t)}`);if(!bm(a,r.v1))throw new ra}};function Ac(e,t){if(!e)throw new Error("agent() requires a non-empty agentId");if(!(t!=null&&t.onMessage))throw new Error(`agent('${e}') requires an onMessage handler`);return{id:e,handlers:t,userOnToolApproval:typeof t.onToolApproval=="function"}}var ae={output:{type:"object",properties:{},required:[],additionalProperties:!0}};var EA={type:"object",properties:{text:{type:"string",description:"Overrides the step body text."},effect:{type:"string",description:"iMessage expressive effect: a friendly name (confetti, fireworks, balloons, heart, lasers, celebration, sparkles, spotlight, echo, slam, loud, gentle, invisible) or a raw com.apple.\u2026 effect id."},attachments:{type:"array",items:{type:"string",format:"uri"},description:"Attachment URLs sent alongside the message."},voice:{type:"string",format:"uri",description:"Audio URL sent as a native iMessage voice note (waveform bubble)."},replyToLast:{type:"boolean",description:"Reply-thread this send to the previous message sent to this recipient."},format:{type:"string",enum:["markdown","text"],description:"Force native styled text (markdown) or plain text for the body."}},additionalProperties:!0},sg={output:EA};var RA={type:"object",properties:{webhookUrl:{type:"string",format:"uri"},text:{type:"string"},blocks:{type:"array",items:{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!0}}},additionalProperties:!0},lg={output:RA};var cg={"chat-webhook":ae,discord:ae,"google-chat":ae,getstream:ae,"grafana-on-call":ae,line:ae,mattermost:ae,msteams:ae,"novu-slack":ae,"novu-web-chat":ae,"photon-imessage":sg,"rocket-chat":ae,ryver:ae,sendblue:ae,slack:lg,"webex-messaging":ae,"whatsapp-business":ae,zulip:ae,telegram:ae};var CA={type:"object",properties:{to:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}],description:'Email address of the recipient(s). Example: "Bob bob@host.com". You can use commas to separate multiple recipients (e.g.: "test@example.com,test@example.com" or ["test@example.com", "test@example.com"]).'},from:{type:"string"},subject:{type:"string",description:"Subject of the message."},text:{type:"string",description:"Text version of the message."},html:{type:"string",description:"HTML version of the message."},message:{type:"string",description:"MIME string of the message. Make sure to use multipart/form-data to send this as a file upload."},cc:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}],description:"Same as To but for carbon copy"},bcc:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}],description:"Same as To but for blind carbon copy"},ampHtml:{type:"string"},tVersion:{type:"string"},tText:{anyOf:[{type:"string",enum:["yes","no"]},{type:"boolean"}]},oTag:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}],description:"Tag string. See Tagging for more information."},oDkim:{anyOf:[{type:"string",enum:["yes","no"]},{type:"boolean"}],description:"Enables/disabled DKIM signatures on per-message basis. Pass yes or no"},oDeliverytime:{type:"string",description:"Desired time of delivery. See Date Format. Note: Messages can be scheduled for a maximum of 3 days in the future."},oDeliverytimeOptimizePeriod:{type:"string"},oTimeZoneLocalize:{type:"string"},oTestmode:{anyOf:[{type:"string",enum:["yes","no"]},{type:"boolean"}],description:"Enables sending in test mode. Pass yes if needed. See Sending in Test Mode"},oTracking:{anyOf:[{type:"string",enum:["yes","no"]},{type:"boolean"}],description:"Toggles tracking on a per-message basis, see Tracking Messages for details. Pass yes or no."},oTrackingClicks:{anyOf:[{type:"string",enum:["yes","no","htmlonly"]},{type:"boolean"}],description:"Toggles clicks tracking on a per-message basis. Has higher priority than domain-level setting. Pass yes, no or htmlonly."},oTrackingOpens:{anyOf:[{type:"string",enum:["yes","no"]},{type:"boolean"}],description:"Toggles opens tracking on a per-message basis. Has higher priority than domain-level setting. Pass yes or no."},oRequireTls:{anyOf:[{type:"string",enum:["yes","no"]},{type:"boolean"}]},oSkipVerification:{anyOf:[{type:"string",enum:["yes","no"]},{type:"boolean"}]},recipientVariables:{type:"string"}},required:[],additionalProperties:!0},ug={output:CA};var Yn={type:"object",properties:{name:{type:"string"},email:{type:"string"}},description:'JSON object, containing 2 properties: Name and Email address of a previously validated and active sender. Including the Name property in the JSON is optional. This property is not mandatory in case you use TemplateID and you specified a From address for the template. Format : { "Email":"value", "Name":"value" }.',required:["Email"],additionalProperties:!0},_A={type:"object",properties:{contentType:{type:"string"},filename:{type:"string"},base64Content:{type:"string"}},required:["ContentType","Filename","Base64Content"],additionalProperties:!0},OA={type:"object",properties:{filename:{type:"string"},contentType:{type:"string"},contentId:{type:"string"},base64Content:{type:"string"}},required:["ContentType","Filename","Base64Content"],additionalProperties:!0},IA={type:"object",properties:{from:Yn,sender:Yn,to:{type:"array",items:Yn},cc:{type:"array",items:Yn},bcc:{type:"array",items:Yn},replyTo:Yn,subject:{type:"string"},textPart:{type:"string",description:"Content of the message, sent in Text and/or HTML format. At least one of these content types needs to be specified. When the HTML part is the only part provided, Mailjet will not generate a Text-part from the HTML version. The property can't be set when you use TemplateID"},htmlPart:{type:"string",description:"Content of the message, sent in Text and/or HTML format. At least one of these content types needs to be specified. When the HTML part is the only part provided, Mailjet will not generate a Text-part from the HTML version. The property can't be set when you use TemplateID"},templateId:{type:"number",description:"an ID for a template that is previously created and stored in Mailjet's system. It is mandatory when From and TextPart and/or HtmlPart are not provided. "},templateLanguage:{type:"boolean"},templateErrorReporting:Yn,templateErrorDeliver:{type:"boolean"},attachments:{type:"array",items:_A},inlineAttachments:{type:"array",items:OA},priority:{type:"number"},customCampaign:{type:"string"},deduplicateCampaign:{type:"boolean"},trackOpens:{type:"string",enum:["account_default","disabled","enabled"]},trackClicks:{type:"string",enum:["account_default","disabled","enabled"]},customId:{type:"string"},eventPayload:{type:"string"},urlTags:{type:"string"},headers:{type:"object",additionalProperties:!0},variables:{type:"object",additionalProperties:!0}},required:[],additionalProperties:!0},pg={output:IA};var Jt={type:"object",properties:{address:{type:"string"},name:{type:"string"}},additionalProperties:!0},Fo={type:"object",properties:{content:{type:"string"},path:{type:"string"}},additionalProperties:!0},PA={type:"object",properties:{from:{anyOf:[{type:"string"},Jt]},sender:{anyOf:[{type:"string"},Jt]},to:{anyOf:[{type:"string"},Jt,{type:"array",items:Jt}]},cc:{anyOf:[{type:"string"},Jt,{type:"array",items:Jt}]},bcc:{anyOf:[{type:"string"},Jt,{type:"array",items:Jt}]},replyTo:{anyOf:[{type:"string"},Jt,{type:"array",items:Jt}]},inReplyTo:{anyOf:[{type:"string"},Jt]},references:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},subject:{type:"string"},text:{anyOf:[{type:"string"},Fo]},html:{anyOf:[{type:"string"},Fo]},watchHtml:{anyOf:[{type:"string"},Fo]},amp:{anyOf:[{type:"string"},{type:"object",properties:{content:{type:"string"},path:{type:"string"},href:{type:"string"},encoding:{type:"string"},contentType:{type:"string"},raw:{anyOf:[{type:"string"},Fo]}}}]},icalEvent:{anyOf:[{type:"string"},{type:"object",properties:{content:{type:"string"},path:{type:"string"},method:{type:"string"},filename:{anyOf:[{type:"string"},{type:"boolean"}]},href:{type:"string"},encoding:{type:"string"}}}]},headers:{anyOf:[{type:"object",additionalProperties:!0},{type:"array",items:{type:"object",additionalProperties:!0}}]},list:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},attachments:{type:"array",items:{type:"object",properties:{content:{type:"string"},path:{type:"string"}},additionalProperties:!0}}},required:[],additionalProperties:!0},dg={output:PA};var MA={type:"object",properties:{},required:[],additionalProperties:!1},hg={output:MA};var NA={type:"object",properties:{personalizations:{type:"array",description:"An array of messages and their metadata. Each object within personalizations can be thought of as an envelope - it defines who should receive an individual message and how that message should be handled. See our [Personalizations documentation](https://sendgrid.com/docs/for-developers/sending-email/personalizations/) for examples.",uniqueItems:!1,maxItems:1e3,items:{type:"object",properties:{from:{title:"From Email Object",type:"object",properties:{email:{type:"string",format:"email",description:"The 'From' email address used to deliver the message. This address should be a verified sender in your Twilio SendGrid account."},name:{type:"string",description:"A name or title associated with the sending email address."}},required:["email"]},to:{title:"To Email Array",type:"array",items:{type:"object",properties:{email:{type:"string",format:"email",description:"The intended recipient's email address."},name:{type:"string",description:"The intended recipient's name."}},required:["email"]}},cc:{type:"array",description:"An array of recipients who will receive a copy of your email. Each object in this array must contain the recipient's email address. Each object in the array may optionally contain the recipient's name.",maxItems:1e3,items:{title:"CC BCC Email Object",type:"object",properties:{email:{type:"string",format:"email",description:"The intended recipient's email address."},name:{type:"string",description:"The intended recipient's name."}},required:["email"]}},bcc:{type:"array",description:"An array of recipients who will receive a blind carbon copy of your email. Each object in this array must contain the recipient's email address. Each object in the array may optionally contain the recipient's name.",maxItems:1e3,items:{title:"CC BCC Email Object",type:"object",properties:{email:{type:"string",format:"email",description:"The intended recipient's email address."},name:{type:"string",description:"The intended recipient's name."}},required:["email"]}},subject:{type:"string",description:"The subject of your email. See character length requirements according to [RFC 2822](http://stackoverflow.com/questions/1592291/what-is-the-email-subject-length-limit#answer-1592310).",minLength:1},headers:{type:"object",description:"A collection of JSON key/value pairs allowing you to specify handling instructions for your email. You may not overwrite the following headers: `x-sg-id`, `x-sg-eid`, `received`, `dkim-signature`, `Content-Type`, `Content-Transfer-Encoding`, `To`, `From`, `Subject`, `Reply-To`, `CC`, `BCC`"},substitutions:{type:"object",description:'Substitutions allow you to insert data without using Dynamic Transactional Templates. This field should **not** be used in combination with a Dynamic Transactional Template, which can be identified by a `templateId` starting with `d-`. This field is a collection of key/value pairs following the pattern "substitutionTag":"value to substitute". The key/value pairs must be strings. These substitutions will apply to the text and html content of the body of your email, in addition to the `subject` and `reply-to` parameters. The total collective size of your substitutions may not exceed 10,000 bytes per personalization object.',maxProperties:1e4},dynamicTemplateData:{type:"object",description:'Dynamic template data is available using Handlebars syntax in Dynamic Transactional Templates. This field should be used in combination with a Dynamic Transactional Template, which can be identified by a `templateId` starting with `d-`. This field is a collection of key/value pairs following the pattern "variable_name":"value to insert".'},customArgs:{type:"object",description:"Values that are specific to this personalization that will be carried along with the email and its activity data. Substitutions will not be made on custom arguments, so any string that is entered into this parameter will be assumed to be the custom argument that you would like to be used. This field may not exceed 10,000 bytes.",maxProperties:1e4},sendAt:{type:"integer",description:"A unix timestamp allowing you to specify when your email should be delivered. Scheduling delivery more than 72 hours in advance is forbidden."}},required:["to"]}},from:{title:"From Email Object",type:"object",properties:{email:{type:"string",format:"email",description:"The 'From' email address used to deliver the message. This address should be a verified sender in your Twilio SendGrid account."},name:{type:"string",description:"A name or title associated with the sending email address."}},required:["email"]},replyTo:{title:"Reply_to Email Object",type:"object",properties:{email:{type:"string",format:"email",description:"The email address where any replies or bounces will be returned."},name:{type:"string",description:"A name or title associated with the `replyTo` email address."}},required:["email"]},replyToList:{type:"array",description:"An array of recipients who will receive replies and/or bounces. Each object in this array must contain the recipient's email address. Each object in the array may optionally contain the recipient's name. You can either choose to use \u201CreplyTo\u201D field or \u201CreplyToList\u201D but not both.",uniqueItems:!0,maxItems:1e3,items:{type:"object",properties:{email:{type:"string",description:"The email address where any replies or bounces will be returned.",format:"email"},name:{type:"string",description:"A name or title associated with the `replyToList` email address."}},required:["email"]}},subject:{type:"string",description:"The global or 'message level' subject of your email. This may be overridden by subject lines set in personalizations.",minLength:1},content:{type:"array",description:"An array where you can specify the content of your email. You can include multiple [MIME types](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) of content, but you must specify at least one MIME type. To include more than one MIME type, add another object to the array containing the `type` and `value` parameters.",items:{type:"object",properties:{type:{type:"string",description:"The MIME type of the content you are including in your email (e.g., `\u201Ctext/plain\u201D` or `\u201Ctext/html\u201D`).",minLength:1},value:{type:"string",description:"The actual content of the specified MIME type that you are including in your email.",minLength:1}},required:["type","value"]}},attachments:{type:"array",description:"An array of objects where you can specify any attachments you want to include.",items:{type:"object",properties:{content:{type:"string",description:"The Base64 encoded content of the attachment.",minLength:1},type:{type:"string",description:"The MIME type of the content you are attaching (e.g., `\u201Ctext/plain\u201D` or `\u201Ctext/html\u201D`).",minLength:1},filename:{type:"string",description:"The attachment's filename."},disposition:{type:"string",default:"attachment",description:"The attachment's content-disposition, specifying how you would like the attachment to be displayed. For example, `\u201Cinline\u201D` results in the attached file are displayed automatically within the message while `\u201Cattachment\u201D` results in the attached file require some action to be taken before it is displayed, such as opening or downloading the file.",enum:["inline","attachment"]},contentId:{type:"string",description:"The attachment's content ID. This is used when the disposition is set to `\u201Cinline\u201D` and the attachment is an image, allowing the file to be displayed within the body of your email."}},required:["content","filename"]}},templateId:{type:"string",description:"An email template ID. A template that contains a subject and content \u2014 either text or html \u2014 will override any subject and content values specified at the personalizations or message level."},headers:{description:"An object containing key/value pairs of header names and the value to substitute for them. The key/value pairs must be strings. You must ensure these are properly encoded if they contain unicode characters. These headers cannot be one of the reserved headers.",type:"object"},categories:{type:"array",description:"An array of category names for this message. Each category name may not exceed 255 characters. ",uniqueItems:!0,maxItems:10,items:{type:"string",maxLength:255}},customArgs:{description:"Values that are specific to the entire send that will be carried along with the email and its activity data. Key/value pairs must be strings. Substitutions will not be made on custom arguments, so any string that is entered into this parameter will be assumed to be the custom argument that you would like to be used. This parameter is overridden by `customArgs` set at the personalizations level. Total `customArgs` size may not exceed 10,000 bytes.",type:"string"},sendAt:{type:"integer",description:"A unix timestamp allowing you to specify when you want your email to be delivered. This may be overridden by the `sendAt` parameter set at the personalizations level. Delivery cannot be scheduled more than 72 hours in advance. If you have the flexibility, it's better to schedule mail for off-peak times. Most emails are scheduled and sent at the top of the hour or half hour. Scheduling email to avoid peak times \u2014 for example, scheduling at 10:53 \u2014 can result in lower deferral rates due to the reduced traffic during off-peak times."},batchId:{type:"string",description:"An ID representing a batch of emails to be sent at the same time. Including a `batchId` in your request allows you include this email in that batch. It also enables you to cancel or pause the delivery of that batch. For more information, see the [Cancel Scheduled Sends API](https://sendgrid.com/docs/api-reference/)."},asm:{type:"object",description:"An object allowing you to specify how to handle unsubscribes.",properties:{groupId:{type:"integer",description:"The unsubscribe group to associate with this email."},groupsToDisplay:{type:"array",description:"An array containing the unsubscribe groups that you would like to be displayed on the unsubscribe preferences page.",maxItems:25,items:{type:"integer"}}},required:["groupId"]},ipPoolName:{type:"string",description:"The IP Pool that you would like to send this email from.",minLength:2,maxLength:64},mailSettings:{type:"object",description:"A collection of different mail settings that you can use to specify how you would like this email to be handled.",properties:{bypassListManagement:{type:"object",description:"Allows you to bypass all unsubscribe groups and suppressions to ensure that the email is delivered to every single recipient. This should only be used in emergencies when it is absolutely necessary that every recipient receives your email. This filter cannot be combined with any other bypass filters. See our [documentation](https://sendgrid.com/docs/ui/sending-email/index-suppressions/#bypass-suppressions) for more about bypass filters.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."}}},bypassSpamManagement:{type:"object",description:"Allows you to bypass the spam report list to ensure that the email is delivered to recipients. Bounce and unsubscribe lists will still be checked; addresses on these other lists will not receive the message. This filter cannot be combined with the `bypassListManagement` filter. See our [documentation](https://sendgrid.com/docs/ui/sending-email/index-suppressions/#bypass-suppressions) for more about bypass filters.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."}}},bypassBounceManagement:{type:"object",description:"Allows you to bypass the bounce list to ensure that the email is delivered to recipients. Spam report and unsubscribe lists will still be checked; addresses on these other lists will not receive the message. This filter cannot be combined with the `bypassListManagement` filter. See our [documentation](https://sendgrid.com/docs/ui/sending-email/index-suppressions/#bypass-suppressions) for more about bypass filters.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."}}},bypassUnsubscribeManagement:{type:"object",description:"Allows you to bypass the global unsubscribe list to ensure that the email is delivered to recipients. Bounce and spam report lists will still be checked; addresses on these other lists will not receive the message. This filter applies only to global unsubscribes and will not bypass group unsubscribes. This filter cannot be combined with the `bypassListManagement` filter. See our [documentation](https://sendgrid.com/docs/ui/sending-email/index-suppressions/#bypass-suppressions) for more about bypass filters.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."}}},footer:{type:"object",description:"The default footer that you would like included on every email.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."},text:{type:"string",description:"The plain text content of your footer."},html:{type:"string",description:"The HTML content of your footer."}}},sandboxMode:{type:"object",description:"Sandbox Mode allows you to send a test email to ensure that your request body is valid and formatted correctly.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."}}}}},trackingSettings:{type:"object",description:"Settings to determine how you would like to track the metrics of how your recipients interact with your email.",properties:{clickTracking:{type:"object",description:"Allows you to track if a recipient clicked a link in your email.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."},enableText:{type:"boolean",description:"Indicates if this setting should be included in the `text/plain` portion of your email."}}},openTracking:{type:"object",description:"Allows you to track if the email was opened by including a single pixel image in the body of the content. When the pixel is loaded, Twilio SendGrid can log that the email was opened.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."},substitutionTag:{type:"string",description:"Allows you to specify a substitution tag that you can insert in the body of your email at a location that you desire. This tag will be replaced by the open tracking pixel."}}},subscriptionTracking:{type:"object",description:"Allows you to insert a subscription management link at the bottom of the text and HTML bodies of your email. If you would like to specify the location of the link within your email, you may use the `substitutionTag`.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."},text:{type:"string",description:"Text to be appended to the email with the subscription tracking link. You may control where the link is by using the tag <% %>"},html:{type:"string",description:"HTML to be appended to the email with the subscription tracking link. You may control where the link is by using the tag <% %>"},substitutionTag:{type:"string",description:"A tag that will be replaced with the unsubscribe URL. for example: `[unsubscribe_url]`. If this parameter is used, it will override both the `text` and `html` parameters. The URL of the link will be placed at the substitution tag\u2019s location with no additional formatting."}}},ganalytics:{type:"object",description:"Allows you to enable tracking provided by Google Analytics.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."},utmSource:{type:"string",description:"Name of the referrer source. (e.g. Google, SomeDomain.com, or Marketing Email)"},utmMedium:{type:"string",description:"Name of the marketing medium. (e.g. Email)"},utmTerm:{type:"string",description:"Used to identify any paid keywords."},utmContent:{type:"string",description:"Used to differentiate your campaign from advertisements."},utmCampaign:{type:"string",description:"The name of the campaign."}}}}}},required:[],additionalProperties:!1},fg={output:NA};var mg={anypost:ae,braze:ae,clickatell:ae,nodemailer:dg,emailjs:ae,"email-webhook":ae,"infobip-email":ae,mailersend:ae,mailgun:ug,mailjet:pg,mailtrap:ae,mandrill:ae,netcore:ae,"novu-email":hg,outlook365:ae,plunk:ae,postmark:ae,resend:ae,sendgrid:fg,sendinblue:ae,ses:ae,sparkpost:ae};var LA={type:"object",properties:{},required:[],additionalProperties:!1},gg={output:LA};var yg={novu:gg};var bg={anyOf:[{type:"string"},{type:"object",additionalProperties:!0,properties:{name:{type:"string"},volume:{type:"number"},critical:{type:"number"}},required:["name","volume","critical"]}]},DA={type:"object",properties:{topic:{type:"string",description:"The destination topic for the notification."},id:{type:"string",description:"A UUID to identify the notification with APNS. If an id is not supplied, APNS will generate one automatically. If an error occurs the response will contain the id. This property populates the apns-id header."},expiry:{type:"number",description:"A UNIX timestamp when the notification should expire. If the notification cannot be delivered to the device, APNS will retry until it expires. An expiry of 0 indicates that the notification expires immediately, therefore no retries will be attempted."},priority:{type:"number",description:`Provide one of the following values:
163
163
 
164
164
  10 - The push notification is sent to the device immediately. (Default)
165
165
  The push notification must trigger an alert, sound, or badge on the device. It is an error to use this priority for a push notification that contains only the content-available key.