@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}$$`},ix=e=>tx(e)%2===0?e:rx(e),ax=e=>nx(e)%2===1?`${e}$`:e,ox=(e,t,n)=>
153
153
  `);n&&r.length>0&&r.at(-1)===""&&r.pop();let i=[],a=!1,o=!1;for(let l=0;l<r.length;l++){let p=r[l].trim();if(!a&&(p.startsWith("```")||p.startsWith("~~~"))){o=!o,i.push(r[l]);continue}if(o){i.push(r[l]);continue}let d=p!==""&&(gc.test(p)||yc.test(p));if(d&&!a){let h=!1;for(let y=l;y<r.length;y++){let g=r[y].trim();if(yc.test(g)){h=!0;break}if(g===""||!gc.test(g))break}h&&(i.push("```"),a=!0)}else!d&&a&&(i.push("```"),a=!1);i.push(r[l])}a&&t&&i.push("```");let s=i.join(`
154
154
  `);return n&&(s+=`
155
155
  `),s}function Nx(e){return"adapterName"in e&&!("adapter"in e)}var dm="thread-state:";function hm(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}var Lx=new AbortController().signal;async function*Dx(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 Fx=class bc{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:Lx,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,Nx(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=mi().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=mi();return this._stateAdapterInstance=t.getState(),this._stateAdapterInstance}get recentMessages(){return this._recentMessages}set recentMessages(t){this._recentMessages=t}get state(){return this._stateAdapter.get(`${dm}${this.id}`)}async setState(t,n){let r=`${dm}${this.id}`;if(n!=null&&n.replace)await this._stateAdapter.set(r,t,fi);else{let a={...await this._stateAdapter.get(r),...t};await this._stateAdapter.set(r,a,fi)}}get channel(){if(!this._channel){let t=wm(this.adapter,this.id);this._channel=new bm({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 l of s)a=!0,yield l;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(wc(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(hm(t))return this.handleStream(t);let n=t;if(Nt(t)){let a=Mt(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 un(i)),i}async handlePostableObject(t){try{await mm(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(Nt(n)){let s=Mt(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 l=await this.adapter.postMessage(s,o);return{id:l.id,threadId:s,usedFallback:!0,raw:l.raw}}return null}async reply(t,n){if(!this.adapter.reply)throw new hi("Message replies are not supported by this adapter","replies");let r=t instanceof un?t:this.findKnownMessage(t);if(r&&r.threadId!==this.id)throw new Error("Cannot reply to a message from another thread");let i;if(hm(n)){let l="";for await(let p of mo(n))typeof p=="string"?l+=p:p.type==="markdown_text"&&(l+=p.text);i={markdown:l.trim()?l:" "}}else if(Nt(n)){let l=Mt(n);if(!l)throw new Error("Invalid JSX element: must be a Card element");i=l}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 un(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 yo(t,this._stateAdapter,n);if("card"in t&&((r=t.card)==null?void 0:r.type)==="card"){let i=await yo(t.card,this._stateAdapter,n);if(i!==t.card)return{...t,card:i}}return t}async schedule(t,n){let r;if(Nt(t)){let i=Mt(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 hi("Scheduled messages are not supported by this adapter","scheduling");return this.adapter.scheduleMessage(this.id,r,n)}async handleStream(t,n){let r=Dx(mo(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}}}},l;try{l=await this.adapter.stream(this.id,s,i)}catch(p){throw await this.finishTyping(),p}if(l){this._typingStarted=!1;let p=this.createSentMessage(l.id,{markdown:o},l.threadId);return this._threadHistory&&await this._threadHistory.append(this.id,new un(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 l=s.value;if(typeof l=="string")return{value:l,done:!1};if(l.type==="markdown_text")return{value:l.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 hi("Read receipts are not supported by this adapter","read-receipts");let n=t!=null?t:this._currentMessage;if(!n)throw new go("A message is required outside a message handler","MESSAGE_REQUIRED");if(typeof n!="string"&&n.threadId!==this.id)throw new go("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 Sm,l="",p=!1,d=null,h=null;a&&(o=a.threadId||this.id,l=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!==l)try{await this.adapter.editMessage(o,a.id,{markdown:ue}),l=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,l=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,l=I),K.trim()&&K!==l&&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 un(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 bc({id:t.id,adapterName:t.adapterName,channelId:t.channelId,channelVisibility:t.channelVisibility,currentMessage:t.currentMessage?un.fromJSON(t.currentMessage):void 0,isDM:t.isDM});return n&&(r._adapter=n),r}static[gr](t){return t.toJSON()}static[yr](t){return bc.fromJSON(t)}createSentMessage(t,n,r,i){let a=this.adapter,o=r||this.id,s=this,{plainText:l,formatted:p,attachments:d}=Ux(n);return{id:t,threadId:o,text:l,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 un(this).toJSON()},async edit(y){let g=y;if(Nt(y)){let I=Mt(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(Nt(o)){let l=Mt(o);if(!l)throw new Error("Invalid JSX element: must be a Card element");s=l}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 Ux(e){if(typeof e=="string")return{plainText:e,formatted:cn([ln([sn(e)])]),attachments:[]};if("raw"in e)return{plainText:e.raw,formatted:cn([ln([sn(e.raw)])]),attachments:e.attachments||[]};if("markdown"in e){let t=to(e.markdown);return{plainText:mr(t),formatted:t,attachments:e.attachments||[]}}if("ast"in e)return{plainText:mr(e.ast),formatted:e.ast,attachments:e.attachments||[]};if("card"in e){let t=e.fallbackText||ui(e.card);return{plainText:t,formatted:cn([ln([sn(t)])]),attachments:[]}}if("type"in e&&e.type==="card"){let t=ui(e);return{plainText:t,formatted:cn([ln([sn(t)])]),attachments:[]}}throw new Error("Invalid PostableMessage format")}po();var Tm=require("async_hooks");var M1=new Tm.AsyncLocalStorage;pi();Sc();var _M=10080*60*1e3;var IM=3600*1e3;var PM=600*1e3,MM=1440*60*1e3;var xm=new Map;function br(e){let t=xm.get(e);return t||(t=Object.freeze({name:e,toString:()=>`{{emoji:${e}}}`,toJSON:()=>`{{emoji:${e}}}`}),xm.set(e,t)),t}var Hx={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}"}},$x=class{constructor(e){Se(this,"emojiMap");Se(this,"slackToNormalized");Se(this,"gchatToNormalized");this.emojiMap={...Hx,...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 br(n)}fromGChat(e){var n;let t=(n=this.gchatToNormalized.get(e))!=null?n:e;return br(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 br(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()}},qx=new $x;function jx(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=>br(r)};for(let r of t)n[r]=br(r);if(e){for(let r of Object.keys(e))n[r]=br(r);qx.extend(e)}return n}var NM=jx(),gi=ni,yi=ri,bi=no;var wi=ci,Si=qf,Ti=li,xi=ei,Am=ai,vm=oi;var Ai=Zr;var vi=ii,km=ti,ki=si;var Em=so,Rm=io;var Cm=co,Ei=oo,Ri=lo,Ci=ao;function wr(e){return"type"in e&&e.type==="card"}function Om(e){return typeof e=="object"&&e!==null&&e.type==="tool-approval-card"}function _m(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 Tc(e,t){return(e==null?void 0:e.workflowId)===t.id}var Bx=Symbol.for("chat.jsx.element"),zx=new Set([gi,yi,bi,wi,Si,Ti,xi,Em,Am,vm,Ai,vi,Rm,Cm,km,Ei,Ri,ki,Ci]);function Vx(e){return typeof e=="object"&&e!==null&&"type"in e}function Wx(e){return typeof e=="object"&&e!==null&&e.$$typeof===Bx}async function wo(e){let t=bo(e);if(t&&typeof t=="object"&&wr(t))return t;let{isJSX:n,toCardElement:r}=await Promise.resolve().then(()=>(Pm(),Im));return n(t)?r(t):null}function bo(e){var t;if(Array.isArray(e))return e.map(n=>bo(n));if(!Wx(e))return Yx(e);if(typeof e.type=="function"&&!zx.has(e.type)){let n={...(t=e.props)!=null?t:{}};return e.children!==void 0&&(n.children=e.children),bo(e.type(n))}return{...e,children:bo(e.children)}}function Yx(e){return typeof e=="string"||typeof e=="number"||Vx(e)?e:null}var Mm=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("")},Nm=(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 Jx=require("cross-fetch");var Lm=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 Dm(e){return!!e&&typeof e=="object"&&"error"in e&&"message"in e&&"statusCode"in e}var So=(e,t)=>{if(!e)throw new ca;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 Dm(a)?new ua(a.statusCode,a.error,a.message):new ar(a)},delete:async n=>(await fetch(`${t}/v1${n}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${e}`}})).json()}};var jm=require("liquidjs");function xc(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]=xc(n[r]||{},i):(Array.isArray(i),n[r]=i)}return n}function To(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 Fm(e,t=2,n,r=", "){if(!Array.isArray(e)||e.length===0)return"";let i=n?e.map(s=>typeof s!="object"||!s?"":To(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),l=i[i.length-1];return`${s.join(r)} and ${l}`}let a=i.slice(0,t),o=i.length-t;return`${a.join(r)} and ${o} ${o===1?"other":"others"}`}var Um=Vt(require("pluralize"),1);function Hm(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,Um.default)(t,i),r==="true"?`${i} ${a}`:a}var Gx=require("liquidjs"),$m=Vt(require("pluralize"),1),Kx=require("zod");var Xx="",Qx=2,Zx="other",eA=", ",tA=" and ",nA=", and ";function qm(e,t=Xx,n=Qx,r=Zx,i=eA,a=tA,o=nA){if(!Array.isArray(e)||e.length===0)return"";let s=t?e.map(y=>typeof y!="object"||!y?"":To(y,t)):e,l=s.length;if(l===1)return s[0];if(l===2)return`${s[0]}${a}${s[1]}`;if(n>=l){let y=s.slice(0,l-1),g=s[l-1];return`${y.join(i)}${o}${g}`}let p=s.slice(0,n),d=l-n,h=n===1?a:o;return`${p.join(i)}${h}${d} ${(0,$m.default)(r,d)}`}function rA(e){return Array.isArray(e)||typeof e=="object"&&e!==null?Bm(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 Bm=(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 zm(e){let t=new jm.Liquid({outputEscape:rA,...e});return t.registerFilter("json",(n,r)=>Bm(n,r)),t.registerFilter("digest",Fm),t.registerFilter("toSentence",qm),t.registerFilter("pluralize",Hm),t}var Qn=Vt(require("chalk"),1),et={info:e=>Qn.default.blue(e),warning:e=>Qn.default.yellow(e),error:e=>Qn.default.red(e),success:e=>Qn.default.green(e),underline:e=>Qn.default.underline(e),bold:e=>Qn.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 xo(e){return e||process.env.NOVU_API_URL||"https://api.novu.co"}function Ao(e){return e||process.env.NOVU_SECRET_KEY||process.env.NOVU_API_KEY||""}var Ac=Vt(require("sanitize-html"),1),iA=["src","alt","width","height","loading","srcset","sizes","crossorigin","usemap","ismap","class","id","style","title","dir","lang"];function aA(e){return e.toLowerCase().startsWith("on")}function oA(e){return e.replace(/<\/([a-zA-Z][a-zA-Z0-9]*)\s*\/[^>]*>/g,"</$1>")}var sA={allowedTags:Ac.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))aA(r)||(n[r]=i);return{tagName:e,attribs:n}},img:(e,t)=>{let n={};for(let[r,i]of Object.entries(t))iA.includes(r.toLowerCase())&&(n[r]=i);return{tagName:e,attribs:n}}},allowVulnerableTags:!0,parseStyleAttributes:!1,parser:{lowerCaseAttributeNames:!0}},Vm=e=>{if(!e)return e;let t=oA(e),n=/^<!DOCTYPE .*?>/,r=t.match(n),i=(0,Ac.default)(t,sA);return r?r[0]+i:i},vo=e=>Object.keys(e).reduce((t,n)=>{let r=e[n];return typeof r=="string"?t[n]=Vm(r):Array.isArray(r)?t[n]=r.map(i=>typeof i=="string"?Vm(i):typeof i=="object"?vo(i):i):typeof r=="object"&&r!==null?t[n]=vo(r):t[n]=r,t},{});function Wm(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,l)=>{let p=l===r.providers.length-1,d=a?" ":"\u2502",h=p?"\u2514":"\u251C";n.info(`${d} ${h} ${lt.PROVIDER} Discovered provider: '${s.type}'`)})}))}var Ym=require("jsonrepair");function Jm(e){let t=e.trim();return(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))&&t.length>2}var Gm="__novuJsonString";function lA(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&e[Gm]===!0}function Oi(e){if(typeof e=="string"){if(!Jm(e))return e;try{let t=JSON.parse(e);return{[Gm]:!0,value:Oi(t)}}catch{return e}}if(Array.isArray(e))return e.map(t=>Oi(t));if(e&&typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=Oi(r);return t}return e}function _i(e){if(lA(e))return JSON.stringify(_i(e.value));if(Array.isArray(e))return e.map(t=>_i(t));if(e&&typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=_i(r);return t}return e}function cA(e){try{return JSON.parse(e),e}catch{try{return(0,Ym.jsonrepair)(e)}catch{return e}}}function Km(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>typeof n=="string"?[t,Jm(n)?cA(n):n]:typeof n=="object"&&n!==null&&!Array.isArray(n)?[t,Km(n)]:[t,n]))}function Xm(e){return!(e!=null&&e.data)||typeof e.data!="object"||Array.isArray(e.data)?e:{...e,data:Km(e.data)}}var Zm=Vt(require("ajv"),1),eg=Vt(require("ajv-formats"),1);var Qm=e=>typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e));var ko=class extends Cn{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 Eo=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(l=>i.value[l]!==void 0)||n.add(o.name)}),n.size>0)throw new ko(t,Array.from(n))};var Ro=class{constructor(){this.requiredImports=[];this.ajv=new Zm.default({useDefaults:!0,removeAdditional:"failing",strict:!1}),(0,eg.default)(this.ajv),this.compiledSchemas=new Map}async canHandle(t){let n=t.type==="object"||!!t.anyOf||!!t.allOf||!!t.oneOf;return n&&await Eo(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=Qm(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 Co=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 Eo(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 Oo=new Co,_o=new Ro,Ii=async(e,t)=>{if(await Oo.canHandle(e))return Oo.validate(t,e);if(await _o.canHandle(e))return _o.validate(t,e);throw new Error("Invalid schema")},bt=async e=>{if(await Oo.canHandle(e))return Oo.transformToJsonSchema(e);if(await _o.canHandle(e))return _o.transformToJsonSchema(e);throw new Error("Invalid schema")};function tg(){return["development",void 0,"dev"].includes(process.env.NODE_ENV)}var Sr=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=zm()}buildOptions(t){let n={apiUrl:xo(t==null?void 0:t.apiUrl),secretKey:Ao(t==null?void 0:t.secretKey),strictAuthentication:!tg(),verbose:tg(),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();Wm(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 $r(t)}getStep(t,n){let i=this.getWorkflow(t).steps.find(a=>a.stepId===n);if(i)return i;throw new ba(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 Ju(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 l=await Ii(n,t);if(l.success)return l.data;switch(r){case"event":this.throwInvalidEvent(i,a,l.errors);case"step":this.throwInvalidStep(o,i,a,l.errors);case"provider":this.throwInvalidProvider(o,s,i,a,l.errors);default:throw new Error(`Invalid component: '${r}'`)}}throwInvalidProvider(t,n,r,i,a){throw t?n?r==="output"?new aa(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 na(r,t,i);case"result":throw new ra(r,t,i);case"controls":throw new ta(r,t,i);default:throw new Error(`Invalid payload type: '${n}'`)}}throwInvalidEvent(t,n,r){switch(t){case"controls":throw new ea(n,r);case"payload":throw new Fr(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),l=t.action==="preview";if(!l&&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(l?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 pa(g.type);return{...g,resolve:I}}),resolve:a});return this.shouldSanitize({stepType:s.type,options:o})&&(y={...y,outputs:vo(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,l)=>{let p=l===r.providers.length-1,d=a?" ":"\u2502",h=p?"\u2514":"\u251C";n.info(`${d} ${h} ${lt.PROVIDER} Discovered provider: '${s.type}'`)})}))}var Ym=require("jsonrepair");function Jm(e){let t=e.trim();return(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))&&t.length>2}var Gm="__novuJsonString";function lA(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&e[Gm]===!0}function Oi(e){if(typeof e=="string"){if(!Jm(e))return e;try{let t=JSON.parse(e);return{[Gm]:!0,value:Oi(t)}}catch{return e}}if(Array.isArray(e))return e.map(t=>Oi(t));if(e&&typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=Oi(r);return t}return e}function _i(e){if(lA(e))return JSON.stringify(_i(e.value));if(Array.isArray(e))return e.map(t=>_i(t));if(e&&typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=_i(r);return t}return e}function cA(e){try{return JSON.parse(e),e}catch{try{return(0,Ym.jsonrepair)(e)}catch{return e}}}function Km(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>typeof n=="string"?[t,Jm(n)?cA(n):n]:typeof n=="object"&&n!==null&&!Array.isArray(n)?[t,Km(n)]:[t,n]))}function Xm(e){return!(e!=null&&e.data)||typeof e.data!="object"||Array.isArray(e.data)?e:{...e,data:Km(e.data)}}var Zm=Vt(require("ajv"),1),eg=Vt(require("ajv-formats"),1);var Qm=e=>typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e));var ko=class extends Cn{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 Eo=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(l=>i.value[l]!==void 0)||n.add(o.name)}),n.size>0)throw new ko(t,Array.from(n))};var Ro=class{constructor(){this.requiredImports=[];this.ajv=new Zm.default({useDefaults:!0,removeAdditional:"failing",strict:!1}),(0,eg.default)(this.ajv),this.compiledSchemas=new Map}async canHandle(t){let n=t.type==="object"||!!t.anyOf||!!t.allOf||!!t.oneOf;return n&&await Eo(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=Qm(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 Co=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 Eo(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 Oo=new Co,_o=new Ro,Ii=async(e,t)=>{if(await Oo.canHandle(e))return Oo.validate(t,e);if(await _o.canHandle(e))return _o.validate(t,e);throw new Error("Invalid schema")},bt=async e=>{if(await Oo.canHandle(e))return Oo.transformToJsonSchema(e);if(await _o.canHandle(e))return _o.transformToJsonSchema(e);throw new Error("Invalid schema")};function tg(){return["development",void 0,"dev"].includes(process.env.NODE_ENV)}var Sr=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=zm()}buildOptions(t){let n={apiUrl:xo(t==null?void 0:t.apiUrl),secretKey:Ao(t==null?void 0:t.secretKey),strictAuthentication:!tg(),verbose:tg(),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();Wm(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 $r(t)}getStep(t,n){let i=this.getWorkflow(t).steps.find(a=>a.stepId===n);if(i)return i;throw new ba(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 Ju(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 l=await Ii(n,t);if(l.success)return l.data;switch(r){case"event":this.throwInvalidEvent(i,a,l.errors);case"step":this.throwInvalidStep(o,i,a,l.errors);case"provider":this.throwInvalidProvider(o,s,i,a,l.errors);default:throw new Error(`Invalid component: '${r}'`)}}throwInvalidProvider(t,n,r,i,a){throw t?n?r==="output"?new aa(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 na(r,t,i);case"result":throw new ra(r,t,i);case"controls":throw new ta(r,t,i);default:throw new Error(`Invalid payload type: '${n}'`)}}throwInvalidEvent(t,n,r){switch(t){case"controls":throw new ea(n,r);case"payload":throw new Fr(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),l=t.action==="preview";if(!l&&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(l?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 pa(g.type);return{...g,resolve:I}}),resolve:a});return this.shouldSanitize({stepType:s.type,options:o})&&(y={...y,outputs:vo(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}},l,p=!1,d=new Promise(Oe=>{l=Oe}),h=Oe=>{if(p)throw new Error("setResult can only be called once per workflow execution");l(),p=!0,s=Oe},y=()=>p,g;try{if(t.action==="execute"&&!t.payload)throw new Fr(t.workflowId,{message:"Event `payload` is required"});let Oe=await this.createExecutionPayload(t,a),$={...t,payload:Oe};await Promise.race([d,a.execute({payload:Oe,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(Oe){g=Oe}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,l=r?et.error:et.success,p=`${i} ${s} workflowId: '${t.workflowId}`;this.logger.info(`
158
158
  ${et.bold(l(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,l=await this.runProvider(t,n,o,r,i);return{...s,[o.type]:l}},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 da(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),l=await this.executeProviders(t,n,s,i);return this.log(` ${lt.SUCCESS} Executed stepId: \`${n.stepId}\``),{outputs:s,providers:l}}catch(r){throw this.log(` ${lt.ERROR} Failed to execute stepId: \`${n.stepId}\``),$n(r)?r:new Hr(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 Zi(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 wo(n.card);return r?{...n,card:r}:n}async compileControls(t,n){var r;try{let i=Oi(t),a=this.preprocessTranslationPatterns(JSON.stringify(i));a=this.preprocessFilterTranslationArgs(a);let o=this.templateEngine.parse(a),s=this.getWorkflow(n.workflowId),l={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:pA(n.state),env:(r=n.env)!=null?r:{}},p=await this.templateEngine.render(o,l),d=this.postprocessTranslationMarkers(p),h=(0,ng.jsonrepair)(d),y=JSON.parse(h),g=_i(y);return Xm(g)}catch(i){throw new ia(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}\``),$n(r)?r:new Hr(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:xc(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 $r(t);return r}};function pA(e){let t={};for(let n of e)t[n.stepId]=n.outputs;return t}var rg=Symbol.for("novu.agent.runtimeContext");var vc=(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))(vc||{});function kc(e){return typeof e=="object"&&e!==null&&"content"in e&&!("type"in e)}var Tr=class{constructor(){this.__novuPendingApproval=!0}};function ig(e){return typeof e=="object"&&e!==null&&"suppress"in e&&e.suppress===!0}var dA=5*1024*1024,hA=5*1024*1024,ag=32768,fA=/^[A-Za-z0-9+/]*={0,2}$/;function Mi(e,t){return e.filename?`"${e.filename}"`:`at index ${t}`}function og(){return globalThis.Buffer}function mA(e){var t,n,r;return(r=(n=(t=og())==null?void 0:t.isBuffer)==null?void 0:n.call(t,e))!=null?r:!1}function gA(e){return typeof Blob!="undefined"&&e instanceof Blob}function Ec(e){let t=og();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+=ag){let i=e.subarray(r,r+ag);n+=String.fromCharCode(...i)}return btoa(n)}function sg(e){let t=e.replace(/\s/g,""),n=t.length%4;if(!t||n===1||!fA.test(t))return null;let r=t.endsWith("==")?2:t.endsWith("=")?1:0;return Math.floor(t.length*3/4)-r}function Pi(e,t,n){if(e>dA)throw new Error(`Invalid file ${Mi(t,n)}: inline data must be 5 MB or smaller. Use a publicly-accessible URL for larger files.`)}async function yA(e,t,n){if(typeof e=="string"){let r=sg(e);if(r===null)throw new Error(`Invalid file ${Mi(t,n)}: data must be a base64-encoded string.`);return Pi(r,t,n),e}if(mA(e))return Pi(e.byteLength,t,n),e.toString("base64");if(e instanceof Uint8Array)return Pi(e.byteLength,t,n),Ec(e);if(e instanceof ArrayBuffer)return Pi(e.byteLength,t,n),Ec(new Uint8Array(e));if(gA(e))return Pi(e.size,t,n),Ec(new Uint8Array(await e.arrayBuffer()));throw new Error(`Invalid file ${Mi(t,n)}: data must be a base64 string, Buffer, Uint8Array, ArrayBuffer, or Blob.`)}async function bA(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,l=o!=null;if(s===l)throw new Error(`Invalid file ${Mi(i,r)}: provide exactly one of data or url.`);if(s){let p=await yA(a,i,r),d=sg(p);if(n+=d!=null?d:0,n>hA)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(l&&typeof o!="string")throw new Error(`Invalid file ${Mi(i,r)}: url must be a string.`);t.push(i)}return t}async function Io(e,t){let n=await bA(t);if(typeof e=="string")return n?{markdown:e,files:n}:{markdown:e};let r=await wo(e);if(r)return n?{card:r,files:n}:{card:r};throw new Error("Invalid message content \u2014 expected string or CardElement")}var lg=1;var wA={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 Po(e){return typeof e=="string"&&e.trim()?e:!e||typeof e!="object"?null:Po(e.message)}function SA(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=Po(n.message);if(r)return r;let i=Po(n.error);if(i)return i;let a=n.errors;return Array.isArray(a)?Po(a[0]):null}function TA(e,t){var i;let n=(i=wA[e])!=null?i:e,r=SA(t);return r?`Delivery failed: ${n}: ${r}`:`Delivery failed: ${n}`}var vn=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}},pn=class extends vn{constructor(t,n){let r={statusCode:t,responseBody:n};super(TA(t,n),{delivery:r}),this.name="AgentDeliveryError",this.statusCode=t,this.responseBody=n}};function Ni(e){return e instanceof vn?e:e instanceof Error?new vn(e.message,{cause:e}):new vn("Turn failed",{cause:e})}function xA(e){return new Promise(t=>{setTimeout(t,e)})}function AA(e){return e>=500||e===408||e===429}var Mo=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:lg,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,!vA(i))throw i;r<this.maxRetries&&await xA(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 kA(i)}let r=await n.text().catch(()=>"");if(!n.ok)throw new pn(n.status,r)}};function vA(e){return!(e instanceof pn)||e.statusCode===0?!0:AA(e.statusCode)}function kA(e){if(e instanceof pn)return e;let t=e instanceof Error?e.message:"Network request failed";return new pn(0,t)}var Rc="human:";function No(e){return`${Rc}${e}:approve`}function Lo(e){return`${Rc}${e}:deny`}function xr(e,t){return`${Rc}${e}:opt:${t}`}function cg(e){return typeof e=="string"?e:e.label}function EA(e){return typeof e=="string"?void 0:e.id}function RA(e){return typeof e=="string"?e:e.id}function Fo(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 CA(e){if(!("title"in e))return;let t=e.title;return typeof t=="string"&&t.trim()?t.trim():void 0}function Uo(e){if(!e||e.length<2||e.length>10)throw new Error("ctx.choose requires between 2 and 10 options");if(e.some(t=>cg(t).trim().length===0))throw new Error("ctx.choose options must be non-empty strings")}function Ho(e){if(e.length>4)throw new Error("ctx.approve card.extraActions supports at most 4 buttons");for(let t of e){let n=EA(t);if(!cg(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 OA(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 Do(e,t=[]){if(Array.isArray(e)){for(let r of e)Do(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"&&Do(r,t);return t}function _A(e){return new Set(Do(e).map(t=>t.id))}function IA(e,t){let n=xr(t,"");return e.startsWith(n)&&e.length>n.length?e.slice(n.length):e}function PA(e,t){let n=Do(e),r=new Set(n.map(s=>s.id)),i=No(t),a=Lo(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:IA(s.id,t),label:s.label}));o.length&&Ho(o)}function MA(e,t,n){if(n){Uo(n);for(let i of n){let a=RA(i);if(!e.has(xr(t,a)))throw new Error(`ctx.choose render must include a button with actionIds.option('${a}')`)}return}let r=NA(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 NA(e,t){let n=xr(t,"");return[...e].filter(r=>r.startsWith(n)&&r.length>n.length).map(r=>r.slice(n.length))}function ug(e,t,n){var r;switch(Fo(e,t.title),e){case"ask":case"tell":return;case"approve":t.type==="human-approve-card"&&t.extraActions&&Ho(t.extraActions);return;case"choose":Uo(t.type==="human-choose-card"&&(r=t.options)!=null?r:n);return;default:return}}function pg(e,t,n,r){switch(OA(t),Fo(e,CA(t)),e){case"ask":case"tell":return;case"approve":PA(t,n);return;case"choose":MA(_A(t),n,r);return;default:return}}function $o(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 dg="tool-approval";function LA(e){return e==="approve"||e==="deny"}function Cc(e,t){return`${dg}:${e}:${t}`}function hg(e){let[t,n,...r]=(e!=null?e:"").split(":"),i=r.join(":");return t!==dg||!LA(n)||!i?null:{approved:n==="approve",approvalId:i}}async function fg(e,t,n,r,i){var d,h;let a=r!=null?r:t.id,o={approve:Cc("approve",a),deny:Cc("deny",a)},s=y=>({type:"tool-approval-card",...y}),l=(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),Om(l)){await e.replyApprovalCard(l);return}await e.reply(l)}function qo(e){return t=>({type:e,...t})}function jo(e,t){switch(e){case"ask":return{requestId:t,askCard:qo("human-ask-card")};case"approve":return{requestId:t,actionIds:{approve:No(t),deny:Lo(t)},approveCard:qo("human-approve-card")};case"choose":return{requestId:t,actionIds:{option:n=>xr(t,n)},chooseCard:qo("human-choose-card")};case"tell":return{requestId:t,tellCard:qo("human-tell-card")};default:return e}}function Ic(e){return`${e}_${crypto.randomUUID()}`}function DA(e){let{type:t,...n}=e;return n}function FA(e){if(!(!e||!("card"in e)))return e.card}function Bo(e){if(!(!e||!("render"in e)))return e.render}function UA(e){return typeof e=="object"&&e!==null&&wr(e)?e:{type:"card",children:[e]}}function Oc(e){if(!(!e||!("ttlSeconds"in e)||typeof e.ttlSeconds!="number"))return e.ttlSeconds}function mg(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 HA(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 gg(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 _c(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 Pc=class{constructor(t){this.outbox=t}async sendReply(t,n,r){let i=Ic("msg"),a=_c(n);return a.push({type:"message",role:"assistant",messageId:i,content:mg(t),files:gg(t.files),...r?{quoteReply:r}:{}}),await this._emitAndFlush(a),{messageId:i,platformThreadId:""}}async sendApprovalCard(t,n){return await this._emitAndFlush(_c(n,{deliverApprovalCard:!0})),"unaddressable"}async editMessage(t,n){return await this.outbox.emit({type:"channel.edit",messageId:t,content:mg(n),files:gg(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(_c(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()}}},zo=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 Io(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)}},Mc=class{constructor(){this.messageId="";this.platformThreadId=""}async edit(){return this}async delete(){}},yg;yg=rg;var Vo=class{constructor(t,n,r){this[yg]=!0;this._signals=[];this._toolResults=[];this._pendingToolApprovalRequest=null;this._pendingReactions=[];this._pendingDeletes=[];this._resolveSignal=null;this._pendingHumanRenders=[];var l,p,d,h,y,g;this.event=t.event,this.action=(l=t.action)!=null?l: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 Pc(new Mo({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 fg(this,I,this._toolApprovalConfig,void 0,K),new Tr)}}asMessageContext(){return this}async reply(t,n){await this.materializePendingHumanRenders();let r=await Io(t,n==null?void 0:n.files),i=this._drainSideEffectsSnapshot(),a=n!=null&&n.quoteReply?HA(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 zo(o.messageId,o.platformThreadId,this._transport)}async replyApprovalCard(t){await this.materializePendingHumanRenders();let n=this._drainSideEffectsSnapshot();return await this._transport.sendApprovalCard(t,n),new Mc}createReplyHandle(t){return new zo(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=Bo(i);return a?this.queueRendered("ask",i,a):this.queueHumanSignal("ask",t,n)}approve(t,n){let i=typeof t!="string"?t:n,a=Bo(i);return a?this.queueRendered("approve",i,a):this.queueHumanSignal("approve",t,n)}choose(t,n,r){var l;let i=typeof t!="string",a,o;i?a=t:Array.isArray(n)?(a=r,o=n):a=n;let s=Bo(a);return s?this.queueRendered("choose",a,s):i?this.queueHumanSignal("choose",t,void 0,"card"in t?(l=t.card)==null?void 0:l.options:void 0):this.queueHumanSignal("choose",t,a,o)}tell(t,n){let r=typeof t!="string",i=r?t:n,a=Bo(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,l=FA(s),p=Fo(t,(o==null?void 0:o.trim())||(l==null?void 0:l.title));if(t==="choose"){let I=i!=null?i:l==null?void 0:l.options;Uo(I)}t==="approve"&&(l!=null&&l.extraActions)&&Ho(l.extraActions);let d=Ic("hr"),h=(s==null?void 0:s.to)!==void 0?$o(s.to):void 0,y={...l,title:p,...t==="choose"&&i?{options:i}:{}},g=Oc(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=Ic("hr");return this._pendingHumanRenders.push(async()=>{let a=await this.invokeHumanRender(t,i,r);if(_m(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(jo("ask",n)));case"approve":return Promise.resolve(r(jo("approve",n)));case"choose":return Promise.resolve(r(jo("choose",n)));case"tell":return Promise.resolve(r(jo("tell",n)));default:{let i=t;return Promise.resolve(i)}}}pushRenderedChrome(t,n,r,i){ug(t,r);let a=DA(r),o=Oc(i),s=(i==null?void 0:i.to)!==void 0?$o(i.to):void 0,l=t==="approve"||t==="choose";this._signals.push({type:"human",kind:t,requestId:n,...l?{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){pg(t,r,n);let a=await Io(UA(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=Oc(i),s=(i==null?void 0:i.to)!==void 0?$o(i.to):void 0,l=t==="approve"||t==="choose";this._signals.push({type:"human",kind:t,requestId:n,...l?{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 $A(e){return!!(typeof e=="string"||typeof e=="object"&&e!==null&&wr(e)||typeof e=="object"&&e!==null&&("markdown"in e||"card"in e||"files"in e))}function qA(e,t){return e}var bg="tool_approval:";function jA(e){if(!(e!=null&&e.startsWith(bg)))return null;let t=e.slice(bg.length);return t.length>0?t:null}async function wg(e,t){await e.reply(t.content,{files:t.files,quoteReply:t.quoteReply})}async function Zn(e,t){if(!(t instanceof Tr||t===void 0)){if(kc(t)){await wg(e,t);return}await e.reply(t)}}async function BA(e,t){return ig(t)?!0:kc(t)?(await wg(e,t),!0):$A(t)?(await e.reply(t),!0):!1}function zA(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 Sg(e){var a;let t=new Vo(e.bridge,e.secretKey,e.agent.handlers.toolApproval),{agent:n,event:r,logger:i}=e;try{t.queueRunStart(),await WA(n,r,t),await t.flush(),await t.emitRunFinish({outcome:"completed"})}catch(o){let s=Ni(o);i==null||i.error(`[agent:${n.id}] Turn failed (${r}): ${s.message}`,(a=s.cause)!=null?a:s);let l=!1;if(n.handlers.onError)try{let p=await n.handlers.onError(s,qA(t,r));l=await BA(t,p)}catch(p){i==null||i.error(`[agent:${n.id}] onError failed:`,p)}l?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,l,p,d,h,y;let n=jA((s=t.humanResponse)==null?void 0:s.requestId),r=hg((l=t.action)==null?void 0:l.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=zA(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 Zn(t,H);return}let o=t.action;o&&e.handlers.onAction&&await Zn(t,await e.handlers.onAction(o,t))}async function WA(e,t,n){switch(t){case"onMessage":{let r=n.message;r&&await Zn(n,await e.handlers.onMessage(r,n));break}case"onMessageUpdated":{let r=n.message;r&&e.handlers.onMessageUpdated&&await Zn(n,await e.handlers.onMessageUpdated(r,n));break}case"onMessageDeleted":{let r=n.message;r&&e.handlers.onMessageDeleted&&await Zn(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 Zn(n,await e.handlers.onReaction(r,n));break}case"onResolve":e.handlers.onResolve&&await Zn(n,await e.handlers.onResolve(n));break;default:throw new qn(t,vc)}}function Tg(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),l=a.slice(o+1);s&&l&&!(s in t)&&(t[s]=l)}let n=t.t,r=n!==void 0?Number(n):Number.NaN;return{t:Number.isFinite(r)?r:void 0,v1:t.v1}}var Ar=class{constructor(t){this.handler=t.handler,this.client=t.client?t.client:new Sr,this.workflows=t.workflows||[],this.agents=t.agents||[],this.http=So(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")||"",l=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,l,(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 la(r))}getPostActionMap(t,n,r,i,a,o,s){return{trigger:this.triggerAction({workflowId:n,...t}),execute:async()=>{let l=await this.client.executeWorkflow({...t,workflowId:n,stepId:r,action:i});return this.createResponse(200,l)},preview:async()=>{let l=await this.client.executeWorkflow({...t,workflowId:n,stepId:r,action:i});return this.createResponse(200,l)},"agent-event":async()=>{let l=this.client.getAgent(a);if(!l)return this.createResponse(404,{error:`Agent '${a}' not registered`});let p=Sg({agent:l,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(Lr).includes(t)){let r=n[t];return r()}else throw new qn(t,Lr)}async handleGetAction(t,n){if(Object.values(Gi).includes(t)){let r=n[t];return r()}else throw new qn(t,Gi)}handleError(t){if($n(t))return t.statusCode>=500&&this.client.logger.error(t),this.createError(t);if($u(t))return this.createError(t);{let n=new ar(t);return this.client.logger.error(n),this.createError(n)}}async validateHmac(t,n){if(!this.hmacEnabled)return;if(!n)throw new fa;if(!this.client.secretKey)throw new ya;let r=Tg(n);if(!r.v1||r.t===void 0)throw new ma;let i=Date.now();if(r.t<i-3e5||r.t>i+3e5)throw new ga;let a=await Mm(this.client.secretKey,`${r.t}.${JSON.stringify(t)}`);if(!Nm(a,r.v1))throw new ha}};function Nc(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 YA={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},Ag={output:YA};var JA={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},vg={output:JA};var kg={"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":Ag,"rocket-chat":ae,ryver:ae,sendblue:ae,slack:vg,"webex-messaging":ae,"whatsapp-business":ae,zulip:ae,telegram:ae};var GA={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},Eg={output:GA};var er={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},KA={type:"object",properties:{contentType:{type:"string"},filename:{type:"string"},base64Content:{type:"string"}},required:["ContentType","Filename","Base64Content"],additionalProperties:!0},XA={type:"object",properties:{filename:{type:"string"},contentType:{type:"string"},contentId:{type:"string"},base64Content:{type:"string"}},required:["ContentType","Filename","Base64Content"],additionalProperties:!0},QA={type:"object",properties:{from:er,sender:er,to:{type:"array",items:er},cc:{type:"array",items:er},bcc:{type:"array",items:er},replyTo:er,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:er,templateErrorDeliver:{type:"boolean"},attachments:{type:"array",items:KA},inlineAttachments:{type:"array",items:XA},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},Rg={output:QA};var en={type:"object",properties:{address:{type:"string"},name:{type:"string"}},additionalProperties:!0},Wo={type:"object",properties:{content:{type:"string"},path:{type:"string"}},additionalProperties:!0},ZA={type:"object",properties:{from:{anyOf:[{type:"string"},en]},sender:{anyOf:[{type:"string"},en]},to:{anyOf:[{type:"string"},en,{type:"array",items:en}]},cc:{anyOf:[{type:"string"},en,{type:"array",items:en}]},bcc:{anyOf:[{type:"string"},en,{type:"array",items:en}]},replyTo:{anyOf:[{type:"string"},en,{type:"array",items:en}]},inReplyTo:{anyOf:[{type:"string"},en]},references:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},subject:{type:"string"},text:{anyOf:[{type:"string"},Wo]},html:{anyOf:[{type:"string"},Wo]},watchHtml:{anyOf:[{type:"string"},Wo]},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"},Wo]}}}]},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},Cg={output:ZA};var ev={type:"object",properties:{},required:[],additionalProperties:!1},Og={output:ev};var tv={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},_g={output:tv};var Ig={anypost:ae,braze:ae,clickatell:ae,nodemailer:Cg,emailjs:ae,"email-webhook":ae,"infobip-email":ae,mailersend:ae,mailgun:Eg,mailjet:Rg,mailtrap:ae,mandrill:ae,netcore:ae,"novu-email":Og,outlook365:ae,plunk:ae,postmark:ae,resend:ae,sendgrid:_g,sendinblue:ae,ses:ae,sparkpost:ae};var nv={type:"object",properties:{},required:[],additionalProperties:!1},Pg={output:nv};var Mg={novu:Pg};var Ng={anyOf:[{type:"string"},{type:"object",additionalProperties:!0,properties:{name:{type:"string"},volume:{type:"number"},critical:{type:"number"}},required:["name","volume","critical"]}]},rv={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,l=await this.runProvider(t,n,o,r,i);return{...s,[o.type]:l}},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 da(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),l=await this.executeProviders(t,n,s,i);return this.log(` ${lt.SUCCESS} Executed stepId: \`${n.stepId}\``),{outputs:s,providers:l}}catch(r){throw this.log(` ${lt.ERROR} Failed to execute stepId: \`${n.stepId}\``),$n(r)?r:new Hr(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 Zi(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 wo(n.card);return r?{...n,card:r}:n}async compileControls(t,n){var r;try{let i=Oi(t),a=this.preprocessTranslationPatterns(JSON.stringify(i));a=this.preprocessFilterTranslationArgs(a);let o=this.templateEngine.parse(a),s=this.getWorkflow(n.workflowId),l={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:pA(n.state),env:(r=n.env)!=null?r:{}},p=await this.templateEngine.render(o,l),d=this.postprocessTranslationMarkers(p),h=(0,ng.jsonrepair)(d),y=JSON.parse(h),g=_i(y);return Xm(g)}catch(i){throw new ia(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}\``),$n(r)?r:new Hr(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:xc(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 $r(t);return r}};function pA(e){let t={};for(let n of e)t[n.stepId]=n.outputs;return t}var rg=Symbol.for("novu.agent.runtimeContext");var vc=(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))(vc||{});function kc(e){return typeof e=="object"&&e!==null&&"content"in e&&!("type"in e)}var Tr=class{constructor(){this.__novuPendingApproval=!0}};function ig(e){return typeof e=="object"&&e!==null&&"suppress"in e&&e.suppress===!0}var dA=5*1024*1024,hA=5*1024*1024,ag=32768,fA=/^[A-Za-z0-9+/]*={0,2}$/;function Mi(e,t){return e.filename?`"${e.filename}"`:`at index ${t}`}function og(){return globalThis.Buffer}function mA(e){var t,n,r;return(r=(n=(t=og())==null?void 0:t.isBuffer)==null?void 0:n.call(t,e))!=null?r:!1}function gA(e){return typeof Blob!="undefined"&&e instanceof Blob}function Ec(e){let t=og();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+=ag){let i=e.subarray(r,r+ag);n+=String.fromCharCode(...i)}return btoa(n)}function sg(e){let t=e.replace(/\s/g,""),n=t.length%4;if(!t||n===1||!fA.test(t))return null;let r=t.endsWith("==")?2:t.endsWith("=")?1:0;return Math.floor(t.length*3/4)-r}function Pi(e,t,n){if(e>dA)throw new Error(`Invalid file ${Mi(t,n)}: inline data must be 5 MB or smaller. Use a publicly-accessible URL for larger files.`)}async function yA(e,t,n){if(typeof e=="string"){let r=sg(e);if(r===null)throw new Error(`Invalid file ${Mi(t,n)}: data must be a base64-encoded string.`);return Pi(r,t,n),e}if(mA(e))return Pi(e.byteLength,t,n),e.toString("base64");if(e instanceof Uint8Array)return Pi(e.byteLength,t,n),Ec(e);if(e instanceof ArrayBuffer)return Pi(e.byteLength,t,n),Ec(new Uint8Array(e));if(gA(e))return Pi(e.size,t,n),Ec(new Uint8Array(await e.arrayBuffer()));throw new Error(`Invalid file ${Mi(t,n)}: data must be a base64 string, Buffer, Uint8Array, ArrayBuffer, or Blob.`)}async function bA(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,l=o!=null;if(s===l)throw new Error(`Invalid file ${Mi(i,r)}: provide exactly one of data or url.`);if(s){let p=await yA(a,i,r),d=sg(p);if(n+=d!=null?d:0,n>hA)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(l&&typeof o!="string")throw new Error(`Invalid file ${Mi(i,r)}: url must be a string.`);t.push(i)}return t}async function Io(e,t){let n=await bA(t);if(typeof e=="string")return n?{markdown:e,files:n}:{markdown:e};let r=await wo(e);if(r)return n?{card:r,files:n}:{card:r};throw new Error("Invalid message content \u2014 expected string or CardElement")}var lg=1;var wA={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 Po(e){return typeof e=="string"&&e.trim()?e:!e||typeof e!="object"?null:Po(e.message)}function SA(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=Po(n.message);if(r)return r;let i=Po(n.error);if(i)return i;let a=n.errors;return Array.isArray(a)?Po(a[0]):null}function TA(e,t){var i;let n=(i=wA[e])!=null?i:e,r=SA(t);return r?`Delivery failed: ${n}: ${r}`:`Delivery failed: ${n}`}var vn=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}},pn=class extends vn{constructor(t,n){let r={statusCode:t,responseBody:n};super(TA(t,n),{delivery:r}),this.name="AgentDeliveryError",this.statusCode=t,this.responseBody=n}};function Ni(e){return e instanceof vn?e:e instanceof Error?new vn(e.message,{cause:e}):new vn("Turn failed",{cause:e})}function xA(e){return new Promise(t=>{setTimeout(t,e)})}function AA(e){return e>=500||e===408||e===429}var Mo=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:lg,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,!vA(i))throw i;r<this.maxRetries&&await xA(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 kA(i)}let r=await n.text().catch(()=>"");if(!n.ok)throw new pn(n.status,r)}};function vA(e){return!(e instanceof pn)||e.statusCode===0?!0:AA(e.statusCode)}function kA(e){if(e instanceof pn)return e;let t=e instanceof Error?e.message:"Network request failed";return new pn(0,t)}var Rc="human:";function No(e){return`${Rc}${e}:approve`}function Lo(e){return`${Rc}${e}:deny`}function xr(e,t){return`${Rc}${e}:opt:${t}`}function cg(e){return typeof e=="string"?e:e.label}function EA(e){return typeof e=="string"?void 0:e.id}function RA(e){return typeof e=="string"?e:e.id}function Fo(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 CA(e){if(!("title"in e))return;let t=e.title;return typeof t=="string"&&t.trim()?t.trim():void 0}function Uo(e){if(!e||e.length<2||e.length>10)throw new Error("ctx.choose requires between 2 and 10 options");if(e.some(t=>cg(t).trim().length===0))throw new Error("ctx.choose options must be non-empty strings")}function Ho(e){if(e.length>4)throw new Error("ctx.approve card.extraActions supports at most 4 buttons");for(let t of e){let n=EA(t);if(!cg(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 OA(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 Do(e,t=[]){if(Array.isArray(e)){for(let r of e)Do(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"&&Do(r,t);return t}function _A(e){return new Set(Do(e).map(t=>t.id))}function IA(e,t){let n=xr(t,"");return e.startsWith(n)&&e.length>n.length?e.slice(n.length):e}function PA(e,t){let n=Do(e),r=new Set(n.map(s=>s.id)),i=No(t),a=Lo(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:IA(s.id,t),label:s.label}));o.length&&Ho(o)}function MA(e,t,n){if(n){Uo(n);for(let i of n){let a=RA(i);if(!e.has(xr(t,a)))throw new Error(`ctx.choose render must include a button with actionIds.option('${a}')`)}return}let r=NA(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 NA(e,t){let n=xr(t,"");return[...e].filter(r=>r.startsWith(n)&&r.length>n.length).map(r=>r.slice(n.length))}function ug(e,t,n){var r;switch(Fo(e,t.title),e){case"ask":case"tell":return;case"approve":t.type==="human-approve-card"&&t.extraActions&&Ho(t.extraActions);return;case"choose":Uo(t.type==="human-choose-card"&&(r=t.options)!=null?r:n);return;default:return}}function pg(e,t,n,r){switch(OA(t),Fo(e,CA(t)),e){case"ask":case"tell":return;case"approve":PA(t,n);return;case"choose":MA(_A(t),n,r);return;default:return}}function $o(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 dg="tool-approval";function LA(e){return e==="approve"||e==="deny"}function Cc(e,t){return`${dg}:${e}:${t}`}function hg(e){let[t,n,...r]=(e!=null?e:"").split(":"),i=r.join(":");return t!==dg||!LA(n)||!i?null:{approved:n==="approve",approvalId:i}}async function fg(e,t,n,r,i){var d,h;let a=r!=null?r:t.id,o={approve:Cc("approve",a),deny:Cc("deny",a)},s=y=>({type:"tool-approval-card",...y}),l=(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),Om(l)){await e.replyApprovalCard(l);return}await e.reply(l)}function qo(e){return t=>({type:e,...t})}function jo(e,t){switch(e){case"ask":return{requestId:t,askCard:qo("human-ask-card")};case"approve":return{requestId:t,actionIds:{approve:No(t),deny:Lo(t)},approveCard:qo("human-approve-card")};case"choose":return{requestId:t,actionIds:{option:n=>xr(t,n)},chooseCard:qo("human-choose-card")};case"tell":return{requestId:t,tellCard:qo("human-tell-card")};default:return e}}function Ic(e){return`${e}_${crypto.randomUUID()}`}function DA(e){let{type:t,...n}=e;return n}function FA(e){if(!(!e||!("card"in e)))return e.card}function Bo(e){if(!(!e||!("render"in e)))return e.render}function UA(e){return typeof e=="object"&&e!==null&&wr(e)?e:{type:"card",children:[e]}}function Oc(e){if(!(!e||!("ttlSeconds"in e)||typeof e.ttlSeconds!="number"))return e.ttlSeconds}function mg(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 HA(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 gg(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 _c(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 Pc=class{constructor(t){this.outbox=t}async sendReply(t,n,r){let i=Ic("msg"),a=_c(n);return a.push({type:"message",role:"assistant",messageId:i,content:mg(t),files:gg(t.files),...r?{quoteReply:r}:{}}),await this._emitAndFlush(a),{messageId:i,platformThreadId:""}}async sendApprovalCard(t,n){return await this._emitAndFlush(_c(n,{deliverApprovalCard:!0})),"unaddressable"}async editMessage(t,n){return await this.outbox.emit({type:"channel.edit",messageId:t,content:mg(n),files:gg(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(_c(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()}}},zo=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 Io(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)}},Mc=class{constructor(){this.messageId="";this.platformThreadId=""}async edit(){return this}async delete(){}},yg;yg=rg;var Vo=class{constructor(t,n,r){this[yg]=!0;this._signals=[];this._toolResults=[];this._pendingToolApprovalRequest=null;this._pendingReactions=[];this._pendingDeletes=[];this._resolveSignal=null;this._pendingHumanRenders=[];var l,p,d,h,y,g;this.event=t.event,this.action=(l=t.action)!=null?l: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 Pc(new Mo({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 fg(this,I,this._toolApprovalConfig,void 0,K),new Tr)}}asMessageContext(){return this}async reply(t,n){await this.materializePendingHumanRenders();let r=await Io(t,n==null?void 0:n.files),i=this._drainSideEffectsSnapshot(),a=n!=null&&n.quoteReply?HA(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 zo(o.messageId,o.platformThreadId,this._transport)}async replyApprovalCard(t){await this.materializePendingHumanRenders();let n=this._drainSideEffectsSnapshot();return await this._transport.sendApprovalCard(t,n),new Mc}createReplyHandle(t){return new zo(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=Bo(i);return a?this.queueRendered("ask",i,a):this.queueHumanSignal("ask",t,n)}approve(t,n){let i=typeof t!="string"?t:n,a=Bo(i);return a?this.queueRendered("approve",i,a):this.queueHumanSignal("approve",t,n)}choose(t,n,r){var l;let i=typeof t!="string",a,o;i?a=t:Array.isArray(n)?(a=r,o=n):a=n;let s=Bo(a);return s?this.queueRendered("choose",a,s):i?this.queueHumanSignal("choose",t,void 0,"card"in t?(l=t.card)==null?void 0:l.options:void 0):this.queueHumanSignal("choose",t,a,o)}tell(t,n){let r=typeof t!="string",i=r?t:n,a=Bo(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,l=FA(s),p=Fo(t,(o==null?void 0:o.trim())||(l==null?void 0:l.title));if(t==="choose"){let I=i!=null?i:l==null?void 0:l.options;Uo(I)}t==="approve"&&(l!=null&&l.extraActions)&&Ho(l.extraActions);let d=Ic("hr"),h=(s==null?void 0:s.to)!==void 0?$o(s.to):void 0,y={...l,title:p,...t==="choose"&&i?{options:i}:{}},g=Oc(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=Ic("hr");return this._pendingHumanRenders.push(async()=>{let a=await this.invokeHumanRender(t,i,r);if(_m(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(jo("ask",n)));case"approve":return Promise.resolve(r(jo("approve",n)));case"choose":return Promise.resolve(r(jo("choose",n)));case"tell":return Promise.resolve(r(jo("tell",n)));default:{let i=t;return Promise.resolve(i)}}}pushRenderedChrome(t,n,r,i){ug(t,r);let a=DA(r),o=Oc(i),s=(i==null?void 0:i.to)!==void 0?$o(i.to):void 0,l=t==="approve"||t==="choose";this._signals.push({type:"human",kind:t,requestId:n,...l?{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){pg(t,r,n);let a=await Io(UA(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=Oc(i),s=(i==null?void 0:i.to)!==void 0?$o(i.to):void 0,l=t==="approve"||t==="choose";this._signals.push({type:"human",kind:t,requestId:n,...l?{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 $A(e){return!!(typeof e=="string"||typeof e=="object"&&e!==null&&wr(e)||typeof e=="object"&&e!==null&&("markdown"in e||"card"in e||"files"in e))}function qA(e,t){return e}var bg="tool_approval:";function jA(e){if(!(e!=null&&e.startsWith(bg)))return null;let t=e.slice(bg.length);return t.length>0?t:null}async function wg(e,t){await e.reply(t.content,{files:t.files,quoteReply:t.quoteReply})}async function Zn(e,t){if(!(t instanceof Tr||t===void 0)){if(kc(t)){await wg(e,t);return}await e.reply(t)}}async function BA(e,t){return ig(t)?!0:kc(t)?(await wg(e,t),!0):$A(t)?(await e.reply(t),!0):!1}function zA(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 Sg(e){var a;let t=new Vo(e.bridge,e.secretKey,e.agent.handlers.toolApproval),{agent:n,event:r,logger:i}=e;try{t.queueRunStart(),await WA(n,r,t),await t.flush(),await t.emitRunFinish({outcome:"completed"})}catch(o){let s=Ni(o);i==null||i.error(`[agent:${n.id}] Turn failed (${r}): ${s.message}`,(a=s.cause)!=null?a:s);let l=!1;if(n.handlers.onError)try{let p=await n.handlers.onError(s,qA(t,r));l=await BA(t,p)}catch(p){i==null||i.error(`[agent:${n.id}] onError failed:`,p)}l?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,l,p,d,h,y;let n=jA((s=t.humanResponse)==null?void 0:s.requestId),r=hg((l=t.action)==null?void 0:l.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=zA(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 Zn(t,H);return}let o=t.action;o&&e.handlers.onAction&&await Zn(t,await e.handlers.onAction(o,t))}async function WA(e,t,n){switch(t){case"onMessage":{let r=n.message;r&&await Zn(n,await e.handlers.onMessage(r,n));break}case"onMessageUpdated":{let r=n.message;r&&e.handlers.onMessageUpdated&&await Zn(n,await e.handlers.onMessageUpdated(r,n));break}case"onMessageDeleted":{let r=n.message;r&&e.handlers.onMessageDeleted&&await Zn(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 Zn(n,await e.handlers.onReaction(r,n));break}case"onResolve":e.handlers.onResolve&&await Zn(n,await e.handlers.onResolve(n));break;default:throw new qn(t,vc)}}function Tg(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),l=a.slice(o+1);s&&l&&!(s in t)&&(t[s]=l)}let n=t.t,r=n!==void 0?Number(n):Number.NaN;return{t:Number.isFinite(r)?r:void 0,v1:t.v1}}var Ar=class{constructor(t){this.handler=t.handler,this.client=t.client?t.client:new Sr,this.workflows=t.workflows||[],this.agents=t.agents||[],this.http=So(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")||"",l=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,l,(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 la(r))}getPostActionMap(t,n,r,i,a,o,s){return{trigger:this.triggerAction({workflowId:n,...t}),execute:async()=>{let l=await this.client.executeWorkflow({...t,workflowId:n,stepId:r,action:i});return this.createResponse(200,l)},preview:async()=>{let l=await this.client.executeWorkflow({...t,workflowId:n,stepId:r,action:i});return this.createResponse(200,l)},"agent-event":async()=>{let l=this.client.getAgent(a);if(!l)return this.createResponse(404,{error:`Agent '${a}' not registered`});let p=Sg({agent:l,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(Lr).includes(t)){let r=n[t];return r()}else throw new qn(t,Lr)}async handleGetAction(t,n){if(Object.values(Gi).includes(t)){let r=n[t];return r()}else throw new qn(t,Gi)}handleError(t){if($n(t))return t.statusCode>=500&&this.client.logger.error(t),this.createError(t);if($u(t))return this.createError(t);{let n=new ar(t);return this.client.logger.error(n),this.createError(n)}}async validateHmac(t,n){if(!this.hmacEnabled)return;if(!n)throw new fa;if(!this.client.secretKey)throw new ya;let r=Tg(n);if(!r.v1||r.t===void 0)throw new ma;let i=Date.now();if(r.t<i-3e5||r.t>i+3e5)throw new ga;let a=await Mm(this.client.secretKey,`${r.t}.${JSON.stringify(t)}`);if(!Nm(a,r.v1))throw new ha}};function Nc(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 YA={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},Ag={output:YA};var JA={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},vg={output:JA};var kg={"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":Ag,"rocket-chat":ae,ryver:ae,sendblue:ae,slack:vg,"webex-messaging":ae,"whatsapp-business":ae,zulip:ae,telegram:ae};var GA={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},Eg={output:GA};var er={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},KA={type:"object",properties:{contentType:{type:"string"},filename:{type:"string"},base64Content:{type:"string"}},required:["ContentType","Filename","Base64Content"],additionalProperties:!0},XA={type:"object",properties:{filename:{type:"string"},contentType:{type:"string"},contentId:{type:"string"},base64Content:{type:"string"}},required:["ContentType","Filename","Base64Content"],additionalProperties:!0},QA={type:"object",properties:{from:er,sender:er,to:{type:"array",items:er},cc:{type:"array",items:er},bcc:{type:"array",items:er},replyTo:er,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:er,templateErrorDeliver:{type:"boolean"},attachments:{type:"array",items:KA},inlineAttachments:{type:"array",items:XA},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},Rg={output:QA};var en={type:"object",properties:{address:{type:"string"},name:{type:"string"}},additionalProperties:!0},Wo={type:"object",properties:{content:{type:"string"},path:{type:"string"}},additionalProperties:!0},ZA={type:"object",properties:{from:{anyOf:[{type:"string"},en]},sender:{anyOf:[{type:"string"},en]},to:{anyOf:[{type:"string"},en,{type:"array",items:en}]},cc:{anyOf:[{type:"string"},en,{type:"array",items:en}]},bcc:{anyOf:[{type:"string"},en,{type:"array",items:en}]},replyTo:{anyOf:[{type:"string"},en,{type:"array",items:en}]},inReplyTo:{anyOf:[{type:"string"},en]},references:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},subject:{type:"string"},text:{anyOf:[{type:"string"},Wo]},html:{anyOf:[{type:"string"},Wo]},watchHtml:{anyOf:[{type:"string"},Wo]},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"},Wo]}}}]},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},Cg={output:ZA};var ev={type:"object",properties:{},required:[],additionalProperties:!1},Og={output:ev};var tv={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},_g={output:tv};var Ig={anypost:ae,braze:ae,clickatell:ae,nodemailer:Cg,emailjs:ae,"email-webhook":ae,"infobip-email":ae,mailersend:ae,mailgun:Eg,mailjet:Rg,mailtrap:ae,mandrill:ae,netcore:ae,"novu-email":Og,outlook365:ae,plunk:ae,postmark:ae,resend:ae,sendgrid:_g,sendinblue:ae,ses:ae,sparkpost:ae};var nv={type:"object",properties:{},required:[],additionalProperties:!1},Pg={output:nv};var Mg={novu:Pg};var Ng={anyOf:[{type:"string"},{type:"object",additionalProperties:!0,properties:{name:{type:"string"},volume:{type:"number"},critical:{type:"number"}},required:["name","volume","critical"]}]},rv={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.