@novu/framework 2.13.1 → 2.13.2-rc.dc9caee828
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.cjs +2 -2
- package/dist/cjs/internal/index.d.cts +111 -1
- package/dist/cjs/servers/express.cjs +2 -2
- package/dist/cjs/servers/h3.cjs +2 -2
- package/dist/cjs/servers/hono.cjs +2 -2
- package/dist/cjs/servers/lambda.cjs +2 -2
- package/dist/cjs/servers/nest.cjs +2 -2
- package/dist/cjs/servers/next.cjs +2 -2
- package/dist/cjs/servers/nuxt.cjs +2 -2
- package/dist/cjs/servers/remix.cjs +2 -2
- package/dist/cjs/servers/sveltekit.cjs +2 -2
- package/dist/esm/{chunk-PBC7WR2R.js → chunk-BXKRUYUB.js} +2 -2
- package/dist/esm/index.js +1 -1
- package/dist/esm/internal/index.d.ts +111 -1
- package/dist/esm/servers/express.js +1 -1
- package/dist/esm/servers/h3.js +1 -1
- package/dist/esm/servers/hono.js +1 -1
- package/dist/esm/servers/lambda.js +1 -1
- package/dist/esm/servers/nest.js +1 -1
- package/dist/esm/servers/next.js +1 -1
- package/dist/esm/servers/nuxt.js +1 -1
- package/dist/esm/servers/remix.js +1 -1
- package/dist/esm/servers/sveltekit.js +1 -1
- package/package.json +3 -2
|
@@ -145,13 +145,13 @@ $$`:`${e}$$`},ST=e=>yT(e)%2===0?e:wT(e),TT=e=>bT(e)%2===1?`${e}$`:e,xT=(e,t,n)=>
|
|
|
145
145
|
`);n&&r.length>0&&r.at(-1)===""&&r.pop();let i=[],o=!1,a=!1;for(let u=0;u<r.length;u++){let p=r[u].trim();if(!o&&(p.startsWith("```")||p.startsWith("~~~"))){a=!a,i.push(r[u]);continue}if(a){i.push(r[u]);continue}let d=p!==""&&(Hl.test(p)||Vl.test(p));if(d&&!o){let h=!1;for(let g=u;g<r.length;g++){let y=r[g].trim();if(Vl.test(y)){h=!0;break}if(y===""||!Hl.test(y))break}h&&(i.push("```"),o=!0)}else!d&&o&&(i.push("```"),o=!1);i.push(r[u])}o&&t&&i.push("```");let s=i.join(`
|
|
146
146
|
`);return n&&(s+=`
|
|
147
147
|
`),s}function tx(e){return"adapterName"in e&&!("adapter"in e)}var Lf="thread-state:";function nx(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}var e1=class Wl{constructor(t){ve(this,"id");ve(this,"channelId");ve(this,"isDM");ve(this,"channelVisibility");ve(this,"_adapter");ve(this,"_adapterName");ve(this,"_stateAdapterInstance");ve(this,"_recentMessages",[]);ve(this,"_isSubscribedContext");ve(this,"_currentMessage");ve(this,"_streamingUpdateIntervalMs");ve(this,"_fallbackStreamingPlaceholderText");ve(this,"_channel");ve(this,"_threadHistory");ve(this,"_logger");var n,r,i,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._isSubscribedContext=(i=t.isSubscribedContext)!=null?i:!1,this._currentMessage=t.currentMessage,this._logger=t.logger,this._streamingUpdateIntervalMs=(o=t.streamingUpdateIntervalMs)!=null?o:500,this._fallbackStreamingPlaceholderText=t.fallbackStreamingPlaceholderText!==void 0?t.fallbackStreamingPlaceholderText:"...",tx(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=Zo().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=Zo();return this._stateAdapterInstance=t.getState(),this._stateAdapterInstance}get recentMessages(){return this._recentMessages}set recentMessages(t){this._recentMessages=t}get state(){return this._stateAdapter.get(`${Lf}${this.id}`)}async setState(t,n){let r=`${Lf}${this.id}`;if(n!=null&&n.replace)await this._stateAdapter.set(r,t,ea);else{let o={...await this._stateAdapter.get(r),...t};await this._stateAdapter.set(r,o,ea)}}get channel(){if(!this._channel){let t=GT(this.adapter,this.id);this._channel=new JT({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,o=!1;for(;;){let a=await t.fetchMessages(n,{cursor:i,direction:"backward"}),s=[...a.messages].reverse();for(let u of s)o=!0,yield u;if(!a.nextCursor||a.messages.length===0)break;i=a.nextCursor}if(!o&&r){let a=await r.getMessages(n);for(let s=a.length-1;s>=0;s--)yield a[s]}}}}get allMessages(){let t=this.adapter,n=this.id,r=this._threadHistory;return{async*[Symbol.asyncIterator](){let i,o=!1;for(;;){let a=await t.fetchMessages(n,{limit:100,cursor:i,direction:"forward"});for(let s of a.messages)o=!0,yield s;if(!a.nextCursor||a.messages.length===0)break;i=a.nextCursor}if(!o&&r){let a=await r.getMessages(n);for(let s of a)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(qf(t)){if(t.kind==="stream"){let o=t.getPostData(),a={...o.options.updateIntervalMs?{updateIntervalMs:o.options.updateIntervalMs}:{},...o.options.groupTasks?{taskDisplayMode:o.options.groupTasks}:{},...o.options.endWith?{stopBlocks:o.options.endWith}:{}};return await this.handleStream(o.stream,a),t}return await this.handlePostableObject(t),t}if(nx(t))return this.handleStream(t);let n=t;if(Yt(t)){let o=Wt(t);if(!o)throw new Error("Invalid JSX element: must be a Card element");n=o}n=await this.processCallbackUrls(n);let r=await this.adapter.postMessage(this.id,n),i=this.createSentMessage(r.id,n,r.threadId);return this._threadHistory&&await this._threadHistory.append(this.id,new Xn(i)),i}async handlePostableObject(t){await jf(t,this.adapter,this.id,(n,r)=>this.adapter.postMessage(n,r),this._logger)}async postEphemeral(t,n,r){let{fallbackToDM:i}=r,o=typeof t=="string"?t:t.userId,a;if(Yt(n)){let s=Wt(n);if(!s)throw new Error("Invalid JSX element: must be a Card element");a=s}else a=n;if(a=await this.processCallbackUrls(a),this.adapter.postEphemeral)return this.adapter.postEphemeral(this.id,o,a);if(!i)return null;if(this.adapter.openDM){let s=await this.adapter.openDM(o),u=await this.adapter.postMessage(s,a);return{id:u.id,threadId:s,usedFallback:!0,raw:u.raw}}return null}async processCallbackUrls(t){var n;if(typeof t=="string")return t;if("type"in t&&t.type==="card")return Qo(t,this._stateAdapter);if("card"in t&&((n=t.card)==null?void 0:n.type)==="card"){let r=await Qo(t.card,this._stateAdapter);if(r!==t.card)return{...t,card:r}}return t}async schedule(t,n){let r;if(Yt(t)){let i=Wt(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 Bf("Scheduled messages are not supported by this adapter","scheduling");return this.adapter.scheduleMessage(this.id,r,n)}async handleStream(t,n){let r=$f(t),i={updateIntervalMs:this._streamingUpdateIntervalMs,...n};if(this._currentMessage&&(i.recipientUserId=this._currentMessage.author.userId,i.recipientTeamId=this.extractSlackRecipientTeamId(this._currentMessage.raw)),this.adapter.stream){let a="",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"?a+=h:h.type==="markdown_text"&&(a+=h.text)}return d}}}},u=await this.adapter.stream(this.id,s,i);if(u){let p=this.createSentMessage(u.id,{markdown:a},u.threadId);return this._threadHistory&&await this._threadHistory.append(this.id,new Xn(p)),p}}let o={[Symbol.asyncIterator]:()=>{let a=r[Symbol.asyncIterator]();return{async next(){for(;;){let s=await a.next();if(s.done)return{value:void 0,done:!0};let u=s.value;if(typeof u=="string")return{value:u,done:!1};if(u.type==="markdown_text")return{value:u.text,done:!1}}}}}};return this.fallbackStream(o,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){await this.adapter.startTyping(this.id,t)}async fallbackStream(t,n){var B;let r=(B=n==null?void 0:n.updateIntervalMs)!=null?B:this._streamingUpdateIntervalMs,i=this._fallbackStreamingPlaceholderText,o=i===null?null:await this.adapter.postMessage(this.id,i),a=this.id,s=new XT,u="",p=!1,d=null,h=null;o&&(a=o.threadId||this.id,u=i!=null?i:"");let g=()=>{h=setTimeout(()=>{d=y()},r)},y=async()=>{var ne;if(p||!o)return;let ue=s.render();if(ue.trim()&&ue!==u)try{await this.adapter.editMessage(a,o.id,{markdown:ue}),u=ue}catch(ke){(ne=this._logger)==null||ne.warn("fallbackStream edit failed",ke)}p||g()};o&&g();try{for await(let ue of t)if(s.push(ue),!o){let ne=s.render();ne.trim()&&(o=await this.adapter.postMessage(this.id,{markdown:ne}),a=o.threadId||this.id,u=ne,g())}}finally{p=!0,h&&(clearTimeout(h),h=null)}d&&await d;let P=s.getText(),ee=s.finish();o||(o=await this.adapter.postMessage(this.id,{markdown:P.trim()?P:" "}),a=o.threadId||this.id,u=P),ee.trim()&&ee!==u&&await this.adapter.editMessage(a,o.id,{markdown:P});let Z=this.createSentMessage(o.id,{markdown:P},a);return this._threadHistory&&await this._threadHistory.append(this.id,new Xn(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 Wl({id:t.id,adapterName:t.adapterName,channelId:t.channelId,channelVisibility:t.channelVisibility,currentMessage:t.currentMessage?Xn.fromJSON(t.currentMessage):void 0,isDM:t.isDM});return n&&(r._adapter=n),r}static[hr](t){return t.toJSON()}static[fr](t){return Wl.fromJSON(t)}createSentMessage(t,n,r){let i=this.adapter,o=r||this.id,a=this,{plainText:s,formatted:u,attachments:p}=rx(n);return{id:t,threadId:o,text:s,formatted:u,raw:null,links:[],author:{userId:"self",userName:i.userName,fullName:i.userName,isBot:!0,isMe:!0},metadata:{dateSent:new Date,edited:!1},attachments:p,toJSON(){return new Xn(this).toJSON()},async edit(h){let g=h;if(Yt(h)){let y=Wt(h);if(!y)throw new Error("Invalid JSX element: must be a Card element");g=y}return g=await a.processCallbackUrls(g),await i.editMessage(o,t,g),a.createSentMessage(t,g)},async delete(){await i.deleteMessage(o,t)},async addReaction(h){await i.addReaction(o,t,h)},async removeReaction(h){await i.removeReaction(o,t,h)}}}createSentMessageFromMessage(t){let n=this.adapter,r=this.id,i=t.id,o=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,links:t.links,isMention:t.isMention,toJSON(){return t.toJSON()},async edit(a){let s=a;if(Yt(a)){let u=Wt(a);if(!u)throw new Error("Invalid JSX element: must be a Card element");s=u}return s=await o.processCallbackUrls(s),await n.editMessage(r,i,s),o.createSentMessage(i,s,r)},async delete(){await n.deleteMessage(r,i)},async addReaction(a){await n.addReaction(r,i,a)},async removeReaction(a){await n.removeReaction(r,i,a)}}}};function rx(e){if(typeof e=="string")return{plainText:e,formatted:vn([xn([Tn(e)])]),attachments:[]};if("raw"in e)return{plainText:e.raw,formatted:vn([xn([Tn(e.raw)])]),attachments:e.attachments||[]};if("markdown"in e){let t=_l(e.markdown);return{plainText:Gr(t),formatted:t,attachments:e.attachments||[]}}if("ast"in e)return{plainText:Gr(e.ast),formatted:e.ast,attachments:e.attachments||[]};if("card"in e){let t=e.fallbackText||Kr(e.card);return{plainText:t,formatted:vn([xn([Tn(t)])]),attachments:[]}}if("type"in e&&e.type==="card"){let t=Kr(e);return{plainText:t,formatted:vn([xn([Tn(t)])]),attachments:[]}}throw new Error("Invalid PostableMessage format")}var t1=10080*60*1e3;var n1=600*1e3,r1=1440*60*1e3;var Df=new Map;function mr(e){let t=Df.get(e);return t||(t=Object.freeze({name:e,toString:()=>`{{emoji:${e}}}`,toJSON:()=>`{{emoji:${e}}}`}),Df.set(e,t)),t}var ix={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}"}},ox=class{constructor(e){ve(this,"emojiMap");ve(this,"slackToNormalized");ve(this,"gchatToNormalized");this.emojiMap={...ix,...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 mr(n)}fromGChat(e){var n;let t=(n=this.gchatToNormalized.get(e))!=null?n:e;return mr(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 mr(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],o=Array.isArray(r.gchat)?r.gchat:[r.gchat],a=e.replace(/^:|:$/g,"").toLowerCase();return i.some(s=>s.toLowerCase()===a)||o.includes(e)}extend(e){Object.assign(this.emojiMap,e),this.buildReverseMaps()}},ax=new ox;function sx(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=>mr(r)};for(let r of t)n[r]=mr(r);if(e){for(let r of Object.keys(e))n[r]=mr(r);ax.extend(e)}return n}var i1=sx(),Qr=Fo,Zr=Uo,ei=Ol;var ti=zo,ni=df,ri=Lo,zf=qo,Hf=jo;var ii=No;var Vf=$o,Wf=Do,Yf=Bo;var Jf=Yo,Gf=Ho,Kf=Go,oi=Wo,ai=Jo,si=Vo;function ta(e){return"type"in e&&e.type==="card"}function Xf(e){return typeof e=="object"&&e!==null&&e.type==="tool-approval-card"}function Yl(e,t){return(e==null?void 0:e.workflowId)===t.id}var lx=Symbol.for("chat.jsx.element"),cx=new Set([Qr,Zr,ei,ti,ni,ri,Jf,zf,Hf,ii,Vf,Gf,Kf,Wf,oi,ai,Yf,si]);function ux(e){return typeof e=="object"&&e!==null&&e.$$typeof===lx}async function ra(e){let t=na(e);if(t&&typeof t=="object"&&ta(t))return t;let{isJSX:n,toCardElement:r}=await Promise.resolve().then(()=>(Zf(),Qf));return n(t)?r(t):null}function na(e){var t;if(Array.isArray(e))return e.map(n=>na(n));if(!ux(e))return e;if(typeof e.type=="function"&&!cx.has(e.type)){let n={...(t=e.props)!=null?t:{}};return e.children!==void 0&&(n.children=e.children),na(e.type(n))}return{...e,children:na(e.children)}}var em=async(e,t)=>{let n=new TextEncoder,r=n.encode(e),i=n.encode(t),o=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),a=await crypto.subtle.sign("HMAC",o,i);return Array.from(new Uint8Array(a)).map(s=>s.toString(16).padStart(2,"0")).join("")},tm=(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 px=require("cross-fetch");var nm=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 rm(e){return!!e&&typeof e=="object"&&"error"in e&&"message"in e&&"statusCode"in e}var ia=(e,t)=>{if(!e)throw new zi;return{post:async(n,r)=>{let i=await fetch(`${t}/v1${n}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${e}`},body:JSON.stringify(r)}),o=await i.json();if(i.ok)return o;throw rm(o)?new Hi(o.statusCode,o.error,o.message):new ir(o)},delete:async n=>(await fetch(`${t}/v1${n}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${e}`}})).json()}};var cm=require("liquidjs");function Jl(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]=Jl(n[r]||{},i):(Array.isArray(i),n[r]=i)}return n}function oa(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 im(e,t=2,n,r=", "){if(!Array.isArray(e)||e.length===0)return"";let i=n?e.map(s=>typeof s!="object"||!s?"":oa(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),u=i[i.length-1];return`${s.join(r)} and ${u}`}let o=i.slice(0,t),a=i.length-t;return`${o.join(r)} and ${a} ${a===1?"other":"others"}`}var om=zt(require("pluralize"),1);function am(e,t="",n="",r="true"){if(e==null)return"";let i=0;if(Array.isArray(e)?i=e.length:typeof e=="object"?i=Object.keys(e).length:typeof e=="string"?i=+e:typeof e=="number"?i=e:i=Number(e),Number.isNaN(i)&&(i=0),i<=0)return"";let o;return n?o=i===1?t:n:o=(0,om.default)(t,i),r==="true"?`${i} ${o}`:o}var dx=require("liquidjs"),sm=zt(require("pluralize"),1),hx=require("zod");var fx="",mx=2,gx="other",yx=", ",bx=" and ",wx=", and ";function lm(e,t=fx,n=mx,r=gx,i=yx,o=bx,a=wx){if(!Array.isArray(e)||e.length===0)return"";let s=t?e.map(g=>typeof g!="object"||!g?"":oa(g,t)):e,u=s.length;if(u===1)return s[0];if(u===2)return`${s[0]}${o}${s[1]}`;if(n>=u){let g=s.slice(0,u-1),y=s[u-1];return`${g.join(i)}${a}${y}`}let p=s.slice(0,n),d=u-n,h=n===1?o:a;return`${p.join(i)}${h}${d} ${(0,sm.default)(r,d)}`}function Sx(e){return Array.isArray(e)||typeof e=="object"&&e!==null?um(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 um=(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 pm(e){let t=new cm.Liquid({outputEscape:Sx,...e});return t.registerFilter("json",(n,r)=>um(n,r)),t.registerFilter("digest",im),t.registerFilter("toSentence",lm),t.registerFilter("pluralize",am),t}var Qn=zt(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 aa(e){return e||process.env.NOVU_API_URL||"https://api.novu.co"}function sa(e){return e||process.env.NOVU_SECRET_KEY||process.env.NOVU_API_KEY||""}var Gl=zt(require("sanitize-html"),1),Tx=["src","alt","width","height","loading","srcset","sizes","crossorigin","usemap","ismap","class","id","style","title","dir","lang"];function xx(e){return e.toLowerCase().startsWith("on")}function vx(e){return e.replace(/<\/([a-zA-Z][a-zA-Z0-9]*)\s*\/[^>]*>/g,"</$1>")}var kx={allowedTags:Gl.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))xx(r)||(n[r]=i);return{tagName:e,attribs:n}},img:(e,t)=>{let n={};for(let[r,i]of Object.entries(t))Tx.includes(r.toLowerCase())&&(n[r]=i);return{tagName:e,attribs:n}}},allowVulnerableTags:!0,parseStyleAttributes:!1,parser:{lowerCaseAttributeNames:!0}},dm=e=>{if(!e)return e;let t=vx(e),n=/^<!DOCTYPE .*?>/,r=t.match(n),i=(0,Gl.default)(t,kx);return r?r[0]+i:i},la=e=>Object.keys(e).reduce((t,n)=>{let r=e[n];return typeof r=="string"?t[n]=dm(r):Array.isArray(r)?t[n]=r.map(i=>typeof i=="string"?dm(i):typeof i=="object"?la(i):i):typeof r=="object"&&r!==null?t[n]=la(r):t[n]=r,t},{});function hm(e,t=!0,n=console){t&&(n.info(`
|
|
148
|
-
${et.bold(et.underline("Discovered workflowId:"))} '${e.workflowId}'`),e.steps.forEach((r,i)=>{let o=i===e.steps.length-1,a=o?"\u2514":"\u251C";n.info(`${a} ${lt.STEP} Discovered stepId: '${r.stepId}' Type: '${r.type}'`),r.providers.forEach((s,u)=>{let p=u===r.providers.length-1,d=o?" ":"\u2502",h=p?"\u2514":"\u251C";n.info(`${d} ${h} ${lt.PROVIDER} Discovered provider: '${s.type}'`)})}))}var fm=require("jsonrepair");function mm(e){let t=e.trim();return(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))&&t.length>2}var gm="__novuJsonString";function Ax(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&e[gm]===!0}function li(e){if(typeof e=="string"){if(!mm(e))return e;try{let t=JSON.parse(e);return{[gm]:!0,value:li(t)}}catch{return e}}if(Array.isArray(e))return e.map(t=>li(t));if(e&&typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=li(r);return t}return e}function ci(e){if(Ax(e))return JSON.stringify(ci(e.value));if(Array.isArray(e))return e.map(t=>ci(t));if(e&&typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=ci(r);return t}return e}function Ex(e){try{return JSON.parse(e),e}catch{try{return(0,fm.jsonrepair)(e)}catch{return e}}}function ym(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>typeof n=="string"?[t,mm(n)?Ex(n):n]:typeof n=="object"&&n!==null&&!Array.isArray(n)?[t,ym(n)]:[t,n]))}function bm(e){return!(e!=null&&e.data)||typeof e.data!="object"||Array.isArray(e.data)?e:{...e,data:ym(e.data)}}var Sm=zt(require("ajv"),1),Tm=zt(require("ajv-formats"),1);var wm=e=>typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e));var ca=class extends _n{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 ua=async(e,t)=>{let n=new Set;if((await Promise.allSettled(e.map(i=>i.import))).forEach((i,o)=>{let a=e[o];i.status==="fulfilled"&&a.exports.every(u=>i.value[u]!==void 0)||n.add(a.name)}),n.size>0)throw new ca(t,Array.from(n))};var pa=class{constructor(){this.requiredImports=[];this.ajv=new Sm.default({useDefaults:!0,removeAdditional:"failing",strict:!1}),(0,Tm.default)(this.ajv),this.compiledSchemas=new Map}async canHandle(t){let n=t.type==="object"||!!t.anyOf||!!t.allOf||!!t.oneOf;return n&&await ua(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=wm(t);return r(i)?{success:!0,data:i}:{success:!1,errors:r.errors.map(a=>({path:a.instancePath,message:a.message}))}}async transformToJsonSchema(t){return t}};var da=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 ua(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 ha=new da,fa=new pa,ui=async(e,t)=>{if(await ha.canHandle(e))return ha.validate(t,e);if(await fa.canHandle(e))return fa.validate(t,e);throw new Error("Invalid schema")},bt=async e=>{if(await ha.canHandle(e))return ha.transformToJsonSchema(e);if(await fa.canHandle(e))return fa.transformToJsonSchema(e);throw new Error("Invalid schema")};function xm(){return["development",void 0,"dev"].includes(process.env.NODE_ENV)}var gr=class{constructor(t){this.discoveredWorkflows=new Map;this.discoverWorkflowPromises=new Map;this.registeredAgents=new Map;this.version="2.13.
|
|
148
|
+
${et.bold(et.underline("Discovered workflowId:"))} '${e.workflowId}'`),e.steps.forEach((r,i)=>{let o=i===e.steps.length-1,a=o?"\u2514":"\u251C";n.info(`${a} ${lt.STEP} Discovered stepId: '${r.stepId}' Type: '${r.type}'`),r.providers.forEach((s,u)=>{let p=u===r.providers.length-1,d=o?" ":"\u2502",h=p?"\u2514":"\u251C";n.info(`${d} ${h} ${lt.PROVIDER} Discovered provider: '${s.type}'`)})}))}var fm=require("jsonrepair");function mm(e){let t=e.trim();return(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))&&t.length>2}var gm="__novuJsonString";function Ax(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&e[gm]===!0}function li(e){if(typeof e=="string"){if(!mm(e))return e;try{let t=JSON.parse(e);return{[gm]:!0,value:li(t)}}catch{return e}}if(Array.isArray(e))return e.map(t=>li(t));if(e&&typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=li(r);return t}return e}function ci(e){if(Ax(e))return JSON.stringify(ci(e.value));if(Array.isArray(e))return e.map(t=>ci(t));if(e&&typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=ci(r);return t}return e}function Ex(e){try{return JSON.parse(e),e}catch{try{return(0,fm.jsonrepair)(e)}catch{return e}}}function ym(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>typeof n=="string"?[t,mm(n)?Ex(n):n]:typeof n=="object"&&n!==null&&!Array.isArray(n)?[t,ym(n)]:[t,n]))}function bm(e){return!(e!=null&&e.data)||typeof e.data!="object"||Array.isArray(e.data)?e:{...e,data:ym(e.data)}}var Sm=zt(require("ajv"),1),Tm=zt(require("ajv-formats"),1);var wm=e=>typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e));var ca=class extends _n{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 ua=async(e,t)=>{let n=new Set;if((await Promise.allSettled(e.map(i=>i.import))).forEach((i,o)=>{let a=e[o];i.status==="fulfilled"&&a.exports.every(u=>i.value[u]!==void 0)||n.add(a.name)}),n.size>0)throw new ca(t,Array.from(n))};var pa=class{constructor(){this.requiredImports=[];this.ajv=new Sm.default({useDefaults:!0,removeAdditional:"failing",strict:!1}),(0,Tm.default)(this.ajv),this.compiledSchemas=new Map}async canHandle(t){let n=t.type==="object"||!!t.anyOf||!!t.allOf||!!t.oneOf;return n&&await ua(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=wm(t);return r(i)?{success:!0,data:i}:{success:!1,errors:r.errors.map(a=>({path:a.instancePath,message:a.message}))}}async transformToJsonSchema(t){return t}};var da=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 ua(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 ha=new da,fa=new pa,ui=async(e,t)=>{if(await ha.canHandle(e))return ha.validate(t,e);if(await fa.canHandle(e))return fa.validate(t,e);throw new Error("Invalid schema")},bt=async e=>{if(await ha.canHandle(e))return ha.transformToJsonSchema(e);if(await fa.canHandle(e))return fa.transformToJsonSchema(e);throw new Error("Invalid schema")};function xm(){return["development",void 0,"dev"].includes(process.env.NODE_ENV)}var gr=class{constructor(t){this.discoveredWorkflows=new Map;this.discoverWorkflowPromises=new Map;this.registeredAgents=new Map;this.version="2.13.2-rc.dc9caee828";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=pm()}buildOptions(t){let n={apiUrl:aa(t==null?void 0:t.apiUrl),secretKey:sa(t==null?void 0:t.secretKey),strictAuthentication:!xm(),verbose:xm(),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();hm(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,o)=>i+o.steps.length,0);return{status:"ok",sdkVersion:"2.13.2-rc.dc9caee828",frameworkVersion:"2024-06-26",discovered:{workflows:n,steps:r}}}getWorkflow(t){let n=this.discoveredWorkflows.get(t);if(n)return n;throw new Lr(t)}getStep(t,n){let i=this.getWorkflow(t).steps.find(o=>o.stepId===n);if(i)return i;throw new Qi(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 bu(t)}catch(n){return this.logger.warn("Failed to mock schema, returning empty object:",n),{}}}async validate(t,n,r,i,o,a,s){let u=await ui(n,t);if(u.success)return u.data;switch(r){case"event":this.throwInvalidEvent(i,o,u.errors);case"step":this.throwInvalidStep(a,i,o,u.errors);case"provider":this.throwInvalidProvider(a,s,i,o,u.errors);default:throw new Error(`Invalid component: '${r}'`)}}throwInvalidProvider(t,n,r,i,o){throw t?n?r==="output"?new $i(i,t,n,o):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 Di(r,t,i);case"result":throw new Fi(r,t,i);case"controls":throw new Li(r,t,i);default:throw new Error(`Invalid payload type: '${n}'`)}}throwInvalidEvent(t,n,r){switch(t){case"controls":throw new Ni(n,r);case"payload":throw new Pr(n,r);default:throw new Error(`Invalid payload type: '${t}'`)}}executeStepFactory(t,n,r){return async(i,o,a)=>{if(r())return;let s=this.getStep(t.workflowId,i),u=t.action==="preview";if(!u&&i===t.stepId){let y=await this.createStepControls(s,t),P=await this.compileControls(y,t);if(await this.shouldSkip(a==null?void 0:a.skip,P))return n({options:{skip:!0},outputs:{},providers:{}}),{}}let p=this.previewStep.bind(this),d=this.executeStep.bind(this),g=await(u?p:d)(t,{...s,providers:s.providers.map(y=>{var ee;let P=(ee=a==null?void 0:a.providers)==null?void 0:ee[y.type];if(!P)throw new Vi(y.type);return{...y,resolve:P}}),resolve:o});return this.shouldSanitize({stepType:s.type,options:a})&&(g={...g,outputs:la(g.outputs)}),i===t.stepId&&n({...g,options:{skip:!1}}),g.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(`
|
|
149
149
|
${et.bold(et.underline(i))} '${t.workflowId}'`);let o=this.getWorkflow(t.workflowId),a=process.hrtime(),s={outputs:{},providers:{},options:{skip:!1}},u,p=!1,d=new Promise(Oe=>{u=Oe}),h=Oe=>{if(p)throw new Error("setResult can only be called once per workflow execution");u(),p=!0,s=Oe},g=()=>p,y;try{if(t.action==="execute"&&!t.payload)throw new Pr(t.workflowId,{message:"Event `payload` is required"});let Oe=await this.createExecutionPayload(t,o),$={...t,payload:Oe};await Promise.race([d,o.execute({payload:Oe,env:t.env,controls:{},subscriber:t.subscriber,context:t.context,step:{email:this.executeStepFactory($,h,g),sms:this.executeStepFactory($,h,g),inApp:this.executeStepFactory($,h,g),digest:this.executeStepFactory($,h,g),delay:this.executeStepFactory($,h,g),push:this.executeStepFactory($,h,g),chat:this.executeStepFactory($,h,g),custom:this.executeStepFactory($,h,g),throttle:this.executeStepFactory($,h,g),tool:this.executeStepFactory($,h,g)}})])}catch(Oe){y=Oe}let P=process.hrtime(a),ee=P[0],Z=P[1],B=ee*1e3+Z/1e6,ue=y?lt.ERROR:lt.SUCCESS,ke={execute:"Executed",preview:"Previewed"}[t.action]||t.action;if(this.log(`${ue} ${ke} workflowId: \`${t.workflowId}\``),this.prettyPrintExecute(t,B,y),y)throw y;return{outputs:s.outputs,providers:s.providers,options:s.options,metadata:{status:"success",error:!1,duration:B}}}async createExecutionPayload(t,n){let{payload:r}=t;if(t.action==="preview"){let o=this.mock(n.payload.schema);r=Object.assign(o,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,a={execute:"Executed",preview:"Previewed"}[t.action]||t.action,s=r?"Failed to execute":a,u=r?et.error:et.success,p=`${i} ${s} workflowId: '${t.workflowId}`;this.logger.info(`
|
|
150
150
|
${et.bold(u(p))}'
|
|
151
151
|
\u251C ${lt.STEP} stepId: '${t.stepId}'
|
|
152
152
|
\u251C ${lt.ACTION} action: '${t.action}'
|
|
153
153
|
\u2514 ${lt.DURATION} duration: '${n.toFixed(2)}ms'
|
|
154
|
-
`)}async executeProviders(t,n,r,i){return n.providers.reduce(async(o,a)=>{let s=await o,u=await this.runProvider(t,n,a,r,i);return{...s,[a.type]:u}},Promise.resolve({}))}async runProvider(t,n,r,i,o){let a=t.action==="preview";if(t.stepId!==n.stepId)return a?(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,o,i)}catch(s){if(this.log(` ${lt.ERROR} Failed to execute provider: \`${r.type}\``),a)return this.log(` ${lt.MOCK} Mocked provider: \`${r.type}\``),this.mock(r.outputs.schema);throw new Wi(r.type,t.action,s)}}async resolveProviderOutput(t,n,r,i,o){let a=await r.resolve({controls:i,outputs:o}),s=await this.validate(a,r.outputs.unknownSchema,"step","output",t.workflowId,n.stepId,r.type);return this.log(` ${lt.SUCCESS} Executed provider: \`${r.type}\``),{...s,_passthrough:a._passthrough}}async executeStep(t,n){if(t.stepId===n.stepId)try{let r=await this.createStepControls(n,t),i=await this.compileControls(r,t),o=await n.resolve(i),a=await this.normalizeChatCardOutput(n,o),s=await this.validate(a,n.outputs.unknownSchema,"step","output",t.workflowId,n.stepId),u=await this.executeProviders(t,n,s,i);return this.log(` ${lt.SUCCESS} Executed stepId: \`${n.stepId}\``),{outputs:s,providers:u}}catch(r){throw this.log(` ${lt.ERROR} Failed to execute stepId: \`${n.stepId}\``),qn(r)?r:new Nr(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 Mi(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 ra(n.card);return r?{...n,card:r}:n}async compileControls(t,n){var r;try{let i=li(t),o=this.preprocessTranslationPatterns(JSON.stringify(i));o=this.preprocessFilterTranslationArgs(o);let a=this.templateEngine.parse(o),s=this.getWorkflow(n.workflowId),u={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:_x(n.state),env:(r=n.env)!=null?r:{}},p=await this.templateEngine.render(a,u),d=this.postprocessTranslationMarkers(p),h=(0,vm.jsonrepair)(d),g=JSON.parse(h),y=ci(g);return bm(y)}catch(i){throw new Ui(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}\``),qn(r)?r:new Nr(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),o=this.mock(n.results.schema);return{outputs:Jl(o,(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),o=await t.resolve(i),a=await this.normalizeChatCardOutput(t,o),s=await this.validate(a,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 Lr(t);return r}};function _x(e){let t={};for(let n of e)t[n.stepId]=n.outputs;return t}var Ox={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 ma(e){return typeof e=="string"&&e.trim()?e:!e||typeof e!="object"?null:ma(e.message)}function Cx(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=ma(n.message);if(r)return r;let i=ma(n.error);if(i)return i;let o=n.errors;return Array.isArray(o)?ma(o[0]):null}function Ix(e,t){var i;let n=(i=Ox[e])!=null?i:e,r=Cx(t);return r?`Delivery failed: ${n}: ${r}`:`Delivery failed: ${n}`}var kn=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}},Jt=class extends kn{constructor(t,n){let r={statusCode:t,responseBody:n};super(Ix(t,n),{delivery:r}),this.name="AgentDeliveryError",this.statusCode=t,this.responseBody=n}};function pi(e){return e instanceof kn?e:e instanceof Error?new kn(e.message,{cause:e}):new kn("Turn failed",{cause:e})}var km=Symbol.for("novu.agent.runtimeContext");var Kl=(i=>(i.ON_MESSAGE="onMessage",i.ON_ACTION="onAction",i.ON_RESOLVE="onResolve",i.ON_REACTION="onReaction",i))(Kl||{}),yr=class{constructor(){this.__novuPendingApproval=!0}};function Am(e){return typeof e=="object"&&e!==null&&"suppress"in e&&e.suppress===!0}var Em=1;function Px(e){return new Promise(t=>{setTimeout(t,e)})}function Mx(e){return e>=500||e===408||e===429}var ga=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:Em,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,!Nx(i))throw i;r<this.maxRetries&&await Px(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 Lx(i)}let r=await n.text().catch(()=>"");if(!n.ok)throw new Jt(n.status,r)}};function Nx(e){return!(e instanceof Jt)||e.statusCode===0?!0:Mx(e.statusCode)}function Lx(e){if(e instanceof Jt)return e;let t=e instanceof Error?e.message:"Network request failed";return new Jt(0,t)}function Rm(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 o=i.trim();!o||r.has(o)||(r.add(o),n.push(o))}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 _m="tool-approval";function Dx(e){return e==="approve"||e==="deny"}function Xl(e,t){return`${_m}:${e}:${t}`}function Om(e){let[t,n,...r]=(e!=null?e:"").split(":"),i=r.join(":");return t!==_m||!Dx(n)||!i?null:{approved:n==="approve",approvalId:i}}async function Cm(e,t,n,r){var p,d;let i=r!=null?r:t.id,o={approve:Xl("approve",i),deny:Xl("deny",i)},a=h=>({type:"tool-approval-card",...h}),s=(d=(p=n==null?void 0:n.renderApproval)==null?void 0:p.call(n,{toolCall:t,actionIds:o,approvalCard:a}))!=null?d:a(),u={approvalId:i,toolCallId:t.id,name:t.name,input:t.input};if(e.emitToolApprovalRequest(u),Xf(s)){await e.replyApprovalCard(s);return}await e.reply(s)}var Fx=5*1024*1024,Ux=5*1024*1024,Im=32768,$x=/^[A-Za-z0-9+/]*={0,2}$/;function fi(e,t){return e.filename?`"${e.filename}"`:`at index ${t}`}function Lm(){return globalThis.Buffer}function qx(e){var t,n,r;return(r=(n=(t=Lm())==null?void 0:t.isBuffer)==null?void 0:n.call(t,e))!=null?r:!1}function jx(e){return typeof Blob!="undefined"&&e instanceof Blob}function Ql(e){let t=Lm();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+=Im){let i=e.subarray(r,r+Im);n+=String.fromCharCode(...i)}return btoa(n)}function Dm(e){let t=e.replace(/\s/g,""),n=t.length%4;if(!t||n===1||!$x.test(t))return null;let r=t.endsWith("==")?2:t.endsWith("=")?1:0;return Math.floor(t.length*3/4)-r}function di(e,t,n){if(e>Fx)throw new Error(`Invalid file ${fi(t,n)}: inline data must be 5 MB or smaller. Use a publicly-accessible URL for larger files.`)}async function Bx(e,t,n){if(typeof e=="string"){let r=Dm(e);if(r===null)throw new Error(`Invalid file ${fi(t,n)}: data must be a base64-encoded string.`);return di(r,t,n),e}if(qx(e))return di(e.byteLength,t,n),e.toString("base64");if(e instanceof Uint8Array)return di(e.byteLength,t,n),Ql(e);if(e instanceof ArrayBuffer)return di(e.byteLength,t,n),Ql(new Uint8Array(e));if(jx(e))return di(e.size,t,n),Ql(new Uint8Array(await e.arrayBuffer()));throw new Error(`Invalid file ${fi(t,n)}: data must be a base64 string, Buffer, Uint8Array, ArrayBuffer, or Blob.`)}async function zx(e){if(!(e!=null&&e.length))return;let t=[],n=0;for(let[r,i]of e.entries()){let o=i.data,a=i.url,s=o!=null,u=a!=null;if(s===u)throw new Error(`Invalid file ${fi(i,r)}: provide exactly one of data or url.`);if(s){let p=await Bx(o,i,r),d=Dm(p);if(n+=d!=null?d:0,n>Ux)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(u&&typeof a!="string")throw new Error(`Invalid file ${fi(i,r)}: url must be a string.`);t.push(i)}return t}async function Fm(e,t){let n=await zx(t);if(typeof e=="string")return n?{markdown:e,files:n}:{markdown:e};let r=await ra(e);if(r)return n?{card:r,files:n}:{card:r};throw new Error("Invalid message content \u2014 expected string or CardElement")}function Um(e){return`${e}_${crypto.randomUUID()}`}function Pm(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 Mm(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 Zl(e,t){t.toolApprovalRequest&&(e.toolApprovalRequest=t.toolApprovalRequest),t.signals.length&&(e.signals=t.signals),t.toolResults.length&&(e.toolResults=t.toolResults),t.addReactions.length&&(e.addReactions=t.addReactions),t.deleteMessages.length&&(e.deleteMessages=t.deleteMessages),t.resolve&&(e.resolve=t.resolve)}function ec(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,...t!=null&&t.deliverApprovalCard?{deliverCard:!0}:{}})}for(let i of e.toolResults)n.push({type:"tool-use-result",toolUseId:i.toolCallId,content:[{type:"text",text:String((r=i.preview)!=null?r:"")},{type:"json",value:i.output}]});for(let i of e.signals)n.push({type:"signal",signal:i});for(let i of e.addReactions)n.push({type:"channel.reaction",messageId:i.messageId,emoji:i.emojiName,op:"add"});for(let i of e.deleteMessages)n.push({type:"channel.delete",messageId:i.messageId});return e.resolve&&n.push({type:"resolve",summary:e.resolve.summary}),n}var tc=class{constructor(t,n,r,i){this.replyUrl=t;this.secretKey=n;this.conversationId=r;this.integrationIdentifier=i}async sendReply(t,n){let r=this._baseBody();return r.reply=t,Zl(r,n),this._post(r)}async sendApprovalCard(t,n){let r=this._baseBody();return r.reply={toolApprovalCard:t},Zl(r,n),this._post(r)}async editMessage(t,n){return this._post({...this._baseBody(),edit:{messageId:t,content:n}})}async deleteMessage(t){await this._post({...this._baseBody(),deleteMessages:[{messageId:t}]})}async setTyping(t){await this._post({...this._baseBody(),typing:t})}async flushSideEffects(t){let n=this._baseBody();Zl(n,t),await this._post(n)}async emitCustom(){}queueRunStart(){}async emitRunFinish(){}async reportTurnError(){await this._post({...this._baseBody(),error:!0})}_baseBody(){return{conversationId:this.conversationId,integrationIdentifier:this.integrationIdentifier}}async _post(t){let n=await fetch(this.replyUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${this.secretKey}`},body:JSON.stringify(t)});if(!n.ok){let i=await n.text().catch(()=>"");throw new Jt(n.status,i)}let r=await n.text().catch(()=>"");if(!r)return null;try{let i=JSON.parse(r),o=i&&typeof i=="object"&&"data"in i?i.data:i;if(o&&typeof o.messageId=="string"&&typeof o.platformThreadId=="string")return{messageId:o.messageId,platformThreadId:o.platformThreadId}}catch{}return null}},nc=class{constructor(t){this.outbox=t}async sendReply(t,n){let r=Um("msg"),i=ec(n);return i.push({type:"message",role:"assistant",messageId:r,content:Pm(t),files:Mm(t.files)}),await this._emitAndFlush(i),{messageId:r,platformThreadId:""}}async sendApprovalCard(t,n){return await this._emitAndFlush(ec(n,{deliverApprovalCard:!0})),"unaddressable"}async editMessage(t,n){return await this.outbox.emit({type:"channel.edit",messageId:t,content:Pm(n),files:Mm(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(ec(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()}}},hi=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 Fm(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)}},rc=class{constructor(){this.messageId="";this.platformThreadId=""}async edit(){return this}async delete(){}},Nm;Nm=km;var ya=class{constructor(t,n,r){this[Nm]=!0;this._signals=[];this._toolResults=[];this._pendingToolApprovalRequest=null;this._pendingReactions=[];this._pendingDeletes=[];this._resolveSignal=null;var s,u,p,d,h;this.event=t.event,this.action=(s=t.action)!=null?s:null,this.message=t.message,this.reaction=t.reaction,this.conversation=t.conversation,this.subscriber=t.subscriber,this.context=(u=t.context)!=null?u:null,this.notification=(p=t.notification)!=null?p:null,this.history=t.history,this.platform=t.platform,this.platformContext=t.platformContext,this.humanResponse=(d=t.humanResponse)!=null?d:null,this._toolApprovalConfig=r,this._transport=t.eventsUrl?new nc(new ga({eventsUrl:t.eventsUrl,secretKey:n,conversationId:t.conversationId,agentId:t.agentId,turnId:t.deliveryId})):new tc(t.replyUrl,n,t.conversationId,t.integrationIdentifier),this._metadataState={...(h=t.conversation.metadata)!=null?h:{}};let i=this;this.metadata={get(g){return i._metadataState[g]},set(g,y){i._metadataState[g]=y,i._signals.push({type:"metadata",action:"set",key:g,value:y})},delete(g){delete i._metadataState[g],i._signals.push({type:"metadata",action:"delete",key:g})},clear(){i._metadataState={},i._signals.push({type:"metadata",action:"clear"})},get current(){return{...i._metadataState}}};let o=g=>this._transport.setTyping(g),a=(g=>o(g===void 0?{}:{status:g}));a.stop=()=>o("stop"),this.typing=a,this.toolApproval={request:async g=>(await Cm(this,g,this._toolApprovalConfig),new yr)}}asMessageContext(){return this}async reply(t,n){let r=await Fm(t,n==null?void 0:n.files),i=this._drainSideEffectsSnapshot(),o=await this._transport.sendReply(r,i);if(!o)throw new Error("Agent reply did not return a message handle");return new hi(o.messageId,o.platformThreadId,this._transport)}async replyApprovalCard(t){let n=this._drainSideEffectsSnapshot(),r=await this._transport.sendApprovalCard(t,n);if(r==="unaddressable")return new rc;if(!r)throw new Error("Agent approval card reply did not return a message handle");return new hi(r.messageId,r.platformThreadId,this._transport)}createReplyHandle(t){return new hi(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){return this.queueHumanSignal("ask",t,n)}approve(t,n){return this.queueHumanSignal("approve",t,n)}choose(t,n,r){if(n.length<2||n.length>10)throw new Error("ctx.choose requires between 2 and 10 options");if(n.some(i=>typeof i!="string"||i.trim().length===0))throw new Error("ctx.choose options must be non-empty strings");return this.queueHumanSignal("choose",t,r,n)}tell(t,n){return this.queueHumanSignal("tell",t,n)}queueHumanSignal(t,n,r,i){let o=Um("hr"),a=(r==null?void 0:r.to)!==void 0?Rm(r.to):void 0;return this._signals.push({type:"human",kind:t,prompt:n,requestId:o,...i?{options:i}:{},...r!=null&&r.from?{from:r.from}:{},...r&&"ttlSeconds"in r&&r.ttlSeconds!==void 0?{ttlSeconds:r.ttlSeconds}:{},...a!==void 0?{to:a}:{}}),o}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(!this._hasPendingSideEffects())return;let t=this._drainSideEffectsSnapshot();await this._transport.flushSideEffects(t)}_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 Hx(e){return!!(typeof e=="string"||typeof e=="object"&&e!==null&&ta(e)||typeof e=="object"&&e!==null&&("markdown"in e||"card"in e||"files"in e))}function Vx(e,t){return e}function Wx(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 $m(e){var o;let t=new ya(e.bridge,e.secretKey,e.agent.handlers.toolApproval),{agent:n,event:r,logger:i}=e;try{t.queueRunStart(),await Yx(n,r,t),await t.flush(),await t.emitRunFinish({outcome:"completed"})}catch(a){let s=pi(a);i==null||i.error(`[agent:${n.id}] Turn failed (${r}): ${s.message}`,(o=s.cause)!=null?o:s);let u=!1;if(n.handlers.onError)try{let p=await n.handlers.onError(s,Vx(t,r));Am(p)?u=!0:Hx(p)&&(await t.reply(p),u=!0)}catch(p){i==null||i.error(`[agent:${n.id}] onError failed:`,p)}u?await t.emitRunFinish({outcome:"completed"}):await t.reportTurnError(s.message)}finally{try{await t.typing.stop(),await t.flush()}catch{}}}async function Yx(e,t,n){var i,o;let r=async a=>{a instanceof yr||a===void 0||await n.reply(a)};switch(t){case"onMessage":{await r(await e.handlers.onMessage(n.message,n));break}case"onAction":{let a=Om((i=n.action)==null?void 0:i.id);if(a&&e.handlers.onToolApproval){let{approved:s,approvalId:u}=a,p=Wx(n.history,u),d=p?{id:p.toolCallId,name:p.name,input:p.input}:{id:u,name:""},h=n.createReplyHandle((o=n.action.sourceMessageId)!=null?o:""),g={toolCall:d,approved:s,approvalMessage:h};e.userOnToolApproval===!1&&(await n.typing(),n.action.sourceMessageId&&await h.delete());let y=await e.handlers.onToolApproval(g,n);await r(y);break}e.handlers.onAction&&await r(await e.handlers.onAction(n.action,n));break}case"onReaction":e.handlers.onReaction&&await r(await e.handlers.onReaction(n.reaction,n));break;case"onResolve":e.handlers.onResolve&&await r(await e.handlers.onResolve(n));break;default:throw new jn(t,Kl)}}function qm(e){let t={};for(let i of e.split(",")){let o=i.trim();if(!o)continue;let a=o.indexOf("=");if(a<=0)continue;let s=o.slice(0,a),u=o.slice(a+1);s&&u&&!(s in t)&&(t[s]=u)}let n=t.t,r=n!==void 0?Number(n):Number.NaN;return{t:Number.isFinite(r)?r:void 0,v1:t.v1}}var br=class{constructor(t){this.handler=t.handler,this.client=t.client?t.client:new gr,this.workflows=t.workflows||[],this.agents=t.agents||[],this.http=ia(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.13.1","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",o=n.searchParams.get("workflowId")||"",a=n.searchParams.get("stepId")||"",s=n.searchParams.get("agentId")||"",u=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 g=this.getPostActionMap(d,o,a,i,s,u,(h=this.waitUntil)!=null?h:t.waitUntil),y=this.getGetActionMap(o,a);if(r==="POST")return await this.handlePostAction(i,g);if(r==="GET")return await this.handleGetAction(i,y);if(r==="OPTIONS")return this.createResponse(200,{})}catch(g){return this.handleError(g)}return this.createError(new Bi(r))}getPostActionMap(t,n,r,i,o,a,s){return{trigger:this.triggerAction({workflowId:n,...t}),execute:async()=>{let u=await this.client.executeWorkflow({...t,workflowId:n,stepId:r,action:i});return this.createResponse(200,u)},preview:async()=>{let u=await this.client.executeWorkflow({...t,workflowId:n,stepId:r,action:i});return this.createResponse(200,u)},"agent-event":async()=>{let u=this.client.getAgent(o);if(!u)return this.createResponse(404,{error:`Agent '${o}' not registered`});let p=$m({agent:u,event:a,bridge:t,secretKey:this.client.secretKey,logger:this.client.logger});return s?s(p):this.warnOnUnprotectedServerlessRuntime(o),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(Cr).includes(t)){let r=n[t];return r()}else throw new jn(t,Cr)}async handleGetAction(t,n){if(Object.values(Oi).includes(t)){let r=n[t];return r()}else throw new jn(t,Oi)}handleError(t){if(qn(t))return t.statusCode>=500&&this.client.logger.error(t),this.createError(t);if(uu(t))return this.createError(t);{let n=new ir(t);return this.client.logger.error(n),this.createError(n)}}async validateHmac(t,n){if(!this.hmacEnabled)return;if(!n)throw new Ji;if(!this.client.secretKey)throw new Xi;let r=qm(n);if(!r.v1||r.t===void 0)throw new Gi;let i=Date.now();if(r.t<i-3e5||r.t>i+3e5)throw new Ki;let o=await em(this.client.secretKey,`${r.t}.${JSON.stringify(t)}`);if(!tm(o,r.v1))throw new Yi}};function ic(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 oe={output:{type:"object",properties:{},required:[],additionalProperties:!0}};var Jx={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},Bm={output:Jx};var zm={"chat-webhook":oe,discord:oe,getstream:oe,"grafana-on-call":oe,line:oe,mattermost:oe,msteams:oe,"novu-slack":oe,"novu-web-chat":oe,"rocket-chat":oe,ryver:oe,sendblue:oe,slack:Bm,"webex-messaging":oe,"whatsapp-business":oe,zulip:oe,telegram:oe};var Gx={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},Hm={output:Gx};var Zn={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},Kx={type:"object",properties:{contentType:{type:"string"},filename:{type:"string"},base64Content:{type:"string"}},required:["ContentType","Filename","Base64Content"],additionalProperties:!0},Xx={type:"object",properties:{filename:{type:"string"},contentType:{type:"string"},contentId:{type:"string"},base64Content:{type:"string"}},required:["ContentType","Filename","Base64Content"],additionalProperties:!0},Qx={type:"object",properties:{from:Zn,sender:Zn,to:{type:"array",items:Zn},cc:{type:"array",items:Zn},bcc:{type:"array",items:Zn},replyTo:Zn,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:Zn,templateErrorDeliver:{type:"boolean"},attachments:{type:"array",items:Kx},inlineAttachments:{type:"array",items:Xx},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},Vm={output:Qx};var tn={type:"object",properties:{address:{type:"string"},name:{type:"string"}},additionalProperties:!0},ba={type:"object",properties:{content:{type:"string"},path:{type:"string"}},additionalProperties:!0},Zx={type:"object",properties:{from:{anyOf:[{type:"string"},tn]},sender:{anyOf:[{type:"string"},tn]},to:{anyOf:[{type:"string"},tn,{type:"array",items:tn}]},cc:{anyOf:[{type:"string"},tn,{type:"array",items:tn}]},bcc:{anyOf:[{type:"string"},tn,{type:"array",items:tn}]},replyTo:{anyOf:[{type:"string"},tn,{type:"array",items:tn}]},inReplyTo:{anyOf:[{type:"string"},tn]},references:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},subject:{type:"string"},text:{anyOf:[{type:"string"},ba]},html:{anyOf:[{type:"string"},ba]},watchHtml:{anyOf:[{type:"string"},ba]},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"},ba]}}}]},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},Wm={output:Zx};var ev={type:"object",properties:{},required:[],additionalProperties:!1},Ym={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},Jm={output:tv};var Gm={anypost:oe,braze:oe,clickatell:oe,nodemailer:Wm,emailjs:oe,"email-webhook":oe,"infobip-email":oe,mailersend:oe,mailgun:Hm,mailjet:Vm,mailtrap:oe,mandrill:oe,netcore:oe,"novu-email":Ym,outlook365:oe,plunk:oe,postmark:oe,resend:oe,sendgrid:Jm,sendinblue:oe,ses:oe,sparkpost:oe};var nv={type:"object",properties:{},required:[],additionalProperties:!1},Km={output:nv};var Xm={novu:Km};var Qm={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:
|
|
154
|
+
`)}async executeProviders(t,n,r,i){return n.providers.reduce(async(o,a)=>{let s=await o,u=await this.runProvider(t,n,a,r,i);return{...s,[a.type]:u}},Promise.resolve({}))}async runProvider(t,n,r,i,o){let a=t.action==="preview";if(t.stepId!==n.stepId)return a?(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,o,i)}catch(s){if(this.log(` ${lt.ERROR} Failed to execute provider: \`${r.type}\``),a)return this.log(` ${lt.MOCK} Mocked provider: \`${r.type}\``),this.mock(r.outputs.schema);throw new Wi(r.type,t.action,s)}}async resolveProviderOutput(t,n,r,i,o){let a=await r.resolve({controls:i,outputs:o}),s=await this.validate(a,r.outputs.unknownSchema,"step","output",t.workflowId,n.stepId,r.type);return this.log(` ${lt.SUCCESS} Executed provider: \`${r.type}\``),{...s,_passthrough:a._passthrough}}async executeStep(t,n){if(t.stepId===n.stepId)try{let r=await this.createStepControls(n,t),i=await this.compileControls(r,t),o=await n.resolve(i),a=await this.normalizeChatCardOutput(n,o),s=await this.validate(a,n.outputs.unknownSchema,"step","output",t.workflowId,n.stepId),u=await this.executeProviders(t,n,s,i);return this.log(` ${lt.SUCCESS} Executed stepId: \`${n.stepId}\``),{outputs:s,providers:u}}catch(r){throw this.log(` ${lt.ERROR} Failed to execute stepId: \`${n.stepId}\``),qn(r)?r:new Nr(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 Mi(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 ra(n.card);return r?{...n,card:r}:n}async compileControls(t,n){var r;try{let i=li(t),o=this.preprocessTranslationPatterns(JSON.stringify(i));o=this.preprocessFilterTranslationArgs(o);let a=this.templateEngine.parse(o),s=this.getWorkflow(n.workflowId),u={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:_x(n.state),env:(r=n.env)!=null?r:{}},p=await this.templateEngine.render(a,u),d=this.postprocessTranslationMarkers(p),h=(0,vm.jsonrepair)(d),g=JSON.parse(h),y=ci(g);return bm(y)}catch(i){throw new Ui(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}\``),qn(r)?r:new Nr(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),o=this.mock(n.results.schema);return{outputs:Jl(o,(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),o=await t.resolve(i),a=await this.normalizeChatCardOutput(t,o),s=await this.validate(a,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 Lr(t);return r}};function _x(e){let t={};for(let n of e)t[n.stepId]=n.outputs;return t}var Ox={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 ma(e){return typeof e=="string"&&e.trim()?e:!e||typeof e!="object"?null:ma(e.message)}function Cx(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=ma(n.message);if(r)return r;let i=ma(n.error);if(i)return i;let o=n.errors;return Array.isArray(o)?ma(o[0]):null}function Ix(e,t){var i;let n=(i=Ox[e])!=null?i:e,r=Cx(t);return r?`Delivery failed: ${n}: ${r}`:`Delivery failed: ${n}`}var kn=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}},Jt=class extends kn{constructor(t,n){let r={statusCode:t,responseBody:n};super(Ix(t,n),{delivery:r}),this.name="AgentDeliveryError",this.statusCode=t,this.responseBody=n}};function pi(e){return e instanceof kn?e:e instanceof Error?new kn(e.message,{cause:e}):new kn("Turn failed",{cause:e})}var km=Symbol.for("novu.agent.runtimeContext");var Kl=(i=>(i.ON_MESSAGE="onMessage",i.ON_ACTION="onAction",i.ON_RESOLVE="onResolve",i.ON_REACTION="onReaction",i))(Kl||{}),yr=class{constructor(){this.__novuPendingApproval=!0}};function Am(e){return typeof e=="object"&&e!==null&&"suppress"in e&&e.suppress===!0}var Em=1;function Px(e){return new Promise(t=>{setTimeout(t,e)})}function Mx(e){return e>=500||e===408||e===429}var ga=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:Em,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,!Nx(i))throw i;r<this.maxRetries&&await Px(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 Lx(i)}let r=await n.text().catch(()=>"");if(!n.ok)throw new Jt(n.status,r)}};function Nx(e){return!(e instanceof Jt)||e.statusCode===0?!0:Mx(e.statusCode)}function Lx(e){if(e instanceof Jt)return e;let t=e instanceof Error?e.message:"Network request failed";return new Jt(0,t)}function Rm(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 o=i.trim();!o||r.has(o)||(r.add(o),n.push(o))}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 _m="tool-approval";function Dx(e){return e==="approve"||e==="deny"}function Xl(e,t){return`${_m}:${e}:${t}`}function Om(e){let[t,n,...r]=(e!=null?e:"").split(":"),i=r.join(":");return t!==_m||!Dx(n)||!i?null:{approved:n==="approve",approvalId:i}}async function Cm(e,t,n,r){var p,d;let i=r!=null?r:t.id,o={approve:Xl("approve",i),deny:Xl("deny",i)},a=h=>({type:"tool-approval-card",...h}),s=(d=(p=n==null?void 0:n.renderApproval)==null?void 0:p.call(n,{toolCall:t,actionIds:o,approvalCard:a}))!=null?d:a(),u={approvalId:i,toolCallId:t.id,name:t.name,input:t.input};if(e.emitToolApprovalRequest(u),Xf(s)){await e.replyApprovalCard(s);return}await e.reply(s)}var Fx=5*1024*1024,Ux=5*1024*1024,Im=32768,$x=/^[A-Za-z0-9+/]*={0,2}$/;function fi(e,t){return e.filename?`"${e.filename}"`:`at index ${t}`}function Lm(){return globalThis.Buffer}function qx(e){var t,n,r;return(r=(n=(t=Lm())==null?void 0:t.isBuffer)==null?void 0:n.call(t,e))!=null?r:!1}function jx(e){return typeof Blob!="undefined"&&e instanceof Blob}function Ql(e){let t=Lm();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+=Im){let i=e.subarray(r,r+Im);n+=String.fromCharCode(...i)}return btoa(n)}function Dm(e){let t=e.replace(/\s/g,""),n=t.length%4;if(!t||n===1||!$x.test(t))return null;let r=t.endsWith("==")?2:t.endsWith("=")?1:0;return Math.floor(t.length*3/4)-r}function di(e,t,n){if(e>Fx)throw new Error(`Invalid file ${fi(t,n)}: inline data must be 5 MB or smaller. Use a publicly-accessible URL for larger files.`)}async function Bx(e,t,n){if(typeof e=="string"){let r=Dm(e);if(r===null)throw new Error(`Invalid file ${fi(t,n)}: data must be a base64-encoded string.`);return di(r,t,n),e}if(qx(e))return di(e.byteLength,t,n),e.toString("base64");if(e instanceof Uint8Array)return di(e.byteLength,t,n),Ql(e);if(e instanceof ArrayBuffer)return di(e.byteLength,t,n),Ql(new Uint8Array(e));if(jx(e))return di(e.size,t,n),Ql(new Uint8Array(await e.arrayBuffer()));throw new Error(`Invalid file ${fi(t,n)}: data must be a base64 string, Buffer, Uint8Array, ArrayBuffer, or Blob.`)}async function zx(e){if(!(e!=null&&e.length))return;let t=[],n=0;for(let[r,i]of e.entries()){let o=i.data,a=i.url,s=o!=null,u=a!=null;if(s===u)throw new Error(`Invalid file ${fi(i,r)}: provide exactly one of data or url.`);if(s){let p=await Bx(o,i,r),d=Dm(p);if(n+=d!=null?d:0,n>Ux)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(u&&typeof a!="string")throw new Error(`Invalid file ${fi(i,r)}: url must be a string.`);t.push(i)}return t}async function Fm(e,t){let n=await zx(t);if(typeof e=="string")return n?{markdown:e,files:n}:{markdown:e};let r=await ra(e);if(r)return n?{card:r,files:n}:{card:r};throw new Error("Invalid message content \u2014 expected string or CardElement")}function Um(e){return`${e}_${crypto.randomUUID()}`}function Pm(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 Mm(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 Zl(e,t){t.toolApprovalRequest&&(e.toolApprovalRequest=t.toolApprovalRequest),t.signals.length&&(e.signals=t.signals),t.toolResults.length&&(e.toolResults=t.toolResults),t.addReactions.length&&(e.addReactions=t.addReactions),t.deleteMessages.length&&(e.deleteMessages=t.deleteMessages),t.resolve&&(e.resolve=t.resolve)}function ec(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,...t!=null&&t.deliverApprovalCard?{deliverCard:!0}:{}})}for(let i of e.toolResults)n.push({type:"tool-use-result",toolUseId:i.toolCallId,content:[{type:"text",text:String((r=i.preview)!=null?r:"")},{type:"json",value:i.output}]});for(let i of e.signals)n.push({type:"signal",signal:i});for(let i of e.addReactions)n.push({type:"channel.reaction",messageId:i.messageId,emoji:i.emojiName,op:"add"});for(let i of e.deleteMessages)n.push({type:"channel.delete",messageId:i.messageId});return e.resolve&&n.push({type:"resolve",summary:e.resolve.summary}),n}var tc=class{constructor(t,n,r,i){this.replyUrl=t;this.secretKey=n;this.conversationId=r;this.integrationIdentifier=i}async sendReply(t,n){let r=this._baseBody();return r.reply=t,Zl(r,n),this._post(r)}async sendApprovalCard(t,n){let r=this._baseBody();return r.reply={toolApprovalCard:t},Zl(r,n),this._post(r)}async editMessage(t,n){return this._post({...this._baseBody(),edit:{messageId:t,content:n}})}async deleteMessage(t){await this._post({...this._baseBody(),deleteMessages:[{messageId:t}]})}async setTyping(t){await this._post({...this._baseBody(),typing:t})}async flushSideEffects(t){let n=this._baseBody();Zl(n,t),await this._post(n)}async emitCustom(){}queueRunStart(){}async emitRunFinish(){}async reportTurnError(){await this._post({...this._baseBody(),error:!0})}_baseBody(){return{conversationId:this.conversationId,integrationIdentifier:this.integrationIdentifier}}async _post(t){let n=await fetch(this.replyUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${this.secretKey}`},body:JSON.stringify(t)});if(!n.ok){let i=await n.text().catch(()=>"");throw new Jt(n.status,i)}let r=await n.text().catch(()=>"");if(!r)return null;try{let i=JSON.parse(r),o=i&&typeof i=="object"&&"data"in i?i.data:i;if(o&&typeof o.messageId=="string"&&typeof o.platformThreadId=="string")return{messageId:o.messageId,platformThreadId:o.platformThreadId}}catch{}return null}},nc=class{constructor(t){this.outbox=t}async sendReply(t,n){let r=Um("msg"),i=ec(n);return i.push({type:"message",role:"assistant",messageId:r,content:Pm(t),files:Mm(t.files)}),await this._emitAndFlush(i),{messageId:r,platformThreadId:""}}async sendApprovalCard(t,n){return await this._emitAndFlush(ec(n,{deliverApprovalCard:!0})),"unaddressable"}async editMessage(t,n){return await this.outbox.emit({type:"channel.edit",messageId:t,content:Pm(n),files:Mm(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(ec(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()}}},hi=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 Fm(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)}},rc=class{constructor(){this.messageId="";this.platformThreadId=""}async edit(){return this}async delete(){}},Nm;Nm=km;var ya=class{constructor(t,n,r){this[Nm]=!0;this._signals=[];this._toolResults=[];this._pendingToolApprovalRequest=null;this._pendingReactions=[];this._pendingDeletes=[];this._resolveSignal=null;var s,u,p,d,h;this.event=t.event,this.action=(s=t.action)!=null?s:null,this.message=t.message,this.reaction=t.reaction,this.conversation=t.conversation,this.subscriber=t.subscriber,this.context=(u=t.context)!=null?u:null,this.notification=(p=t.notification)!=null?p:null,this.history=t.history,this.platform=t.platform,this.platformContext=t.platformContext,this.humanResponse=(d=t.humanResponse)!=null?d:null,this._toolApprovalConfig=r,this._transport=t.eventsUrl?new nc(new ga({eventsUrl:t.eventsUrl,secretKey:n,conversationId:t.conversationId,agentId:t.agentId,turnId:t.deliveryId})):new tc(t.replyUrl,n,t.conversationId,t.integrationIdentifier),this._metadataState={...(h=t.conversation.metadata)!=null?h:{}};let i=this;this.metadata={get(g){return i._metadataState[g]},set(g,y){i._metadataState[g]=y,i._signals.push({type:"metadata",action:"set",key:g,value:y})},delete(g){delete i._metadataState[g],i._signals.push({type:"metadata",action:"delete",key:g})},clear(){i._metadataState={},i._signals.push({type:"metadata",action:"clear"})},get current(){return{...i._metadataState}}};let o=g=>this._transport.setTyping(g),a=(g=>o(g===void 0?{}:{status:g}));a.stop=()=>o("stop"),this.typing=a,this.toolApproval={request:async g=>(await Cm(this,g,this._toolApprovalConfig),new yr)}}asMessageContext(){return this}async reply(t,n){let r=await Fm(t,n==null?void 0:n.files),i=this._drainSideEffectsSnapshot(),o=await this._transport.sendReply(r,i);if(!o)throw new Error("Agent reply did not return a message handle");return new hi(o.messageId,o.platformThreadId,this._transport)}async replyApprovalCard(t){let n=this._drainSideEffectsSnapshot(),r=await this._transport.sendApprovalCard(t,n);if(r==="unaddressable")return new rc;if(!r)throw new Error("Agent approval card reply did not return a message handle");return new hi(r.messageId,r.platformThreadId,this._transport)}createReplyHandle(t){return new hi(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){return this.queueHumanSignal("ask",t,n)}approve(t,n){return this.queueHumanSignal("approve",t,n)}choose(t,n,r){if(n.length<2||n.length>10)throw new Error("ctx.choose requires between 2 and 10 options");if(n.some(i=>typeof i!="string"||i.trim().length===0))throw new Error("ctx.choose options must be non-empty strings");return this.queueHumanSignal("choose",t,r,n)}tell(t,n){return this.queueHumanSignal("tell",t,n)}queueHumanSignal(t,n,r,i){let o=Um("hr"),a=(r==null?void 0:r.to)!==void 0?Rm(r.to):void 0;return this._signals.push({type:"human",kind:t,prompt:n,requestId:o,...i?{options:i}:{},...r!=null&&r.from?{from:r.from}:{},...r&&"ttlSeconds"in r&&r.ttlSeconds!==void 0?{ttlSeconds:r.ttlSeconds}:{},...a!==void 0?{to:a}:{}}),o}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(!this._hasPendingSideEffects())return;let t=this._drainSideEffectsSnapshot();await this._transport.flushSideEffects(t)}_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 Hx(e){return!!(typeof e=="string"||typeof e=="object"&&e!==null&&ta(e)||typeof e=="object"&&e!==null&&("markdown"in e||"card"in e||"files"in e))}function Vx(e,t){return e}function Wx(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 $m(e){var o;let t=new ya(e.bridge,e.secretKey,e.agent.handlers.toolApproval),{agent:n,event:r,logger:i}=e;try{t.queueRunStart(),await Yx(n,r,t),await t.flush(),await t.emitRunFinish({outcome:"completed"})}catch(a){let s=pi(a);i==null||i.error(`[agent:${n.id}] Turn failed (${r}): ${s.message}`,(o=s.cause)!=null?o:s);let u=!1;if(n.handlers.onError)try{let p=await n.handlers.onError(s,Vx(t,r));Am(p)?u=!0:Hx(p)&&(await t.reply(p),u=!0)}catch(p){i==null||i.error(`[agent:${n.id}] onError failed:`,p)}u?await t.emitRunFinish({outcome:"completed"}):await t.reportTurnError(s.message)}finally{try{await t.typing.stop(),await t.flush()}catch{}}}async function Yx(e,t,n){var i,o;let r=async a=>{a instanceof yr||a===void 0||await n.reply(a)};switch(t){case"onMessage":{await r(await e.handlers.onMessage(n.message,n));break}case"onAction":{let a=Om((i=n.action)==null?void 0:i.id);if(a&&e.handlers.onToolApproval){let{approved:s,approvalId:u}=a,p=Wx(n.history,u),d=p?{id:p.toolCallId,name:p.name,input:p.input}:{id:u,name:""},h=n.createReplyHandle((o=n.action.sourceMessageId)!=null?o:""),g={toolCall:d,approved:s,approvalMessage:h};e.userOnToolApproval===!1&&(await n.typing(),n.action.sourceMessageId&&await h.delete());let y=await e.handlers.onToolApproval(g,n);await r(y);break}e.handlers.onAction&&await r(await e.handlers.onAction(n.action,n));break}case"onReaction":e.handlers.onReaction&&await r(await e.handlers.onReaction(n.reaction,n));break;case"onResolve":e.handlers.onResolve&&await r(await e.handlers.onResolve(n));break;default:throw new jn(t,Kl)}}function qm(e){let t={};for(let i of e.split(",")){let o=i.trim();if(!o)continue;let a=o.indexOf("=");if(a<=0)continue;let s=o.slice(0,a),u=o.slice(a+1);s&&u&&!(s in t)&&(t[s]=u)}let n=t.t,r=n!==void 0?Number(n):Number.NaN;return{t:Number.isFinite(r)?r:void 0,v1:t.v1}}var br=class{constructor(t){this.handler=t.handler,this.client=t.client?t.client:new gr,this.workflows=t.workflows||[],this.agents=t.agents||[],this.http=ia(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.13.2-rc.dc9caee828","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",o=n.searchParams.get("workflowId")||"",a=n.searchParams.get("stepId")||"",s=n.searchParams.get("agentId")||"",u=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 g=this.getPostActionMap(d,o,a,i,s,u,(h=this.waitUntil)!=null?h:t.waitUntil),y=this.getGetActionMap(o,a);if(r==="POST")return await this.handlePostAction(i,g);if(r==="GET")return await this.handleGetAction(i,y);if(r==="OPTIONS")return this.createResponse(200,{})}catch(g){return this.handleError(g)}return this.createError(new Bi(r))}getPostActionMap(t,n,r,i,o,a,s){return{trigger:this.triggerAction({workflowId:n,...t}),execute:async()=>{let u=await this.client.executeWorkflow({...t,workflowId:n,stepId:r,action:i});return this.createResponse(200,u)},preview:async()=>{let u=await this.client.executeWorkflow({...t,workflowId:n,stepId:r,action:i});return this.createResponse(200,u)},"agent-event":async()=>{let u=this.client.getAgent(o);if(!u)return this.createResponse(404,{error:`Agent '${o}' not registered`});let p=$m({agent:u,event:a,bridge:t,secretKey:this.client.secretKey,logger:this.client.logger});return s?s(p):this.warnOnUnprotectedServerlessRuntime(o),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(Cr).includes(t)){let r=n[t];return r()}else throw new jn(t,Cr)}async handleGetAction(t,n){if(Object.values(Oi).includes(t)){let r=n[t];return r()}else throw new jn(t,Oi)}handleError(t){if(qn(t))return t.statusCode>=500&&this.client.logger.error(t),this.createError(t);if(uu(t))return this.createError(t);{let n=new ir(t);return this.client.logger.error(n),this.createError(n)}}async validateHmac(t,n){if(!this.hmacEnabled)return;if(!n)throw new Ji;if(!this.client.secretKey)throw new Xi;let r=qm(n);if(!r.v1||r.t===void 0)throw new Gi;let i=Date.now();if(r.t<i-3e5||r.t>i+3e5)throw new Ki;let o=await em(this.client.secretKey,`${r.t}.${JSON.stringify(t)}`);if(!tm(o,r.v1))throw new Yi}};function ic(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 oe={output:{type:"object",properties:{},required:[],additionalProperties:!0}};var Jx={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},Bm={output:Jx};var zm={"chat-webhook":oe,discord:oe,getstream:oe,"grafana-on-call":oe,line:oe,mattermost:oe,msteams:oe,"novu-slack":oe,"novu-web-chat":oe,"rocket-chat":oe,ryver:oe,sendblue:oe,slack:Bm,"webex-messaging":oe,"whatsapp-business":oe,zulip:oe,telegram:oe};var Gx={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},Hm={output:Gx};var Zn={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},Kx={type:"object",properties:{contentType:{type:"string"},filename:{type:"string"},base64Content:{type:"string"}},required:["ContentType","Filename","Base64Content"],additionalProperties:!0},Xx={type:"object",properties:{filename:{type:"string"},contentType:{type:"string"},contentId:{type:"string"},base64Content:{type:"string"}},required:["ContentType","Filename","Base64Content"],additionalProperties:!0},Qx={type:"object",properties:{from:Zn,sender:Zn,to:{type:"array",items:Zn},cc:{type:"array",items:Zn},bcc:{type:"array",items:Zn},replyTo:Zn,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:Zn,templateErrorDeliver:{type:"boolean"},attachments:{type:"array",items:Kx},inlineAttachments:{type:"array",items:Xx},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},Vm={output:Qx};var tn={type:"object",properties:{address:{type:"string"},name:{type:"string"}},additionalProperties:!0},ba={type:"object",properties:{content:{type:"string"},path:{type:"string"}},additionalProperties:!0},Zx={type:"object",properties:{from:{anyOf:[{type:"string"},tn]},sender:{anyOf:[{type:"string"},tn]},to:{anyOf:[{type:"string"},tn,{type:"array",items:tn}]},cc:{anyOf:[{type:"string"},tn,{type:"array",items:tn}]},bcc:{anyOf:[{type:"string"},tn,{type:"array",items:tn}]},replyTo:{anyOf:[{type:"string"},tn,{type:"array",items:tn}]},inReplyTo:{anyOf:[{type:"string"},tn]},references:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},subject:{type:"string"},text:{anyOf:[{type:"string"},ba]},html:{anyOf:[{type:"string"},ba]},watchHtml:{anyOf:[{type:"string"},ba]},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"},ba]}}}]},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},Wm={output:Zx};var ev={type:"object",properties:{},required:[],additionalProperties:!1},Ym={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},Jm={output:tv};var Gm={anypost:oe,braze:oe,clickatell:oe,nodemailer:Wm,emailjs:oe,"email-webhook":oe,"infobip-email":oe,mailersend:oe,mailgun:Hm,mailjet:Vm,mailtrap:oe,mandrill:oe,netcore:oe,"novu-email":Ym,outlook365:oe,plunk:oe,postmark:oe,resend:oe,sendgrid:Jm,sendinblue:oe,ses:oe,sparkpost:oe};var nv={type:"object",properties:{},required:[],additionalProperties:!1},Km={output:nv};var Xm={novu:Km};var Qm={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:
|
|
155
155
|
|
|
156
156
|
10 - The push notification is sent to the device immediately. (Default)
|
|
157
157
|
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.
|