@novu/framework 2.11.2 → 2.12.1
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/README.md +1 -0
- package/dist/cjs/index.cjs +3 -3
- package/dist/cjs/internal/index.cjs +1 -1
- package/dist/cjs/internal/index.d.cts +10 -10
- package/dist/cjs/{server.types-BRWsA1CA.d.cts → server.types-Cc6o5eYH.d.cts} +1 -1
- package/dist/cjs/servers/express.cjs +3 -3
- package/dist/cjs/servers/express.d.cts +1 -1
- package/dist/cjs/servers/h3.cjs +3 -3
- package/dist/cjs/servers/h3.d.cts +1 -1
- package/dist/cjs/servers/hono.cjs +564 -0
- package/dist/cjs/servers/hono.d.cts +41 -0
- package/dist/cjs/servers/lambda.cjs +3 -3
- package/dist/cjs/servers/lambda.d.cts +1 -1
- package/dist/cjs/servers/nest.cjs +3 -3
- package/dist/cjs/servers/nest.d.cts +1 -1
- package/dist/cjs/servers/next.cjs +3 -3
- package/dist/cjs/servers/next.d.cts +1 -1
- package/dist/cjs/servers/nuxt.cjs +3 -3
- package/dist/cjs/servers/nuxt.d.cts +1 -1
- package/dist/cjs/servers/remix.cjs +3 -3
- package/dist/cjs/servers/remix.d.cts +1 -1
- package/dist/cjs/servers/sveltekit.cjs +3 -3
- package/dist/cjs/servers/sveltekit.d.cts +1 -1
- package/dist/esm/chunk-T4QVGWWK.js +1 -0
- package/dist/esm/{chunk-EZ22F362.js → chunk-XC7ATSSO.js} +3 -3
- package/dist/esm/index.js +1 -1
- package/dist/esm/internal/index.d.ts +1 -1
- package/dist/esm/internal/index.js +1 -1
- package/dist/esm/{server.types-BRWsA1CA.d.ts → server.types-Cc6o5eYH.d.ts} +1 -1
- package/dist/esm/servers/express.d.ts +1 -1
- package/dist/esm/servers/express.js +1 -1
- package/dist/esm/servers/h3.d.ts +1 -1
- package/dist/esm/servers/h3.js +1 -1
- package/dist/esm/servers/hono.d.ts +41 -0
- package/dist/esm/servers/hono.js +1 -0
- package/dist/esm/servers/lambda.d.ts +1 -1
- package/dist/esm/servers/lambda.js +1 -1
- package/dist/esm/servers/nest.d.ts +1 -1
- package/dist/esm/servers/nest.js +1 -1
- package/dist/esm/servers/next.d.ts +1 -1
- package/dist/esm/servers/next.js +1 -1
- package/dist/esm/servers/nuxt.d.ts +1 -1
- package/dist/esm/servers/nuxt.js +1 -1
- package/dist/esm/servers/remix.d.ts +1 -1
- package/dist/esm/servers/remix.js +1 -1
- package/dist/esm/servers/sveltekit.d.ts +1 -1
- package/dist/esm/servers/sveltekit.js +1 -1
- package/hono/package.json +3 -0
- package/package.json +18 -1
- package/dist/esm/chunk-E2MET7IR.js +0 -1
package/README.md
CHANGED
|
@@ -151,6 +151,7 @@ Serve workflows and agents from your framework of choice:
|
|
|
151
151
|
| `@novu/framework/nest` | NestJS |
|
|
152
152
|
| `@novu/framework/express` | Express |
|
|
153
153
|
| `@novu/framework/h3` | H3 / Nuxt |
|
|
154
|
+
| `@novu/framework/hono` | Hono |
|
|
154
155
|
| `@novu/framework/lambda` | AWS Lambda |
|
|
155
156
|
| `@novu/framework/sveltekit` | SvelteKit |
|
|
156
157
|
| `@novu/framework/remix` | Remix |
|
package/dist/cjs/index.cjs
CHANGED
|
@@ -109,14 +109,14 @@ ${Ee.comment}`:fe.comment),fe=Ee}G.items[pe]=fe instanceof f.Pair?fe:new f.Pair(
|
|
|
109
109
|
et dolore magna aliqua Ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
|
|
110
110
|
commodo consequat Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
|
|
111
111
|
pariatur Excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est
|
|
112
|
-
laborum`.split(/\W/),ii=Xr,ai={type:Gt.ALLOWED_TYPES},xc=Qr,ho=Ja,Tc=Zr,oi=ei,kc=Ga,Ac=Ka,fo="[a-zA-Z][a-zA-Z0-9+-.]*",si=`https?://{hostname}(?:${fo})+`,vc="(?:\\?([a-z]{1,7}(=\\w{1,5})?&){0,3})?",Ut={email:"[a-zA-Z\\d][a-zA-Z\\d-]{1,13}[a-zA-Z\\d]@{hostname}",hostname:"[a-zA-Z]{1,33}\\.[a-z]{2,4}",ipv6:"[a-f\\d]{4}(:[a-f\\d]{4}){7}",uri:si,slug:"[a-zA-Z\\d_-]+","uri-reference":`${si}${vc}`,"uri-template":si.replace("(?:","(?:/\\{[a-z][:a-zA-Z0-9-]*\\}|"),"json-pointer":`(/(?:${fo.replace("]*","/]*")}|~[01]))+`,uuid:"^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$",duration:"^P(?!$)((\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+S)?)?|(\\d+W)?)$"},Ut.iri=Ut["uri-reference"],Ut["iri-reference"]=Ut["uri-reference"],Ut["idn-email"]=Ut.email,Ut["idn-hostname"]=Ut.hostname,Ec=new RegExp(`\\{(${Object.keys(Ut).join("|")})\\}`),_c=Xa,Rc=Za,Oc={boolean:fc,null:yc,array:bc,integer:wc,number:po,object:xc,string:Rc},br=Oc,Ic=re,Cc=({refs:l,schema:c,container:f,synchronous:S,refDepthMax:x,refDepthMin:A})=>{let k={},L={},Q=0,N,ie;return k.resolveSchema=(j,he,ce)=>{if(j==null)return null;if(typeof j.generate=="function")return j;if(typeof(j.$id||j.id)=="string"&&(delete j.id,delete j.$id,delete j.$schema),typeof j.$ref=="string"){let Te=Math.max(A,x)-1;if(j.$ref==="#"||L[j.$ref]<0||N===j.$ref&&++Q>Te)return j.$ref!=="#"&&ie&&ie.length===ce.length?Ye.getLocalRef(c,j.$ref,S&&l):(delete j.$ref,j);typeof L[j.$ref]=="undefined"&&(L[j.$ref]=ve.number(A,x)-1),ie=ce,N=j.$ref;let Re;j.$ref.indexOf("#/")===-1?Re=l[j.$ref]||null:Re=Ye.getLocalRef(c,j.$ref,S&&l)||null;let Ge;if(typeof Re!="undefined"){if(!Re&&_e("ignoreMissingRefs")!==!0)throw new Error(`Reference not found: ${j.$ref}`);L[j.$ref]-=1,Ye.merge(j,Re||{}),Ge=S&&Re&&Re.$ref}return Ge||delete j.$ref,j}if(Array.isArray(j.allOf)){let Te=j.allOf;delete j.allOf,Te.forEach(Re=>{let Ge=k.resolveSchema(Re,null,ce);Ye.merge(j,typeof Ge.thunk=="function"?Ge.thunk(j):Ge),Array.isArray(j.allOf)&&k.resolveSchema(j,he,ce)})}if(Array.isArray(j.oneOf||j.anyOf)&&ce[ce.length-2]!=="dependencies"){let Te=j.oneOf||j.anyOf;return j.enum&&j.oneOf&&(j.enum=j.enum.filter(Re=>Ye.validate(Re,Te))),{thunk(Re){let Ge=Ye.omitProps(j,["anyOf","oneOf"]),Qe=ve.pick(Te);return Ye.merge(Ge,Qe),Te.forEach(ae=>{ae.required&&ae!==Qe&&ae.required.forEach(I=>{if(Qe.required&&Qe.required.includes(I))return;let C=Ge.required&&Ge.required.includes(I);Ge.properties&&!C&&delete Ge.properties[I],Re&&Re.properties&&delete Re.properties[I]})}),Ge}}}if(Object.keys(j).forEach(Te=>{(Array.isArray(j[Te])||typeof j[Te]=="object")&&!Ye.isKey(Te)&&(j[Te]=k.resolveSchema(j[Te],Te,ce.concat(Te)))}),ce){let Te=ce[ce.length-1];if(Te==="properties"||Te==="items")return j}return f.wrap(j)},k},Pc=Cc,mo=Nt,go=nn,vt=no(Gl(),1),Mm=vt.default.binaryOptions,Nm=vt.default.boolOptions,Lm=vt.default.intOptions,Dm=vt.default.nullOptions,Fm=vt.default.strOptions,Um=vt.default.Schema,$m=vt.default.Alias,qm=vt.default.Collection,jm=vt.default.Merge,Bm=vt.default.Node,zm=vt.default.Pair,Vm=vt.default.Scalar,Mc=vt.default.YAMLMap,Nc=vt.default.YAMLSeq,wr=Cn,on=new lc,rt=(l,c,f)=>(console.debug("[json-schema-faker] calling JSONSchemaFaker() is deprecated, call either .generate() or .resolve()"),f&&console.debug("[json-schema-faker] local references are only supported by calling .resolve()"),rt.generate(l,c)),rt.generateWithContext=(l,c)=>{let f=an(c,l);return mo(f,l,on,!0)},rt.generate=(l,c)=>go(rt.generateWithContext(l,c)),rt.generateYAML=(l,c)=>wr(rt.generateWithContext(l,c)),rt.resolveWithContext=(l,c,f)=>{typeof c=="string"&&(f=c,c={}),f=f||(typeof process!="undefined"&&typeof process.cwd=="function"?process.cwd():""),f=`${f.replace(/\/+$/,"")}/`;let S=an(c,l),x={order:1,canRead(k){let L=k.url.replace("/:",":");return S[L]||S[L.split("/").pop()]},read(k,L){try{L(null,this.canRead(k))}catch(Q){L(Q)}}},{$RefParser:A}=ao();return A.bundle(f,l,{resolve:{file:{order:100},http:{order:200},fixedRefs:x},dereference:{circular:"ignore"}}).then(k=>mo(S,k,on)).catch(k=>{throw new Error(`Error while resolving schema (${k.message})`)})},rt.resolve=(l,c,f)=>rt.resolveWithContext(l,c,f).then(go),rt.resolveYAML=(l,c,f)=>rt.resolveWithContext(l,c,f).then(wr),St(),rt.format=uo,rt.option=_e,rt.random=ve,rt.extend=(l,c)=>(on.extend(l,c),rt),rt.define=(l,c)=>(on.define(l,c),rt),rt.reset=l=>(on.reset(l),St(),rt),rt.locate=l=>on.get(l),rt.VERSION="0.5.5",Lc={...rt},Dc=rt}}),Hm=a({"src/src/main.iife.js"(l,c){var f=(Wm(),u(p));typeof $RefParser!="undefined"&&typeof JSONPath!="undefined"&&f.setDependencies({...JSONPath,$RefParser}),typeof window!="undefined"&&(window.JSONSchemaFaker=f.default),c.exports=f.default,c.exports.JSONSchemaFaker=f.JSONSchemaFaker}});return Hm()})();((e,n)=>{e.JSONSchemaFaker=n()})(typeof self!="undefined"?self:typeof window!="undefined"?window:globalThis,()=>Ni);Ni.random.shuffle=function(){return["[placeholder]"]};Ni.option({useDefaultValue:!0,alwaysFakeOptionals:!0});function Hc(e){return Ni.generate(e)}var Yc=async(e,n)=>{let t=new TextEncoder,r=t.encode(e),i=t.encode(n),a=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("HMAC",a,i);return Array.from(new Uint8Array(o)).map(s=>s.toString(16).padStart(2,"0")).join("")},Jc=(e,n)=>{if(typeof e!="string"||typeof n!="string"||e.length!==n.length)return!1;let t=0;for(let r=0;r<e.length;r+=1)t|=e.charCodeAt(r)^n.charCodeAt(r);return t===0};var yg=require("cross-fetch");var Gc=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 n=await(await fetch("http://localhost:2022/.well-known/novu")).json();return`${n.tunnelOrigin}${n.route}`}}catch(e){console.error(e)}return""};function Kc(e){return!!e&&typeof e=="object"&&"error"in e&&"message"in e&&"statusCode"in e}var Li=(e,n)=>{if(!e)throw new ki;return{post:async(t,r)=>{let i=await fetch(`${n}/v1${t}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${e}`},body:JSON.stringify(r)}),a=await i.json();if(i.ok)return a;throw Kc(a)?new Ai(a.statusCode,a.error,a.message):new Gn(a)},delete:async t=>(await fetch(`${n}/v1${t}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${e}`}})).json()}};var nu=require("liquidjs");function xo(e,n){let t={...e};for(let r of Object.keys(n)){let i=n[r];i&&typeof i=="object"&&!Array.isArray(i)?t[r]=xo(t[r]||{},i):(Array.isArray(i),t[r]=i)}return t}function Di(e,n){let t=n.split(".").reduce((r,i)=>{if(r&&typeof r=="object")return r[i]},e);if(t==null)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);if(typeof t=="object"){let r=JSON.stringify(t);return r==="{}"?"":r}return""}function Xc(e,n=2,t,r=", "){if(!Array.isArray(e)||e.length===0)return"";let i=t?e.map(s=>typeof s!="object"||!s?"":Di(s,t)):e;if(i.length===1)return i[0];if(i.length===2)return`${i[0]} and ${i[1]}`;if(i.length===3&&n>=3)return`${i[0]}, ${r}${i[1]} and ${i[2]}`;let a=i.slice(0,n),o=i.length-n;return`${a.join(r)} and ${o} ${o===1?"other":"others"}`}var Qc=qt(require("pluralize"),1);function Zc(e,n="",t="",r="true"){if(e==null)return"";let i=0;if(Array.isArray(e)?i=e.length:typeof e=="object"?i=Object.keys(e).length:typeof e=="string"?i=+e:typeof e=="number"?i=e:i=Number(e),Number.isNaN(i)&&(i=0),i<=0)return"";let a;return t?a=i===1?n:t:a=(0,Qc.default)(n,i),r==="true"?`${i} ${a}`:a}var bg=require("liquidjs"),eu=qt(require("pluralize"),1),wg=require("zod");var Sg="",xg=2,Tg="other",kg=", ",Ag=" and ",vg=", and ";function tu(e,n=Sg,t=xg,r=Tg,i=kg,a=Ag,o=vg){if(!Array.isArray(e)||e.length===0)return"";let s=n?e.map(y=>typeof y!="object"||!y?"":Di(y,n)):e,u=s.length;if(u===1)return s[0];if(u===2)return`${s[0]}${a}${s[1]}`;if(t>=u){let y=s.slice(0,u-1),g=s[u-1];return`${y.join(i)}${o}${g}`}let p=s.slice(0,t),d=u-t,h=t===1?a:o;return`${p.join(i)}${h}${d} ${(0,eu.default)(r,d)}`}function Eg(e){return Array.isArray(e)||typeof e=="object"&&e!==null?ru(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 ru=(e,n=0)=>Array.isArray(e)||typeof e=="object"&&e!==null?JSON.stringify(e,null,n).replace(/"/g,"'").replace(/\n/g,"\\n"):e==null?"":String(e);function iu(e){let n=new nu.Liquid({outputEscape:Eg,...e});return n.registerFilter("json",(t,r)=>ru(t,r)),n.registerFilter("digest",Xc),n.registerFilter("toSentence",tu),n.registerFilter("pluralize",Zc),n}var Ln=qt(require("chalk"),1),et={info:e=>Ln.default.blue(e),warning:e=>Ln.default.yellow(e),error:e=>Ln.default.red(e),success:e=>Ln.default.green(e),underline:e=>Ln.default.underline(e),bold:e=>Ln.default.bold(e)},ct={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 Fi(e){return e||process.env.NOVU_API_URL||"https://api.novu.co"}function Ui(e){return e||process.env.NOVU_SECRET_KEY||process.env.NOVU_API_KEY||""}var To=qt(require("sanitize-html"),1),_g=["src","alt","width","height","loading","srcset","sizes","crossorigin","usemap","ismap","class","id","style","title","dir","lang"];function Rg(e){return e.toLowerCase().startsWith("on")}function Og(e){return e.replace(/<\/([a-zA-Z][a-zA-Z0-9]*)\s*\/[^>]*>/g,"</$1>")}var Ig={allowedTags:To.default.defaults.allowedTags.concat(["style","img","html","head","body","link","meta","title"]),allowedAttributes:!1,transformTags:{"*":(e,n)=>{let t={};for(let[r,i]of Object.entries(n))Rg(r)||(t[r]=i);return{tagName:e,attribs:t}},img:(e,n)=>{let t={};for(let[r,i]of Object.entries(n))_g.includes(r.toLowerCase())&&(t[r]=i);return{tagName:e,attribs:t}}},allowVulnerableTags:!0,parseStyleAttributes:!1,parser:{lowerCaseAttributeNames:!0}},au=e=>{if(!e)return e;let n=Og(e),t=/^<!DOCTYPE .*?>/,r=n.match(t),i=(0,To.default)(n,Ig);return r?r[0]+i:i},$i=e=>Object.keys(e).reduce((n,t)=>{let r=e[t];return typeof r=="string"?n[t]=au(r):Array.isArray(r)?n[t]=r.map(i=>typeof i=="string"?au(i):typeof i=="object"?$i(i):i):typeof r=="object"&&r!==null?n[t]=$i(r):n[t]=r,n},{});function ou(e,n=!0,t=console){n&&(t.info(`
|
|
113
|
-
${et.bold(et.underline("Discovered workflowId:"))} '${e.workflowId}'`),e.steps.forEach((r,i)=>{let a=i===e.steps.length-1,o=a?"\u2514":"\u251C";t.info(`${o} ${ct.STEP} Discovered stepId: '${r.stepId}' Type: '${r.type}'`),r.providers.forEach((s,u)=>{let p=u===r.providers.length-1,d=a?" ":"\u2502",h=p?"\u2514":"\u251C";t.info(`${d} ${h} ${ct.PROVIDER} Discovered provider: '${s.type}'`)})}))}var su=require("jsonrepair");function lu(e){let n=e.trim();return(n.startsWith("{")&&n.endsWith("}")||n.startsWith("[")&&n.endsWith("]"))&&n.length>2}var cu="__novuJsonString";function Cg(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&e[cu]===!0}function Ir(e){if(typeof e=="string"){if(!lu(e))return e;try{let n=JSON.parse(e);return{[cu]:!0,value:Ir(n)}}catch{return e}}if(Array.isArray(e))return e.map(n=>Ir(n));if(e&&typeof e=="object"){let n={};for(let[t,r]of Object.entries(e))n[t]=Ir(r);return n}return e}function Cr(e){if(Cg(e))return JSON.stringify(Cr(e.value));if(Array.isArray(e))return e.map(n=>Cr(n));if(e&&typeof e=="object"){let n={};for(let[t,r]of Object.entries(e))n[t]=Cr(r);return n}return e}function Pg(e){try{return JSON.parse(e),e}catch{try{return(0,su.jsonrepair)(e)}catch{return e}}}function uu(e){return Object.fromEntries(Object.entries(e).map(([n,t])=>typeof t=="string"?[n,lu(t)?Pg(t):t]:typeof t=="object"&&t!==null&&!Array.isArray(t)?[n,uu(t)]:[n,t]))}function pu(e){return!(e!=null&&e.data)||typeof e.data!="object"||Array.isArray(e.data)?e:{...e,data:uu(e.data)}}var hu=qt(require("ajv"),1),fu=qt(require("ajv-formats"),1);var du=e=>typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e));var qi=class extends xn{constructor(t,r){let i=r.length===1?"it":"them";super(`Tried to use a ${t} in @novu/framework without ${r.join(", ")} installed. Please install ${i} by running \`npm install ${r.join(" ")}\`.`);this.statusCode=500;this.code="MissingDependencyError"}};var ji=async(e,n)=>{let t=new Set;if((await Promise.allSettled(e.map(i=>i.import))).forEach((i,a)=>{let o=e[a];i.status==="fulfilled"&&o.exports.every(u=>i.value[u]!==void 0)||t.add(o.name)}),t.size>0)throw new qi(n,Array.from(t))};var Bi=class{constructor(){this.requiredImports=[];this.ajv=new hu.default({useDefaults:!0,removeAdditional:"failing",strict:!1}),(0,fu.default)(this.ajv),this.compiledSchemas=new Map}async canHandle(n){let t=n.type==="object"||!!n.anyOf||!!n.allOf||!!n.oneOf;return t&&await ji(this.requiredImports,"JSON schema"),t}async validate(n,t){let r=this.compiledSchemas.get(t);r||(r=this.ajv.compile(t),this.compiledSchemas.set(t,r));let i=du(n);return r(i)?{success:!0,data:i}:{success:!1,errors:r.errors.map(o=>({path:o.instancePath,message:o.message}))}}async transformToJsonSchema(n){return n}};var zi=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(n){let t=n.safeParseAsync!==void 0;return t&&await ji(this.requiredImports,"Zod schema"),t}async validate(n,t){let r=await t.safeParseAsync(n);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(n){let{zodToJsonSchema:t}=await import("zod-to-json-schema");return t(n)}};var Vi=new zi,Wi=new Bi,Pr=async(e,n)=>{if(await Vi.canHandle(e))return Vi.validate(n,e);if(await Wi.canHandle(e))return Wi.validate(n,e);throw new Error("Invalid schema")},yt=async e=>{if(await Vi.canHandle(e))return Vi.transformToJsonSchema(e);if(await Wi.canHandle(e))return Wi.transformToJsonSchema(e);throw new Error("Invalid schema")};function mu(){return["development",void 0,"dev"].includes(process.env.NODE_ENV)}var Qn=class{constructor(n){this.discoveredWorkflows=new Map;this.discoverWorkflowPromises=new Map;this.registeredAgents=new Map;this.version="2.
|
|
112
|
+
laborum`.split(/\W/),ii=Xr,ai={type:Gt.ALLOWED_TYPES},xc=Qr,ho=Ja,Tc=Zr,oi=ei,kc=Ga,Ac=Ka,fo="[a-zA-Z][a-zA-Z0-9+-.]*",si=`https?://{hostname}(?:${fo})+`,vc="(?:\\?([a-z]{1,7}(=\\w{1,5})?&){0,3})?",Ut={email:"[a-zA-Z\\d][a-zA-Z\\d-]{1,13}[a-zA-Z\\d]@{hostname}",hostname:"[a-zA-Z]{1,33}\\.[a-z]{2,4}",ipv6:"[a-f\\d]{4}(:[a-f\\d]{4}){7}",uri:si,slug:"[a-zA-Z\\d_-]+","uri-reference":`${si}${vc}`,"uri-template":si.replace("(?:","(?:/\\{[a-z][:a-zA-Z0-9-]*\\}|"),"json-pointer":`(/(?:${fo.replace("]*","/]*")}|~[01]))+`,uuid:"^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$",duration:"^P(?!$)((\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+S)?)?|(\\d+W)?)$"},Ut.iri=Ut["uri-reference"],Ut["iri-reference"]=Ut["uri-reference"],Ut["idn-email"]=Ut.email,Ut["idn-hostname"]=Ut.hostname,Ec=new RegExp(`\\{(${Object.keys(Ut).join("|")})\\}`),_c=Xa,Rc=Za,Oc={boolean:fc,null:yc,array:bc,integer:wc,number:po,object:xc,string:Rc},br=Oc,Ic=re,Cc=({refs:l,schema:c,container:f,synchronous:S,refDepthMax:x,refDepthMin:A})=>{let k={},L={},Q=0,N,ie;return k.resolveSchema=(j,he,ce)=>{if(j==null)return null;if(typeof j.generate=="function")return j;if(typeof(j.$id||j.id)=="string"&&(delete j.id,delete j.$id,delete j.$schema),typeof j.$ref=="string"){let Te=Math.max(A,x)-1;if(j.$ref==="#"||L[j.$ref]<0||N===j.$ref&&++Q>Te)return j.$ref!=="#"&&ie&&ie.length===ce.length?Ye.getLocalRef(c,j.$ref,S&&l):(delete j.$ref,j);typeof L[j.$ref]=="undefined"&&(L[j.$ref]=ve.number(A,x)-1),ie=ce,N=j.$ref;let Re;j.$ref.indexOf("#/")===-1?Re=l[j.$ref]||null:Re=Ye.getLocalRef(c,j.$ref,S&&l)||null;let Ge;if(typeof Re!="undefined"){if(!Re&&_e("ignoreMissingRefs")!==!0)throw new Error(`Reference not found: ${j.$ref}`);L[j.$ref]-=1,Ye.merge(j,Re||{}),Ge=S&&Re&&Re.$ref}return Ge||delete j.$ref,j}if(Array.isArray(j.allOf)){let Te=j.allOf;delete j.allOf,Te.forEach(Re=>{let Ge=k.resolveSchema(Re,null,ce);Ye.merge(j,typeof Ge.thunk=="function"?Ge.thunk(j):Ge),Array.isArray(j.allOf)&&k.resolveSchema(j,he,ce)})}if(Array.isArray(j.oneOf||j.anyOf)&&ce[ce.length-2]!=="dependencies"){let Te=j.oneOf||j.anyOf;return j.enum&&j.oneOf&&(j.enum=j.enum.filter(Re=>Ye.validate(Re,Te))),{thunk(Re){let Ge=Ye.omitProps(j,["anyOf","oneOf"]),Qe=ve.pick(Te);return Ye.merge(Ge,Qe),Te.forEach(ae=>{ae.required&&ae!==Qe&&ae.required.forEach(I=>{if(Qe.required&&Qe.required.includes(I))return;let C=Ge.required&&Ge.required.includes(I);Ge.properties&&!C&&delete Ge.properties[I],Re&&Re.properties&&delete Re.properties[I]})}),Ge}}}if(Object.keys(j).forEach(Te=>{(Array.isArray(j[Te])||typeof j[Te]=="object")&&!Ye.isKey(Te)&&(j[Te]=k.resolveSchema(j[Te],Te,ce.concat(Te)))}),ce){let Te=ce[ce.length-1];if(Te==="properties"||Te==="items")return j}return f.wrap(j)},k},Pc=Cc,mo=Nt,go=nn,vt=no(Gl(),1),Mm=vt.default.binaryOptions,Nm=vt.default.boolOptions,Lm=vt.default.intOptions,Dm=vt.default.nullOptions,Fm=vt.default.strOptions,Um=vt.default.Schema,$m=vt.default.Alias,qm=vt.default.Collection,jm=vt.default.Merge,Bm=vt.default.Node,zm=vt.default.Pair,Vm=vt.default.Scalar,Mc=vt.default.YAMLMap,Nc=vt.default.YAMLSeq,wr=Cn,on=new lc,rt=(l,c,f)=>(console.debug("[json-schema-faker] calling JSONSchemaFaker() is deprecated, call either .generate() or .resolve()"),f&&console.debug("[json-schema-faker] local references are only supported by calling .resolve()"),rt.generate(l,c)),rt.generateWithContext=(l,c)=>{let f=an(c,l);return mo(f,l,on,!0)},rt.generate=(l,c)=>go(rt.generateWithContext(l,c)),rt.generateYAML=(l,c)=>wr(rt.generateWithContext(l,c)),rt.resolveWithContext=(l,c,f)=>{typeof c=="string"&&(f=c,c={}),f=f||(typeof process!="undefined"&&typeof process.cwd=="function"?process.cwd():""),f=`${f.replace(/\/+$/,"")}/`;let S=an(c,l),x={order:1,canRead(k){let L=k.url.replace("/:",":");return S[L]||S[L.split("/").pop()]},read(k,L){try{L(null,this.canRead(k))}catch(Q){L(Q)}}},{$RefParser:A}=ao();return A.bundle(f,l,{resolve:{file:{order:100},http:{order:200},fixedRefs:x},dereference:{circular:"ignore"}}).then(k=>mo(S,k,on)).catch(k=>{throw new Error(`Error while resolving schema (${k.message})`)})},rt.resolve=(l,c,f)=>rt.resolveWithContext(l,c,f).then(go),rt.resolveYAML=(l,c,f)=>rt.resolveWithContext(l,c,f).then(wr),St(),rt.format=uo,rt.option=_e,rt.random=ve,rt.extend=(l,c)=>(on.extend(l,c),rt),rt.define=(l,c)=>(on.define(l,c),rt),rt.reset=l=>(on.reset(l),St(),rt),rt.locate=l=>on.get(l),rt.VERSION="0.5.5",Lc={...rt},Dc=rt}}),Hm=a({"src/src/main.iife.js"(l,c){var f=(Wm(),u(p));typeof $RefParser!="undefined"&&typeof JSONPath!="undefined"&&f.setDependencies({...JSONPath,$RefParser}),typeof window!="undefined"&&(window.JSONSchemaFaker=f.default),c.exports=f.default,c.exports.JSONSchemaFaker=f.JSONSchemaFaker}});return Hm()})();((e,n)=>{e.JSONSchemaFaker=n()})(typeof self!="undefined"?self:typeof window!="undefined"?window:globalThis,()=>Ni);Ni.random.shuffle=function(){return["[placeholder]"]};Ni.option({useDefaultValue:!0,alwaysFakeOptionals:!0});function Hc(e){return Ni.generate(e)}var Yc=async(e,n)=>{let t=new TextEncoder,r=t.encode(e),i=t.encode(n),a=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("HMAC",a,i);return Array.from(new Uint8Array(o)).map(s=>s.toString(16).padStart(2,"0")).join("")},Jc=(e,n)=>{if(typeof e!="string"||typeof n!="string"||e.length!==n.length)return!1;let t=0;for(let r=0;r<e.length;r+=1)t|=e.charCodeAt(r)^n.charCodeAt(r);return t===0};var yg=require("cross-fetch");var Gc=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 n=await(await fetch("http://localhost:2022/.well-known/novu")).json();return`${n.tunnelOrigin}${n.route}`}}catch(e){console.error(e)}return""};function Kc(e){return!!e&&typeof e=="object"&&"error"in e&&"message"in e&&"statusCode"in e}var Li=(e,n)=>{if(!e)throw new ki;return{post:async(t,r)=>{let i=await fetch(`${n}/v1${t}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${e}`},body:JSON.stringify(r)}),a=await i.json();if(i.ok)return a;throw Kc(a)?new Ai(a.statusCode,a.error,a.message):new Gn(a)},delete:async t=>(await fetch(`${n}/v1${t}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${e}`}})).json()}};var nu=require("liquidjs");function xo(e,n){let t={...e};for(let r of Object.keys(n)){let i=n[r];i&&typeof i=="object"&&!Array.isArray(i)?t[r]=xo(t[r]||{},i):(Array.isArray(i),t[r]=i)}return t}function Di(e,n){let t=n.split(".").reduce((r,i)=>{if(r&&typeof r=="object")return r[i]},e);if(t==null)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);if(typeof t=="object"){let r=JSON.stringify(t);return r==="{}"?"":r}return""}function Xc(e,n=2,t,r=", "){if(!Array.isArray(e)||e.length===0)return"";let i=t?e.map(s=>typeof s!="object"||!s?"":Di(s,t)):e;if(i.length===1)return i[0];if(i.length===2)return`${i[0]} and ${i[1]}`;if(i.length===3&&n>=3)return`${i[0]}${r}${i[1]} and ${i[2]}`;let a=i.slice(0,n),o=i.length-n;return`${a.join(r)} and ${o} ${o===1?"other":"others"}`}var Qc=qt(require("pluralize"),1);function Zc(e,n="",t="",r="true"){if(e==null)return"";let i=0;if(Array.isArray(e)?i=e.length:typeof e=="object"?i=Object.keys(e).length:typeof e=="string"?i=+e:typeof e=="number"?i=e:i=Number(e),Number.isNaN(i)&&(i=0),i<=0)return"";let a;return t?a=i===1?n:t:a=(0,Qc.default)(n,i),r==="true"?`${i} ${a}`:a}var bg=require("liquidjs"),eu=qt(require("pluralize"),1),wg=require("zod");var Sg="",xg=2,Tg="other",kg=", ",Ag=" and ",vg=", and ";function tu(e,n=Sg,t=xg,r=Tg,i=kg,a=Ag,o=vg){if(!Array.isArray(e)||e.length===0)return"";let s=n?e.map(y=>typeof y!="object"||!y?"":Di(y,n)):e,u=s.length;if(u===1)return s[0];if(u===2)return`${s[0]}${a}${s[1]}`;if(t>=u){let y=s.slice(0,u-1),g=s[u-1];return`${y.join(i)}${o}${g}`}let p=s.slice(0,t),d=u-t,h=t===1?a:o;return`${p.join(i)}${h}${d} ${(0,eu.default)(r,d)}`}function Eg(e){return Array.isArray(e)||typeof e=="object"&&e!==null?ru(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 ru=(e,n=0)=>Array.isArray(e)||typeof e=="object"&&e!==null?JSON.stringify(e,null,n).replace(/"/g,"'").replace(/\n/g,"\\n"):e==null?"":String(e);function iu(e){let n=new nu.Liquid({outputEscape:Eg,...e});return n.registerFilter("json",(t,r)=>ru(t,r)),n.registerFilter("digest",Xc),n.registerFilter("toSentence",tu),n.registerFilter("pluralize",Zc),n}var Ln=qt(require("chalk"),1),et={info:e=>Ln.default.blue(e),warning:e=>Ln.default.yellow(e),error:e=>Ln.default.red(e),success:e=>Ln.default.green(e),underline:e=>Ln.default.underline(e),bold:e=>Ln.default.bold(e)},ct={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 Fi(e){return e||process.env.NOVU_API_URL||"https://api.novu.co"}function Ui(e){return e||process.env.NOVU_SECRET_KEY||process.env.NOVU_API_KEY||""}var To=qt(require("sanitize-html"),1),_g=["src","alt","width","height","loading","srcset","sizes","crossorigin","usemap","ismap","class","id","style","title","dir","lang"];function Rg(e){return e.toLowerCase().startsWith("on")}function Og(e){return e.replace(/<\/([a-zA-Z][a-zA-Z0-9]*)\s*\/[^>]*>/g,"</$1>")}var Ig={allowedTags:To.default.defaults.allowedTags.concat(["style","img","html","head","body","link","meta","title"]),allowedAttributes:!1,transformTags:{"*":(e,n)=>{let t={};for(let[r,i]of Object.entries(n))Rg(r)||(t[r]=i);return{tagName:e,attribs:t}},img:(e,n)=>{let t={};for(let[r,i]of Object.entries(n))_g.includes(r.toLowerCase())&&(t[r]=i);return{tagName:e,attribs:t}}},allowVulnerableTags:!0,parseStyleAttributes:!1,parser:{lowerCaseAttributeNames:!0}},au=e=>{if(!e)return e;let n=Og(e),t=/^<!DOCTYPE .*?>/,r=n.match(t),i=(0,To.default)(n,Ig);return r?r[0]+i:i},$i=e=>Object.keys(e).reduce((n,t)=>{let r=e[t];return typeof r=="string"?n[t]=au(r):Array.isArray(r)?n[t]=r.map(i=>typeof i=="string"?au(i):typeof i=="object"?$i(i):i):typeof r=="object"&&r!==null?n[t]=$i(r):n[t]=r,n},{});function ou(e,n=!0,t=console){n&&(t.info(`
|
|
113
|
+
${et.bold(et.underline("Discovered workflowId:"))} '${e.workflowId}'`),e.steps.forEach((r,i)=>{let a=i===e.steps.length-1,o=a?"\u2514":"\u251C";t.info(`${o} ${ct.STEP} Discovered stepId: '${r.stepId}' Type: '${r.type}'`),r.providers.forEach((s,u)=>{let p=u===r.providers.length-1,d=a?" ":"\u2502",h=p?"\u2514":"\u251C";t.info(`${d} ${h} ${ct.PROVIDER} Discovered provider: '${s.type}'`)})}))}var su=require("jsonrepair");function lu(e){let n=e.trim();return(n.startsWith("{")&&n.endsWith("}")||n.startsWith("[")&&n.endsWith("]"))&&n.length>2}var cu="__novuJsonString";function Cg(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&e[cu]===!0}function Ir(e){if(typeof e=="string"){if(!lu(e))return e;try{let n=JSON.parse(e);return{[cu]:!0,value:Ir(n)}}catch{return e}}if(Array.isArray(e))return e.map(n=>Ir(n));if(e&&typeof e=="object"){let n={};for(let[t,r]of Object.entries(e))n[t]=Ir(r);return n}return e}function Cr(e){if(Cg(e))return JSON.stringify(Cr(e.value));if(Array.isArray(e))return e.map(n=>Cr(n));if(e&&typeof e=="object"){let n={};for(let[t,r]of Object.entries(e))n[t]=Cr(r);return n}return e}function Pg(e){try{return JSON.parse(e),e}catch{try{return(0,su.jsonrepair)(e)}catch{return e}}}function uu(e){return Object.fromEntries(Object.entries(e).map(([n,t])=>typeof t=="string"?[n,lu(t)?Pg(t):t]:typeof t=="object"&&t!==null&&!Array.isArray(t)?[n,uu(t)]:[n,t]))}function pu(e){return!(e!=null&&e.data)||typeof e.data!="object"||Array.isArray(e.data)?e:{...e,data:uu(e.data)}}var hu=qt(require("ajv"),1),fu=qt(require("ajv-formats"),1);var du=e=>typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e));var qi=class extends xn{constructor(t,r){let i=r.length===1?"it":"them";super(`Tried to use a ${t} in @novu/framework without ${r.join(", ")} installed. Please install ${i} by running \`npm install ${r.join(" ")}\`.`);this.statusCode=500;this.code="MissingDependencyError"}};var ji=async(e,n)=>{let t=new Set;if((await Promise.allSettled(e.map(i=>i.import))).forEach((i,a)=>{let o=e[a];i.status==="fulfilled"&&o.exports.every(u=>i.value[u]!==void 0)||t.add(o.name)}),t.size>0)throw new qi(n,Array.from(t))};var Bi=class{constructor(){this.requiredImports=[];this.ajv=new hu.default({useDefaults:!0,removeAdditional:"failing",strict:!1}),(0,fu.default)(this.ajv),this.compiledSchemas=new Map}async canHandle(n){let t=n.type==="object"||!!n.anyOf||!!n.allOf||!!n.oneOf;return t&&await ji(this.requiredImports,"JSON schema"),t}async validate(n,t){let r=this.compiledSchemas.get(t);r||(r=this.ajv.compile(t),this.compiledSchemas.set(t,r));let i=du(n);return r(i)?{success:!0,data:i}:{success:!1,errors:r.errors.map(o=>({path:o.instancePath,message:o.message}))}}async transformToJsonSchema(n){return n}};var zi=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(n){let t=n.safeParseAsync!==void 0;return t&&await ji(this.requiredImports,"Zod schema"),t}async validate(n,t){let r=await t.safeParseAsync(n);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(n){let{zodToJsonSchema:t}=await import("zod-to-json-schema");return t(n)}};var Vi=new zi,Wi=new Bi,Pr=async(e,n)=>{if(await Vi.canHandle(e))return Vi.validate(n,e);if(await Wi.canHandle(e))return Wi.validate(n,e);throw new Error("Invalid schema")},yt=async e=>{if(await Vi.canHandle(e))return Vi.transformToJsonSchema(e);if(await Wi.canHandle(e))return Wi.transformToJsonSchema(e);throw new Error("Invalid schema")};function mu(){return["development",void 0,"dev"].includes(process.env.NODE_ENV)}var Qn=class{constructor(n){this.discoveredWorkflows=new Map;this.discoverWorkflowPromises=new Map;this.registeredAgents=new Map;this.version="2.12.1";let t=this.buildOptions(n);this.apiUrl=t.apiUrl,this.secretKey=t.secretKey,this.strictAuthentication=t.strictAuthentication,this.verbose=t.verbose,this.logger=t.logger,this.templateEngine=iu()}buildOptions(n){let t={apiUrl:Fi(n==null?void 0:n.apiUrl),secretKey:Ui(n==null?void 0:n.secretKey),strictAuthentication:!mu(),verbose:mu(),logger:console};return(n==null?void 0:n.strictAuthentication)!==void 0?t.strictAuthentication=n.strictAuthentication:process.env.NOVU_STRICT_AUTHENTICATION_ENABLED!==void 0&&(t.strictAuthentication=process.env.NOVU_STRICT_AUTHENTICATION_ENABLED==="true"),(n==null?void 0:n.verbose)!==void 0&&(t.verbose=n.verbose),(n==null?void 0:n.logger)!==void 0&&(t.logger=n.logger),t}log(...n){this.verbose&&this.logger.info(...n)}async addWorkflows(n){for(let t of n){if(this.discoveredWorkflows.has(t.id))continue;let r=this.discoverWorkflowPromises.get(t.id);if(r){await r;continue}let i=this.addWorkflow(t);this.discoverWorkflowPromises.set(t.id,i),await i}}addAgents(n){for(let t of n)this.registeredAgents.set(t.id,t)}getAgent(n){return this.registeredAgents.get(n)}async addWorkflow(n){try{let t=await n.discover();ou(t,this.verbose,this.logger),this.discoveredWorkflows.set(n.id,t)}finally{this.discoverWorkflowPromises.delete(n.id)}}healthCheck(){let n=this.getRegisteredWorkflows(),t=n.length,r=n.reduce((i,a)=>i+a.steps.length,0);return{status:"ok",sdkVersion:"2.12.1",frameworkVersion:"2024-06-26",discovered:{workflows:t,steps:r}}}getWorkflow(n){let t=this.discoveredWorkflows.get(n);if(t)return t;throw new _r(n)}getStep(n,t){let i=this.getWorkflow(n).steps.find(a=>a.stepId===t);if(i)return i;throw new Pi(t)}getRegisteredWorkflows(){return Array.from(this.discoveredWorkflows.values())}discover(){return{workflows:this.getRegisteredWorkflows(),agents:Array.from(this.registeredAgents.keys()).map(n=>({agentId:n}))}}mock(n){try{return Hc(n)}catch(t){return this.logger.warn("Failed to mock schema, returning empty object:",t),{}}}async validate(n,t,r,i,a,o,s){let u=await Pr(t,n);if(u.success)return u.data;switch(r){case"event":this.throwInvalidEvent(i,a,u.errors);case"step":this.throwInvalidStep(o,i,a,u.errors);case"provider":this.throwInvalidProvider(o,s,i,a,u.errors);default:throw new Error(`Invalid component: '${r}'`)}}throwInvalidProvider(n,t,r,i,a){throw n?t?r==="output"?new wi(i,n,t,a):new Error(`Invalid payload type: '${r}'`):new Error("providerId is required"):new Error("stepId is required")}throwInvalidStep(n,t,r,i){if(!n)throw new Error("stepId is required");switch(t){case"output":throw new gi(r,n,i);case"result":throw new yi(r,n,i);case"controls":throw new mi(r,n,i);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(n,t,r){switch(n){case"controls":throw new fi(t,r);case"payload":throw new Ar(t,r);default:throw new Error(`Invalid payload type: '${n}'`)}}executeStepFactory(n,t,r){return async(i,a,o)=>{if(r())return;let s=this.getStep(n.workflowId,i),u=n.action==="preview";if(!u&&i===n.stepId){let g=await this.createStepControls(s,n),P=await this.compileControls(g,n);if(await this.shouldSkip(o==null?void 0:o.skip,P))return t({options:{skip:!0},outputs:{},providers:{}}),{}}let p=this.previewStep.bind(this),d=this.executeStep.bind(this),y=await(u?p:d)(n,{...s,providers:s.providers.map(g=>{var ee;let P=(ee=o==null?void 0:o.providers)==null?void 0:ee[g.type];if(!P)throw new vi(g.type);return{...g,resolve:P}}),resolve:a});return this.shouldSanitize({stepType:s.type,options:o})&&(y={...y,outputs:$i(y.outputs)}),i===n.stepId&&t({...y,options:{skip:!1}}),y.outputs}}shouldSanitize({stepType:n,options:t}){return(t==null?void 0:t.disableOutputSanitization)===!0?!1:["email","in_app"].includes(n)}async shouldSkip(n,t){return n?n(t):!1}async executeWorkflow(n){let i=`${{execute:"Executing",preview:"Previewing"}[n.action]||n.action} workflowId:`;this.log(`
|
|
114
114
|
${et.bold(et.underline(i))} '${n.workflowId}'`);let a=this.getWorkflow(n.workflowId),o=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},y=()=>p,g;try{if(n.action==="execute"&&!n.payload)throw new Ar(n.workflowId,{message:"Event `payload` is required"});let Oe=await this.createExecutionPayload(n,a),$={...n,payload:Oe};await Promise.race([d,a.execute({payload:Oe,env:n.env,controls:{},subscriber:n.subscriber,context:n.context,step:{email:this.executeStepFactory($,h,y),sms:this.executeStepFactory($,h,y),inApp:this.executeStepFactory($,h,y),digest:this.executeStepFactory($,h,y),delay:this.executeStepFactory($,h,y),push:this.executeStepFactory($,h,y),chat:this.executeStepFactory($,h,y),custom:this.executeStepFactory($,h,y),throttle:this.executeStepFactory($,h,y)}})])}catch(Oe){g=Oe}let P=process.hrtime(o),ee=P[0],Z=P[1],B=ee*1e3+Z/1e6,ue=g?ct.ERROR:ct.SUCCESS,Ae={execute:"Executed",preview:"Previewed"}[n.action]||n.action;if(this.log(`${ue} ${Ae} workflowId: \`${n.workflowId}\``),this.prettyPrintExecute(n,B,g),g)throw g;return{outputs:s.outputs,providers:s.providers,options:s.options,metadata:{status:"success",error:!1,duration:B}}}async createExecutionPayload(n,t){let{payload:r}=n;if(n.action==="preview"){let a=this.mock(t.payload.schema);r=Object.assign(a,r)}return await this.validate(r,t.payload.unknownSchema,"event","payload",n.workflowId)}prettyPrintExecute(n,t,r){if(!this.verbose)return;let i=r?ct.ERROR:ct.SUCCESS,o={execute:"Executed",preview:"Previewed"}[n.action]||n.action,s=r?"Failed to execute":o,u=r?et.error:et.success,p=`${i} ${s} workflowId: '${n.workflowId}`;this.logger.info(`
|
|
115
115
|
${et.bold(u(p))}'
|
|
116
116
|
\u251C ${ct.STEP} stepId: '${n.stepId}'
|
|
117
117
|
\u251C ${ct.ACTION} action: '${n.action}'
|
|
118
118
|
\u2514 ${ct.DURATION} duration: '${t.toFixed(2)}ms'
|
|
119
|
-
`)}async executeProviders(n,t,r){return t.providers.reduce(async(i,a)=>{let o=await i,s=this.previewProvider.bind(this),u=this.executeProvider.bind(this),d=await(n.action==="preview"?s:u)(n,t,a,r);return{...o,[a.type]:d}},Promise.resolve({}))}previewProvider(n,t,r,i){return this.log(` ${ct.MOCK} Mocked provider: \`${r.type}\``),this.mock(r.outputs.schema)}async executeProvider(n,t,r,i){try{if(n.stepId===t.stepId){let a=await this.createStepControls(t,n),o=await r.resolve({controls:a,outputs:i}),s=await this.validate(o,r.outputs.unknownSchema,"step","output",n.workflowId,t.stepId,r.type);return this.log(` ${ct.SUCCESS} Executed provider: \`${r.type}\``),{...s,_passthrough:o._passthrough}}else return this.log(` ${ct.HYDRATED} Hydrated provider: \`${r.type}\``),{}}catch(a){throw this.log(` ${ct.ERROR} Failed to execute provider: \`${r.type}\``),new Ei(r.type,n.action,a)}}async executeStep(n,t){if(n.stepId===t.stepId)try{let r=await this.createStepControls(t,n),i=await this.compileControls(r,n),a=await t.resolve(i),o=await this.validate(a,t.outputs.unknownSchema,"step","output",n.workflowId,t.stepId),s=await this.executeProviders(n,t,o);return this.log(` ${ct.SUCCESS} Executed stepId: \`${t.stepId}\``),{outputs:o,providers:s}}catch(r){throw this.log(` ${ct.ERROR} Failed to execute stepId: \`${t.stepId}\``),Pn(r)?r:new Er(t.stepId,n.action,r)}else try{let r=this.getStepState(n,t.stepId);if(r){let i=await this.validate(r.outputs,t.results.unknownSchema,"step","result",n.workflowId,t.stepId);return this.log(` ${ct.HYDRATED} Hydrated stepId: \`${t.stepId}\``),{outputs:i,providers:await this.executeProviders(n,t,i)}}else throw new hi(n.workflowId,t.stepId)}catch(r){throw this.log(` ${ct.ERROR} Failed to hydrate stepId: \`${t.stepId}\``),r}}async compileControls(n,t){var r;try{let i=Ir(n),a=this.preprocessTranslationPatterns(JSON.stringify(i));a=this.preprocessFilterTranslationArgs(a);let o=this.templateEngine.parse(a),s=this.getWorkflow(t.workflowId),u={workflow:{workflowId:s.workflowId,name:s.name,description:s.description,tags:s.tags,severity:s.severity},payload:t.payload,subscriber:t.subscriber,...t.actor&&{actor:t.actor},context:t.context,steps:Mg(t.state),env:(r=t.env)!=null?r:{}},p=await this.templateEngine.render(o,u),d=this.postprocessTranslationMarkers(p),h=(0,gu.jsonrepair)(d),y=JSON.parse(h),g=Cr(y);return pu(g)}catch(i){throw new bi(t.workflowId,t.stepId,i)}}preprocessTranslationPatterns(n){return n.replace(/\{\{\s*t\.([\p{L}\p{N}_.-]+)\s*\}\}/gu,"[T:$1]")}preprocessFilterTranslationArgs(n){return n.replace(/'t\.([\p{L}\p{N}_.-]+)'/gu,"'[T:$1]'")}postprocessTranslationMarkers(n){return n.replace(/\[T:([\p{L}\p{N}_.-]+)\]/gu,"{{t.$1}}")}async createStepControls(n,t){return await this.validate(t.controls,n.controls.unknownSchema,"step","controls",t.workflowId,n.stepId)}async previewStep(n,t){try{return await this.constructStepForPreview(n,t)}catch(r){throw this.log(` ${ct.ERROR} Failed to preview stepId: \`${t.stepId}\``),Pn(r)?r:new Er(t.stepId,n.action,r)}}async constructStepForPreview(n,t){return n.stepId===t.stepId?await this.previewRequiredStep(t,n):await this.extractMockDataForPreviousSteps(n,t)}async extractMockDataForPreviousSteps(n,t){let r={},i=this.getStepState(n,t.stepId),a=this.mock(t.results.schema);return{outputs:xo(a,(i==null?void 0:i.outputs)||{}),providers:await this.executeProviders(n,t,r)}}async previewRequiredStep(n,t){let r=await this.createStepControls(n,t),i=await this.compileControls(r,t),a=await n.resolve(i),o=await this.validate(a,n.outputs.unknownSchema,"step","output",t.workflowId,n.stepId);return this.log(` ${ct.MOCK} Mocked stepId: \`${n.stepId}\``),{outputs:o,providers:await this.executeProviders(t,n,o)}}getStepState(n,t){return n.state.find(r=>r.stepId===t)}getStepCode(n,t){return{code:this.getStep(n,t).resolve.toString()}}getWorkflowCode(n){return{code:this.getWorkflow(n).execute.toString()}}getCode(n,t){let r;if(n)t?r=this.getStepCode(n,t):r=this.getWorkflowCode(n);else throw new _r(n);return r}};function Mg(e){let n={};for(let t of e)n[t.stepId]=t.outputs;return n}var Ng={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 Hi(e){return typeof e=="string"&&e.trim()?e:!e||typeof e!="object"?null:Hi(e.message)}function Lg(e){if(!e)return null;let n;try{n=JSON.parse(e)}catch{return null}if(!n||typeof n!="object")return null;let t=n,r=Hi(t.message);if(r)return r;let i=Hi(t.error);if(i)return i;let a=t.errors;return Array.isArray(a)?Hi(a[0]):null}function Dg(e,n){var i;let t=(i=Ng[e])!=null?i:e,r=Lg(n);return r?`Delivery failed: ${t}: ${r}`:`Delivery failed: ${t}`}var pn=class extends Error{constructor(n,t){super(n),this.name="AgentError",this.cause=t==null?void 0:t.cause,this.delivery=t==null?void 0:t.delivery}},Dn=class extends pn{constructor(n,t){let r={statusCode:n,responseBody:t};super(Dg(n,t),{delivery:r}),this.name="AgentDeliveryError",this.statusCode=n,this.responseBody=t}};function Mr(e){return e instanceof pn?e:e instanceof Error?new pn(e.message,{cause:e}):new pn("Turn failed",{cause:e})}var yu=Symbol.for("novu.agent.runtimeContext");var ko=(i=>(i.ON_MESSAGE="onMessage",i.ON_ACTION="onAction",i.ON_RESOLVE="onResolve",i.ON_REACTION="onReaction",i))(ko||{}),Zn=class{constructor(){this.__novuPendingApproval=!0}};function bu(e){return typeof e=="object"&&e!==null&&"suppress"in e&&e.suppress===!0}function Yi(e){return"type"in e&&e.type==="card"}function wu(e){return typeof e=="object"&&e!==null&&e.type==="tool-approval-card"}var Su="tool-approval";function Fg(e){return e==="approve"||e==="deny"}function Ao(e,n){return`${Su}:${e}:${n}`}function xu(e){let[n,t,...r]=(e!=null?e:"").split(":"),i=r.join(":");return n!==Su||!Fg(t)||!i?null:{approved:t==="approve",approvalId:i}}async function Tu(e,n,t,r){var p,d;let i=r!=null?r:n.id,a={approve:Ao("approve",i),deny:Ao("deny",i)},o=h=>({type:"tool-approval-card",...h}),s=(d=(p=t==null?void 0:t.renderApproval)==null?void 0:p.call(t,{toolCall:n,actionIds:a,approvalCard:o}))!=null?d:o(),u={approvalId:i,toolCallId:n.id,name:n.name,input:n.input};if(e.emitToolApprovalRequest(u),wu(s)){await e.replyApprovalCard(s);return}await e.reply(s)}var Zw=5*1024*1024,eS=5*1024*1024,kf=32768,tS=/^[A-Za-z0-9+/]*={0,2}$/;function Gr(e,n){return e.filename?`"${e.filename}"`:`at index ${n}`}function vf(){return globalThis.Buffer}function nS(e){var n,t,r;return(r=(t=(n=vf())==null?void 0:n.isBuffer)==null?void 0:t.call(n,e))!=null?r:!1}function rS(e){return typeof Blob!="undefined"&&e instanceof Blob}function bl(e){let n=vf();if(n)return n.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 t="";for(let r=0;r<e.length;r+=kf){let i=e.subarray(r,r+kf);t+=String.fromCharCode(...i)}return btoa(t)}function Ef(e){let n=e.replace(/\s/g,""),t=n.length%4;if(!n||t===1||!tS.test(n))return null;let r=n.endsWith("==")?2:n.endsWith("=")?1:0;return Math.floor(n.length*3/4)-r}function Yr(e,n,t){if(e>Zw)throw new Error(`Invalid file ${Gr(n,t)}: inline data must be 5 MB or smaller. Use a publicly-accessible URL for larger files.`)}async function iS(e,n,t){if(typeof e=="string"){let r=Ef(e);if(r===null)throw new Error(`Invalid file ${Gr(n,t)}: data must be a base64-encoded string.`);return Yr(r,n,t),e}if(nS(e))return Yr(e.byteLength,n,t),e.toString("base64");if(e instanceof Uint8Array)return Yr(e.byteLength,n,t),bl(e);if(e instanceof ArrayBuffer)return Yr(e.byteLength,n,t),bl(new Uint8Array(e));if(rS(e))return Yr(e.size,n,t),bl(new Uint8Array(await e.arrayBuffer()));throw new Error(`Invalid file ${Gr(n,t)}: data must be a base64 string, Buffer, Uint8Array, ArrayBuffer, or Blob.`)}async function aS(e){if(!(e!=null&&e.length))return;let n=[],t=0;for(let[r,i]of e.entries()){let a=i.data,o=i.url,s=a!=null,u=o!=null;if(s===u)throw new Error(`Invalid file ${Gr(i,r)}: provide exactly one of data or url.`);if(s){let p=await iS(a,i,r),d=Ef(p);if(t+=d!=null?d:0,t>eS)throw new Error("Invalid files: total inline data must be 5 MB or smaller. Use publicly-accessible URLs for larger files.");n.push({...i,data:p});continue}if(u&&typeof o!="string")throw new Error(`Invalid file ${Gr(i,r)}: url must be a string.`);n.push(i)}return n}async function _f(e,n){let t=await aS(n);if(typeof e=="string")return t?{markdown:e,files:t}:{markdown:e};let{isJSX:r,toCardElement:i}=await Promise.resolve().then(()=>(Tf(),xf));if(r(e)){let a=i(e);if(a)return t?{card:a,files:t}:{card:a}}if(Yi(e))return t?{card:e,files:t}:{card:e};throw new Error("Invalid message content \u2014 expected string or CardElement")}var Jr=class{constructor(n,t,r,i,a){this.conversationId=r;this.integrationIdentifier=i;this.poster=a;this.editedByHandler=!1;this.messageId=n,this.platformThreadId=t}async edit(n,t){this.editedByHandler=!0;let r=await this.poster.post({conversationId:this.conversationId,integrationIdentifier:this.integrationIdentifier,edit:{messageId:this.messageId,content:await _f(n,t==null?void 0:t.files)}});if(!r)throw new Error("Agent edit did not return a message handle");return this.messageId=r.messageId,this.platformThreadId=r.platformThreadId,this}async delete(){await this.poster.post({conversationId:this.conversationId,integrationIdentifier:this.integrationIdentifier,deleteMessages:[{messageId:this.messageId}]})}},Af;Af=yu;var Na=class{constructor(n,t,r){this[Af]=!0;this._signals=[];this._toolResults=[];this._pendingToolApprovalRequest=null;this._pendingReactions=[];this._pendingDeletes=[];this._resolveSignal=null;var s,u;this.event=n.event,this.action=(s=n.action)!=null?s:null,this.message=n.message,this.reaction=n.reaction,this.conversation=n.conversation,this.subscriber=n.subscriber,this.history=n.history,this.platform=n.platform,this.platformContext=n.platformContext,this._replyUrl=n.replyUrl,this._conversationId=n.conversationId,this._integrationIdentifier=n.integrationIdentifier,this._secretKey=t,this._poster={post:p=>this._post(p)},this._toolApprovalConfig=r,this._metadataState={...(u=n.conversation.metadata)!=null?u:{}};let i=this;this.metadata={get(p){return i._metadataState[p]},set(p,d){i._metadataState[p]=d,i._signals.push({type:"metadata",action:"set",key:p,value:d})},delete(p){delete i._metadataState[p],i._signals.push({type:"metadata",action:"delete",key:p})},clear(){i._metadataState={},i._signals.push({type:"metadata",action:"clear"})},get current(){return{...i._metadataState}}};let a=p=>this._post({conversationId:this._conversationId,integrationIdentifier:this._integrationIdentifier,typing:p}).then(()=>{}),o=(p=>a(p===void 0?{}:{status:p}));o.stop=()=>a("stop"),this.typing=o,this.toolApproval={request:async p=>(await Tu(this,p,this._toolApprovalConfig),new Zn)}}asMessageContext(){return this}async reply(n,t){let r=await _f(n,t==null?void 0:t.files),i={conversationId:this._conversationId,integrationIdentifier:this._integrationIdentifier,reply:r};this._drainSideEffects(i);let a=await this._post(i);if(!a)throw new Error("Agent reply did not return a message handle");return new Jr(a.messageId,a.platformThreadId,this._conversationId,this._integrationIdentifier,this._poster)}async replyApprovalCard(n){let t={conversationId:this._conversationId,integrationIdentifier:this._integrationIdentifier,reply:{toolApprovalCard:n}};this._drainSideEffects(t);let r=await this._post(t);if(!r)throw new Error("Agent approval card reply did not return a message handle");return new Jr(r.messageId,r.platformThreadId,this._conversationId,this._integrationIdentifier,this._poster)}createReplyHandle(n){return new Jr(n,"",this._conversationId,this._integrationIdentifier,this._poster)}resolve(n){this._resolveSignal={summary:n}}trigger(n,t){this._signals.push({...t,type:"trigger",workflowId:n})}emitToolApprovalRequest(n){if(this._pendingToolApprovalRequest)throw new Error("Only one tool approval request can be queued before the next reply");this._pendingToolApprovalRequest=n}emitToolResult(n){this._toolResults.push(n)}addReaction(n,t){this._pendingReactions.push({messageId:n,emojiName:t})}deleteMessage(n){this._pendingDeletes.push({messageId:n})}async reportTurnError(){try{await this._post({conversationId:this._conversationId,integrationIdentifier:this._integrationIdentifier,error:!0})}catch(n){console.error("[agent] Failed to report turn error:",n)}}async flush(){if(!this._hasPendingSideEffects())return;let n={conversationId:this._conversationId,integrationIdentifier:this._integrationIdentifier};this._drainSideEffects(n),await this._post(n)}_hasPendingSideEffects(){return!!(this._pendingToolApprovalRequest||this._signals.length||this._toolResults.length||this._resolveSignal||this._pendingReactions.length||this._pendingDeletes.length)}_drainSideEffects(n){this._pendingToolApprovalRequest&&(n.toolApprovalRequest=this._pendingToolApprovalRequest,this._pendingToolApprovalRequest=null),this._signals.length&&(n.signals=this._signals,this._signals=[]),this._toolResults.length&&(n.toolResults=this._toolResults,this._toolResults=[]),this._pendingReactions.length&&(n.addReactions=this._pendingReactions,this._pendingReactions=[]),this._pendingDeletes.length&&(n.deleteMessages=this._pendingDeletes,this._pendingDeletes=[]),this._resolveSignal&&(n.resolve=this._resolveSignal,this._resolveSignal=null)}async _post(n){let t=await fetch(this._replyUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${this._secretKey}`},body:JSON.stringify(n)});if(!t.ok){let i=await t.text().catch(()=>"");throw new Dn(t.status,i)}let r=await t.text().catch(()=>"");if(!r)return null;try{let i=JSON.parse(r),a=i&&typeof i=="object"&&"data"in i?i.data:i;if(a&&typeof a.messageId=="string"&&typeof a.platformThreadId=="string")return{messageId:a.messageId,platformThreadId:a.platformThreadId}}catch{}return null}};function oS(e){return!!(typeof e=="string"||typeof e=="object"&&e!==null&&Yi(e)||typeof e=="object"&&e!==null&&("markdown"in e||"card"in e||"files"in e))}function sS(e,n){return e}function lS(e,n){var t;for(let r of e){let i=r.toolData;if(r.type==="tool_approval_request"&&(i==null?void 0:i.approvalId)===n&&i.toolCallId)return{approvalId:i.approvalId,toolCallId:i.toolCallId,name:(t=i.toolName)!=null?t:"tool",input:i.input}}}async function Rf(e){var a;let n=new Na(e.bridge,e.secretKey,e.agent.handlers.toolApproval),{agent:t,event:r,logger:i}=e;try{await cS(t,r,n),await n.flush()}catch(o){let s=Mr(o);i==null||i.error(`[agent:${t.id}] Turn failed (${r}): ${s.message}`,(a=s.cause)!=null?a:s);let u=!1;if(t.handlers.onError)try{let p=await t.handlers.onError(s,sS(n,r));bu(p)?u=!0:oS(p)&&(await n.reply(p),u=!0)}catch(p){i==null||i.error(`[agent:${t.id}] onError failed:`,p)}u||await n.reportTurnError()}finally{try{await n.typing.stop()}catch{}}}async function cS(e,n,t){var i,a;let r=async o=>{o instanceof Zn||o===void 0||await t.reply(o)};switch(n){case"onMessage":{await r(await e.handlers.onMessage(t.message,t));break}case"onAction":{let o=xu((i=t.action)==null?void 0:i.id);if(o&&e.handlers.onToolApproval){let{approved:s,approvalId:u}=o,p=lS(t.history,u),d=p?{id:p.toolCallId,name:p.name,input:p.input}:{id:u,name:""},h=t.createReplyHandle((a=t.action.sourceMessageId)!=null?a:""),y={toolCall:d,approved:s,approvalMessage:h};e.userOnToolApproval===!1&&(await t.typing(),t.action.sourceMessageId&&await h.delete());let g=await e.handlers.onToolApproval(y,t);await r(g);break}e.handlers.onAction&&await r(await e.handlers.onAction(t.action,t));break}case"onReaction":e.handlers.onReaction&&await r(await e.handlers.onReaction(t.reaction,t));break;case"onResolve":e.handlers.onResolve&&await r(await e.handlers.onResolve(t));break;default:throw new Mn(n,ko)}}function Of(e){let n={};for(let i of e.split(",")){let a=i.trim();if(!a)continue;let o=a.indexOf("=");if(o<=0)continue;let s=a.slice(0,o),u=a.slice(o+1);s&&u&&!(s in n)&&(n[s]=u)}let t=n.t,r=t!==void 0?Number(t):Number.NaN;return{t:Number.isFinite(r)?r:void 0,v1:n.v1}}var La=class{constructor(n){this.handler=n.handler,this.client=n.client?n.client:new Qn,this.workflows=n.workflows||[],this.agents=n.agents||[],this.http=Li(this.client.secretKey,this.client.apiUrl),this.frameworkName=n.frameworkName,this.hmacEnabled=this.client.strictAuthentication,this.client.addAgents(this.agents)}createHandler(){return async(...n)=>{await this.client.addWorkflows(this.workflows);let t=await this.handler(...n),r=await this.handleAction({actions:t});return t.transformResponse(r)}}getStaticHeaders(){let n=`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.11.2-alpha.0","novu-framework-server":this.frameworkName,"user-agent":n}}createResponse(n,t){return{status:n,body:JSON.stringify(t),headers:{...this.getStaticHeaders()}}}createError(n){return{status:n.statusCode,body:JSON.stringify({message:n.message,data:n.data,code:n.code}),headers:this.getStaticHeaders()}}async handleAction({actions:n}){let t=await n.url(),r=await n.method(),i=t.searchParams.get("action")||"health-check",a=t.searchParams.get("workflowId")||"",o=t.searchParams.get("stepId")||"",s=t.searchParams.get("agentId")||"",u=t.searchParams.get("event")||"",p=await n.headers("novu-signature")||"",d={};try{r==="POST"&&(d=await n.body())}catch{}try{i!=="health-check"&&await this.validateHmac(d,p);let h=this.getPostActionMap(d,a,o,i,s,u,n.waitUntil),y=this.getGetActionMap(a,o);if(r==="POST")return await this.handlePostAction(i,h);if(r==="GET")return await this.handleGetAction(i,y);if(r==="OPTIONS")return this.createResponse(200,{})}catch(h){return this.handleError(h)}return this.createError(new Ti(r))}getPostActionMap(n,t,r,i,a,o,s){return{trigger:this.triggerAction({workflowId:t,...n}),execute:async()=>{let u=await this.client.executeWorkflow({...n,workflowId:t,stepId:r,action:i});return this.createResponse(200,u)},preview:async()=>{let u=await this.client.executeWorkflow({...n,workflowId:t,stepId:r,action:i});return this.createResponse(200,u)},"agent-event":async()=>{let u=this.client.getAgent(a);if(!u)return this.createResponse(404,{error:`Agent '${a}' not registered`});let p=Rf({agent:u,event:o,bridge:n,secretKey:this.client.secretKey,logger:this.client.logger});return s&&s(p),this.createResponse(200,{status:"ack"})}}}triggerAction(n){return async()=>{let t={name:n.workflowId,to:n.to,payload:(n==null?void 0:n.payload)||{},transactionId:n.transactionId,overrides:n.overrides||{},...n.actor&&{actor:n.actor},...n.bridgeUrl&&{bridgeUrl:n.bridgeUrl},...n.controls&&{controls:n.controls},...n.context&&{context:n.context}},r=await this.http.post("/events/trigger",t);return this.createResponse(200,r)}}getGetActionMap(n,t){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(n,t);return this.createResponse(200,r)}}}async handlePostAction(n,t){if(Object.values(Tr).includes(n)){let r=t[n];return r()}else throw new Mn(n,Tr)}async handleGetAction(n,t){if(Object.values(ci).includes(n)){let r=t[n];return r()}else throw new Mn(n,ci)}handleError(n){if(Pn(n))return n.statusCode>=500&&this.client.logger.error(n),this.createError(n);if(Uc(n))return this.createError(n);{let t=new Gn(n);return this.client.logger.error(t),this.createError(t)}}async validateHmac(n,t){if(!this.hmacEnabled)return;if(!t)throw new Ri;if(!this.client.secretKey)throw new Ci;let r=Of(t);if(!r.v1||r.t===void 0)throw new Oi;let i=Date.now();if(r.t<i-3e5||r.t>i+3e5)throw new Ii;let a=await Yc(this.client.secretKey,`${r.t}.${JSON.stringify(n)}`);if(!Jc(a,r.v1))throw new _i}};yl();var or=Symbol.for("workflow-serialize"),sr=Symbol.for("workflow-deserialize");var uS=Object.defineProperty,pS=Object.defineProperties,dS=Object.getOwnPropertyDescriptors,Cf=Object.getOwnPropertySymbols,hS=Object.prototype.hasOwnProperty,fS=Object.prototype.propertyIsEnumerable,Pf=(e,n,t)=>n in e?uS(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t,Df=(e,n)=>{for(var t in n||(n={}))hS.call(n,t)&&Pf(e,t,n[t]);if(Cf)for(var t of Cf(n))fS.call(n,t)&&Pf(e,t,n[t]);return e},Ff=(e,n)=>pS(e,dS(n)),It=(e,n)=>{let t=!1,r=!1;for(let i=0;i<n;i+=1){if(e[i]==="\\"&&i+1<e.length&&e[i+1]==="`"){i+=1;continue}if(e.substring(i,i+3)==="```"){r=!r,i+=2;continue}!r&&e[i]==="`"&&(t=!t)}return t||r},mS=(e,n)=>{let t=e.substring(n,n+3)==="```",r=n>0&&e.substring(n-1,n+2)==="```",i=n>1&&e.substring(n-2,n+1)==="```";return t||r||i},gS=e=>{let n=0;for(let t=0;t<e.length;t+=1){if(e[t]==="\\"&&t+1<e.length&&e[t+1]==="`"){t+=1;continue}e[t]==="`"&&!mS(e,t)&&(n+=1)}return n},Rn=(e,n)=>{let t=!1,r=!1,i=-1;for(let a=0;a<e.length;a+=1){if(e[a]==="\\"&&a+1<e.length&&e[a+1]==="`"){a+=1;continue}if(e.substring(a,a+3)==="```"){r=!r,a+=2;continue}if(!r&&e[a]==="`")if(t){if(i<n&&n<a)return!0;t=!1,i=-1}else t=!0,i=a}return!1},yS=/^(\s*(?:[-*+]|\d+[.)]) +)>(=?\s*[$]?\d)/gm,bS=e=>!e||typeof e!="string"||!e.includes(">")?e:e.replace(yS,(n,t,r,i)=>It(e,i)?n:`${t}\\>${r}`),wS=/(\*\*)([^*]*\*?)$/,SS=/(__)([^_]*?)$/,xS=/(\*\*\*)([^*]*?)$/,TS=/(\*)([^*]*?)$/,kS=/(_)([^_]*?)$/,AS=/(`)([^`]*?)$/,vS=/(~~)([^~]*?)$/,Vn=/^[\s_~*`]*$/,Uf=/^[\s]*[-*+][\s]+$/,ES=/[\p{L}\p{N}_]/u,_S=/^```[^`\n]*```?$/,RS=/^\*{4,}$/,OS=/(__)([^_]+)_$/,IS=/(~~)([^~]+)~$/,Mf=/~~/g,On=e=>{if(!e)return!1;let n=e.charCodeAt(0);return n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122||n===95?!0:ES.test(e)};var CS=(e,n)=>{let t=1;for(let r=n-1;r>=0;r-=1)if(e[r]==="]")t+=1;else if(e[r]==="["&&(t-=1,t===0))return r;return-1},$f=(e,n)=>{let t=1;for(let r=n+1;r<e.length;r+=1)if(e[r]==="[")t+=1;else if(e[r]==="]"&&(t-=1,t===0))return r;return-1},Da=(e,n)=>{let t=!1,r=!1;for(let i=0;i<e.length&&i<n;i+=1){if(e[i]==="\\"&&e[i+1]==="$"){i+=1;continue}e[i]==="$"&&(e[i+1]==="$"?(r=!r,i+=1,t=!1):r||(t=!t))}return t||r},PS=(e,n)=>{for(let t=n;t<e.length;t+=1){if(e[t]===")")return!0;if(e[t]===`
|
|
119
|
+
`)}async executeProviders(n,t,r){return t.providers.reduce(async(i,a)=>{let o=await i,s=this.previewProvider.bind(this),u=this.executeProvider.bind(this),d=await(n.action==="preview"?s:u)(n,t,a,r);return{...o,[a.type]:d}},Promise.resolve({}))}previewProvider(n,t,r,i){return this.log(` ${ct.MOCK} Mocked provider: \`${r.type}\``),this.mock(r.outputs.schema)}async executeProvider(n,t,r,i){try{if(n.stepId===t.stepId){let a=await this.createStepControls(t,n),o=await r.resolve({controls:a,outputs:i}),s=await this.validate(o,r.outputs.unknownSchema,"step","output",n.workflowId,t.stepId,r.type);return this.log(` ${ct.SUCCESS} Executed provider: \`${r.type}\``),{...s,_passthrough:o._passthrough}}else return this.log(` ${ct.HYDRATED} Hydrated provider: \`${r.type}\``),{}}catch(a){throw this.log(` ${ct.ERROR} Failed to execute provider: \`${r.type}\``),new Ei(r.type,n.action,a)}}async executeStep(n,t){if(n.stepId===t.stepId)try{let r=await this.createStepControls(t,n),i=await this.compileControls(r,n),a=await t.resolve(i),o=await this.validate(a,t.outputs.unknownSchema,"step","output",n.workflowId,t.stepId),s=await this.executeProviders(n,t,o);return this.log(` ${ct.SUCCESS} Executed stepId: \`${t.stepId}\``),{outputs:o,providers:s}}catch(r){throw this.log(` ${ct.ERROR} Failed to execute stepId: \`${t.stepId}\``),Pn(r)?r:new Er(t.stepId,n.action,r)}else try{let r=this.getStepState(n,t.stepId);if(r){let i=await this.validate(r.outputs,t.results.unknownSchema,"step","result",n.workflowId,t.stepId);return this.log(` ${ct.HYDRATED} Hydrated stepId: \`${t.stepId}\``),{outputs:i,providers:await this.executeProviders(n,t,i)}}else throw new hi(n.workflowId,t.stepId)}catch(r){throw this.log(` ${ct.ERROR} Failed to hydrate stepId: \`${t.stepId}\``),r}}async compileControls(n,t){var r;try{let i=Ir(n),a=this.preprocessTranslationPatterns(JSON.stringify(i));a=this.preprocessFilterTranslationArgs(a);let o=this.templateEngine.parse(a),s=this.getWorkflow(t.workflowId),u={workflow:{workflowId:s.workflowId,name:s.name,description:s.description,tags:s.tags,severity:s.severity},payload:t.payload,subscriber:t.subscriber,...t.actor&&{actor:t.actor},context:t.context,steps:Mg(t.state),env:(r=t.env)!=null?r:{}},p=await this.templateEngine.render(o,u),d=this.postprocessTranslationMarkers(p),h=(0,gu.jsonrepair)(d),y=JSON.parse(h),g=Cr(y);return pu(g)}catch(i){throw new bi(t.workflowId,t.stepId,i)}}preprocessTranslationPatterns(n){return n.replace(/\{\{\s*t\.([\p{L}\p{N}_.-]+)\s*\}\}/gu,"[T:$1]")}preprocessFilterTranslationArgs(n){return n.replace(/'t\.([\p{L}\p{N}_.-]+)'/gu,"'[T:$1]'")}postprocessTranslationMarkers(n){return n.replace(/\[T:([\p{L}\p{N}_.-]+)\]/gu,"{{t.$1}}")}async createStepControls(n,t){return await this.validate(t.controls,n.controls.unknownSchema,"step","controls",t.workflowId,n.stepId)}async previewStep(n,t){try{return await this.constructStepForPreview(n,t)}catch(r){throw this.log(` ${ct.ERROR} Failed to preview stepId: \`${t.stepId}\``),Pn(r)?r:new Er(t.stepId,n.action,r)}}async constructStepForPreview(n,t){return n.stepId===t.stepId?await this.previewRequiredStep(t,n):await this.extractMockDataForPreviousSteps(n,t)}async extractMockDataForPreviousSteps(n,t){let r={},i=this.getStepState(n,t.stepId),a=this.mock(t.results.schema);return{outputs:xo(a,(i==null?void 0:i.outputs)||{}),providers:await this.executeProviders(n,t,r)}}async previewRequiredStep(n,t){let r=await this.createStepControls(n,t),i=await this.compileControls(r,t),a=await n.resolve(i),o=await this.validate(a,n.outputs.unknownSchema,"step","output",t.workflowId,n.stepId);return this.log(` ${ct.MOCK} Mocked stepId: \`${n.stepId}\``),{outputs:o,providers:await this.executeProviders(t,n,o)}}getStepState(n,t){return n.state.find(r=>r.stepId===t)}getStepCode(n,t){return{code:this.getStep(n,t).resolve.toString()}}getWorkflowCode(n){return{code:this.getWorkflow(n).execute.toString()}}getCode(n,t){let r;if(n)t?r=this.getStepCode(n,t):r=this.getWorkflowCode(n);else throw new _r(n);return r}};function Mg(e){let n={};for(let t of e)n[t.stepId]=t.outputs;return n}var Ng={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 Hi(e){return typeof e=="string"&&e.trim()?e:!e||typeof e!="object"?null:Hi(e.message)}function Lg(e){if(!e)return null;let n;try{n=JSON.parse(e)}catch{return null}if(!n||typeof n!="object")return null;let t=n,r=Hi(t.message);if(r)return r;let i=Hi(t.error);if(i)return i;let a=t.errors;return Array.isArray(a)?Hi(a[0]):null}function Dg(e,n){var i;let t=(i=Ng[e])!=null?i:e,r=Lg(n);return r?`Delivery failed: ${t}: ${r}`:`Delivery failed: ${t}`}var pn=class extends Error{constructor(n,t){super(n),this.name="AgentError",this.cause=t==null?void 0:t.cause,this.delivery=t==null?void 0:t.delivery}},Dn=class extends pn{constructor(n,t){let r={statusCode:n,responseBody:t};super(Dg(n,t),{delivery:r}),this.name="AgentDeliveryError",this.statusCode=n,this.responseBody=t}};function Mr(e){return e instanceof pn?e:e instanceof Error?new pn(e.message,{cause:e}):new pn("Turn failed",{cause:e})}var yu=Symbol.for("novu.agent.runtimeContext");var ko=(i=>(i.ON_MESSAGE="onMessage",i.ON_ACTION="onAction",i.ON_RESOLVE="onResolve",i.ON_REACTION="onReaction",i))(ko||{}),Zn=class{constructor(){this.__novuPendingApproval=!0}};function bu(e){return typeof e=="object"&&e!==null&&"suppress"in e&&e.suppress===!0}function Yi(e){return"type"in e&&e.type==="card"}function wu(e){return typeof e=="object"&&e!==null&&e.type==="tool-approval-card"}var Su="tool-approval";function Fg(e){return e==="approve"||e==="deny"}function Ao(e,n){return`${Su}:${e}:${n}`}function xu(e){let[n,t,...r]=(e!=null?e:"").split(":"),i=r.join(":");return n!==Su||!Fg(t)||!i?null:{approved:t==="approve",approvalId:i}}async function Tu(e,n,t,r){var p,d;let i=r!=null?r:n.id,a={approve:Ao("approve",i),deny:Ao("deny",i)},o=h=>({type:"tool-approval-card",...h}),s=(d=(p=t==null?void 0:t.renderApproval)==null?void 0:p.call(t,{toolCall:n,actionIds:a,approvalCard:o}))!=null?d:o(),u={approvalId:i,toolCallId:n.id,name:n.name,input:n.input};if(e.emitToolApprovalRequest(u),wu(s)){await e.replyApprovalCard(s);return}await e.reply(s)}var Zw=5*1024*1024,eS=5*1024*1024,kf=32768,tS=/^[A-Za-z0-9+/]*={0,2}$/;function Gr(e,n){return e.filename?`"${e.filename}"`:`at index ${n}`}function vf(){return globalThis.Buffer}function nS(e){var n,t,r;return(r=(t=(n=vf())==null?void 0:n.isBuffer)==null?void 0:t.call(n,e))!=null?r:!1}function rS(e){return typeof Blob!="undefined"&&e instanceof Blob}function bl(e){let n=vf();if(n)return n.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 t="";for(let r=0;r<e.length;r+=kf){let i=e.subarray(r,r+kf);t+=String.fromCharCode(...i)}return btoa(t)}function Ef(e){let n=e.replace(/\s/g,""),t=n.length%4;if(!n||t===1||!tS.test(n))return null;let r=n.endsWith("==")?2:n.endsWith("=")?1:0;return Math.floor(n.length*3/4)-r}function Yr(e,n,t){if(e>Zw)throw new Error(`Invalid file ${Gr(n,t)}: inline data must be 5 MB or smaller. Use a publicly-accessible URL for larger files.`)}async function iS(e,n,t){if(typeof e=="string"){let r=Ef(e);if(r===null)throw new Error(`Invalid file ${Gr(n,t)}: data must be a base64-encoded string.`);return Yr(r,n,t),e}if(nS(e))return Yr(e.byteLength,n,t),e.toString("base64");if(e instanceof Uint8Array)return Yr(e.byteLength,n,t),bl(e);if(e instanceof ArrayBuffer)return Yr(e.byteLength,n,t),bl(new Uint8Array(e));if(rS(e))return Yr(e.size,n,t),bl(new Uint8Array(await e.arrayBuffer()));throw new Error(`Invalid file ${Gr(n,t)}: data must be a base64 string, Buffer, Uint8Array, ArrayBuffer, or Blob.`)}async function aS(e){if(!(e!=null&&e.length))return;let n=[],t=0;for(let[r,i]of e.entries()){let a=i.data,o=i.url,s=a!=null,u=o!=null;if(s===u)throw new Error(`Invalid file ${Gr(i,r)}: provide exactly one of data or url.`);if(s){let p=await iS(a,i,r),d=Ef(p);if(t+=d!=null?d:0,t>eS)throw new Error("Invalid files: total inline data must be 5 MB or smaller. Use publicly-accessible URLs for larger files.");n.push({...i,data:p});continue}if(u&&typeof o!="string")throw new Error(`Invalid file ${Gr(i,r)}: url must be a string.`);n.push(i)}return n}async function _f(e,n){let t=await aS(n);if(typeof e=="string")return t?{markdown:e,files:t}:{markdown:e};let{isJSX:r,toCardElement:i}=await Promise.resolve().then(()=>(Tf(),xf));if(r(e)){let a=i(e);if(a)return t?{card:a,files:t}:{card:a}}if(Yi(e))return t?{card:e,files:t}:{card:e};throw new Error("Invalid message content \u2014 expected string or CardElement")}var Jr=class{constructor(n,t,r,i,a){this.conversationId=r;this.integrationIdentifier=i;this.poster=a;this.editedByHandler=!1;this.messageId=n,this.platformThreadId=t}async edit(n,t){this.editedByHandler=!0;let r=await this.poster.post({conversationId:this.conversationId,integrationIdentifier:this.integrationIdentifier,edit:{messageId:this.messageId,content:await _f(n,t==null?void 0:t.files)}});if(!r)throw new Error("Agent edit did not return a message handle");return this.messageId=r.messageId,this.platformThreadId=r.platformThreadId,this}async delete(){await this.poster.post({conversationId:this.conversationId,integrationIdentifier:this.integrationIdentifier,deleteMessages:[{messageId:this.messageId}]})}},Af;Af=yu;var Na=class{constructor(n,t,r){this[Af]=!0;this._signals=[];this._toolResults=[];this._pendingToolApprovalRequest=null;this._pendingReactions=[];this._pendingDeletes=[];this._resolveSignal=null;var s,u;this.event=n.event,this.action=(s=n.action)!=null?s:null,this.message=n.message,this.reaction=n.reaction,this.conversation=n.conversation,this.subscriber=n.subscriber,this.history=n.history,this.platform=n.platform,this.platformContext=n.platformContext,this._replyUrl=n.replyUrl,this._conversationId=n.conversationId,this._integrationIdentifier=n.integrationIdentifier,this._secretKey=t,this._poster={post:p=>this._post(p)},this._toolApprovalConfig=r,this._metadataState={...(u=n.conversation.metadata)!=null?u:{}};let i=this;this.metadata={get(p){return i._metadataState[p]},set(p,d){i._metadataState[p]=d,i._signals.push({type:"metadata",action:"set",key:p,value:d})},delete(p){delete i._metadataState[p],i._signals.push({type:"metadata",action:"delete",key:p})},clear(){i._metadataState={},i._signals.push({type:"metadata",action:"clear"})},get current(){return{...i._metadataState}}};let a=p=>this._post({conversationId:this._conversationId,integrationIdentifier:this._integrationIdentifier,typing:p}).then(()=>{}),o=(p=>a(p===void 0?{}:{status:p}));o.stop=()=>a("stop"),this.typing=o,this.toolApproval={request:async p=>(await Tu(this,p,this._toolApprovalConfig),new Zn)}}asMessageContext(){return this}async reply(n,t){let r=await _f(n,t==null?void 0:t.files),i={conversationId:this._conversationId,integrationIdentifier:this._integrationIdentifier,reply:r};this._drainSideEffects(i);let a=await this._post(i);if(!a)throw new Error("Agent reply did not return a message handle");return new Jr(a.messageId,a.platformThreadId,this._conversationId,this._integrationIdentifier,this._poster)}async replyApprovalCard(n){let t={conversationId:this._conversationId,integrationIdentifier:this._integrationIdentifier,reply:{toolApprovalCard:n}};this._drainSideEffects(t);let r=await this._post(t);if(!r)throw new Error("Agent approval card reply did not return a message handle");return new Jr(r.messageId,r.platformThreadId,this._conversationId,this._integrationIdentifier,this._poster)}createReplyHandle(n){return new Jr(n,"",this._conversationId,this._integrationIdentifier,this._poster)}resolve(n){this._resolveSignal={summary:n}}trigger(n,t){this._signals.push({...t,type:"trigger",workflowId:n})}emitToolApprovalRequest(n){if(this._pendingToolApprovalRequest)throw new Error("Only one tool approval request can be queued before the next reply");this._pendingToolApprovalRequest=n}emitToolResult(n){this._toolResults.push(n)}addReaction(n,t){this._pendingReactions.push({messageId:n,emojiName:t})}deleteMessage(n){this._pendingDeletes.push({messageId:n})}async reportTurnError(){try{await this._post({conversationId:this._conversationId,integrationIdentifier:this._integrationIdentifier,error:!0})}catch(n){console.error("[agent] Failed to report turn error:",n)}}async flush(){if(!this._hasPendingSideEffects())return;let n={conversationId:this._conversationId,integrationIdentifier:this._integrationIdentifier};this._drainSideEffects(n),await this._post(n)}_hasPendingSideEffects(){return!!(this._pendingToolApprovalRequest||this._signals.length||this._toolResults.length||this._resolveSignal||this._pendingReactions.length||this._pendingDeletes.length)}_drainSideEffects(n){this._pendingToolApprovalRequest&&(n.toolApprovalRequest=this._pendingToolApprovalRequest,this._pendingToolApprovalRequest=null),this._signals.length&&(n.signals=this._signals,this._signals=[]),this._toolResults.length&&(n.toolResults=this._toolResults,this._toolResults=[]),this._pendingReactions.length&&(n.addReactions=this._pendingReactions,this._pendingReactions=[]),this._pendingDeletes.length&&(n.deleteMessages=this._pendingDeletes,this._pendingDeletes=[]),this._resolveSignal&&(n.resolve=this._resolveSignal,this._resolveSignal=null)}async _post(n){let t=await fetch(this._replyUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${this._secretKey}`},body:JSON.stringify(n)});if(!t.ok){let i=await t.text().catch(()=>"");throw new Dn(t.status,i)}let r=await t.text().catch(()=>"");if(!r)return null;try{let i=JSON.parse(r),a=i&&typeof i=="object"&&"data"in i?i.data:i;if(a&&typeof a.messageId=="string"&&typeof a.platformThreadId=="string")return{messageId:a.messageId,platformThreadId:a.platformThreadId}}catch{}return null}};function oS(e){return!!(typeof e=="string"||typeof e=="object"&&e!==null&&Yi(e)||typeof e=="object"&&e!==null&&("markdown"in e||"card"in e||"files"in e))}function sS(e,n){return e}function lS(e,n){var t;for(let r of e){let i=r.toolData;if(r.type==="tool_approval_request"&&(i==null?void 0:i.approvalId)===n&&i.toolCallId)return{approvalId:i.approvalId,toolCallId:i.toolCallId,name:(t=i.toolName)!=null?t:"tool",input:i.input}}}async function Rf(e){var a;let n=new Na(e.bridge,e.secretKey,e.agent.handlers.toolApproval),{agent:t,event:r,logger:i}=e;try{await cS(t,r,n),await n.flush()}catch(o){let s=Mr(o);i==null||i.error(`[agent:${t.id}] Turn failed (${r}): ${s.message}`,(a=s.cause)!=null?a:s);let u=!1;if(t.handlers.onError)try{let p=await t.handlers.onError(s,sS(n,r));bu(p)?u=!0:oS(p)&&(await n.reply(p),u=!0)}catch(p){i==null||i.error(`[agent:${t.id}] onError failed:`,p)}u||await n.reportTurnError()}finally{try{await n.typing.stop()}catch{}}}async function cS(e,n,t){var i,a;let r=async o=>{o instanceof Zn||o===void 0||await t.reply(o)};switch(n){case"onMessage":{await r(await e.handlers.onMessage(t.message,t));break}case"onAction":{let o=xu((i=t.action)==null?void 0:i.id);if(o&&e.handlers.onToolApproval){let{approved:s,approvalId:u}=o,p=lS(t.history,u),d=p?{id:p.toolCallId,name:p.name,input:p.input}:{id:u,name:""},h=t.createReplyHandle((a=t.action.sourceMessageId)!=null?a:""),y={toolCall:d,approved:s,approvalMessage:h};e.userOnToolApproval===!1&&(await t.typing(),t.action.sourceMessageId&&await h.delete());let g=await e.handlers.onToolApproval(y,t);await r(g);break}e.handlers.onAction&&await r(await e.handlers.onAction(t.action,t));break}case"onReaction":e.handlers.onReaction&&await r(await e.handlers.onReaction(t.reaction,t));break;case"onResolve":e.handlers.onResolve&&await r(await e.handlers.onResolve(t));break;default:throw new Mn(n,ko)}}function Of(e){let n={};for(let i of e.split(",")){let a=i.trim();if(!a)continue;let o=a.indexOf("=");if(o<=0)continue;let s=a.slice(0,o),u=a.slice(o+1);s&&u&&!(s in n)&&(n[s]=u)}let t=n.t,r=t!==void 0?Number(t):Number.NaN;return{t:Number.isFinite(r)?r:void 0,v1:n.v1}}var La=class{constructor(n){this.handler=n.handler,this.client=n.client?n.client:new Qn,this.workflows=n.workflows||[],this.agents=n.agents||[],this.http=Li(this.client.secretKey,this.client.apiUrl),this.frameworkName=n.frameworkName,this.hmacEnabled=this.client.strictAuthentication,this.client.addAgents(this.agents)}createHandler(){return async(...n)=>{await this.client.addWorkflows(this.workflows);let t=await this.handler(...n),r=await this.handleAction({actions:t});return t.transformResponse(r)}}getStaticHeaders(){let n=`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.12.1","novu-framework-server":this.frameworkName,"user-agent":n}}createResponse(n,t){return{status:n,body:JSON.stringify(t),headers:{...this.getStaticHeaders()}}}createError(n){return{status:n.statusCode,body:JSON.stringify({message:n.message,data:n.data,code:n.code}),headers:this.getStaticHeaders()}}async handleAction({actions:n}){let t=await n.url(),r=await n.method(),i=t.searchParams.get("action")||"health-check",a=t.searchParams.get("workflowId")||"",o=t.searchParams.get("stepId")||"",s=t.searchParams.get("agentId")||"",u=t.searchParams.get("event")||"",p=await n.headers("novu-signature")||"",d={};try{r==="POST"&&(d=await n.body())}catch{}try{i!=="health-check"&&await this.validateHmac(d,p);let h=this.getPostActionMap(d,a,o,i,s,u,n.waitUntil),y=this.getGetActionMap(a,o);if(r==="POST")return await this.handlePostAction(i,h);if(r==="GET")return await this.handleGetAction(i,y);if(r==="OPTIONS")return this.createResponse(200,{})}catch(h){return this.handleError(h)}return this.createError(new Ti(r))}getPostActionMap(n,t,r,i,a,o,s){return{trigger:this.triggerAction({workflowId:t,...n}),execute:async()=>{let u=await this.client.executeWorkflow({...n,workflowId:t,stepId:r,action:i});return this.createResponse(200,u)},preview:async()=>{let u=await this.client.executeWorkflow({...n,workflowId:t,stepId:r,action:i});return this.createResponse(200,u)},"agent-event":async()=>{let u=this.client.getAgent(a);if(!u)return this.createResponse(404,{error:`Agent '${a}' not registered`});let p=Rf({agent:u,event:o,bridge:n,secretKey:this.client.secretKey,logger:this.client.logger});return s&&s(p),this.createResponse(200,{status:"ack"})}}}triggerAction(n){return async()=>{let t={name:n.workflowId,to:n.to,payload:(n==null?void 0:n.payload)||{},transactionId:n.transactionId,overrides:n.overrides||{},...n.actor&&{actor:n.actor},...n.bridgeUrl&&{bridgeUrl:n.bridgeUrl},...n.controls&&{controls:n.controls},...n.context&&{context:n.context}},r=await this.http.post("/events/trigger",t);return this.createResponse(200,r)}}getGetActionMap(n,t){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(n,t);return this.createResponse(200,r)}}}async handlePostAction(n,t){if(Object.values(Tr).includes(n)){let r=t[n];return r()}else throw new Mn(n,Tr)}async handleGetAction(n,t){if(Object.values(ci).includes(n)){let r=t[n];return r()}else throw new Mn(n,ci)}handleError(n){if(Pn(n))return n.statusCode>=500&&this.client.logger.error(n),this.createError(n);if(Uc(n))return this.createError(n);{let t=new Gn(n);return this.client.logger.error(t),this.createError(t)}}async validateHmac(n,t){if(!this.hmacEnabled)return;if(!t)throw new Ri;if(!this.client.secretKey)throw new Ci;let r=Of(t);if(!r.v1||r.t===void 0)throw new Oi;let i=Date.now();if(r.t<i-3e5||r.t>i+3e5)throw new Ii;let a=await Yc(this.client.secretKey,`${r.t}.${JSON.stringify(n)}`);if(!Jc(a,r.v1))throw new _i}};yl();var or=Symbol.for("workflow-serialize"),sr=Symbol.for("workflow-deserialize");var uS=Object.defineProperty,pS=Object.defineProperties,dS=Object.getOwnPropertyDescriptors,Cf=Object.getOwnPropertySymbols,hS=Object.prototype.hasOwnProperty,fS=Object.prototype.propertyIsEnumerable,Pf=(e,n,t)=>n in e?uS(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t,Df=(e,n)=>{for(var t in n||(n={}))hS.call(n,t)&&Pf(e,t,n[t]);if(Cf)for(var t of Cf(n))fS.call(n,t)&&Pf(e,t,n[t]);return e},Ff=(e,n)=>pS(e,dS(n)),It=(e,n)=>{let t=!1,r=!1;for(let i=0;i<n;i+=1){if(e[i]==="\\"&&i+1<e.length&&e[i+1]==="`"){i+=1;continue}if(e.substring(i,i+3)==="```"){r=!r,i+=2;continue}!r&&e[i]==="`"&&(t=!t)}return t||r},mS=(e,n)=>{let t=e.substring(n,n+3)==="```",r=n>0&&e.substring(n-1,n+2)==="```",i=n>1&&e.substring(n-2,n+1)==="```";return t||r||i},gS=e=>{let n=0;for(let t=0;t<e.length;t+=1){if(e[t]==="\\"&&t+1<e.length&&e[t+1]==="`"){t+=1;continue}e[t]==="`"&&!mS(e,t)&&(n+=1)}return n},Rn=(e,n)=>{let t=!1,r=!1,i=-1;for(let a=0;a<e.length;a+=1){if(e[a]==="\\"&&a+1<e.length&&e[a+1]==="`"){a+=1;continue}if(e.substring(a,a+3)==="```"){r=!r,a+=2;continue}if(!r&&e[a]==="`")if(t){if(i<n&&n<a)return!0;t=!1,i=-1}else t=!0,i=a}return!1},yS=/^(\s*(?:[-*+]|\d+[.)]) +)>(=?\s*[$]?\d)/gm,bS=e=>!e||typeof e!="string"||!e.includes(">")?e:e.replace(yS,(n,t,r,i)=>It(e,i)?n:`${t}\\>${r}`),wS=/(\*\*)([^*]*\*?)$/,SS=/(__)([^_]*?)$/,xS=/(\*\*\*)([^*]*?)$/,TS=/(\*)([^*]*?)$/,kS=/(_)([^_]*?)$/,AS=/(`)([^`]*?)$/,vS=/(~~)([^~]*?)$/,Vn=/^[\s_~*`]*$/,Uf=/^[\s]*[-*+][\s]+$/,ES=/[\p{L}\p{N}_]/u,_S=/^```[^`\n]*```?$/,RS=/^\*{4,}$/,OS=/(__)([^_]+)_$/,IS=/(~~)([^~]+)~$/,Mf=/~~/g,On=e=>{if(!e)return!1;let n=e.charCodeAt(0);return n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122||n===95?!0:ES.test(e)};var CS=(e,n)=>{let t=1;for(let r=n-1;r>=0;r-=1)if(e[r]==="]")t+=1;else if(e[r]==="["&&(t-=1,t===0))return r;return-1},$f=(e,n)=>{let t=1;for(let r=n+1;r<e.length;r+=1)if(e[r]==="[")t+=1;else if(e[r]==="]"&&(t-=1,t===0))return r;return-1},Da=(e,n)=>{let t=!1,r=!1;for(let i=0;i<e.length&&i<n;i+=1){if(e[i]==="\\"&&e[i+1]==="$"){i+=1;continue}e[i]==="$"&&(e[i+1]==="$"?(r=!r,i+=1,t=!1):r||(t=!t))}return t||r},PS=(e,n)=>{for(let t=n;t<e.length;t+=1){if(e[t]===")")return!0;if(e[t]===`
|
|
120
120
|
`)return!1}return!1},qf=(e,n)=>{for(let t=n-1;t>=0;t-=1){if(e[t]===")")return!1;if(e[t]==="(")return t>0&&e[t-1]==="]"?PS(e,n):!1;if(e[t]===`
|
|
121
121
|
`)return!1}return!1},MS=(e,n)=>{for(let t=n-1;t>=0;t-=1){if(e[t]===">")return!1;if(e[t]==="<"){let r=t+1<e.length?e[t+1]:"";return r>="a"&&r<="z"||r>="A"&&r<="Z"||r==="/"}if(e[t]===`
|
|
122
122
|
`)return!1}return!1},Sl=(e,n,t)=>{let r=0;for(let u=n-1;u>=0;u-=1)if(e[u]===`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var sn=Object.create;var k=Object.defineProperty;var an=Object.getOwnPropertyDescriptor;var ln=Object.getOwnPropertyNames;var pn=Object.getPrototypeOf,cn=Object.prototype.hasOwnProperty;var De=(e,n,t)=>()=>{if(t)throw t[0];try{return e&&(n=e(e=0)),n}catch(i){throw t=[i],i}};var Me=(e,n)=>{for(var t in n)k(e,t,{get:n[t],enumerable:!0})},Ue=(e,n,t,i)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of ln(n))!cn.call(e,o)&&o!==t&&k(e,o,{get:()=>n[o],enumerable:!(i=an(n,o))||i.enumerable});return e};var Le=(e,n,t)=>(t=e!=null?sn(pn(e)):{},Ue(n||!e||!e.__esModule?k(t,"default",{value:e,enumerable:!0}):t,e)),dn=e=>Ue(k({},"__esModule",{value:!0}),e);function bn(e={}){var n;return{type:"card",title:e.title,subtitle:e.subtitle,imageUrl:e.imageUrl,children:(n=e.children)!=null?n:[]}}function pt(e,n={}){return{type:"text",content:e,style:n.style}}function ct(e){return{type:"image",url:e.url,alt:e.alt}}function dt(){return{type:"divider"}}function ut(e){return{type:"section",children:e}}function mt(e){return{type:"actions",children:e}}function ht(e){return{type:"button",id:e.id,label:e.label,style:e.style,value:e.value,disabled:e.disabled,actionType:e.actionType,callbackUrl:e.callbackUrl}}function yt(e){return{type:"link-button",id:e.id,url:e.url,label:e.label,style:e.style}}function gt(e){return{type:"field",label:e.label,value:e.value}}function ft(e){return{type:"fields",children:e}}function bt(e){return{type:"table",headers:e.headers,rows:e.rows,align:e.align}}function Tt(e){return{type:"link",url:e.url,label:e.label}}function wn(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="modal"}function An(e){let n=e.filter(t=>typeof t=="object"&&t!==null&&"type"in t&&Tn.includes(t.type));return n.length<e.length&&console.warn("[chat] Modal contains unsupported child elements that were ignored"),n}function wt(e){var n;return{type:"modal",callbackId:e.callbackId,callbackUrl:e.callbackUrl,title:e.title,submitLabel:e.submitLabel,closeLabel:e.closeLabel,notifyOnClose:e.notifyOnClose,privateMetadata:e.privateMetadata,children:(n=e.children)!=null?n:[]}}function At(e){return{type:"text_input",id:e.id,label:e.label,placeholder:e.placeholder,initialValue:e.initialValue,multiline:e.multiline,optional:e.optional,maxLength:e.maxLength}}function St(e){if(!e.options||e.options.length===0)throw new Error("Select requires at least one option");return{type:"select",id:e.id,label:e.label,placeholder:e.placeholder,options:e.options,initialOption:e.initialOption,optional:e.optional}}function vt(e){return{type:"external_select",id:e.id,initialOption:e.initialOption,label:e.label,placeholder:e.placeholder,minQueryLength:e.minQueryLength,optional:e.optional}}function Rt(e){return{label:e.label,value:e.value,description:e.description}}function xt(e){if(!e.options||e.options.length===0)throw new Error("RadioSelect requires at least one option");return{type:"radio_select",id:e.id,label:e.label,options:e.options,initialOption:e.initialOption,optional:e.optional}}function Y(e){return typeof e=="object"&&e!==null&&e.$$typeof===_e}function Oe(e){if(e==null)return[];if(Array.isArray(e))return e.flatMap(Oe);if(Y(e)){let n=Ee(e);return n?[n]:[]}return typeof e=="object"&&"type"in e?[e]:typeof e=="string"||typeof e=="number"?[String(e)]:[]}function Sn(e){return!("id"in e||"url"in e||"label"in e)}function vn(e){return"id"in e&&typeof e.id=="string"&&!("url"in e)}function Rn(e){return"url"in e&&typeof e.url=="string"&&!("id"in e)}function Ie(e){return"url"in e&&typeof e.url=="string"&&!("id"in e)&&!("alt"in e)&&!("style"in e)}function xn(e){return"url"in e&&typeof e.url=="string"}function _n(e){return"label"in e&&"value"in e&&typeof e.label=="string"&&typeof e.value=="string"}function On(e){return!("id"in e||"url"in e||"callbackId"in e)&&("title"in e||"subtitle"in e||"imageUrl"in e)}function In(e){return"callbackId"in e&&"title"in e}function En(e){return"id"in e&&"label"in e&&!("options"in e)&&!("value"in e)}function _t(e){return"id"in e&&"label"in e&&!("value"in e)}function Pn(e){return"id"in e&&"label"in e&&!("value"in e)&&!("children"in e)}function Cn(e){return"label"in e&&"value"in e&&!("id"in e)}function Ee(e){var d,p,h,l;let{type:n,props:t,children:i}=e,o=Oe(i);if(n===pt){let c=Sn(t)?t:{style:void 0},A=o.length>0?o.map(String).join(""):String((d=c.children)!=null?d:"");return pt(A,{style:c.style})}if(n===ut)return ut(o);if(n===mt)return mt(o);if(n===ft)return ft(o);if(n===ht){if(!vn(t))throw new Error("Button requires an 'id' prop");let c=o.length>0?o.map(String).join(""):(p=t.label)!=null?p:"";return ht({id:t.id,label:c,style:t.style,value:t.value,actionType:t.actionType,callbackUrl:t.callbackUrl,disabled:t.disabled})}if(n===yt){if(!Rn(t))throw new Error("LinkButton requires a 'url' prop");let c=o.length>0?o.map(String).join(""):(h=t.label)!=null?h:"";return yt({id:t.id,url:t.url,label:c,style:t.style})}if(n===Tt){if(!Ie(t))throw new Error("CardLink requires a 'url' prop");let c=o.length>0?o.map(String).join(""):(l=t.label)!=null?l:"";return Tt({url:t.url,label:c})}if(n===ct){if(!xn(t))throw new Error("Image requires a 'url' prop");return ct({url:t.url,alt:t.alt})}if(n===gt){if(!_n(t))throw new Error("Field requires 'label' and 'value' props");return gt({label:t.label,value:t.value})}if(n===dt)return dt();if(n===wt){if(!In(t))throw new Error("Modal requires 'callbackId' and 'title' props");return wt({callbackId:t.callbackId,callbackUrl:t.callbackUrl,title:t.title,submitLabel:t.submitLabel,closeLabel:t.closeLabel,notifyOnClose:t.notifyOnClose,privateMetadata:t.privateMetadata,children:An(o)})}if(n===At){if(!En(t))throw new Error("TextInput requires 'id' and 'label' props");return At({id:t.id,label:t.label,placeholder:t.placeholder,initialValue:t.initialValue,multiline:t.multiline,optional:t.optional,maxLength:t.maxLength})}if(n===St){if(!_t(t))throw new Error("Select requires 'id' and 'label' props");return St({id:t.id,label:t.label,placeholder:t.placeholder,initialOption:t.initialOption,optional:t.optional,options:o})}if(n===vt){if(!Pn(t))throw new Error("ExternalSelect requires 'id' and 'label' props");return vt({id:t.id,initialOption:t.initialOption,label:t.label,placeholder:t.placeholder,minQueryLength:t.minQueryLength,optional:t.optional})}if(n===xt){if(!_t(t))throw new Error("RadioSelect requires 'id' and 'label' props");return xt({id:t.id,label:t.label,initialOption:t.initialOption,optional:t.optional,options:o})}if(n===Rt){if(!Cn(t))throw new Error("SelectOption requires 'label' and 'value' props");return Rt({label:t.label,value:t.value,description:t.description})}if(n===bt){let c=t;return bt({headers:c.headers,rows:c.rows})}let a=On(t)?t:{};return bn({title:a.title,subtitle:a.subtitle,imageUrl:a.imageUrl,children:o})}function Pe(e,n,t){let{children:i,...o}=n;return{$$typeof:_e,type:e,props:o,children:i!=null?[i]:[]}}function Ot(e,n,t){let{children:i,...o}=n,a;return Array.isArray(i)?a=i:i!=null?a=[i]:a=[],{$$typeof:_e,type:e,props:o,children:a}}function Et(e){return Oe(e.children)}function Pt(e){if(Y(e)){let n=Ee(e);if(n&&typeof n=="object"&&"type"in n&&n.type==="card")return n}return typeof e=="object"&&e!==null&&"type"in e&&e.type==="card"?e:null}function Ct(e){if(Y(e)){let n=Ee(e);if(n&&typeof n=="object"&&"type"in n&&n.type==="modal")return n}return wn(e)?e:null}function Nt(e){if(Y(e))return!0;if(typeof e=="object"&&e!==null&&"$$typeof"in e&&typeof e.$$typeof=="symbol"){let n=e.$$typeof.toString();return n.includes("react.element")||n.includes("react.transitional.element")}return!1}var Tn,_e,It,kt=De(()=>{"use strict";Tn=["text_input","select","external_select","radio_select","text","fields"];_e=Symbol.for("chat.jsx.element");It=Pe});var Dt={};Me(Dt,{Fragment:()=>Et,isCardLinkProps:()=>Ie,isJSX:()=>Nt,jsx:()=>Pe,jsxDEV:()=>It,jsxs:()=>Ot,toCardElement:()=>Pt,toModalElement:()=>Ct});var Mt=De(()=>{"use strict";kt()});var si={};Me(si,{ActionStepEnum:()=>$e,AgentContextImpl:()=>V,AgentEventEnum:()=>xe,BadRequestError:()=>y,BridgeError:()=>W,ChannelStepEnum:()=>Be,ConflictError:()=>I,CronExpression:()=>Ve,ErrorCodeEnum:()=>g,ExecutionEventControlsInvalidError:()=>z,ExecutionEventPayloadInvalidError:()=>G,ExecutionProviderOutputInvalidError:()=>Z,ExecutionStateControlsInvalidError:()=>X,ExecutionStateCorruptError:()=>J,ExecutionStateOutputInvalidError:()=>K,ExecutionStateResultInvalidError:()=>H,FILTER_VALIDATORS:()=>mn,ForbiddenError:()=>$,FrameworkError:()=>f,GetActionEnum:()=>je,HttpHeaderKeysEnum:()=>B,HttpMethodEnum:()=>D,HttpQueryKeysEnum:()=>qe,HttpStatusEnum:()=>x,InvalidActionError:()=>ie,JobStatusEnum:()=>Zt,MethodNotAllowedError:()=>ne,MissingSecretKeyError:()=>oe,NotFoundError:()=>O,NovuApiEndpointsEnum:()=>Ye,PlatformError:()=>re,PostActionEnum:()=>Fe,ProviderExecutionFailedError:()=>ae,ProviderNotFoundError:()=>se,ResourceConflictError:()=>v,ResourceEnum:()=>_,ResourceExecutionFailed:()=>R,ResourceNotFoundError:()=>T,SIGNATURE_TIMESTAMP_TOLERANCE:()=>un,SIGNATURE_TIMESTAMP_TOLERANCE_MINUTES:()=>q,ServerError:()=>S,SeverityLevelEnum:()=>en,SignatureExpiredError:()=>de,SignatureInvalidError:()=>ce,SignatureMismatchError:()=>le,SignatureNotFoundError:()=>pe,SignatureVersionInvalidError:()=>me,SigningKeyNotFoundError:()=>ue,StepAlreadyExistsError:()=>ye,StepControlCompilationFailedError:()=>Q,StepExecutionFailedError:()=>ge,StepNotFoundError:()=>he,UnauthorizedError:()=>b,WorkflowAlreadyExistsError:()=>be,WorkflowChannelEnum:()=>We,WorkflowNotFoundError:()=>fe,WorkflowPayloadInvalidError:()=>ee,actionStepSchemas:()=>$t,buildApprovalActionId:()=>E,channelStepSchemas:()=>Qt,createLiquidEngine:()=>on,digest:()=>Te,isFrameworkError:()=>Ge,isNativeError:()=>Je,parseApprovalActionId:()=>at,pluralize:()=>we,toSentence:()=>Se,toSentenceArgsValidator:()=>ve});module.exports=dn(si);var Fe=(o=>(o.TRIGGER="trigger",o.EXECUTE="execute",o.PREVIEW="preview",o.AGENT_EVENT="agent-event",o))(Fe||{}),je=(i=>(i.DISCOVER="discover",i.HEALTH_CHECK="health-check",i.CODE="code",i))(je||{});var Ye=(t=>(t.SYNC="/v1/bridge/sync",t.DIFF="/v1/bridge/diff",t))(Ye||{}),q=5,un=3e5;var Ve=(s=>(s.EVERY_SECOND="* * * * * *",s.EVERY_5_SECONDS="*/5 * * * * *",s.EVERY_10_SECONDS="*/10 * * * * *",s.EVERY_30_SECONDS="*/30 * * * * *",s.EVERY_MINUTE="*/1 * * * *",s.EVERY_5_MINUTES="0 */5 * * * *",s.EVERY_10_MINUTES="0 */10 * * * *",s.EVERY_30_MINUTES="0 */30 * * * *",s.EVERY_HOUR="0 0-23/1 * * *",s.EVERY_2_HOURS="0 0-23/2 * * *",s.EVERY_3_HOURS="0 0-23/3 * * *",s.EVERY_4_HOURS="0 0-23/4 * * *",s.EVERY_5_HOURS="0 0-23/5 * * *",s.EVERY_6_HOURS="0 0-23/6 * * *",s.EVERY_7_HOURS="0 0-23/7 * * *",s.EVERY_8_HOURS="0 0-23/8 * * *",s.EVERY_9_HOURS="0 0-23/9 * * *",s.EVERY_10_HOURS="0 0-23/10 * * *",s.EVERY_11_HOURS="0 0-23/11 * * *",s.EVERY_12_HOURS="0 0-23/12 * * *",s.EVERY_DAY_AT_1AM="0 01 * * *",s.EVERY_DAY_AT_2AM="0 02 * * *",s.EVERY_DAY_AT_3AM="0 03 * * *",s.EVERY_DAY_AT_4AM="0 04 * * *",s.EVERY_DAY_AT_5AM="0 05 * * *",s.EVERY_DAY_AT_6AM="0 06 * * *",s.EVERY_DAY_AT_7AM="0 07 * * *",s.EVERY_DAY_AT_8AM="0 08 * * *",s.EVERY_DAY_AT_9AM="0 09 * * *",s.EVERY_DAY_AT_10AM="0 10 * * *",s.EVERY_DAY_AT_11AM="0 11 * * *",s.EVERY_DAY_AT_NOON="0 12 * * *",s.EVERY_DAY_AT_1PM="0 13 * * *",s.EVERY_DAY_AT_2PM="0 14 * * *",s.EVERY_DAY_AT_3PM="0 15 * * *",s.EVERY_DAY_AT_4PM="0 16 * * *",s.EVERY_DAY_AT_5PM="0 17 * * *",s.EVERY_DAY_AT_6PM="0 18 * * *",s.EVERY_DAY_AT_7PM="0 19 * * *",s.EVERY_DAY_AT_8PM="0 20 * * *",s.EVERY_DAY_AT_9PM="0 21 * * *",s.EVERY_DAY_AT_10PM="0 22 * * *",s.EVERY_DAY_AT_11PM="0 23 * * *",s.EVERY_DAY_AT_MIDNIGHT="0 0 * * *",s.EVERY_WEEK="0 0 * * 0",s.EVERY_WEEKDAY="0 0 * * 1-5",s.EVERY_WEEKEND="0 0 * * 6,0",s.EVERY_1ST_DAY_OF_MONTH_AT_MIDNIGHT="0 0 1 * *",s.EVERY_1ST_DAY_OF_MONTH_AT_NOON="0 12 1 * *",s.EVERY_2ND_DAY_OF_MONTH_AT_10AM="0 10 2 * *",s.EVERY_2ND_HOUR="0 */2 * * *",s.EVERY_2ND_HOUR_FROM_1AM_THROUGH_11PM="0 1-23/2 * * *",s.EVERY_2ND_MONTH="0 0 1 */2 *",s.EVERY_QUARTER="0 0 1 */3 *",s.EVERY_6_MONTHS="0 0 1 */6 *",s.EVERY_YEAR="0 0 1 0 *",s.EVERY_30_MINUTES_BETWEEN_9AM_AND_5PM="0 */30 9-17 * * *",s.EVERY_30_MINUTES_BETWEEN_9AM_AND_6PM="0 */30 9-18 * * *",s.EVERY_30_MINUTES_BETWEEN_10AM_AND_7PM="0 */30 10-19 * * *",s.MONDAY_TO_FRIDAY_AT_1AM="0 0 01 * * 1-5",s.MONDAY_TO_FRIDAY_AT_2AM="0 0 02 * * 1-5",s.MONDAY_TO_FRIDAY_AT_3AM="0 0 03 * * 1-5",s.MONDAY_TO_FRIDAY_AT_4AM="0 0 04 * * 1-5",s.MONDAY_TO_FRIDAY_AT_5AM="0 0 05 * * 1-5",s.MONDAY_TO_FRIDAY_AT_6AM="0 0 06 * * 1-5",s.MONDAY_TO_FRIDAY_AT_7AM="0 0 07 * * 1-5",s.MONDAY_TO_FRIDAY_AT_8AM="0 0 08 * * 1-5",s.MONDAY_TO_FRIDAY_AT_9AM="0 0 09 * * 1-5",s.MONDAY_TO_FRIDAY_AT_09_30AM="0 30 09 * * 1-5",s.MONDAY_TO_FRIDAY_AT_10AM="0 0 10 * * 1-5",s.MONDAY_TO_FRIDAY_AT_11AM="0 0 11 * * 1-5",s.MONDAY_TO_FRIDAY_AT_11_30AM="0 30 11 * * 1-5",s.MONDAY_TO_FRIDAY_AT_12PM="0 0 12 * * 1-5",s.MONDAY_TO_FRIDAY_AT_1PM="0 0 13 * * 1-5",s.MONDAY_TO_FRIDAY_AT_2PM="0 0 14 * * 1-5",s.MONDAY_TO_FRIDAY_AT_3PM="0 0 15 * * 1-5",s.MONDAY_TO_FRIDAY_AT_4PM="0 0 16 * * 1-5",s.MONDAY_TO_FRIDAY_AT_5PM="0 0 17 * * 1-5",s.MONDAY_TO_FRIDAY_AT_6PM="0 0 18 * * 1-5",s.MONDAY_TO_FRIDAY_AT_7PM="0 0 19 * * 1-5",s.MONDAY_TO_FRIDAY_AT_8PM="0 0 20 * * 1-5",s.MONDAY_TO_FRIDAY_AT_9PM="0 0 21 * * 1-5",s.MONDAY_TO_FRIDAY_AT_10PM="0 0 22 * * 1-5",s.MONDAY_TO_FRIDAY_AT_11PM="0 0 23 * * 1-5",s))(Ve||{});var g=(u=>(u.BRIDGE_ERROR="BridgeError",u.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",u.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",u.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",u.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",u.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",u.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",u.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",u.INVALID_ACTION_ERROR="InvalidActionError",u.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",u.MISSING_DEPENDENCY_ERROR="MissingDependencyError",u.MISSING_SECRET_KEY_ERROR="MissingSecretKeyError",u.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",u.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",u.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",u.SIGNATURE_INVALID_ERROR="SignatureInvalidError",u.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",u.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",u.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",u.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",u.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",u.STEP_CONTROL_COMPILATION_FAILED_ERROR="StepControlCompilationFailedError",u.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",u.STEP_NOT_FOUND_ERROR="StepNotFoundError",u.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",u.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",u.WORKFLOW_PAYLOAD_INVALID_ERROR="WorkflowPayloadInvalidError",u))(g||{});var B=(m=>(m.NOVU_SIGNATURE="novu-signature",m.NOVU_ANONYMOUS="novu-anonymous",m.NOVU_FRAMEWORK_SDK="novu-framework-sdk",m.NOVU_FRAMEWORK_SERVER="novu-framework-server",m.NOVU_FRAMEWORK_VERSION="novu-framework-version",m.USER_AGENT="user-agent",m.CONTENT_TYPE="content-type",m.ACCESS_CONTROL_ALLOW_ORIGIN="access-control-allow-origin",m.ACCESS_CONTROL_ALLOW_METHODS="access-control-allow-methods",m.ACCESS_CONTROL_ALLOW_HEADERS="access-control-allow-headers",m.ACCESS_CONTROL_MAX_AGE="access-control-max-age",m.ACCESS_CONTROL_ALLOW_PRIVATE_NETWORK="access-control-allow-private-network",m))(B||{});var D=(i=>(i.POST="POST",i.GET="GET",i.OPTIONS="OPTIONS",i))(D||{});var qe=(d=>(d.WORKFLOW_ID="workflowId",d.STEP_ID="stepId",d.ACTION="action",d.SOURCE="source",d.AGENT_ID="agentId",d.EVENT="event",d))(qe||{});var x=(r=>(r[r.CONTINUE=100]="CONTINUE",r[r.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",r[r.PROCESSING=102]="PROCESSING",r[r.EARLYHINTS=103]="EARLYHINTS",r[r.OK=200]="OK",r[r.CREATED=201]="CREATED",r[r.ACCEPTED=202]="ACCEPTED",r[r.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",r[r.NO_CONTENT=204]="NO_CONTENT",r[r.RESET_CONTENT=205]="RESET_CONTENT",r[r.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",r[r.AMBIGUOUS=300]="AMBIGUOUS",r[r.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",r[r.FOUND=302]="FOUND",r[r.SEE_OTHER=303]="SEE_OTHER",r[r.NOT_MODIFIED=304]="NOT_MODIFIED",r[r.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",r[r.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",r[r.BAD_REQUEST=400]="BAD_REQUEST",r[r.UNAUTHORIZED=401]="UNAUTHORIZED",r[r.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",r[r.FORBIDDEN=403]="FORBIDDEN",r[r.NOT_FOUND=404]="NOT_FOUND",r[r.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",r[r.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",r[r.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",r[r.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",r[r.CONFLICT=409]="CONFLICT",r[r.GONE=410]="GONE",r[r.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",r[r.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",r[r.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",r[r.URI_TOO_LONG=414]="URI_TOO_LONG",r[r.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",r[r.REQUESTED_RANGE_NOT_SATISFIABLE=416]="REQUESTED_RANGE_NOT_SATISFIABLE",r[r.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",r[r.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",r[r.MISDIRECTED=421]="MISDIRECTED",r[r.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",r[r.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",r[r.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",r[r.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",r[r.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",r[r.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",r[r.BAD_GATEWAY=502]="BAD_GATEWAY",r[r.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",r[r.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",r[r.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",r))(x||{});var _=(i=>(i.WORKFLOW="workflow",i.PROVIDER="provider",i.STEP="step",i))(_||{});var Be=(a=>(a.EMAIL="email",a.SMS="sms",a.PUSH="push",a.CHAT="chat",a.IN_APP="in_app",a))(Be||{}),$e=(a=>(a.DIGEST="digest",a.DELAY="delay",a.THROTTLE="throttle",a.CUSTOM="custom",a.HTTP_REQUEST="http_request",a))($e||{});var We=(a=>(a.EMAIL="email",a.SMS="sms",a.PUSH="push",a.CHAT="chat",a.IN_APP="inApp",a))(We||{});var Je=e=>{var t,i;if(typeof e!="object"||e===null)return!1;let n=Object.getPrototypeOf(e);return(i=(t=n==null?void 0:n.constructor)==null?void 0:t.name.endsWith("Error"))!=null?i:!1},f=class extends Error{},O=class extends f{constructor(){super(...arguments);this.statusCode=404}},y=class extends f{constructor(){super(...arguments);this.statusCode=400}},b=class extends f{constructor(){super(...arguments);this.statusCode=401}},S=class extends f{constructor(n,{cause:t}={}){var i;Je(t)?(super(`${n}: ${t.message}`),this.data={stack:(i=t.stack)!=null?i:n}):(super(`${n}${t?`: ${JSON.stringify(t,null,2)}`:""}`),this.data={stack:n})}},I=class extends f{constructor(){super(...arguments);this.statusCode=409}},$=class extends f{constructor(){super(...arguments);this.statusCode=403}};var W=class extends S{constructor(t){super("Unknown BridgeError",{cause:t});this.statusCode=500;this.code="BridgeError"}};var J=class extends y{constructor(t,i){super(`Workflow with id: \`${t}\` has a corrupt state. Step with id: \`${i}\` does not exist. Please provide the missing state.`);this.code="ExecutionStateCorruptError";this.data={workflowId:t,stepId:i}}},G=class extends y{constructor(t,i){super(`Workflow with id: \`${t}\` has invalid \`payload\`. Please provide the correct event payload.`);this.code="ExecutionEventPayloadInvalidError";this.data=i}},z=class extends y{constructor(t,i){super(`Workflow with id: \`${t}\` has invalid \`controls\`. Please provide the correct event controls.`);this.code="ExecutionEventControlInvalidError";this.data=i}},X=class extends y{constructor(t,i,o){super(`Workflow with id: \`${t}\` has an invalid state. Step with id: \`${i}\` has invalid \`controls\`. Please provide the correct step controls.`);this.code="ExecutionStateControlInvalidError";this.data=o}},K=class extends y{constructor(t,i,o){super(`Workflow with id: \`${t}\` has an invalid state. Step with id: \`${i}\` has invalid output. Please provide the correct step output.`);this.code="ExecutionStateOutputInvalidError";this.data=o}},H=class extends y{constructor(t,i,o){super(`Workflow with id: \`${t}\` has an invalid state. Step with id: \`${i}\` has invalid result. Please provide the correct step result.`);this.code="ExecutionStateResultInvalidError";this.data=o}},Q=class extends y{constructor(t,i,o){super(`Workflow with id: \`${t}\` has invalid controls syntax in step with id: \`${i}\`. Please correct step control syntax.`);this.code="StepControlCompilationFailedError";this.data=o}},Z=class extends y{constructor(t,i,o,a){super(`Workflow with id: \`${t}\` has an invalid state. Step with id: \`${i}\` and provider with id: \`${o}\` has invalid output. Please provide the correct provider output.`);this.code="ExecutionProviderOutputInvalidError";this.data=a}},ee=class extends y{constructor(t,i){super(`Workflow with id: \`${t}\` has invalid \`payload\`. Please provide the correct payload.`);this.code="WorkflowPayloadInvalidError";this.data=i}};var Ge=e=>Object.values(g).includes(e==null?void 0:e.code);var te=e=>Object.values(e).map(n=>`\`${n}\``).join(", "),M=e=>e.replaceAll(/(\w)(\w*)/g,(n,t,i)=>t.toUpperCase()+i.toLowerCase()).replaceAll(/[\s-]+/g,"");var ne=class extends f{constructor(){super(...arguments);this.code="MethodNotAllowedError";this.statusCode=405;this.message=`Method not allowed. Please use one of ${te(D)}`}},ie=class extends y{constructor(t,i){super(`Invalid query string: \`action\`=\`${t}\`. Please use one of ${te(i)}`);this.code="InvalidActionError"}},oe=class extends y{constructor(){super("Missing secret key. Set the `NOVU_SECRET_KEY` environment variable or pass `secretKey` to the client options.");this.code="MissingSecretKeyError"}};var re=class extends Error{constructor(n,t,i){super(),this.data={message:i},this.statusCode=n,this.code=t}};var v=class extends I{constructor(n,t){super(`${M(n)} with id: \`${t}\` already exists. Please use a different id.`)}},T=class extends O{constructor(n,t){super(`${M(n)} with id: \`${t}\` does not exist. Please provide a valid id.`)}},R=class extends S{constructor(t,i,o,a){super(`Failed to ${o} ${M(t)} with id: \`${i}\``,{cause:a});this.statusCode=502}};var se=class extends T{constructor(t){super("provider",t);this.code="ProviderNotFoundError"}},ae=class extends R{constructor(t,i,o){super("provider",t,i,o);this.code="ProviderExecutionFailedError"}};var le=class extends b{constructor(){super("Signature does not match the expected signature. Please ensure the signature provided in the `novu-signature` header is correct and try again.");this.code="SignatureMismatchError"}},pe=class extends b{constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");this.code="SignatureNotFoundError"}},ce=class extends b{constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");this.code="SignatureInvalidError"}},de=class extends b{constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);this.code="SignatureExpiredError"}},ue=class extends b{constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.secretKey`");this.code="SigningKeyNotFoundError"}},me=class extends b{constructor(){super("Signature version is invalid. Please provide a signature version with version `v1` in the `novu-signature` header");this.code="SignatureVersionInvalidError"}};var he=class extends T{constructor(t){super("step",t);this.code="StepNotFoundError"}},ye=class extends v{constructor(t){super("step",t);this.code="StepAlreadyExistsError"}},ge=class extends R{constructor(t,i,o){super("step",t,i,o);this.code="StepExecutionFailedError"}};var fe=class extends T{constructor(t){super("workflow",t);this.code="WorkflowNotFoundError"}},be=class extends v{constructor(t){super("workflow",t);this.code="WorkflowAlreadyExistsError"}};function U(e,n){let t=n.split(".").reduce((i,o)=>{if(i&&typeof i=="object")return i[o]},e);if(t==null)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);if(typeof t=="object"){let i=JSON.stringify(t);return i==="{}"?"":i}return""}function Te(e,n=2,t,i=", "){if(!Array.isArray(e)||e.length===0)return"";let o=t?e.map(p=>typeof p!="object"||!p?"":U(p,t)):e;if(o.length===1)return o[0];if(o.length===2)return`${o[0]} and ${o[1]}`;if(o.length===3&&n>=3)return`${o[0]}, ${i}${o[1]} and ${o[2]}`;let a=o.slice(0,n),d=o.length-n;return`${a.join(i)} and ${d} ${d===1?"other":"others"}`}var ze=Le(require("pluralize"),1);function we(e,n="",t="",i="true"){if(e==null)return"";let o=0;if(Array.isArray(e)?o=e.length:typeof e=="object"?o=Object.keys(e).length:typeof e=="string"?o=+e:typeof e=="number"?o=e:o=Number(e),Number.isNaN(o)&&(o=0),o<=0)return"";let a;return t?a=o===1?n:t:a=(0,ze.default)(n,o),i==="true"?`${o} ${a}`:a}var Ae=require("liquidjs"),Ke=Le(require("pluralize"),1),w=require("zod");var He="",Qe=2,Ze="other",et=", ",tt=" and ",nt=", and ",Xe={0:"keyPath",1:"limit",2:"overflowSuffix",3:"wordsConnector",4:"twoWordsConnector",5:"lastWordConnector"};function Se(e,n=He,t=Qe,i=Ze,o=et,a=tt,d=nt){if(!Array.isArray(e)||e.length===0)return"";let p=n?e.map(m=>typeof m!="object"||!m?"":U(m,n)):e,h=p.length;if(h===1)return p[0];if(h===2)return`${p[0]}${a}${p[1]}`;if(t>=h){let m=p.slice(0,h-1),ke=p[h-1];return`${m.join(o)}${d}${ke}`}let l=p.slice(0,t),c=h-t,A=t===1?a:d;return`${l.join(o)}${A}${c} ${(0,Ke.default)(i,c)}`}function ve(e={},...n){let{requireKeyPath:t=!1}=e,i=[];if(n.length<1)return i.push({message:"Expected at least 1 argument",begin:0,end:0,value:""}),i;let o=w.z.object({keyPath:t?w.z.string().min(1,"must be non-empty"):w.z.string().optional().default(He),limit:w.z.number().optional().default(Qe).refine(p=>p>=0,"must be greater than or equal to 0"),overflowSuffix:w.z.string().optional().default(Ze),wordsConnector:w.z.string().optional().default(et),twoWordsConnector:w.z.string().optional().default(tt),lastWordConnector:w.z.string().optional().default(nt)}),a={};n.forEach((p,h)=>{if(!Array.isArray(p)){let l=p.getText();(p.kind===Ae.TokenKind.Quoted||p.kind===Ae.TokenKind.Number)&&(l=p.content);let c=Xe[h];a[c]=l}});let d=o.safeParse(a);if(!d.success)for(let p of d.error.issues){let h="string";"type"in p&&(h=p.type);let l=p.path[0],c=Object.entries(Xe).find(([ke,rn])=>rn===l),A=c?parseInt(c[0],10):null,m=typeof A=="number"?n[A]:null;m&&!Array.isArray(m)&&i.push({message:`"toSentence" expects a ${h}${p.message?` that ${p.message}`:""} for argument "${l}"`,begin:m.begin,end:m.end,value:m.getText()})}return i}var mn={toSentence:ve};var hn={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 L(e){return typeof e=="string"&&e.trim()?e:!e||typeof e!="object"?null:L(e.message)}function yn(e){if(!e)return null;let n;try{n=JSON.parse(e)}catch{return null}if(!n||typeof n!="object")return null;let t=n,i=L(t.message);if(i)return i;let o=L(t.error);if(o)return o;let a=t.errors;return Array.isArray(a)?L(a[0]):null}function gn(e,n){var o;let t=(o=hn[e])!=null?o:e,i=yn(n);return i?`Delivery failed: ${t}: ${i}`:`Delivery failed: ${t}`}var Re=class extends Error{constructor(n,t){super(n),this.name="AgentError",this.cause=t==null?void 0:t.cause,this.delivery=t==null?void 0:t.delivery}},F=class extends Re{constructor(n,t){let i={statusCode:n,responseBody:t};super(gn(n,t),{delivery:i}),this.name="AgentDeliveryError",this.statusCode=n,this.responseBody=t}};var it=Symbol.for("novu.agent.runtimeContext");var xe=(o=>(o.ON_MESSAGE="onMessage",o.ON_ACTION="onAction",o.ON_RESOLVE="onResolve",o.ON_REACTION="onReaction",o))(xe||{}),j=class{constructor(){this.__novuPendingApproval=!0}};function ot(e){return"type"in e&&e.type==="card"}function rt(e){return typeof e=="object"&&e!==null&&e.type==="tool-approval-card"}var st="tool-approval";function fn(e){return e==="approve"||e==="deny"}function E(e,n){return`${st}:${e}:${n}`}function at(e){let[n,t,...i]=(e!=null?e:"").split(":"),o=i.join(":");return n!==st||!fn(t)||!o?null:{approved:t==="approve",approvalId:o}}async function lt(e,n,t,i){var l,c;let o=i!=null?i:n.id,a={approve:E("approve",o),deny:E("deny",o)},d=A=>({type:"tool-approval-card",...A}),p=(c=(l=t==null?void 0:t.renderApproval)==null?void 0:l.call(t,{toolCall:n,actionIds:a,approvalCard:d}))!=null?c:d(),h={approvalId:o,toolCallId:n.id,name:n.name,input:n.input};if(e.emitToolApprovalRequest(h),rt(p)){await e.replyApprovalCard(p);return}await e.reply(p)}var Nn=5*1024*1024,kn=5*1024*1024,Ut=32768,Dn=/^[A-Za-z0-9+/]*={0,2}$/;function N(e,n){return e.filename?`"${e.filename}"`:`at index ${n}`}function Ft(){return globalThis.Buffer}function Mn(e){var n,t,i;return(i=(t=(n=Ft())==null?void 0:n.isBuffer)==null?void 0:t.call(n,e))!=null?i:!1}function Un(e){return typeof Blob!="undefined"&&e instanceof Blob}function Ce(e){let n=Ft();if(n)return n.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 t="";for(let i=0;i<e.length;i+=Ut){let o=e.subarray(i,i+Ut);t+=String.fromCharCode(...o)}return btoa(t)}function jt(e){let n=e.replace(/\s/g,""),t=n.length%4;if(!n||t===1||!Dn.test(n))return null;let i=n.endsWith("==")?2:n.endsWith("=")?1:0;return Math.floor(n.length*3/4)-i}function P(e,n,t){if(e>Nn)throw new Error(`Invalid file ${N(n,t)}: inline data must be 5 MB or smaller. Use a publicly-accessible URL for larger files.`)}async function Ln(e,n,t){if(typeof e=="string"){let i=jt(e);if(i===null)throw new Error(`Invalid file ${N(n,t)}: data must be a base64-encoded string.`);return P(i,n,t),e}if(Mn(e))return P(e.byteLength,n,t),e.toString("base64");if(e instanceof Uint8Array)return P(e.byteLength,n,t),Ce(e);if(e instanceof ArrayBuffer)return P(e.byteLength,n,t),Ce(new Uint8Array(e));if(Un(e))return P(e.size,n,t),Ce(new Uint8Array(await e.arrayBuffer()));throw new Error(`Invalid file ${N(n,t)}: data must be a base64 string, Buffer, Uint8Array, ArrayBuffer, or Blob.`)}async function Fn(e){if(!(e!=null&&e.length))return;let n=[],t=0;for(let[i,o]of e.entries()){let a=o.data,d=o.url,p=a!=null,h=d!=null;if(p===h)throw new Error(`Invalid file ${N(o,i)}: provide exactly one of data or url.`);if(p){let l=await Ln(a,o,i),c=jt(l);if(t+=c!=null?c:0,t>kn)throw new Error("Invalid files: total inline data must be 5 MB or smaller. Use publicly-accessible URLs for larger files.");n.push({...o,data:l});continue}if(h&&typeof d!="string")throw new Error(`Invalid file ${N(o,i)}: url must be a string.`);n.push(o)}return n}async function Yt(e,n){let t=await Fn(n);if(typeof e=="string")return t?{markdown:e,files:t}:{markdown:e};let{isJSX:i,toCardElement:o}=await Promise.resolve().then(()=>(Mt(),Dt));if(i(e)){let a=o(e);if(a)return t?{card:a,files:t}:{card:a}}if(ot(e))return t?{card:e,files:t}:{card:e};throw new Error("Invalid message content \u2014 expected string or CardElement")}var C=class{constructor(n,t,i,o,a){this.conversationId=i;this.integrationIdentifier=o;this.poster=a;this.editedByHandler=!1;this.messageId=n,this.platformThreadId=t}async edit(n,t){this.editedByHandler=!0;let i=await this.poster.post({conversationId:this.conversationId,integrationIdentifier:this.integrationIdentifier,edit:{messageId:this.messageId,content:await Yt(n,t==null?void 0:t.files)}});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.poster.post({conversationId:this.conversationId,integrationIdentifier:this.integrationIdentifier,deleteMessages:[{messageId:this.messageId}]})}},Lt;Lt=it;var V=class{constructor(n,t,i){this[Lt]=!0;this._signals=[];this._toolResults=[];this._pendingToolApprovalRequest=null;this._pendingReactions=[];this._pendingDeletes=[];this._resolveSignal=null;var p,h;this.event=n.event,this.action=(p=n.action)!=null?p:null,this.message=n.message,this.reaction=n.reaction,this.conversation=n.conversation,this.subscriber=n.subscriber,this.history=n.history,this.platform=n.platform,this.platformContext=n.platformContext,this._replyUrl=n.replyUrl,this._conversationId=n.conversationId,this._integrationIdentifier=n.integrationIdentifier,this._secretKey=t,this._poster={post:l=>this._post(l)},this._toolApprovalConfig=i,this._metadataState={...(h=n.conversation.metadata)!=null?h:{}};let o=this;this.metadata={get(l){return o._metadataState[l]},set(l,c){o._metadataState[l]=c,o._signals.push({type:"metadata",action:"set",key:l,value:c})},delete(l){delete o._metadataState[l],o._signals.push({type:"metadata",action:"delete",key:l})},clear(){o._metadataState={},o._signals.push({type:"metadata",action:"clear"})},get current(){return{...o._metadataState}}};let a=l=>this._post({conversationId:this._conversationId,integrationIdentifier:this._integrationIdentifier,typing:l}).then(()=>{}),d=(l=>a(l===void 0?{}:{status:l}));d.stop=()=>a("stop"),this.typing=d,this.toolApproval={request:async l=>(await lt(this,l,this._toolApprovalConfig),new j)}}asMessageContext(){return this}async reply(n,t){let i=await Yt(n,t==null?void 0:t.files),o={conversationId:this._conversationId,integrationIdentifier:this._integrationIdentifier,reply:i};this._drainSideEffects(o);let a=await this._post(o);if(!a)throw new Error("Agent reply did not return a message handle");return new C(a.messageId,a.platformThreadId,this._conversationId,this._integrationIdentifier,this._poster)}async replyApprovalCard(n){let t={conversationId:this._conversationId,integrationIdentifier:this._integrationIdentifier,reply:{toolApprovalCard:n}};this._drainSideEffects(t);let i=await this._post(t);if(!i)throw new Error("Agent approval card reply did not return a message handle");return new C(i.messageId,i.platformThreadId,this._conversationId,this._integrationIdentifier,this._poster)}createReplyHandle(n){return new C(n,"",this._conversationId,this._integrationIdentifier,this._poster)}resolve(n){this._resolveSignal={summary:n}}trigger(n,t){this._signals.push({...t,type:"trigger",workflowId:n})}emitToolApprovalRequest(n){if(this._pendingToolApprovalRequest)throw new Error("Only one tool approval request can be queued before the next reply");this._pendingToolApprovalRequest=n}emitToolResult(n){this._toolResults.push(n)}addReaction(n,t){this._pendingReactions.push({messageId:n,emojiName:t})}deleteMessage(n){this._pendingDeletes.push({messageId:n})}async reportTurnError(){try{await this._post({conversationId:this._conversationId,integrationIdentifier:this._integrationIdentifier,error:!0})}catch(n){console.error("[agent] Failed to report turn error:",n)}}async flush(){if(!this._hasPendingSideEffects())return;let n={conversationId:this._conversationId,integrationIdentifier:this._integrationIdentifier};this._drainSideEffects(n),await this._post(n)}_hasPendingSideEffects(){return!!(this._pendingToolApprovalRequest||this._signals.length||this._toolResults.length||this._resolveSignal||this._pendingReactions.length||this._pendingDeletes.length)}_drainSideEffects(n){this._pendingToolApprovalRequest&&(n.toolApprovalRequest=this._pendingToolApprovalRequest,this._pendingToolApprovalRequest=null),this._signals.length&&(n.signals=this._signals,this._signals=[]),this._toolResults.length&&(n.toolResults=this._toolResults,this._toolResults=[]),this._pendingReactions.length&&(n.addReactions=this._pendingReactions,this._pendingReactions=[]),this._pendingDeletes.length&&(n.deleteMessages=this._pendingDeletes,this._pendingDeletes=[]),this._resolveSignal&&(n.resolve=this._resolveSignal,this._resolveSignal=null)}async _post(n){let t=await fetch(this._replyUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${this._secretKey}`},body:JSON.stringify(n)});if(!t.ok){let o=await t.text().catch(()=>"");throw new F(t.status,o)}let i=await t.text().catch(()=>"");if(!i)return null;try{let o=JSON.parse(i),a=o&&typeof o=="object"&&"data"in o?o.data:o;if(a&&typeof a.messageId=="string"&&typeof a.platformThreadId=="string")return{messageId:a.messageId,platformThreadId:a.platformThreadId}}catch{}return null}};var jn={type:"object",properties:{type:{enum:["regular"]},amount:{type:"number"},unit:{type:"string",enum:["seconds","minutes","hours","days","weeks","months"]},extendToSchedule:{type:"boolean"}},required:["amount","unit"],additionalProperties:!1},Yn={type:"object",properties:{type:{enum:["timed"]},cron:{type:"string"},extendToSchedule:{type:"boolean"}},required:["cron"],additionalProperties:!1},Vn={type:"object",properties:{type:{enum:["dynamic"]},dynamicKey:{type:"string"},extendToSchedule:{type:"boolean"}},required:["dynamicKey"],additionalProperties:!1},qn={oneOf:[jn,Yn,Vn]},Bn={type:"object",properties:{duration:{type:"number"}},required:["duration"],additionalProperties:!1},Vt={output:qn,result:Bn};var $n={type:"object",properties:{type:{enum:["regular"]},amount:{type:"number"},unit:{type:"string",enum:["seconds","minutes","hours","days","weeks","months"]},digestKey:{type:"string"},lookBackWindow:{type:"object",properties:{amount:{type:"number"},unit:{type:"string",enum:["seconds","minutes","hours","days","weeks","months"]}},required:["amount","unit"],additionalProperties:!1},extendToSchedule:{type:"boolean"}},required:["amount","unit"],additionalProperties:!1},Wn={type:"object",properties:{type:{enum:["timed"]},cron:{type:"string"},digestKey:{type:"string"},extendToSchedule:{type:"boolean"}},required:["cron"],additionalProperties:!1},Jn={oneOf:[$n,Wn]},Gn={type:"object",properties:{eventCount:{type:"number"},events:{type:"array",items:{type:"object",properties:{id:{type:"string"},time:{type:"string"},payload:{type:"object"}},required:["id","time","payload"],additionalProperties:!1}}},required:["events"],additionalProperties:!1},qt={output:Jn,result:Gn};var Bt={output:{type:"object",properties:{type:{type:"string",enum:["fixed","dynamic"]},amount:{type:"number"},unit:{type:"string",enum:["minutes","hours","days"]},dynamicKey:{type:"string"},threshold:{type:"number"},throttleKey:{type:"string"}},required:["type"],additionalProperties:!1},result:{type:"object",properties:{throttled:{type:"boolean",description:"Whether the workflow execution was throttled"},executionCount:{type:"number",description:"Number of executions within the throttle window"},threshold:{type:"number",description:"The throttle threshold that was applied"},windowStart:{type:"string",format:"date-time",description:"Start time of the throttle window"}},required:["throttled"],additionalProperties:!1}};var $t={delay:Vt,digest:qt,throttle:Bt};var zn={type:"object",properties:{body:{type:"string"}},required:["body"],additionalProperties:!1},Xn={type:"object",properties:{},required:[],additionalProperties:!1},Wt={output:zn,result:Xn};var Kn={type:"object",properties:{subject:{type:"string",minLength:1},body:{type:"string"},from:{type:"object",properties:{email:{type:"string"},name:{type:"string"}},additionalProperties:!1}},required:["subject","body"],additionalProperties:!1},Hn={type:"object",properties:{},required:[],additionalProperties:!1},Jt={output:Kn,result:Hn};var Qn="^(?!mailto:)(?:(https?):\\/\\/[^\\s/$.?#].[^\\s]*)|^(\\/[^\\s]*)$",zt={type:"object",properties:{url:{type:"string",pattern:Qn},target:{type:"string",enum:["_self","_blank","_parent","_top","_unfencedTop"],default:"_blank"}},if:{properties:{url:{type:"string",pattern:"^/"}}},then:{properties:{target:{default:"_self"}}},else:{properties:{target:{default:"_blank"}}},required:["url"],additionalProperties:!1},Gt={type:"object",properties:{label:{type:"string"},redirect:zt},required:["label"],additionalProperties:!1},Zn={type:"object",properties:{subject:{type:"string",minLength:1},body:{type:"string",minLength:1},avatar:{type:"string",format:"uri"},primaryAction:Gt,secondaryAction:Gt,data:{type:"object",additionalProperties:!0},redirect:zt},anyOf:[{required:["subject"]},{required:["body"]}],additionalProperties:!1},ei={type:"object",properties:{seen:{type:"boolean"},read:{type:"boolean"},lastSeenDate:{type:"string",format:"date-time",nullable:!0},lastReadDate:{type:"string",format:"date-time",nullable:!0}},required:["seen","read","lastSeenDate","lastReadDate"],additionalProperties:!1},Xt={output:Zn,result:ei};var ti={type:"object",properties:{subject:{type:"string"},body:{type:"string"}},required:["subject","body"],additionalProperties:!1},ni={type:"object",properties:{},required:[],additionalProperties:!1},Kt={output:ti,result:ni};var ii={type:"object",properties:{body:{type:"string"}},required:["body"],additionalProperties:!1},oi={type:"object",properties:{},required:[],additionalProperties:!1},Ht={output:ii,result:oi};var Qt={chat:Wt,sms:Ht,push:Kt,email:Jt,in_app:Xt};var Zt=(l=>(l.PENDING="pending",l.QUEUED="queued",l.RUNNING="running",l.COMPLETED="completed",l.FAILED="failed",l.DELAYED="delayed",l.CANCELED="canceled",l.MERGED="merged",l.SKIPPED="skipped",l))(Zt||{});var en=(o=>(o.NONE="none",o.LOW="low",o.MEDIUM="medium",o.HIGH="high",o))(en||{});var tn=require("liquidjs");function ri(e){return Array.isArray(e)||typeof e=="object"&&e!==null?nn(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 nn=(e,n=0)=>Array.isArray(e)||typeof e=="object"&&e!==null?JSON.stringify(e,null,n).replace(/"/g,"'").replace(/\n/g,"\\n"):e==null?"":String(e);function on(e){let n=new tn.Liquid({outputEscape:ri,...e});return n.registerFilter("json",(t,i)=>nn(t,i)),n.registerFilter("digest",Te),n.registerFilter("toSentence",Se),n.registerFilter("pluralize",we),n}0&&(module.exports={ActionStepEnum,AgentContextImpl,AgentEventEnum,BadRequestError,BridgeError,ChannelStepEnum,ConflictError,CronExpression,ErrorCodeEnum,ExecutionEventControlsInvalidError,ExecutionEventPayloadInvalidError,ExecutionProviderOutputInvalidError,ExecutionStateControlsInvalidError,ExecutionStateCorruptError,ExecutionStateOutputInvalidError,ExecutionStateResultInvalidError,FILTER_VALIDATORS,ForbiddenError,FrameworkError,GetActionEnum,HttpHeaderKeysEnum,HttpMethodEnum,HttpQueryKeysEnum,HttpStatusEnum,InvalidActionError,JobStatusEnum,MethodNotAllowedError,MissingSecretKeyError,NotFoundError,NovuApiEndpointsEnum,PlatformError,PostActionEnum,ProviderExecutionFailedError,ProviderNotFoundError,ResourceConflictError,ResourceEnum,ResourceExecutionFailed,ResourceNotFoundError,SIGNATURE_TIMESTAMP_TOLERANCE,SIGNATURE_TIMESTAMP_TOLERANCE_MINUTES,ServerError,SeverityLevelEnum,SignatureExpiredError,SignatureInvalidError,SignatureMismatchError,SignatureNotFoundError,SignatureVersionInvalidError,SigningKeyNotFoundError,StepAlreadyExistsError,StepControlCompilationFailedError,StepExecutionFailedError,StepNotFoundError,UnauthorizedError,WorkflowAlreadyExistsError,WorkflowChannelEnum,WorkflowNotFoundError,WorkflowPayloadInvalidError,actionStepSchemas,buildApprovalActionId,channelStepSchemas,createLiquidEngine,digest,isFrameworkError,isNativeError,parseApprovalActionId,pluralize,toSentence,toSentenceArgsValidator});
|
|
1
|
+
"use strict";var sn=Object.create;var k=Object.defineProperty;var an=Object.getOwnPropertyDescriptor;var ln=Object.getOwnPropertyNames;var pn=Object.getPrototypeOf,cn=Object.prototype.hasOwnProperty;var De=(e,n,t)=>()=>{if(t)throw t[0];try{return e&&(n=e(e=0)),n}catch(i){throw t=[i],i}};var Me=(e,n)=>{for(var t in n)k(e,t,{get:n[t],enumerable:!0})},Ue=(e,n,t,i)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of ln(n))!cn.call(e,o)&&o!==t&&k(e,o,{get:()=>n[o],enumerable:!(i=an(n,o))||i.enumerable});return e};var Le=(e,n,t)=>(t=e!=null?sn(pn(e)):{},Ue(n||!e||!e.__esModule?k(t,"default",{value:e,enumerable:!0}):t,e)),dn=e=>Ue(k({},"__esModule",{value:!0}),e);function bn(e={}){var n;return{type:"card",title:e.title,subtitle:e.subtitle,imageUrl:e.imageUrl,children:(n=e.children)!=null?n:[]}}function pt(e,n={}){return{type:"text",content:e,style:n.style}}function ct(e){return{type:"image",url:e.url,alt:e.alt}}function dt(){return{type:"divider"}}function ut(e){return{type:"section",children:e}}function mt(e){return{type:"actions",children:e}}function ht(e){return{type:"button",id:e.id,label:e.label,style:e.style,value:e.value,disabled:e.disabled,actionType:e.actionType,callbackUrl:e.callbackUrl}}function yt(e){return{type:"link-button",id:e.id,url:e.url,label:e.label,style:e.style}}function gt(e){return{type:"field",label:e.label,value:e.value}}function ft(e){return{type:"fields",children:e}}function bt(e){return{type:"table",headers:e.headers,rows:e.rows,align:e.align}}function Tt(e){return{type:"link",url:e.url,label:e.label}}function wn(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="modal"}function An(e){let n=e.filter(t=>typeof t=="object"&&t!==null&&"type"in t&&Tn.includes(t.type));return n.length<e.length&&console.warn("[chat] Modal contains unsupported child elements that were ignored"),n}function wt(e){var n;return{type:"modal",callbackId:e.callbackId,callbackUrl:e.callbackUrl,title:e.title,submitLabel:e.submitLabel,closeLabel:e.closeLabel,notifyOnClose:e.notifyOnClose,privateMetadata:e.privateMetadata,children:(n=e.children)!=null?n:[]}}function At(e){return{type:"text_input",id:e.id,label:e.label,placeholder:e.placeholder,initialValue:e.initialValue,multiline:e.multiline,optional:e.optional,maxLength:e.maxLength}}function St(e){if(!e.options||e.options.length===0)throw new Error("Select requires at least one option");return{type:"select",id:e.id,label:e.label,placeholder:e.placeholder,options:e.options,initialOption:e.initialOption,optional:e.optional}}function vt(e){return{type:"external_select",id:e.id,initialOption:e.initialOption,label:e.label,placeholder:e.placeholder,minQueryLength:e.minQueryLength,optional:e.optional}}function Rt(e){return{label:e.label,value:e.value,description:e.description}}function xt(e){if(!e.options||e.options.length===0)throw new Error("RadioSelect requires at least one option");return{type:"radio_select",id:e.id,label:e.label,options:e.options,initialOption:e.initialOption,optional:e.optional}}function Y(e){return typeof e=="object"&&e!==null&&e.$$typeof===_e}function Oe(e){if(e==null)return[];if(Array.isArray(e))return e.flatMap(Oe);if(Y(e)){let n=Ee(e);return n?[n]:[]}return typeof e=="object"&&"type"in e?[e]:typeof e=="string"||typeof e=="number"?[String(e)]:[]}function Sn(e){return!("id"in e||"url"in e||"label"in e)}function vn(e){return"id"in e&&typeof e.id=="string"&&!("url"in e)}function Rn(e){return"url"in e&&typeof e.url=="string"&&!("id"in e)}function Ie(e){return"url"in e&&typeof e.url=="string"&&!("id"in e)&&!("alt"in e)&&!("style"in e)}function xn(e){return"url"in e&&typeof e.url=="string"}function _n(e){return"label"in e&&"value"in e&&typeof e.label=="string"&&typeof e.value=="string"}function On(e){return!("id"in e||"url"in e||"callbackId"in e)&&("title"in e||"subtitle"in e||"imageUrl"in e)}function In(e){return"callbackId"in e&&"title"in e}function En(e){return"id"in e&&"label"in e&&!("options"in e)&&!("value"in e)}function _t(e){return"id"in e&&"label"in e&&!("value"in e)}function Pn(e){return"id"in e&&"label"in e&&!("value"in e)&&!("children"in e)}function Cn(e){return"label"in e&&"value"in e&&!("id"in e)}function Ee(e){var d,p,h,l;let{type:n,props:t,children:i}=e,o=Oe(i);if(n===pt){let c=Sn(t)?t:{style:void 0},A=o.length>0?o.map(String).join(""):String((d=c.children)!=null?d:"");return pt(A,{style:c.style})}if(n===ut)return ut(o);if(n===mt)return mt(o);if(n===ft)return ft(o);if(n===ht){if(!vn(t))throw new Error("Button requires an 'id' prop");let c=o.length>0?o.map(String).join(""):(p=t.label)!=null?p:"";return ht({id:t.id,label:c,style:t.style,value:t.value,actionType:t.actionType,callbackUrl:t.callbackUrl,disabled:t.disabled})}if(n===yt){if(!Rn(t))throw new Error("LinkButton requires a 'url' prop");let c=o.length>0?o.map(String).join(""):(h=t.label)!=null?h:"";return yt({id:t.id,url:t.url,label:c,style:t.style})}if(n===Tt){if(!Ie(t))throw new Error("CardLink requires a 'url' prop");let c=o.length>0?o.map(String).join(""):(l=t.label)!=null?l:"";return Tt({url:t.url,label:c})}if(n===ct){if(!xn(t))throw new Error("Image requires a 'url' prop");return ct({url:t.url,alt:t.alt})}if(n===gt){if(!_n(t))throw new Error("Field requires 'label' and 'value' props");return gt({label:t.label,value:t.value})}if(n===dt)return dt();if(n===wt){if(!In(t))throw new Error("Modal requires 'callbackId' and 'title' props");return wt({callbackId:t.callbackId,callbackUrl:t.callbackUrl,title:t.title,submitLabel:t.submitLabel,closeLabel:t.closeLabel,notifyOnClose:t.notifyOnClose,privateMetadata:t.privateMetadata,children:An(o)})}if(n===At){if(!En(t))throw new Error("TextInput requires 'id' and 'label' props");return At({id:t.id,label:t.label,placeholder:t.placeholder,initialValue:t.initialValue,multiline:t.multiline,optional:t.optional,maxLength:t.maxLength})}if(n===St){if(!_t(t))throw new Error("Select requires 'id' and 'label' props");return St({id:t.id,label:t.label,placeholder:t.placeholder,initialOption:t.initialOption,optional:t.optional,options:o})}if(n===vt){if(!Pn(t))throw new Error("ExternalSelect requires 'id' and 'label' props");return vt({id:t.id,initialOption:t.initialOption,label:t.label,placeholder:t.placeholder,minQueryLength:t.minQueryLength,optional:t.optional})}if(n===xt){if(!_t(t))throw new Error("RadioSelect requires 'id' and 'label' props");return xt({id:t.id,label:t.label,initialOption:t.initialOption,optional:t.optional,options:o})}if(n===Rt){if(!Cn(t))throw new Error("SelectOption requires 'label' and 'value' props");return Rt({label:t.label,value:t.value,description:t.description})}if(n===bt){let c=t;return bt({headers:c.headers,rows:c.rows})}let a=On(t)?t:{};return bn({title:a.title,subtitle:a.subtitle,imageUrl:a.imageUrl,children:o})}function Pe(e,n,t){let{children:i,...o}=n;return{$$typeof:_e,type:e,props:o,children:i!=null?[i]:[]}}function Ot(e,n,t){let{children:i,...o}=n,a;return Array.isArray(i)?a=i:i!=null?a=[i]:a=[],{$$typeof:_e,type:e,props:o,children:a}}function Et(e){return Oe(e.children)}function Pt(e){if(Y(e)){let n=Ee(e);if(n&&typeof n=="object"&&"type"in n&&n.type==="card")return n}return typeof e=="object"&&e!==null&&"type"in e&&e.type==="card"?e:null}function Ct(e){if(Y(e)){let n=Ee(e);if(n&&typeof n=="object"&&"type"in n&&n.type==="modal")return n}return wn(e)?e:null}function Nt(e){if(Y(e))return!0;if(typeof e=="object"&&e!==null&&"$$typeof"in e&&typeof e.$$typeof=="symbol"){let n=e.$$typeof.toString();return n.includes("react.element")||n.includes("react.transitional.element")}return!1}var Tn,_e,It,kt=De(()=>{"use strict";Tn=["text_input","select","external_select","radio_select","text","fields"];_e=Symbol.for("chat.jsx.element");It=Pe});var Dt={};Me(Dt,{Fragment:()=>Et,isCardLinkProps:()=>Ie,isJSX:()=>Nt,jsx:()=>Pe,jsxDEV:()=>It,jsxs:()=>Ot,toCardElement:()=>Pt,toModalElement:()=>Ct});var Mt=De(()=>{"use strict";kt()});var si={};Me(si,{ActionStepEnum:()=>$e,AgentContextImpl:()=>V,AgentEventEnum:()=>xe,BadRequestError:()=>y,BridgeError:()=>W,ChannelStepEnum:()=>Be,ConflictError:()=>I,CronExpression:()=>Ve,ErrorCodeEnum:()=>g,ExecutionEventControlsInvalidError:()=>z,ExecutionEventPayloadInvalidError:()=>G,ExecutionProviderOutputInvalidError:()=>Z,ExecutionStateControlsInvalidError:()=>X,ExecutionStateCorruptError:()=>J,ExecutionStateOutputInvalidError:()=>K,ExecutionStateResultInvalidError:()=>H,FILTER_VALIDATORS:()=>mn,ForbiddenError:()=>$,FrameworkError:()=>f,GetActionEnum:()=>je,HttpHeaderKeysEnum:()=>B,HttpMethodEnum:()=>D,HttpQueryKeysEnum:()=>qe,HttpStatusEnum:()=>x,InvalidActionError:()=>ie,JobStatusEnum:()=>Zt,MethodNotAllowedError:()=>ne,MissingSecretKeyError:()=>oe,NotFoundError:()=>O,NovuApiEndpointsEnum:()=>Ye,PlatformError:()=>re,PostActionEnum:()=>Fe,ProviderExecutionFailedError:()=>ae,ProviderNotFoundError:()=>se,ResourceConflictError:()=>v,ResourceEnum:()=>_,ResourceExecutionFailed:()=>R,ResourceNotFoundError:()=>T,SIGNATURE_TIMESTAMP_TOLERANCE:()=>un,SIGNATURE_TIMESTAMP_TOLERANCE_MINUTES:()=>q,ServerError:()=>S,SeverityLevelEnum:()=>en,SignatureExpiredError:()=>de,SignatureInvalidError:()=>ce,SignatureMismatchError:()=>le,SignatureNotFoundError:()=>pe,SignatureVersionInvalidError:()=>me,SigningKeyNotFoundError:()=>ue,StepAlreadyExistsError:()=>ye,StepControlCompilationFailedError:()=>Q,StepExecutionFailedError:()=>ge,StepNotFoundError:()=>he,UnauthorizedError:()=>b,WorkflowAlreadyExistsError:()=>be,WorkflowChannelEnum:()=>We,WorkflowNotFoundError:()=>fe,WorkflowPayloadInvalidError:()=>ee,actionStepSchemas:()=>$t,buildApprovalActionId:()=>E,channelStepSchemas:()=>Qt,createLiquidEngine:()=>on,digest:()=>Te,isFrameworkError:()=>Ge,isNativeError:()=>Je,parseApprovalActionId:()=>at,pluralize:()=>we,toSentence:()=>Se,toSentenceArgsValidator:()=>ve});module.exports=dn(si);var Fe=(o=>(o.TRIGGER="trigger",o.EXECUTE="execute",o.PREVIEW="preview",o.AGENT_EVENT="agent-event",o))(Fe||{}),je=(i=>(i.DISCOVER="discover",i.HEALTH_CHECK="health-check",i.CODE="code",i))(je||{});var Ye=(t=>(t.SYNC="/v1/bridge/sync",t.DIFF="/v1/bridge/diff",t))(Ye||{}),q=5,un=3e5;var Ve=(s=>(s.EVERY_SECOND="* * * * * *",s.EVERY_5_SECONDS="*/5 * * * * *",s.EVERY_10_SECONDS="*/10 * * * * *",s.EVERY_30_SECONDS="*/30 * * * * *",s.EVERY_MINUTE="*/1 * * * *",s.EVERY_5_MINUTES="0 */5 * * * *",s.EVERY_10_MINUTES="0 */10 * * * *",s.EVERY_30_MINUTES="0 */30 * * * *",s.EVERY_HOUR="0 0-23/1 * * *",s.EVERY_2_HOURS="0 0-23/2 * * *",s.EVERY_3_HOURS="0 0-23/3 * * *",s.EVERY_4_HOURS="0 0-23/4 * * *",s.EVERY_5_HOURS="0 0-23/5 * * *",s.EVERY_6_HOURS="0 0-23/6 * * *",s.EVERY_7_HOURS="0 0-23/7 * * *",s.EVERY_8_HOURS="0 0-23/8 * * *",s.EVERY_9_HOURS="0 0-23/9 * * *",s.EVERY_10_HOURS="0 0-23/10 * * *",s.EVERY_11_HOURS="0 0-23/11 * * *",s.EVERY_12_HOURS="0 0-23/12 * * *",s.EVERY_DAY_AT_1AM="0 01 * * *",s.EVERY_DAY_AT_2AM="0 02 * * *",s.EVERY_DAY_AT_3AM="0 03 * * *",s.EVERY_DAY_AT_4AM="0 04 * * *",s.EVERY_DAY_AT_5AM="0 05 * * *",s.EVERY_DAY_AT_6AM="0 06 * * *",s.EVERY_DAY_AT_7AM="0 07 * * *",s.EVERY_DAY_AT_8AM="0 08 * * *",s.EVERY_DAY_AT_9AM="0 09 * * *",s.EVERY_DAY_AT_10AM="0 10 * * *",s.EVERY_DAY_AT_11AM="0 11 * * *",s.EVERY_DAY_AT_NOON="0 12 * * *",s.EVERY_DAY_AT_1PM="0 13 * * *",s.EVERY_DAY_AT_2PM="0 14 * * *",s.EVERY_DAY_AT_3PM="0 15 * * *",s.EVERY_DAY_AT_4PM="0 16 * * *",s.EVERY_DAY_AT_5PM="0 17 * * *",s.EVERY_DAY_AT_6PM="0 18 * * *",s.EVERY_DAY_AT_7PM="0 19 * * *",s.EVERY_DAY_AT_8PM="0 20 * * *",s.EVERY_DAY_AT_9PM="0 21 * * *",s.EVERY_DAY_AT_10PM="0 22 * * *",s.EVERY_DAY_AT_11PM="0 23 * * *",s.EVERY_DAY_AT_MIDNIGHT="0 0 * * *",s.EVERY_WEEK="0 0 * * 0",s.EVERY_WEEKDAY="0 0 * * 1-5",s.EVERY_WEEKEND="0 0 * * 6,0",s.EVERY_1ST_DAY_OF_MONTH_AT_MIDNIGHT="0 0 1 * *",s.EVERY_1ST_DAY_OF_MONTH_AT_NOON="0 12 1 * *",s.EVERY_2ND_DAY_OF_MONTH_AT_10AM="0 10 2 * *",s.EVERY_2ND_HOUR="0 */2 * * *",s.EVERY_2ND_HOUR_FROM_1AM_THROUGH_11PM="0 1-23/2 * * *",s.EVERY_2ND_MONTH="0 0 1 */2 *",s.EVERY_QUARTER="0 0 1 */3 *",s.EVERY_6_MONTHS="0 0 1 */6 *",s.EVERY_YEAR="0 0 1 0 *",s.EVERY_30_MINUTES_BETWEEN_9AM_AND_5PM="0 */30 9-17 * * *",s.EVERY_30_MINUTES_BETWEEN_9AM_AND_6PM="0 */30 9-18 * * *",s.EVERY_30_MINUTES_BETWEEN_10AM_AND_7PM="0 */30 10-19 * * *",s.MONDAY_TO_FRIDAY_AT_1AM="0 0 01 * * 1-5",s.MONDAY_TO_FRIDAY_AT_2AM="0 0 02 * * 1-5",s.MONDAY_TO_FRIDAY_AT_3AM="0 0 03 * * 1-5",s.MONDAY_TO_FRIDAY_AT_4AM="0 0 04 * * 1-5",s.MONDAY_TO_FRIDAY_AT_5AM="0 0 05 * * 1-5",s.MONDAY_TO_FRIDAY_AT_6AM="0 0 06 * * 1-5",s.MONDAY_TO_FRIDAY_AT_7AM="0 0 07 * * 1-5",s.MONDAY_TO_FRIDAY_AT_8AM="0 0 08 * * 1-5",s.MONDAY_TO_FRIDAY_AT_9AM="0 0 09 * * 1-5",s.MONDAY_TO_FRIDAY_AT_09_30AM="0 30 09 * * 1-5",s.MONDAY_TO_FRIDAY_AT_10AM="0 0 10 * * 1-5",s.MONDAY_TO_FRIDAY_AT_11AM="0 0 11 * * 1-5",s.MONDAY_TO_FRIDAY_AT_11_30AM="0 30 11 * * 1-5",s.MONDAY_TO_FRIDAY_AT_12PM="0 0 12 * * 1-5",s.MONDAY_TO_FRIDAY_AT_1PM="0 0 13 * * 1-5",s.MONDAY_TO_FRIDAY_AT_2PM="0 0 14 * * 1-5",s.MONDAY_TO_FRIDAY_AT_3PM="0 0 15 * * 1-5",s.MONDAY_TO_FRIDAY_AT_4PM="0 0 16 * * 1-5",s.MONDAY_TO_FRIDAY_AT_5PM="0 0 17 * * 1-5",s.MONDAY_TO_FRIDAY_AT_6PM="0 0 18 * * 1-5",s.MONDAY_TO_FRIDAY_AT_7PM="0 0 19 * * 1-5",s.MONDAY_TO_FRIDAY_AT_8PM="0 0 20 * * 1-5",s.MONDAY_TO_FRIDAY_AT_9PM="0 0 21 * * 1-5",s.MONDAY_TO_FRIDAY_AT_10PM="0 0 22 * * 1-5",s.MONDAY_TO_FRIDAY_AT_11PM="0 0 23 * * 1-5",s))(Ve||{});var g=(u=>(u.BRIDGE_ERROR="BridgeError",u.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",u.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",u.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",u.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",u.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",u.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",u.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",u.INVALID_ACTION_ERROR="InvalidActionError",u.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",u.MISSING_DEPENDENCY_ERROR="MissingDependencyError",u.MISSING_SECRET_KEY_ERROR="MissingSecretKeyError",u.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",u.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",u.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",u.SIGNATURE_INVALID_ERROR="SignatureInvalidError",u.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",u.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",u.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",u.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",u.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",u.STEP_CONTROL_COMPILATION_FAILED_ERROR="StepControlCompilationFailedError",u.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",u.STEP_NOT_FOUND_ERROR="StepNotFoundError",u.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",u.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",u.WORKFLOW_PAYLOAD_INVALID_ERROR="WorkflowPayloadInvalidError",u))(g||{});var B=(m=>(m.NOVU_SIGNATURE="novu-signature",m.NOVU_ANONYMOUS="novu-anonymous",m.NOVU_FRAMEWORK_SDK="novu-framework-sdk",m.NOVU_FRAMEWORK_SERVER="novu-framework-server",m.NOVU_FRAMEWORK_VERSION="novu-framework-version",m.USER_AGENT="user-agent",m.CONTENT_TYPE="content-type",m.ACCESS_CONTROL_ALLOW_ORIGIN="access-control-allow-origin",m.ACCESS_CONTROL_ALLOW_METHODS="access-control-allow-methods",m.ACCESS_CONTROL_ALLOW_HEADERS="access-control-allow-headers",m.ACCESS_CONTROL_MAX_AGE="access-control-max-age",m.ACCESS_CONTROL_ALLOW_PRIVATE_NETWORK="access-control-allow-private-network",m))(B||{});var D=(i=>(i.POST="POST",i.GET="GET",i.OPTIONS="OPTIONS",i))(D||{});var qe=(d=>(d.WORKFLOW_ID="workflowId",d.STEP_ID="stepId",d.ACTION="action",d.SOURCE="source",d.AGENT_ID="agentId",d.EVENT="event",d))(qe||{});var x=(r=>(r[r.CONTINUE=100]="CONTINUE",r[r.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",r[r.PROCESSING=102]="PROCESSING",r[r.EARLYHINTS=103]="EARLYHINTS",r[r.OK=200]="OK",r[r.CREATED=201]="CREATED",r[r.ACCEPTED=202]="ACCEPTED",r[r.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",r[r.NO_CONTENT=204]="NO_CONTENT",r[r.RESET_CONTENT=205]="RESET_CONTENT",r[r.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",r[r.AMBIGUOUS=300]="AMBIGUOUS",r[r.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",r[r.FOUND=302]="FOUND",r[r.SEE_OTHER=303]="SEE_OTHER",r[r.NOT_MODIFIED=304]="NOT_MODIFIED",r[r.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",r[r.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",r[r.BAD_REQUEST=400]="BAD_REQUEST",r[r.UNAUTHORIZED=401]="UNAUTHORIZED",r[r.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",r[r.FORBIDDEN=403]="FORBIDDEN",r[r.NOT_FOUND=404]="NOT_FOUND",r[r.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",r[r.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",r[r.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",r[r.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",r[r.CONFLICT=409]="CONFLICT",r[r.GONE=410]="GONE",r[r.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",r[r.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",r[r.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",r[r.URI_TOO_LONG=414]="URI_TOO_LONG",r[r.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",r[r.REQUESTED_RANGE_NOT_SATISFIABLE=416]="REQUESTED_RANGE_NOT_SATISFIABLE",r[r.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",r[r.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",r[r.MISDIRECTED=421]="MISDIRECTED",r[r.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",r[r.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",r[r.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",r[r.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",r[r.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",r[r.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",r[r.BAD_GATEWAY=502]="BAD_GATEWAY",r[r.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",r[r.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",r[r.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",r))(x||{});var _=(i=>(i.WORKFLOW="workflow",i.PROVIDER="provider",i.STEP="step",i))(_||{});var Be=(a=>(a.EMAIL="email",a.SMS="sms",a.PUSH="push",a.CHAT="chat",a.IN_APP="in_app",a))(Be||{}),$e=(a=>(a.DIGEST="digest",a.DELAY="delay",a.THROTTLE="throttle",a.CUSTOM="custom",a.HTTP_REQUEST="http_request",a))($e||{});var We=(a=>(a.EMAIL="email",a.SMS="sms",a.PUSH="push",a.CHAT="chat",a.IN_APP="inApp",a))(We||{});var Je=e=>{var t,i;if(typeof e!="object"||e===null)return!1;let n=Object.getPrototypeOf(e);return(i=(t=n==null?void 0:n.constructor)==null?void 0:t.name.endsWith("Error"))!=null?i:!1},f=class extends Error{},O=class extends f{constructor(){super(...arguments);this.statusCode=404}},y=class extends f{constructor(){super(...arguments);this.statusCode=400}},b=class extends f{constructor(){super(...arguments);this.statusCode=401}},S=class extends f{constructor(n,{cause:t}={}){var i;Je(t)?(super(`${n}: ${t.message}`),this.data={stack:(i=t.stack)!=null?i:n}):(super(`${n}${t?`: ${JSON.stringify(t,null,2)}`:""}`),this.data={stack:n})}},I=class extends f{constructor(){super(...arguments);this.statusCode=409}},$=class extends f{constructor(){super(...arguments);this.statusCode=403}};var W=class extends S{constructor(t){super("Unknown BridgeError",{cause:t});this.statusCode=500;this.code="BridgeError"}};var J=class extends y{constructor(t,i){super(`Workflow with id: \`${t}\` has a corrupt state. Step with id: \`${i}\` does not exist. Please provide the missing state.`);this.code="ExecutionStateCorruptError";this.data={workflowId:t,stepId:i}}},G=class extends y{constructor(t,i){super(`Workflow with id: \`${t}\` has invalid \`payload\`. Please provide the correct event payload.`);this.code="ExecutionEventPayloadInvalidError";this.data=i}},z=class extends y{constructor(t,i){super(`Workflow with id: \`${t}\` has invalid \`controls\`. Please provide the correct event controls.`);this.code="ExecutionEventControlInvalidError";this.data=i}},X=class extends y{constructor(t,i,o){super(`Workflow with id: \`${t}\` has an invalid state. Step with id: \`${i}\` has invalid \`controls\`. Please provide the correct step controls.`);this.code="ExecutionStateControlInvalidError";this.data=o}},K=class extends y{constructor(t,i,o){super(`Workflow with id: \`${t}\` has an invalid state. Step with id: \`${i}\` has invalid output. Please provide the correct step output.`);this.code="ExecutionStateOutputInvalidError";this.data=o}},H=class extends y{constructor(t,i,o){super(`Workflow with id: \`${t}\` has an invalid state. Step with id: \`${i}\` has invalid result. Please provide the correct step result.`);this.code="ExecutionStateResultInvalidError";this.data=o}},Q=class extends y{constructor(t,i,o){super(`Workflow with id: \`${t}\` has invalid controls syntax in step with id: \`${i}\`. Please correct step control syntax.`);this.code="StepControlCompilationFailedError";this.data=o}},Z=class extends y{constructor(t,i,o,a){super(`Workflow with id: \`${t}\` has an invalid state. Step with id: \`${i}\` and provider with id: \`${o}\` has invalid output. Please provide the correct provider output.`);this.code="ExecutionProviderOutputInvalidError";this.data=a}},ee=class extends y{constructor(t,i){super(`Workflow with id: \`${t}\` has invalid \`payload\`. Please provide the correct payload.`);this.code="WorkflowPayloadInvalidError";this.data=i}};var Ge=e=>Object.values(g).includes(e==null?void 0:e.code);var te=e=>Object.values(e).map(n=>`\`${n}\``).join(", "),M=e=>e.replaceAll(/(\w)(\w*)/g,(n,t,i)=>t.toUpperCase()+i.toLowerCase()).replaceAll(/[\s-]+/g,"");var ne=class extends f{constructor(){super(...arguments);this.code="MethodNotAllowedError";this.statusCode=405;this.message=`Method not allowed. Please use one of ${te(D)}`}},ie=class extends y{constructor(t,i){super(`Invalid query string: \`action\`=\`${t}\`. Please use one of ${te(i)}`);this.code="InvalidActionError"}},oe=class extends y{constructor(){super("Missing secret key. Set the `NOVU_SECRET_KEY` environment variable or pass `secretKey` to the client options.");this.code="MissingSecretKeyError"}};var re=class extends Error{constructor(n,t,i){super(),this.data={message:i},this.statusCode=n,this.code=t}};var v=class extends I{constructor(n,t){super(`${M(n)} with id: \`${t}\` already exists. Please use a different id.`)}},T=class extends O{constructor(n,t){super(`${M(n)} with id: \`${t}\` does not exist. Please provide a valid id.`)}},R=class extends S{constructor(t,i,o,a){super(`Failed to ${o} ${M(t)} with id: \`${i}\``,{cause:a});this.statusCode=502}};var se=class extends T{constructor(t){super("provider",t);this.code="ProviderNotFoundError"}},ae=class extends R{constructor(t,i,o){super("provider",t,i,o);this.code="ProviderExecutionFailedError"}};var le=class extends b{constructor(){super("Signature does not match the expected signature. Please ensure the signature provided in the `novu-signature` header is correct and try again.");this.code="SignatureMismatchError"}},pe=class extends b{constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");this.code="SignatureNotFoundError"}},ce=class extends b{constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");this.code="SignatureInvalidError"}},de=class extends b{constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);this.code="SignatureExpiredError"}},ue=class extends b{constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.secretKey`");this.code="SigningKeyNotFoundError"}},me=class extends b{constructor(){super("Signature version is invalid. Please provide a signature version with version `v1` in the `novu-signature` header");this.code="SignatureVersionInvalidError"}};var he=class extends T{constructor(t){super("step",t);this.code="StepNotFoundError"}},ye=class extends v{constructor(t){super("step",t);this.code="StepAlreadyExistsError"}},ge=class extends R{constructor(t,i,o){super("step",t,i,o);this.code="StepExecutionFailedError"}};var fe=class extends T{constructor(t){super("workflow",t);this.code="WorkflowNotFoundError"}},be=class extends v{constructor(t){super("workflow",t);this.code="WorkflowAlreadyExistsError"}};function U(e,n){let t=n.split(".").reduce((i,o)=>{if(i&&typeof i=="object")return i[o]},e);if(t==null)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);if(typeof t=="object"){let i=JSON.stringify(t);return i==="{}"?"":i}return""}function Te(e,n=2,t,i=", "){if(!Array.isArray(e)||e.length===0)return"";let o=t?e.map(p=>typeof p!="object"||!p?"":U(p,t)):e;if(o.length===1)return o[0];if(o.length===2)return`${o[0]} and ${o[1]}`;if(o.length===3&&n>=3)return`${o[0]}${i}${o[1]} and ${o[2]}`;let a=o.slice(0,n),d=o.length-n;return`${a.join(i)} and ${d} ${d===1?"other":"others"}`}var ze=Le(require("pluralize"),1);function we(e,n="",t="",i="true"){if(e==null)return"";let o=0;if(Array.isArray(e)?o=e.length:typeof e=="object"?o=Object.keys(e).length:typeof e=="string"?o=+e:typeof e=="number"?o=e:o=Number(e),Number.isNaN(o)&&(o=0),o<=0)return"";let a;return t?a=o===1?n:t:a=(0,ze.default)(n,o),i==="true"?`${o} ${a}`:a}var Ae=require("liquidjs"),Ke=Le(require("pluralize"),1),w=require("zod");var He="",Qe=2,Ze="other",et=", ",tt=" and ",nt=", and ",Xe={0:"keyPath",1:"limit",2:"overflowSuffix",3:"wordsConnector",4:"twoWordsConnector",5:"lastWordConnector"};function Se(e,n=He,t=Qe,i=Ze,o=et,a=tt,d=nt){if(!Array.isArray(e)||e.length===0)return"";let p=n?e.map(m=>typeof m!="object"||!m?"":U(m,n)):e,h=p.length;if(h===1)return p[0];if(h===2)return`${p[0]}${a}${p[1]}`;if(t>=h){let m=p.slice(0,h-1),ke=p[h-1];return`${m.join(o)}${d}${ke}`}let l=p.slice(0,t),c=h-t,A=t===1?a:d;return`${l.join(o)}${A}${c} ${(0,Ke.default)(i,c)}`}function ve(e={},...n){let{requireKeyPath:t=!1}=e,i=[];if(n.length<1)return i.push({message:"Expected at least 1 argument",begin:0,end:0,value:""}),i;let o=w.z.object({keyPath:t?w.z.string().min(1,"must be non-empty"):w.z.string().optional().default(He),limit:w.z.number().optional().default(Qe).refine(p=>p>=0,"must be greater than or equal to 0"),overflowSuffix:w.z.string().optional().default(Ze),wordsConnector:w.z.string().optional().default(et),twoWordsConnector:w.z.string().optional().default(tt),lastWordConnector:w.z.string().optional().default(nt)}),a={};n.forEach((p,h)=>{if(!Array.isArray(p)){let l=p.getText();(p.kind===Ae.TokenKind.Quoted||p.kind===Ae.TokenKind.Number)&&(l=p.content);let c=Xe[h];a[c]=l}});let d=o.safeParse(a);if(!d.success)for(let p of d.error.issues){let h="string";"type"in p&&(h=p.type);let l=p.path[0],c=Object.entries(Xe).find(([ke,rn])=>rn===l),A=c?parseInt(c[0],10):null,m=typeof A=="number"?n[A]:null;m&&!Array.isArray(m)&&i.push({message:`"toSentence" expects a ${h}${p.message?` that ${p.message}`:""} for argument "${l}"`,begin:m.begin,end:m.end,value:m.getText()})}return i}var mn={toSentence:ve};var hn={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 L(e){return typeof e=="string"&&e.trim()?e:!e||typeof e!="object"?null:L(e.message)}function yn(e){if(!e)return null;let n;try{n=JSON.parse(e)}catch{return null}if(!n||typeof n!="object")return null;let t=n,i=L(t.message);if(i)return i;let o=L(t.error);if(o)return o;let a=t.errors;return Array.isArray(a)?L(a[0]):null}function gn(e,n){var o;let t=(o=hn[e])!=null?o:e,i=yn(n);return i?`Delivery failed: ${t}: ${i}`:`Delivery failed: ${t}`}var Re=class extends Error{constructor(n,t){super(n),this.name="AgentError",this.cause=t==null?void 0:t.cause,this.delivery=t==null?void 0:t.delivery}},F=class extends Re{constructor(n,t){let i={statusCode:n,responseBody:t};super(gn(n,t),{delivery:i}),this.name="AgentDeliveryError",this.statusCode=n,this.responseBody=t}};var it=Symbol.for("novu.agent.runtimeContext");var xe=(o=>(o.ON_MESSAGE="onMessage",o.ON_ACTION="onAction",o.ON_RESOLVE="onResolve",o.ON_REACTION="onReaction",o))(xe||{}),j=class{constructor(){this.__novuPendingApproval=!0}};function ot(e){return"type"in e&&e.type==="card"}function rt(e){return typeof e=="object"&&e!==null&&e.type==="tool-approval-card"}var st="tool-approval";function fn(e){return e==="approve"||e==="deny"}function E(e,n){return`${st}:${e}:${n}`}function at(e){let[n,t,...i]=(e!=null?e:"").split(":"),o=i.join(":");return n!==st||!fn(t)||!o?null:{approved:t==="approve",approvalId:o}}async function lt(e,n,t,i){var l,c;let o=i!=null?i:n.id,a={approve:E("approve",o),deny:E("deny",o)},d=A=>({type:"tool-approval-card",...A}),p=(c=(l=t==null?void 0:t.renderApproval)==null?void 0:l.call(t,{toolCall:n,actionIds:a,approvalCard:d}))!=null?c:d(),h={approvalId:o,toolCallId:n.id,name:n.name,input:n.input};if(e.emitToolApprovalRequest(h),rt(p)){await e.replyApprovalCard(p);return}await e.reply(p)}var Nn=5*1024*1024,kn=5*1024*1024,Ut=32768,Dn=/^[A-Za-z0-9+/]*={0,2}$/;function N(e,n){return e.filename?`"${e.filename}"`:`at index ${n}`}function Ft(){return globalThis.Buffer}function Mn(e){var n,t,i;return(i=(t=(n=Ft())==null?void 0:n.isBuffer)==null?void 0:t.call(n,e))!=null?i:!1}function Un(e){return typeof Blob!="undefined"&&e instanceof Blob}function Ce(e){let n=Ft();if(n)return n.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 t="";for(let i=0;i<e.length;i+=Ut){let o=e.subarray(i,i+Ut);t+=String.fromCharCode(...o)}return btoa(t)}function jt(e){let n=e.replace(/\s/g,""),t=n.length%4;if(!n||t===1||!Dn.test(n))return null;let i=n.endsWith("==")?2:n.endsWith("=")?1:0;return Math.floor(n.length*3/4)-i}function P(e,n,t){if(e>Nn)throw new Error(`Invalid file ${N(n,t)}: inline data must be 5 MB or smaller. Use a publicly-accessible URL for larger files.`)}async function Ln(e,n,t){if(typeof e=="string"){let i=jt(e);if(i===null)throw new Error(`Invalid file ${N(n,t)}: data must be a base64-encoded string.`);return P(i,n,t),e}if(Mn(e))return P(e.byteLength,n,t),e.toString("base64");if(e instanceof Uint8Array)return P(e.byteLength,n,t),Ce(e);if(e instanceof ArrayBuffer)return P(e.byteLength,n,t),Ce(new Uint8Array(e));if(Un(e))return P(e.size,n,t),Ce(new Uint8Array(await e.arrayBuffer()));throw new Error(`Invalid file ${N(n,t)}: data must be a base64 string, Buffer, Uint8Array, ArrayBuffer, or Blob.`)}async function Fn(e){if(!(e!=null&&e.length))return;let n=[],t=0;for(let[i,o]of e.entries()){let a=o.data,d=o.url,p=a!=null,h=d!=null;if(p===h)throw new Error(`Invalid file ${N(o,i)}: provide exactly one of data or url.`);if(p){let l=await Ln(a,o,i),c=jt(l);if(t+=c!=null?c:0,t>kn)throw new Error("Invalid files: total inline data must be 5 MB or smaller. Use publicly-accessible URLs for larger files.");n.push({...o,data:l});continue}if(h&&typeof d!="string")throw new Error(`Invalid file ${N(o,i)}: url must be a string.`);n.push(o)}return n}async function Yt(e,n){let t=await Fn(n);if(typeof e=="string")return t?{markdown:e,files:t}:{markdown:e};let{isJSX:i,toCardElement:o}=await Promise.resolve().then(()=>(Mt(),Dt));if(i(e)){let a=o(e);if(a)return t?{card:a,files:t}:{card:a}}if(ot(e))return t?{card:e,files:t}:{card:e};throw new Error("Invalid message content \u2014 expected string or CardElement")}var C=class{constructor(n,t,i,o,a){this.conversationId=i;this.integrationIdentifier=o;this.poster=a;this.editedByHandler=!1;this.messageId=n,this.platformThreadId=t}async edit(n,t){this.editedByHandler=!0;let i=await this.poster.post({conversationId:this.conversationId,integrationIdentifier:this.integrationIdentifier,edit:{messageId:this.messageId,content:await Yt(n,t==null?void 0:t.files)}});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.poster.post({conversationId:this.conversationId,integrationIdentifier:this.integrationIdentifier,deleteMessages:[{messageId:this.messageId}]})}},Lt;Lt=it;var V=class{constructor(n,t,i){this[Lt]=!0;this._signals=[];this._toolResults=[];this._pendingToolApprovalRequest=null;this._pendingReactions=[];this._pendingDeletes=[];this._resolveSignal=null;var p,h;this.event=n.event,this.action=(p=n.action)!=null?p:null,this.message=n.message,this.reaction=n.reaction,this.conversation=n.conversation,this.subscriber=n.subscriber,this.history=n.history,this.platform=n.platform,this.platformContext=n.platformContext,this._replyUrl=n.replyUrl,this._conversationId=n.conversationId,this._integrationIdentifier=n.integrationIdentifier,this._secretKey=t,this._poster={post:l=>this._post(l)},this._toolApprovalConfig=i,this._metadataState={...(h=n.conversation.metadata)!=null?h:{}};let o=this;this.metadata={get(l){return o._metadataState[l]},set(l,c){o._metadataState[l]=c,o._signals.push({type:"metadata",action:"set",key:l,value:c})},delete(l){delete o._metadataState[l],o._signals.push({type:"metadata",action:"delete",key:l})},clear(){o._metadataState={},o._signals.push({type:"metadata",action:"clear"})},get current(){return{...o._metadataState}}};let a=l=>this._post({conversationId:this._conversationId,integrationIdentifier:this._integrationIdentifier,typing:l}).then(()=>{}),d=(l=>a(l===void 0?{}:{status:l}));d.stop=()=>a("stop"),this.typing=d,this.toolApproval={request:async l=>(await lt(this,l,this._toolApprovalConfig),new j)}}asMessageContext(){return this}async reply(n,t){let i=await Yt(n,t==null?void 0:t.files),o={conversationId:this._conversationId,integrationIdentifier:this._integrationIdentifier,reply:i};this._drainSideEffects(o);let a=await this._post(o);if(!a)throw new Error("Agent reply did not return a message handle");return new C(a.messageId,a.platformThreadId,this._conversationId,this._integrationIdentifier,this._poster)}async replyApprovalCard(n){let t={conversationId:this._conversationId,integrationIdentifier:this._integrationIdentifier,reply:{toolApprovalCard:n}};this._drainSideEffects(t);let i=await this._post(t);if(!i)throw new Error("Agent approval card reply did not return a message handle");return new C(i.messageId,i.platformThreadId,this._conversationId,this._integrationIdentifier,this._poster)}createReplyHandle(n){return new C(n,"",this._conversationId,this._integrationIdentifier,this._poster)}resolve(n){this._resolveSignal={summary:n}}trigger(n,t){this._signals.push({...t,type:"trigger",workflowId:n})}emitToolApprovalRequest(n){if(this._pendingToolApprovalRequest)throw new Error("Only one tool approval request can be queued before the next reply");this._pendingToolApprovalRequest=n}emitToolResult(n){this._toolResults.push(n)}addReaction(n,t){this._pendingReactions.push({messageId:n,emojiName:t})}deleteMessage(n){this._pendingDeletes.push({messageId:n})}async reportTurnError(){try{await this._post({conversationId:this._conversationId,integrationIdentifier:this._integrationIdentifier,error:!0})}catch(n){console.error("[agent] Failed to report turn error:",n)}}async flush(){if(!this._hasPendingSideEffects())return;let n={conversationId:this._conversationId,integrationIdentifier:this._integrationIdentifier};this._drainSideEffects(n),await this._post(n)}_hasPendingSideEffects(){return!!(this._pendingToolApprovalRequest||this._signals.length||this._toolResults.length||this._resolveSignal||this._pendingReactions.length||this._pendingDeletes.length)}_drainSideEffects(n){this._pendingToolApprovalRequest&&(n.toolApprovalRequest=this._pendingToolApprovalRequest,this._pendingToolApprovalRequest=null),this._signals.length&&(n.signals=this._signals,this._signals=[]),this._toolResults.length&&(n.toolResults=this._toolResults,this._toolResults=[]),this._pendingReactions.length&&(n.addReactions=this._pendingReactions,this._pendingReactions=[]),this._pendingDeletes.length&&(n.deleteMessages=this._pendingDeletes,this._pendingDeletes=[]),this._resolveSignal&&(n.resolve=this._resolveSignal,this._resolveSignal=null)}async _post(n){let t=await fetch(this._replyUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${this._secretKey}`},body:JSON.stringify(n)});if(!t.ok){let o=await t.text().catch(()=>"");throw new F(t.status,o)}let i=await t.text().catch(()=>"");if(!i)return null;try{let o=JSON.parse(i),a=o&&typeof o=="object"&&"data"in o?o.data:o;if(a&&typeof a.messageId=="string"&&typeof a.platformThreadId=="string")return{messageId:a.messageId,platformThreadId:a.platformThreadId}}catch{}return null}};var jn={type:"object",properties:{type:{enum:["regular"]},amount:{type:"number"},unit:{type:"string",enum:["seconds","minutes","hours","days","weeks","months"]},extendToSchedule:{type:"boolean"}},required:["amount","unit"],additionalProperties:!1},Yn={type:"object",properties:{type:{enum:["timed"]},cron:{type:"string"},extendToSchedule:{type:"boolean"}},required:["cron"],additionalProperties:!1},Vn={type:"object",properties:{type:{enum:["dynamic"]},dynamicKey:{type:"string"},extendToSchedule:{type:"boolean"}},required:["dynamicKey"],additionalProperties:!1},qn={oneOf:[jn,Yn,Vn]},Bn={type:"object",properties:{duration:{type:"number"}},required:["duration"],additionalProperties:!1},Vt={output:qn,result:Bn};var $n={type:"object",properties:{type:{enum:["regular"]},amount:{type:"number"},unit:{type:"string",enum:["seconds","minutes","hours","days","weeks","months"]},digestKey:{type:"string"},lookBackWindow:{type:"object",properties:{amount:{type:"number"},unit:{type:"string",enum:["seconds","minutes","hours","days","weeks","months"]}},required:["amount","unit"],additionalProperties:!1},extendToSchedule:{type:"boolean"}},required:["amount","unit"],additionalProperties:!1},Wn={type:"object",properties:{type:{enum:["timed"]},cron:{type:"string"},digestKey:{type:"string"},extendToSchedule:{type:"boolean"}},required:["cron"],additionalProperties:!1},Jn={oneOf:[$n,Wn]},Gn={type:"object",properties:{eventCount:{type:"number"},events:{type:"array",items:{type:"object",properties:{id:{type:"string"},time:{type:"string"},payload:{type:"object"}},required:["id","time","payload"],additionalProperties:!1}}},required:["events"],additionalProperties:!1},qt={output:Jn,result:Gn};var Bt={output:{type:"object",properties:{type:{type:"string",enum:["fixed","dynamic"]},amount:{type:"number"},unit:{type:"string",enum:["minutes","hours","days"]},dynamicKey:{type:"string"},threshold:{type:"number"},throttleKey:{type:"string"}},required:["type"],additionalProperties:!1},result:{type:"object",properties:{throttled:{type:"boolean",description:"Whether the workflow execution was throttled"},executionCount:{type:"number",description:"Number of executions within the throttle window"},threshold:{type:"number",description:"The throttle threshold that was applied"},windowStart:{type:"string",format:"date-time",description:"Start time of the throttle window"}},required:["throttled"],additionalProperties:!1}};var $t={delay:Vt,digest:qt,throttle:Bt};var zn={type:"object",properties:{body:{type:"string"}},required:["body"],additionalProperties:!1},Xn={type:"object",properties:{},required:[],additionalProperties:!1},Wt={output:zn,result:Xn};var Kn={type:"object",properties:{subject:{type:"string",minLength:1},body:{type:"string"},from:{type:"object",properties:{email:{type:"string"},name:{type:"string"}},additionalProperties:!1}},required:["subject","body"],additionalProperties:!1},Hn={type:"object",properties:{},required:[],additionalProperties:!1},Jt={output:Kn,result:Hn};var Qn="^(?!mailto:)(?:(https?):\\/\\/[^\\s/$.?#].[^\\s]*)|^(\\/[^\\s]*)$",zt={type:"object",properties:{url:{type:"string",pattern:Qn},target:{type:"string",enum:["_self","_blank","_parent","_top","_unfencedTop"],default:"_blank"}},if:{properties:{url:{type:"string",pattern:"^/"}}},then:{properties:{target:{default:"_self"}}},else:{properties:{target:{default:"_blank"}}},required:["url"],additionalProperties:!1},Gt={type:"object",properties:{label:{type:"string"},redirect:zt},required:["label"],additionalProperties:!1},Zn={type:"object",properties:{subject:{type:"string",minLength:1},body:{type:"string",minLength:1},avatar:{type:"string",format:"uri"},primaryAction:Gt,secondaryAction:Gt,data:{type:"object",additionalProperties:!0},redirect:zt},anyOf:[{required:["subject"]},{required:["body"]}],additionalProperties:!1},ei={type:"object",properties:{seen:{type:"boolean"},read:{type:"boolean"},lastSeenDate:{type:"string",format:"date-time",nullable:!0},lastReadDate:{type:"string",format:"date-time",nullable:!0}},required:["seen","read","lastSeenDate","lastReadDate"],additionalProperties:!1},Xt={output:Zn,result:ei};var ti={type:"object",properties:{subject:{type:"string"},body:{type:"string"}},required:["subject","body"],additionalProperties:!1},ni={type:"object",properties:{},required:[],additionalProperties:!1},Kt={output:ti,result:ni};var ii={type:"object",properties:{body:{type:"string"}},required:["body"],additionalProperties:!1},oi={type:"object",properties:{},required:[],additionalProperties:!1},Ht={output:ii,result:oi};var Qt={chat:Wt,sms:Ht,push:Kt,email:Jt,in_app:Xt};var Zt=(l=>(l.PENDING="pending",l.QUEUED="queued",l.RUNNING="running",l.COMPLETED="completed",l.FAILED="failed",l.DELAYED="delayed",l.CANCELED="canceled",l.MERGED="merged",l.SKIPPED="skipped",l))(Zt||{});var en=(o=>(o.NONE="none",o.LOW="low",o.MEDIUM="medium",o.HIGH="high",o))(en||{});var tn=require("liquidjs");function ri(e){return Array.isArray(e)||typeof e=="object"&&e!==null?nn(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 nn=(e,n=0)=>Array.isArray(e)||typeof e=="object"&&e!==null?JSON.stringify(e,null,n).replace(/"/g,"'").replace(/\n/g,"\\n"):e==null?"":String(e);function on(e){let n=new tn.Liquid({outputEscape:ri,...e});return n.registerFilter("json",(t,i)=>nn(t,i)),n.registerFilter("digest",Te),n.registerFilter("toSentence",Se),n.registerFilter("pluralize",we),n}0&&(module.exports={ActionStepEnum,AgentContextImpl,AgentEventEnum,BadRequestError,BridgeError,ChannelStepEnum,ConflictError,CronExpression,ErrorCodeEnum,ExecutionEventControlsInvalidError,ExecutionEventPayloadInvalidError,ExecutionProviderOutputInvalidError,ExecutionStateControlsInvalidError,ExecutionStateCorruptError,ExecutionStateOutputInvalidError,ExecutionStateResultInvalidError,FILTER_VALIDATORS,ForbiddenError,FrameworkError,GetActionEnum,HttpHeaderKeysEnum,HttpMethodEnum,HttpQueryKeysEnum,HttpStatusEnum,InvalidActionError,JobStatusEnum,MethodNotAllowedError,MissingSecretKeyError,NotFoundError,NovuApiEndpointsEnum,PlatformError,PostActionEnum,ProviderExecutionFailedError,ProviderNotFoundError,ResourceConflictError,ResourceEnum,ResourceExecutionFailed,ResourceNotFoundError,SIGNATURE_TIMESTAMP_TOLERANCE,SIGNATURE_TIMESTAMP_TOLERANCE_MINUTES,ServerError,SeverityLevelEnum,SignatureExpiredError,SignatureInvalidError,SignatureMismatchError,SignatureNotFoundError,SignatureVersionInvalidError,SigningKeyNotFoundError,StepAlreadyExistsError,StepControlCompilationFailedError,StepExecutionFailedError,StepNotFoundError,UnauthorizedError,WorkflowAlreadyExistsError,WorkflowChannelEnum,WorkflowNotFoundError,WorkflowPayloadInvalidError,actionStepSchemas,buildApprovalActionId,channelStepSchemas,createLiquidEngine,digest,isFrameworkError,isNativeError,parseApprovalActionId,pluralize,toSentence,toSentenceArgsValidator});
|
|
@@ -6,7 +6,7 @@ import { Emoji } from 'chat';
|
|
|
6
6
|
import { h as AgentHandlerContext, z as ToolResult, B as ToolApprovalRequestPayload, T as ToolApprovalCard, R as ReplyHandle, m as AgentMessageContext, C as AgentEventEnum, a as AgentAction, k as AgentMessage, o as AgentReaction, e as AgentConversation, r as AgentSubscriber, j as AgentHistoryEntry, n as AgentPlatformContext, D as TypingControl, E as ToolApprovalControl, G as AgentBridgeRequest, t as ToolApprovalConfig, M as MessageContent, F as FileRef, H as AgentReplyPayload, S as SentMessageInfo, w as TriggerRecipientsPayload } from '../agent.types-Dqm2VBTO.cjs';
|
|
7
7
|
export { J as DeleteMessagePayload, K as EditPayload, L as MetadataSignal, P as ParsedApprovalAction, N as ReplyContent, O as Signal, Q as TriggerSignal, U as buildApprovalActionId, V as parseApprovalActionId } from '../agent.types-Dqm2VBTO.cjs';
|
|
8
8
|
export { a as FromSchema, F as FromSchemaUnvalidated, J as JsonSchema, S as Schema, Z as ZodSchema, b as ZodSchemaMinimal } from '../base.schema.types-BApIn9jr.cjs';
|
|
9
|
-
export { S as SupportedFrameworkName } from '../server.types-
|
|
9
|
+
export { S as SupportedFrameworkName } from '../server.types-Cc6o5eYH.cjs';
|
|
10
10
|
export { A as Awaitable, C as ConditionalPartial, D as DeepPartial, b as DeepRequired, E as Either, I as Indexable, c as PickOptional, d as PickOptionalKeys, e as PickRequired, P as PickRequiredKeys, a as Prettify } from '../util.types-DaFfsxgy.cjs';
|
|
11
11
|
export { a as ValidateFunction, V as ValidateResult, b as ValidationError, c as Validator } from '../validator.types-BeoiKdnR.cjs';
|
|
12
12
|
import 'json-schema-to-ts';
|
|
@@ -137,6 +137,15 @@ declare enum ResourceEnum {
|
|
|
137
137
|
STEP = "step"
|
|
138
138
|
}
|
|
139
139
|
|
|
140
|
+
declare const RUNTIME_CONTEXT_BRAND: unique symbol;
|
|
141
|
+
interface AgentRuntimeContext extends AgentHandlerContext {
|
|
142
|
+
readonly [RUNTIME_CONTEXT_BRAND]: true;
|
|
143
|
+
emitToolResult(result: ToolResult): void;
|
|
144
|
+
emitToolApprovalRequest(request: ToolApprovalRequestPayload): void;
|
|
145
|
+
replyApprovalCard(card: ToolApprovalCard): Promise<ReplyHandle>;
|
|
146
|
+
asMessageContext(): AgentMessageContext;
|
|
147
|
+
}
|
|
148
|
+
|
|
140
149
|
/**
|
|
141
150
|
* Check if the object is a native error.
|
|
142
151
|
*
|
|
@@ -422,15 +431,6 @@ type FilterValidators = {
|
|
|
422
431
|
};
|
|
423
432
|
declare const FILTER_VALIDATORS: FilterValidators;
|
|
424
433
|
|
|
425
|
-
declare const RUNTIME_CONTEXT_BRAND: unique symbol;
|
|
426
|
-
interface AgentRuntimeContext extends AgentHandlerContext {
|
|
427
|
-
readonly [RUNTIME_CONTEXT_BRAND]: true;
|
|
428
|
-
emitToolResult(result: ToolResult): void;
|
|
429
|
-
emitToolApprovalRequest(request: ToolApprovalRequestPayload): void;
|
|
430
|
-
replyApprovalCard(card: ToolApprovalCard): Promise<ReplyHandle>;
|
|
431
|
-
asMessageContext(): AgentMessageContext;
|
|
432
|
-
}
|
|
433
|
-
|
|
434
434
|
interface ReplyPoster {
|
|
435
435
|
post(body: AgentReplyPayload): Promise<SentMessageInfo | null>;
|
|
436
436
|
}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
type SupportedFrameworkName = 'next' | 'express' | 'nuxt' | 'h3' | 'sveltekit' | 'remix' | 'lambda' | 'nest';
|
|
1
|
+
type SupportedFrameworkName = 'next' | 'express' | 'nuxt' | 'h3' | 'hono' | 'sveltekit' | 'remix' | 'lambda' | 'nest';
|
|
2
2
|
|
|
3
3
|
export type { SupportedFrameworkName as S };
|