@novu/framework 2.0.2 → 2.0.3

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.
@@ -7,8 +7,8 @@ var le = require('ora');
7
7
  require('cross-fetch');
8
8
  var N = require('chalk');
9
9
  var shared = require('@novu/shared');
10
- var Ie = require('sanitize-html');
11
- var Ue = require('ajv');
10
+ var me = require('sanitize-html');
11
+ var ke = require('ajv');
12
12
  var Ve = require('ajv-formats');
13
13
  var zodToJsonSchema = require('zod-to-json-schema');
14
14
 
@@ -16,15 +16,15 @@ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
16
16
 
17
17
  var le__default = /*#__PURE__*/_interopDefault(le);
18
18
  var N__default = /*#__PURE__*/_interopDefault(N);
19
- var Ie__default = /*#__PURE__*/_interopDefault(Ie);
20
- var Ue__default = /*#__PURE__*/_interopDefault(Ue);
19
+ var me__default = /*#__PURE__*/_interopDefault(me);
20
+ var ke__default = /*#__PURE__*/_interopDefault(ke);
21
21
  var Ve__default = /*#__PURE__*/_interopDefault(Ve);
22
22
 
23
- var y=(r=>(r.TRIGGER="trigger",r.EXECUTE="execute",r.PREVIEW="preview",r))(y||{}),M=(r=>(r.DISCOVER="discover",r.HEALTH_CHECK="health-check",r.CODE="code",r))(M||{});var _=(c=>(c.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",c.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",c.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",c.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",c.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",c.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",c.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",c.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",c.STEP_NOT_FOUND_ERROR="StepNotFoundError",c.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",c.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",c.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",c.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",c.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",c.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",c.STEP_CONTROL_COMPILATION_FAILED_ERROR="StepControlCompilationFailedError",c.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",c.INVALID_ACTION_ERROR="InvalidActionError",c.MISSING_SECRET_KEY_ERROR="MissingSecretKeyError",c.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",c.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",c.SIGNATURE_INVALID_ERROR="SignatureInvalidError",c.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",c.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",c.BRIDGE_ERROR="BridgeError",c.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",c.WORKFLOW_PAYLOAD_INVALID_ERROR="WorkflowPayloadInvalidError",c))(_||{});var Y=(r=>(r.POST="POST",r.GET="GET",r.OPTIONS="OPTIONS",r))(Y||{});var Re=(i=>(i.EMAIL="email",i.SMS="sms",i.PUSH="push",i.CHAT="chat",i.IN_APP="in_app",i))(Re||{});var Te="2.0.2";var D=Te,F="2024-06-26";var E=class extends Error{data},C=class extends E{statusCode=404},R=class extends E{statusCode=400},m=class extends E{statusCode=401},f=class extends E{statusCode=500},L=class extends E{statusCode=409};var b=class extends R{code="ExecutionStateCorruptError";constructor(e,t){super(`Workflow with id: \`${e}\` has a corrupt state. Step with id: \`${t}\` does not exist. Please provide the missing state.`),this.data={workflowId:e,stepId:t};}},P=class extends R{code="ExecutionEventPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct event payload.`),this.data=t;}},W=class extends R{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},$=class extends R{code="ExecutionStateControlInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid \`controls\`. Please provide the correct step controls.`),this.data=r;}},G=class extends R{code="ExecutionStateOutputInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid output. Please provide the correct step output.`),this.data=r;}},j=class extends R{code="ExecutionStateResultInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid result. Please provide the correct step result.`),this.data=r;}},K=class extends R{code="StepControlCompilationFailedError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has invalid controls syntax in step with id: \`${t}\`. Please correct step control syntax.`),this.data=r;}},B=class extends R{code="ExecutionProviderOutputInvalidError";constructor(e,t,r,o){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` and provider with id: \`${r}\` has invalid output. Please provide the correct provider output.`),this.data=o;}};var X=class extends E{statusCode;data;code;constructor(e,t,r){super(),this.data={message:r},this.statusCode=e,this.code=t;}};var l={info:s=>N__default.default.blue(s),warning:s=>N__default.default.yellow(s),error:s=>N__default.default.red(s),success:s=>N__default.default.green(s),underline:s=>N__default.default.underline(s),bold:s=>N__default.default.bold(s)},p={SUCCESS:l.success("\u2714"),ERROR:l.error("\u2717"),WARNING:l.warning("\u26A0"),INFO:l.info("\u2139"),ARROW:l.bold("\u2192"),MOCK:l.info("\u25CB"),HYDRATED:l.bold(l.info("\u2192")),STEP:l.info("\u03C3"),ACTION:l.info("\u03B1"),DURATION:l.info("\u0394"),PROVIDER:l.info("\u2699"),OUTPUT:l.info("\u21E2"),INPUT:l.info("\u21E0"),WORKFLOW:l.info("\u03C9"),STATE:l.info("\u03C3"),EXECUTE:l.info("\u03B5"),PREVIEW:l.info("\u03C1")};var _e=s=>Object.values(s).map(e=>`\`${e}\``).join(", "),J=s=>s.replaceAll(/(\w)(\w*)/g,(e,t,r)=>t.toUpperCase()+r.toLowerCase()).replaceAll(/[\s-]+/g,"");var Ae=(s,e="https://api.novu.co")=>{let t=process.env.NOVU_API_URL||e;return {post:async(r,o)=>{let i=await fetch(`${t}/v1${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${s}`},body:JSON.stringify(o)}),a=await i.json();if(i.ok)return a;throw shared.checkIsResponseError(a)?new X(a.statusCode,a.error,a.message):new v("Error processing API request to Novu Cloud from Bridge application.")},delete:async r=>(await fetch(`${t}/v1${r}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${s}`}})).json()}};var Pe={allowedTags:Ie__default.default.defaults.allowedTags.concat(["style","img","html","head","body","link","meta","title"]),allowedAttributes:!1,allowVulnerableTags:!0,parseStyleAttributes:!1,parser:{lowerCaseAttributeNames:!0}},me=s=>{if(!s)return s;let e=/^<!DOCTYPE .*?>/,t=s.match(e),r=Ie__default.default(s,Pe);return t?t[0]+r:r},z=s=>Object.keys(s).reduce((e,t)=>{let r=s[t];return typeof r=="string"?e[t]=me(r):Array.isArray(r)?e[t]=r.map(o=>typeof o=="string"?me(o):typeof o=="object"?z(o):o):typeof r=="object"&&r!==null?e[t]=z(r):e[t]=r,e},{});var q=class extends E{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${_e(Y)}`},x=class extends R{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${_e(t)}`);}};var v=class extends f{code="BridgeError";message="Something went wrong. Please try again later."};var k=class extends L{constructor(e,t){super(`${J(e)} with id: \`${t}\` already exists. Please use a different id.`);}},I=class extends C{constructor(e,t){super(`${J(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},g=class extends f{constructor(e,t){super(`Failed to execute ${J(e)} with id: \`${t}\`. Please try again later.`);}};var Z=class extends I{code="ProviderNotFoundError";constructor(e){super("provider",e);}},Q=class extends g{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var H=class extends m{code="SignatureMismatchError";constructor(){super("Signature does not match the expected signature. Please ensure the signature provided in the `novu-signature` header is correct and try again.");}},ee=class extends m{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},te=class extends m{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},re=class extends m{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},oe=class extends m{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.secretKey`");}};var se=class extends I{code="StepNotFoundError";constructor(e){super("step",e);}};var U=class extends I{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},ie=class extends k{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var fe=s=>typeof structuredClone=="function"?structuredClone(s):JSON.parse(JSON.stringify(s));var ae=class{ajv;compiledSchemas;constructor(){this.ajv=new Ue__default.default({useDefaults:!0,removeAdditional:"failing"}),Ve__default.default(this.ajv),this.compiledSchemas=new Map;}canHandle(e){return typeof e=="boolean"?!1:e.type==="object"||!!e.anyOf||!!e.allOf||!!e.oneOf}async validate(e,t){let r=this.compiledSchemas.get(t);r||(r=this.ajv.compile(t),this.compiledSchemas.set(t,r));let o=fe(e);return r(o)?{success:!0,data:o}:{success:!1,errors:r.errors.map(a=>({path:a.instancePath,message:a.message}))}}transformToJsonSchema(e){return e}};var ne=class{canHandle(e){return e.safeParseAsync!==void 0}async validate(e,t){let r=t.safeParse(e);return r.success?{success:!0,data:r.data}:{success:!1,errors:r.error.errors.map(o=>({path:`/${o.path.join("/")}`,message:o.message}))}}transformToJsonSchema(e){try{return zodToJsonSchema.zodToJsonSchema(e)}catch(t){throw t?.message?.includes("Cannot find module")&&console.error("Tried to use a zod schema in @novu/framework without `zod-to-json-schema` installed. Please install it by running `npm install zod-to-json-schema`."),t}}};var ce=new ne,de=new ae,Ne=async(s,e)=>{if(ce.canHandle(s))return ce.validate(e,s);if(de.canHandle(s))return de.validate(e,s);throw new Error("Invalid schema")},ve=s=>{if(ce.canHandle(s))return ce.transformToJsonSchema(s);if(de.canHandle(s))return de.transformToJsonSchema(s);throw new Error("Invalid schema")};jsonSchemaFaker.JSONSchemaFaker.random.shuffle=function(){return ["[placeholder]"]};jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});function Fe(){return ["development",void 0].includes(process.env.NODE_ENV)}var pe=class{discoveredWorkflows=[];templateEngine=new liquidjs.Liquid;secretKey;version=D;strictAuthentication;constructor(e){let t=this.buildOptions(e);this.secretKey=t.secretKey,this.strictAuthentication=t.strictAuthentication;}buildOptions(e){let t={secretKey:void 0,strictAuthentication:!Fe()};return t.secretKey=e?.secretKey||process.env.NOVU_SECRET_KEY||process.env.NOVU_API_KEY,e?.strictAuthentication!==void 0?t.strictAuthentication=e.strictAuthentication:process.env.NOVU_STRICT_AUTHENTICATION_ENABLED!==void 0&&(t.strictAuthentication=process.env.NOVU_STRICT_AUTHENTICATION_ENABLED==="true"),t}addWorkflows(e){for(let t of e){if(this.discoveredWorkflows.some(r=>r.workflowId===t.definition.workflowId))throw new ie(t.definition.workflowId);this.discoveredWorkflows.push(t.definition);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((r,o)=>r+o.steps.length,0);return {status:"ok",sdkVersion:D,frameworkVersion:F,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(r=>r.workflowId===e);if(t)return t;throw new U(e)}getStep(e,t){let o=this.getWorkflow(e).steps.find(i=>i.stepId===t);if(o)return o;throw new se(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(ve(e))}async validate(e,t,r,o,i,a,d){let n=await Ne(t,e);if(n.success)return n.data;switch(r){case"event":this.throwInvalidEvent(o,i,n.errors);case"step":this.throwInvalidStep(a,o,i,n.errors);case"provider":this.throwInvalidProvider(a,d,o,i,n.errors);default:throw new Error(`Invalid component: '${r}'`)}}throwInvalidProvider(e,t,r,o,i){if(!e)throw new Error("stepId is required");if(!t)throw new Error("providerId is required");switch(r){case"output":throw new B(o,e,t,i);default:throw new Error(`Invalid payload type: '${r}'`)}}throwInvalidStep(e,t,r,o){if(!e)throw new Error("stepId is required");switch(t){case"output":throw new G(r,e,o);case"result":throw new j(r,e,o);case"controls":throw new $(r,e,o);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(e,t,r){switch(e){case"controls":throw new W(t,r);case"payload":throw new P(t,r);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(r,o,i)=>{let a=this.getStep(e.workflowId,r),d=await this.createStepControls(a,e),n=e.action==="preview";if(!n&&await this.shouldSkip(i?.skip,d))return r===e.stepId&&t({options:{skip:!0},outputs:{},providers:{}}),{};let O=this.previewStep.bind(this),u=this.executeStep.bind(this),T=await(n?O:u)(e,{...a,providers:a.providers.map(S=>{let V=i?.providers?.[S.type];if(!V)throw new Z(S.type);return {...S,resolve:V}}),resolve:o});return Object.values(Re).includes(a.type)&&(T={...T,outputs:z(T.outputs)}),r===e.stepId&&t({...T,options:{skip:!1}}),T.outputs}}async shouldSkip(e,t){return e?e(t):!1}async executeWorkflow(e){let o=`${e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action"} workflowId:`;console.log(`
24
- ${l.bold(l.underline(o))} '${e.workflowId}'`);let i=this.getWorkflow(e.workflowId),a=process.hrtime(),d={outputs:{},providers:{},options:{skip:!1}},n,O=new Promise(h=>{n=h;}),u=h=>{n(),d=h;},w;try{if(e.action==="execute"&&!e.payload&&!e.data)throw new P(e.workflowId,{message:"Event `payload` is required"});let h=await this.createExecutionPayload(e,i),A={...e,payload:h};await Promise.race([O,i.execute({payload:h,environment:{},input:{},controls:{},subscriber:e.subscriber,step:{email:this.executeStepFactory(A,u),sms:this.executeStepFactory(A,u),inApp:this.executeStepFactory(A,u),digest:this.executeStepFactory(A,u),delay:this.executeStepFactory(A,u),push:this.executeStepFactory(A,u),chat:this.executeStepFactory(A,u),custom:this.executeStepFactory(A,u)}})]);}catch(h){w=h;}let T=process.hrtime(a),S=T[0],V=T[1],Oe=S*1e3+V/1e6,ge=w?p.ERROR:p.SUCCESS,Se=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action";if(console.log(`${ge} ${Se} workflowId: \`${e.workflowId}\``),this.prettyPrintExecute(e,Oe,w),w)throw w;return {outputs:d.outputs,providers:d.providers,options:d.options,metadata:{status:"success",error:!1,duration:Oe}}}async createExecutionPayload(e,t){let r=e.payload||e.data;if(e.action==="preview"){let i=this.mock(t.payload.schema);r=Object.assign(i,r);}return await this.validate(r,t.payload.unknownSchema,"event","payload",e.workflowId)}prettyPrintExecute(e,t,r){let o=r?p.ERROR:p.SUCCESS,i=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action",a=r?"Failed to execute":i,d=r?l.error:l.success,n=`${o} ${a} workflowId: '${e.workflowId}`;console.log(`
23
+ var y=(r=>(r.TRIGGER="trigger",r.EXECUTE="execute",r.PREVIEW="preview",r))(y||{}),M=(r=>(r.DISCOVER="discover",r.HEALTH_CHECK="health-check",r.CODE="code",r))(M||{});var u=(c=>(c.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",c.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",c.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",c.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",c.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",c.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",c.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",c.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",c.STEP_NOT_FOUND_ERROR="StepNotFoundError",c.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",c.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",c.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",c.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",c.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",c.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",c.STEP_CONTROL_COMPILATION_FAILED_ERROR="StepControlCompilationFailedError",c.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",c.INVALID_ACTION_ERROR="InvalidActionError",c.MISSING_SECRET_KEY_ERROR="MissingSecretKeyError",c.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",c.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",c.SIGNATURE_INVALID_ERROR="SignatureInvalidError",c.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",c.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",c.BRIDGE_ERROR="BridgeError",c.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",c.WORKFLOW_PAYLOAD_INVALID_ERROR="WorkflowPayloadInvalidError",c))(u||{});var Y=(r=>(r.POST="POST",r.GET="GET",r.OPTIONS="OPTIONS",r))(Y||{});var Re=(i=>(i.EMAIL="email",i.SMS="sms",i.PUSH="push",i.CHAT="chat",i.IN_APP="in_app",i))(Re||{});var Te="2.0.3";var D=Te,F="2024-06-26";var O=class extends Error{data},L=class extends O{statusCode=404},R=class extends O{statusCode=400},I=class extends O{statusCode=401},f=class extends O{statusCode=500},C=class extends O{statusCode=409};var b=class extends R{code="ExecutionStateCorruptError";constructor(e,t){super(`Workflow with id: \`${e}\` has a corrupt state. Step with id: \`${t}\` does not exist. Please provide the missing state.`),this.data={workflowId:e,stepId:t};}},P=class extends R{code="ExecutionEventPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct event payload.`),this.data=t;}},W=class extends R{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},$=class extends R{code="ExecutionStateControlInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid \`controls\`. Please provide the correct step controls.`),this.data=r;}},G=class extends R{code="ExecutionStateOutputInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid output. Please provide the correct step output.`),this.data=r;}},j=class extends R{code="ExecutionStateResultInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid result. Please provide the correct step result.`),this.data=r;}},K=class extends R{code="StepControlCompilationFailedError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has invalid controls syntax in step with id: \`${t}\`. Please correct step control syntax.`),this.data=r;}},B=class extends R{code="ExecutionProviderOutputInvalidError";constructor(e,t,r,o){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` and provider with id: \`${r}\` has invalid output. Please provide the correct provider output.`),this.data=o;}};var X=class extends O{statusCode;data;code;constructor(e,t,r){super(),this.data={message:r},this.statusCode=e,this.code=t;}};var l={info:s=>N__default.default.blue(s),warning:s=>N__default.default.yellow(s),error:s=>N__default.default.red(s),success:s=>N__default.default.green(s),underline:s=>N__default.default.underline(s),bold:s=>N__default.default.bold(s)},p={SUCCESS:l.success("\u2714"),ERROR:l.error("\u2717"),WARNING:l.warning("\u26A0"),INFO:l.info("\u2139"),ARROW:l.bold("\u2192"),MOCK:l.info("\u25CB"),HYDRATED:l.bold(l.info("\u2192")),STEP:l.info("\u03C3"),ACTION:l.info("\u03B1"),DURATION:l.info("\u0394"),PROVIDER:l.info("\u2699"),OUTPUT:l.info("\u21E2"),INPUT:l.info("\u21E0"),WORKFLOW:l.info("\u03C9"),STATE:l.info("\u03C3"),EXECUTE:l.info("\u03B5"),PREVIEW:l.info("\u03C1")};var ue=s=>Object.values(s).map(e=>`\`${e}\``).join(", "),J=s=>s.replaceAll(/(\w)(\w*)/g,(e,t,r)=>t.toUpperCase()+r.toLowerCase()).replaceAll(/[\s-]+/g,"");var Ae=(s,e="https://api.novu.co")=>{let t=process.env.NOVU_API_URL||e;return {post:async(r,o)=>{let i=await fetch(`${t}/v1${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${s}`},body:JSON.stringify(o)}),a=await i.json();if(i.ok)return a;throw shared.checkIsResponseError(a)?new X(a.statusCode,a.error,a.message):new v("Error processing API request to Novu Cloud from Bridge application.")},delete:async r=>(await fetch(`${t}/v1${r}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${s}`}})).json()}};var Pe={allowedTags:me__default.default.defaults.allowedTags.concat(["style","img","html","head","body","link","meta","title"]),allowedAttributes:!1,allowVulnerableTags:!0,parseStyleAttributes:!1,parser:{lowerCaseAttributeNames:!0}},Ie=s=>{if(!s)return s;let e=/^<!DOCTYPE .*?>/,t=s.match(e),r=me__default.default(s,Pe);return t?t[0]+r:r},z=s=>Object.keys(s).reduce((e,t)=>{let r=s[t];return typeof r=="string"?e[t]=Ie(r):Array.isArray(r)?e[t]=r.map(o=>typeof o=="string"?Ie(o):typeof o=="object"?z(o):o):typeof r=="object"&&r!==null?e[t]=z(r):e[t]=r,e},{});var q=class extends O{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${ue(Y)}`},x=class extends R{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${ue(t)}`);}};var v=class extends f{code="BridgeError";message="Something went wrong. Please try again later."};var U=class extends C{constructor(e,t){super(`${J(e)} with id: \`${t}\` already exists. Please use a different id.`);}},m=class extends L{constructor(e,t){super(`${J(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},g=class extends f{constructor(e,t){super(`Failed to execute ${J(e)} with id: \`${t}\`. Please try again later.`);}};var Z=class extends m{code="ProviderNotFoundError";constructor(e){super("provider",e);}},Q=class extends g{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var H=class extends I{code="SignatureMismatchError";constructor(){super("Signature does not match the expected signature. Please ensure the signature provided in the `novu-signature` header is correct and try again.");}},ee=class extends I{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},te=class extends I{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},re=class extends I{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},oe=class extends I{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.secretKey`");}};var se=class extends m{code="StepNotFoundError";constructor(e){super("step",e);}};var k=class extends m{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},ie=class extends U{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var fe=s=>typeof structuredClone=="function"?structuredClone(s):JSON.parse(JSON.stringify(s));var ae=class{ajv;compiledSchemas;constructor(){this.ajv=new ke__default.default({useDefaults:!0,removeAdditional:"failing"}),Ve__default.default(this.ajv),this.compiledSchemas=new Map;}canHandle(e){return typeof e=="boolean"?!1:e.type==="object"||!!e.anyOf||!!e.allOf||!!e.oneOf}async validate(e,t){let r=this.compiledSchemas.get(t);r||(r=this.ajv.compile(t),this.compiledSchemas.set(t,r));let o=fe(e);return r(o)?{success:!0,data:o}:{success:!1,errors:r.errors.map(a=>({path:a.instancePath,message:a.message}))}}transformToJsonSchema(e){return e}};var ne=class{canHandle(e){return e.safeParseAsync!==void 0}async validate(e,t){let r=t.safeParse(e);return r.success?{success:!0,data:r.data}:{success:!1,errors:r.error.errors.map(o=>({path:`/${o.path.join("/")}`,message:o.message}))}}transformToJsonSchema(e){try{return zodToJsonSchema.zodToJsonSchema(e)}catch(t){throw t?.message?.includes("Cannot find module")&&console.error("Tried to use a zod schema in @novu/framework without `zod-to-json-schema` installed. Please install it by running `npm install zod-to-json-schema`."),t}}};var ce=new ne,de=new ae,Ne=async(s,e)=>{if(ce.canHandle(s))return ce.validate(e,s);if(de.canHandle(s))return de.validate(e,s);throw new Error("Invalid schema")},ve=s=>{if(ce.canHandle(s))return ce.transformToJsonSchema(s);if(de.canHandle(s))return de.transformToJsonSchema(s);throw new Error("Invalid schema")};jsonSchemaFaker.JSONSchemaFaker.random.shuffle=function(){return ["[placeholder]"]};jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});function Fe(){return ["development",void 0].includes(process.env.NODE_ENV)}var pe=class{discoveredWorkflows=[];templateEngine=new liquidjs.Liquid;secretKey;version=D;strictAuthentication;constructor(e){let t=this.buildOptions(e);this.secretKey=t.secretKey,this.strictAuthentication=t.strictAuthentication;}buildOptions(e){let t={secretKey:void 0,strictAuthentication:!Fe()};return t.secretKey=e?.secretKey||process.env.NOVU_SECRET_KEY||process.env.NOVU_API_KEY,e?.strictAuthentication!==void 0?t.strictAuthentication=e.strictAuthentication:process.env.NOVU_STRICT_AUTHENTICATION_ENABLED!==void 0&&(t.strictAuthentication=process.env.NOVU_STRICT_AUTHENTICATION_ENABLED==="true"),t}addWorkflows(e){for(let t of e){if(this.discoveredWorkflows.some(r=>r.workflowId===t.definition.workflowId))throw new ie(t.definition.workflowId);this.discoveredWorkflows.push(t.definition);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((r,o)=>r+o.steps.length,0);return {status:"ok",sdkVersion:D,frameworkVersion:F,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(r=>r.workflowId===e);if(t)return t;throw new k(e)}getStep(e,t){let o=this.getWorkflow(e).steps.find(i=>i.stepId===t);if(o)return o;throw new se(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(ve(e))}async validate(e,t,r,o,i,a,d){let n=await Ne(t,e);if(n.success)return n.data;switch(r){case"event":this.throwInvalidEvent(o,i,n.errors);case"step":this.throwInvalidStep(a,o,i,n.errors);case"provider":this.throwInvalidProvider(a,d,o,i,n.errors);default:throw new Error(`Invalid component: '${r}'`)}}throwInvalidProvider(e,t,r,o,i){if(!e)throw new Error("stepId is required");if(!t)throw new Error("providerId is required");switch(r){case"output":throw new B(o,e,t,i);default:throw new Error(`Invalid payload type: '${r}'`)}}throwInvalidStep(e,t,r,o){if(!e)throw new Error("stepId is required");switch(t){case"output":throw new G(r,e,o);case"result":throw new j(r,e,o);case"controls":throw new $(r,e,o);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(e,t,r){switch(e){case"controls":throw new W(t,r);case"payload":throw new P(t,r);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(r,o,i)=>{let a=this.getStep(e.workflowId,r),d=await this.createStepControls(a,e),n=e.action==="preview";if(!n&&await this.shouldSkip(i?.skip,d))return r===e.stepId&&t({options:{skip:!0},outputs:{},providers:{}}),{};let E=this.previewStep.bind(this),_=this.executeStep.bind(this),T=await(n?E:_)(e,{...a,providers:a.providers.map(S=>{let V=i?.providers?.[S.type];if(!V)throw new Z(S.type);return {...S,resolve:V}}),resolve:o});return Object.values(Re).includes(a.type)&&(T={...T,outputs:z(T.outputs)}),r===e.stepId&&t({...T,options:{skip:!1}}),T.outputs}}async shouldSkip(e,t){return e?e(t):!1}async executeWorkflow(e){let o=`${e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action"} workflowId:`;console.log(`
24
+ ${l.bold(l.underline(o))} '${e.workflowId}'`);let i=this.getWorkflow(e.workflowId),a=process.hrtime(),d={outputs:{},providers:{},options:{skip:!1}},n,E=new Promise(h=>{n=h;}),_=h=>{n(),d=h;},w;try{if(e.action==="execute"&&!e.payload&&!e.data)throw new P(e.workflowId,{message:"Event `payload` is required"});let h=await this.createExecutionPayload(e,i),A={...e,payload:h};await Promise.race([E,i.execute({payload:h,environment:{},input:{},controls:{},subscriber:e.subscriber,step:{email:this.executeStepFactory(A,_),sms:this.executeStepFactory(A,_),inApp:this.executeStepFactory(A,_),digest:this.executeStepFactory(A,_),delay:this.executeStepFactory(A,_),push:this.executeStepFactory(A,_),chat:this.executeStepFactory(A,_),custom:this.executeStepFactory(A,_)}})]);}catch(h){w=h;}let T=process.hrtime(a),S=T[0],V=T[1],Ee=S*1e3+V/1e6,ge=w?p.ERROR:p.SUCCESS,Se=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action";if(console.log(`${ge} ${Se} workflowId: \`${e.workflowId}\``),this.prettyPrintExecute(e,Ee,w),w)throw w;return {outputs:d.outputs,providers:d.providers,options:d.options,metadata:{status:"success",error:!1,duration:Ee}}}async createExecutionPayload(e,t){let r=e.payload||e.data;if(e.action==="preview"){let i=this.mock(t.payload.schema);r=Object.assign(i,r);}return await this.validate(r,t.payload.unknownSchema,"event","payload",e.workflowId)}prettyPrintExecute(e,t,r){let o=r?p.ERROR:p.SUCCESS,i=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action",a=r?"Failed to execute":i,d=r?l.error:l.success,n=`${o} ${a} workflowId: '${e.workflowId}`;console.log(`
25
25
  ${l.bold(d(n))}'`),console.log(` \u251C ${p.STEP} stepId: '${e.stepId}'`),console.log(` \u251C ${p.ACTION} action: '${e.action}'`),console.log(` \u2514 ${p.DURATION} duration: '${t.toFixed(2)}ms'
26
- `);}async executeProviders(e,t,r){return t.providers.reduce(async(o,i)=>{let a=await o,d=this.previewProvider.bind(this),n=this.executeProvider.bind(this),u=await(e.action==="preview"?d:n)(e,t,i,r);return {...a,[i.type]:u}},Promise.resolve({}))}previewProvider(e,t,r,o){return console.log(` ${p.MOCK} Mocked provider: \`${r.type}\``),this.mock(r.outputs.schema)}async executeProvider(e,t,r,o){let i=le__default.default({indent:2}).start(`Executing provider: \`${r.type}\``);try{if(e.stepId===t.stepId){let a=await this.createStepControls(t,e),d=await r.resolve({controls:a,outputs:o}),n=await this.validate(d,r.outputs.unknownSchema,"step","output",e.workflowId,t.stepId,r.type);return i.succeed(`Executed provider: \`${r.type}\``),{...n,_passthrough:d._passthrough}}else return i.stopAndPersist({symbol:p.HYDRATED,text:`Hydrated provider: \`${r.type}\``}),{}}catch(a){throw i.stopAndPersist({symbol:p.ERROR,text:`Failed to execute provider: \`${r.type}\``}),new Q(`Failed to execute provider: '${r.type}'.
27
- ${a.message}`)}}async executeStep(e,t){if(e.stepId===t.stepId){let r=le__default.default({indent:1}).start(`Executing stepId: \`${t.stepId}\``);try{let o=await this.createStepControls(t,e),i=await this.compileControls(o,e),a=await t.resolve(i),d=await this.validate(a,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId),n=await this.executeProviders(e,t,d);return r.succeed(`Executed stepId: \`${t.stepId}\``),{outputs:d,providers:n}}catch(o){throw r.stopAndPersist({prefixText:"",symbol:p.ERROR,text:`Failed to execute stepId: \`${t.stepId}\``}),o}}else {let r=le__default.default({indent:1}).start(`Hydrating stepId: \`${t.stepId}\``);try{let o=e.state.find(i=>i.stepId===t.stepId);if(o){let i=await this.validate(o.outputs,t.results.unknownSchema,"step","result",e.workflowId,t.stepId);return r.stopAndPersist({symbol:p.HYDRATED,text:`Hydrated stepId: \`${t.stepId}\``}),{outputs:i,providers:await this.executeProviders(e,t,i)}}else throw new b(e.workflowId,t.stepId)}catch(o){throw r.stopAndPersist({symbol:p.ERROR,text:`Failed to hydrate stepId: \`${t.stepId}\``}),o}}}async compileControls(e,t){try{let r=this.templateEngine.parse(JSON.stringify(e)),o=await this.templateEngine.render(r,{payload:t.payload||t.data,subscriber:t.subscriber,...t.payload||t.data});return JSON.parse(o)}catch(r){throw new K(t.workflowId,t.stepId,r)}}async createStepControls(e,t){let r=t.controls||t.inputs;return await this.validate(r,e.controls.unknownSchema,"step","controls",t.workflowId,e.stepId)}async previewStep(e,t){let r=le__default.default({indent:1}).start(`Previewing stepId: \`${t.stepId}\``);try{if(e.stepId===t.stepId){let o=await this.createStepControls(t,e),i=await this.compileControls(o,e),a=await t.resolve(i),d=await this.validate(a,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId);return r.stopAndPersist({symbol:p.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:d,providers:await this.executeProviders(e,t,d)}}else {let o=this.mock(t.results.schema);return r.stopAndPersist({symbol:p.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:o,providers:await this.executeProviders(e,t,o)}}}catch(o){throw r.stopAndPersist({symbol:p.ERROR,text:`Failed to preview stepId: \`${t.stepId}\``}),o}}getStepCode(e,t){return {code:this.getStep(e,t).resolve.toString()}}getWorkflowCode(e){return {code:this.getWorkflow(e).execute.toString()}}getCode(e,t){let r;if(e)t?r=this.getStepCode(e,t):r=this.getWorkflowCode(e);else throw new U(e);return r}};var ue=class{frameworkName;handler;client;hmacEnabled;http;constructor(e){this.handler=e.handler,this.client=e.client?e.client:new pe,this.client.addWorkflows(e.workflows),this.http=Ae(this.client.secretKey),this.frameworkName=e.frameworkName,this.hmacEnabled=this.client.strictAuthentication;}createHandler(){return async(...e)=>{let t=await this.handler(...e),r=await this.handleAction({actions:t});return t.transformResponse(r)}}getStaticHeaders(){let e=`novu-framework:v${this.client.version}`;return {"content-type":"application/json","access-control-allow-origin":"*","access-control-allow-methods":"GET, POST","access-control-allow-headers":"*","access-control-max-age":"604800","novu-framework-version":F,"novu-framework-sdk":D,"novu-framework-server":this.frameworkName,"user-agent":e}}createResponse(e,t){return {status:e,body:JSON.stringify(t),headers:{...this.getStaticHeaders()}}}createError(e){return {status:e.statusCode,body:JSON.stringify({message:e.message,data:e.data,code:e.code}),headers:this.getStaticHeaders()}}async handleAction({actions:e}){let t=await e.url(),r=await e.method(),o=t.searchParams.get("action")||"",i=t.searchParams.get("workflowId")||"",a=t.searchParams.get("stepId")||"",d=await e.headers("novu-signature")||await e.headers("x-novu-signature")||"",n={};try{r==="POST"&&(n=await e.body());}catch{}try{o!=="health-check"&&this.validateHmac(n,d);let O=this.getPostActionMap(n,i,a,o),u=this.getGetActionMap(i,a);if(r==="POST")return await this.handlePostAction(o,O);if(r==="GET")return await this.handleGetAction(o,u);if(r==="OPTIONS")return this.createResponse(200,{})}catch(O){return this.handleError(O)}return this.createError(new q(r))}getPostActionMap(e,t,r,o){return {trigger:this.triggerAction({workflowId:t,...e}),execute:async()=>{let i=await this.client.executeWorkflow({...e,workflowId:t,stepId:r,action:o});return this.createResponse(200,i)},preview:async()=>{let i=await this.client.executeWorkflow({...e,workflowId:t,stepId:r,action:o});return this.createResponse(200,i)}}}triggerAction(e){return async()=>{let t={name:e.workflowId,to:e.to,payload:e?.payload||{},transactionId:e.transactionId,overrides:e.overrides||{},...e.actor&&{actor:e.actor},...e.bridgeUrl&&{bridgeUrl:e.bridgeUrl},...e.controls&&{controls:e.controls}},r=await this.http.post("/events/trigger",t);return this.createResponse(200,r)}}getGetActionMap(e,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(e,t);return this.createResponse(200,r)}}}async handlePostAction(e,t){if(Object.values(y).includes(e)){let r=t[e];return r()}else throw new x(e,y)}async handleGetAction(e,t){if(Object.values(M).includes(e)){let r=t[e];return r()}else throw new x(e,M)}isBridgeError(e){return Object.values(_).includes(e?.code)}isPlatformError(e){return e?.statusCode>=400&&e?.statusCode<500}handleError(e){return this.isBridgeError(e)?(e.statusCode===500&&console.error(e),this.createError(e)):this.isPlatformError(e)?this.createError(e):(console.error(e),this.createError(new v))}validateHmac(e,t){if(!this.hmacEnabled)return;if(!t)throw new ee;if(!this.client.secretKey)throw new oe;let[r,o]=t.split(",");if(!r||!o)throw new te;let[i,a]=r.split("="),[d,n]=o.split("=");if(Number(i)<Date.now()-1500)throw new re;if(!(this.hashHmac(this.client.secretKey,`${a}.${JSON.stringify(e)}`)===n))throw new H}hashHmac(e,t){return crypto.createHmac("sha256",e).update(t).digest("hex")}};var be="express",Jr=s=>new ue({frameworkName:be,...s,handler:(t,r)=>({body:()=>t.body,headers:o=>{let i=t.headers[o];return Array.isArray(i)?i[0]:i},method:()=>t.method||"GET",url:()=>{let o=t.headers.host||"",i=o?.includes("://")?"":`${t.protocol||"https"}://`;return new URL(t.originalUrl||t.url||"",`${i}${o||""}`)},queryString:o=>{let i=t.query[o];return Array.isArray(i)?i[0]:i},transformResponse:({body:o,headers:i,status:a})=>(Object.entries(i).forEach(([d,n])=>{r.setHeader(d,n);}),r.status(a).send(o))})}).createHandler();
26
+ `);}async executeProviders(e,t,r){return t.providers.reduce(async(o,i)=>{let a=await o,d=this.previewProvider.bind(this),n=this.executeProvider.bind(this),_=await(e.action==="preview"?d:n)(e,t,i,r);return {...a,[i.type]:_}},Promise.resolve({}))}previewProvider(e,t,r,o){return console.log(` ${p.MOCK} Mocked provider: \`${r.type}\``),this.mock(r.outputs.schema)}async executeProvider(e,t,r,o){let i=le__default.default({indent:2}).start(`Executing provider: \`${r.type}\``);try{if(e.stepId===t.stepId){let a=await this.createStepControls(t,e),d=await r.resolve({controls:a,outputs:o}),n=await this.validate(d,r.outputs.unknownSchema,"step","output",e.workflowId,t.stepId,r.type);return i.succeed(`Executed provider: \`${r.type}\``),{...n,_passthrough:d._passthrough}}else return i.stopAndPersist({symbol:p.HYDRATED,text:`Hydrated provider: \`${r.type}\``}),{}}catch(a){throw i.stopAndPersist({symbol:p.ERROR,text:`Failed to execute provider: \`${r.type}\``}),new Q(`Failed to execute provider: '${r.type}'.
27
+ ${a.message}`)}}async executeStep(e,t){if(e.stepId===t.stepId){let r=le__default.default({indent:1}).start(`Executing stepId: \`${t.stepId}\``);try{let o=await this.createStepControls(t,e),i=await this.compileControls(o,e),a=await t.resolve(i),d=await this.validate(a,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId),n=await this.executeProviders(e,t,d);return r.succeed(`Executed stepId: \`${t.stepId}\``),{outputs:d,providers:n}}catch(o){throw r.stopAndPersist({prefixText:"",symbol:p.ERROR,text:`Failed to execute stepId: \`${t.stepId}\``}),o}}else {let r=le__default.default({indent:1}).start(`Hydrating stepId: \`${t.stepId}\``);try{let o=e.state.find(i=>i.stepId===t.stepId);if(o){let i=await this.validate(o.outputs,t.results.unknownSchema,"step","result",e.workflowId,t.stepId);return r.stopAndPersist({symbol:p.HYDRATED,text:`Hydrated stepId: \`${t.stepId}\``}),{outputs:i,providers:await this.executeProviders(e,t,i)}}else throw new b(e.workflowId,t.stepId)}catch(o){throw r.stopAndPersist({symbol:p.ERROR,text:`Failed to hydrate stepId: \`${t.stepId}\``}),o}}}async compileControls(e,t){try{let r=this.templateEngine.parse(JSON.stringify(e)),o=await this.templateEngine.render(r,{payload:t.payload||t.data,subscriber:t.subscriber,...t.payload||t.data});return JSON.parse(o)}catch(r){throw new K(t.workflowId,t.stepId,r)}}async createStepControls(e,t){let r=t.controls||t.inputs;return await this.validate(r,e.controls.unknownSchema,"step","controls",t.workflowId,e.stepId)}async previewStep(e,t){let r=le__default.default({indent:1}).start(`Previewing stepId: \`${t.stepId}\``);try{if(e.stepId===t.stepId){let o=await this.createStepControls(t,e),i=await this.compileControls(o,e),a=await t.resolve(i),d=await this.validate(a,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId);return r.stopAndPersist({symbol:p.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:d,providers:await this.executeProviders(e,t,d)}}else {let o=this.mock(t.results.schema);return r.stopAndPersist({symbol:p.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:o,providers:await this.executeProviders(e,t,o)}}}catch(o){throw r.stopAndPersist({symbol:p.ERROR,text:`Failed to preview stepId: \`${t.stepId}\``}),o}}getStepCode(e,t){return {code:this.getStep(e,t).resolve.toString()}}getWorkflowCode(e){return {code:this.getWorkflow(e).execute.toString()}}getCode(e,t){let r;if(e)t?r=this.getStepCode(e,t):r=this.getWorkflowCode(e);else throw new k(e);return r}};var _e=class{frameworkName;handler;client;hmacEnabled;http;constructor(e){this.handler=e.handler,this.client=e.client?e.client:new pe,this.client.addWorkflows(e.workflows),this.http=Ae(this.client.secretKey),this.frameworkName=e.frameworkName,this.hmacEnabled=this.client.strictAuthentication;}createHandler(){return async(...e)=>{let t=await this.handler(...e),r=await this.handleAction({actions:t});return t.transformResponse(r)}}getStaticHeaders(){let e=`novu-framework:v${this.client.version}`;return {"content-type":"application/json","access-control-allow-origin":"*","access-control-allow-methods":"GET, POST","access-control-allow-headers":"*","access-control-max-age":"604800","novu-framework-version":F,"novu-framework-sdk":D,"novu-framework-server":this.frameworkName,"user-agent":e}}createResponse(e,t){return {status:e,body:JSON.stringify(t),headers:{...this.getStaticHeaders()}}}createError(e){return {status:e.statusCode,body:JSON.stringify({message:e.message,data:e.data,code:e.code}),headers:this.getStaticHeaders()}}async handleAction({actions:e}){let t=await e.url(),r=await e.method(),o=t.searchParams.get("action")||"",i=t.searchParams.get("workflowId")||"",a=t.searchParams.get("stepId")||"",d=await e.headers("novu-signature")||await e.headers("x-novu-signature")||"",n={};try{r==="POST"&&(n=await e.body());}catch{}try{o!=="health-check"&&this.validateHmac(n,d);let E=this.getPostActionMap(n,i,a,o),_=this.getGetActionMap(i,a);if(r==="POST")return await this.handlePostAction(o,E);if(r==="GET")return await this.handleGetAction(o,_);if(r==="OPTIONS")return this.createResponse(200,{})}catch(E){return this.handleError(E)}return this.createError(new q(r))}getPostActionMap(e,t,r,o){return {trigger:this.triggerAction({workflowId:t,...e}),execute:async()=>{let i=await this.client.executeWorkflow({...e,workflowId:t,stepId:r,action:o});return this.createResponse(200,i)},preview:async()=>{let i=await this.client.executeWorkflow({...e,workflowId:t,stepId:r,action:o});return this.createResponse(200,i)}}}triggerAction(e){return async()=>{let t={name:e.workflowId,to:e.to,payload:e?.payload||{},transactionId:e.transactionId,overrides:e.overrides||{},...e.actor&&{actor:e.actor},...e.bridgeUrl&&{bridgeUrl:e.bridgeUrl},...e.controls&&{controls:e.controls}},r=await this.http.post("/events/trigger",t);return this.createResponse(200,r)}}getGetActionMap(e,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(e,t);return this.createResponse(200,r)}}}async handlePostAction(e,t){if(Object.values(y).includes(e)){let r=t[e];return r()}else throw new x(e,y)}async handleGetAction(e,t){if(Object.values(M).includes(e)){let r=t[e];return r()}else throw new x(e,M)}isBridgeError(e){return Object.values(u).includes(e?.code)}isPlatformError(e){return e?.statusCode>=400&&e?.statusCode<500}handleError(e){return this.isBridgeError(e)?(e.statusCode===500&&console.error(e),this.createError(e)):this.isPlatformError(e)?this.createError(e):(console.error(e),this.createError(new v))}validateHmac(e,t){if(!this.hmacEnabled)return;if(!t)throw new ee;if(!this.client.secretKey)throw new oe;let[r,o]=t.split(",");if(!r||!o)throw new te;let[i,a]=r.split("="),[d,n]=o.split("=");if(Number(i)<Date.now()-1500)throw new re;if(!(this.hashHmac(this.client.secretKey,`${a}.${JSON.stringify(e)}`)===n))throw new H}hashHmac(e,t){return crypto.createHmac("sha256",e).update(t).digest("hex")}};var be="express",qr=s=>new _e({frameworkName:be,...s,handler:(t,r)=>({body:()=>t.body,headers:o=>{let i=t.headers[o];return Array.isArray(i)?i[0]:i},method:()=>t.method||"GET",url:()=>{let o=t.headers.host||"",i=o?.includes("://")?"":`${t.protocol||"https"}://`;return new URL(t.originalUrl||t.url||"",`${i}${o||""}`)},queryString:o=>{let i=t.query[o];return Array.isArray(i)?i[0]:i},transformResponse:({body:o,headers:i,status:a})=>(Object.entries(i).forEach(([d,n])=>{r.setHeader(d,n);}),r.status(a).send(o))})}).createHandler();
28
28
 
29
29
  exports.frameworkName = be;
30
- exports.serve = Jr;
30
+ exports.serve = qr;
@@ -1,5 +1,5 @@
1
1
  import { H3Event, EventHandlerRequest } from 'h3';
2
- import { v as SupportedFrameworkName, c as ServeHandlerOptions } from '../handler-xDdUZXcL.js';
2
+ import { w as SupportedFrameworkName, c as ServeHandlerOptions } from '../handler-WKKD7ESp.js';
3
3
  import '@novu/shared';
4
4
  import 'json-schema-to-ts';
5
5
  import 'zod';
@@ -9,8 +9,8 @@ require('cross-fetch');
9
9
  var N = require('chalk');
10
10
  var shared = require('@novu/shared');
11
11
  var Ie = require('sanitize-html');
12
- var Ve = require('ajv');
13
- var Me = require('ajv-formats');
12
+ var Me = require('ajv');
13
+ var Ve = require('ajv-formats');
14
14
  var zodToJsonSchema = require('zod-to-json-schema');
15
15
 
16
16
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
@@ -18,14 +18,14 @@ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
18
18
  var le__default = /*#__PURE__*/_interopDefault(le);
19
19
  var N__default = /*#__PURE__*/_interopDefault(N);
20
20
  var Ie__default = /*#__PURE__*/_interopDefault(Ie);
21
- var Ve__default = /*#__PURE__*/_interopDefault(Ve);
22
21
  var Me__default = /*#__PURE__*/_interopDefault(Me);
22
+ var Ve__default = /*#__PURE__*/_interopDefault(Ve);
23
23
 
24
- var D=(r=>(r.TRIGGER="trigger",r.EXECUTE="execute",r.PREVIEW="preview",r))(D||{}),M=(r=>(r.DISCOVER="discover",r.HEALTH_CHECK="health-check",r.CODE="code",r))(M||{});var R=(n=>(n.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",n.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",n.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",n.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",n.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",n.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",n.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",n.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",n.STEP_NOT_FOUND_ERROR="StepNotFoundError",n.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",n.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",n.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",n.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",n.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",n.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",n.STEP_CONTROL_COMPILATION_FAILED_ERROR="StepControlCompilationFailedError",n.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",n.INVALID_ACTION_ERROR="InvalidActionError",n.MISSING_SECRET_KEY_ERROR="MissingSecretKeyError",n.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",n.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",n.SIGNATURE_INVALID_ERROR="SignatureInvalidError",n.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",n.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",n.BRIDGE_ERROR="BridgeError",n.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",n.WORKFLOW_PAYLOAD_INVALID_ERROR="WorkflowPayloadInvalidError",n))(R||{});var Y=(r=>(r.POST="POST",r.GET="GET",r.OPTIONS="OPTIONS",r))(Y||{});var ue=(i=>(i.EMAIL="email",i.SMS="sms",i.PUSH="push",i.CHAT="chat",i.IN_APP="in_app",i))(ue||{});var Te="2.0.2";var y=Te,F="2024-06-26";var E=class extends Error{data},C=class extends E{statusCode=404},u=class extends E{statusCode=400},m=class extends E{statusCode=401},f=class extends E{statusCode=500},L=class extends E{statusCode=409};var b=class extends u{code="ExecutionStateCorruptError";constructor(e,t){super(`Workflow with id: \`${e}\` has a corrupt state. Step with id: \`${t}\` does not exist. Please provide the missing state.`),this.data={workflowId:e,stepId:t};}},P=class extends u{code="ExecutionEventPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct event payload.`),this.data=t;}},W=class extends u{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},$=class extends u{code="ExecutionStateControlInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid \`controls\`. Please provide the correct step controls.`),this.data=r;}},G=class extends u{code="ExecutionStateOutputInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid output. Please provide the correct step output.`),this.data=r;}},j=class extends u{code="ExecutionStateResultInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid result. Please provide the correct step result.`),this.data=r;}},K=class extends u{code="StepControlCompilationFailedError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has invalid controls syntax in step with id: \`${t}\`. Please correct step control syntax.`),this.data=r;}},B=class extends u{code="ExecutionProviderOutputInvalidError";constructor(e,t,r,s){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` and provider with id: \`${r}\` has invalid output. Please provide the correct provider output.`),this.data=s;}};var X=class extends E{statusCode;data;code;constructor(e,t,r){super(),this.data={message:r},this.statusCode=e,this.code=t;}};var l={info:o=>N__default.default.blue(o),warning:o=>N__default.default.yellow(o),error:o=>N__default.default.red(o),success:o=>N__default.default.green(o),underline:o=>N__default.default.underline(o),bold:o=>N__default.default.bold(o)},p={SUCCESS:l.success("\u2714"),ERROR:l.error("\u2717"),WARNING:l.warning("\u26A0"),INFO:l.info("\u2139"),ARROW:l.bold("\u2192"),MOCK:l.info("\u25CB"),HYDRATED:l.bold(l.info("\u2192")),STEP:l.info("\u03C3"),ACTION:l.info("\u03B1"),DURATION:l.info("\u0394"),PROVIDER:l.info("\u2699"),OUTPUT:l.info("\u21E2"),INPUT:l.info("\u21E0"),WORKFLOW:l.info("\u03C9"),STATE:l.info("\u03C3"),EXECUTE:l.info("\u03B5"),PREVIEW:l.info("\u03C1")};var Re=o=>Object.values(o).map(e=>`\`${e}\``).join(", "),J=o=>o.replaceAll(/(\w)(\w*)/g,(e,t,r)=>t.toUpperCase()+r.toLowerCase()).replaceAll(/[\s-]+/g,"");var Ae=(o,e="https://api.novu.co")=>{let t=process.env.NOVU_API_URL||e;return {post:async(r,s)=>{let i=await fetch(`${t}/v1${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${o}`},body:JSON.stringify(s)}),a=await i.json();if(i.ok)return a;throw shared.checkIsResponseError(a)?new X(a.statusCode,a.error,a.message):new v("Error processing API request to Novu Cloud from Bridge application.")},delete:async r=>(await fetch(`${t}/v1${r}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${o}`}})).json()}};var xe={allowedTags:Ie__default.default.defaults.allowedTags.concat(["style","img","html","head","body","link","meta","title"]),allowedAttributes:!1,allowVulnerableTags:!0,parseStyleAttributes:!1,parser:{lowerCaseAttributeNames:!0}},me=o=>{if(!o)return o;let e=/^<!DOCTYPE .*?>/,t=o.match(e),r=Ie__default.default(o,xe);return t?t[0]+r:r},q=o=>Object.keys(o).reduce((e,t)=>{let r=o[t];return typeof r=="string"?e[t]=me(r):Array.isArray(r)?e[t]=r.map(s=>typeof s=="string"?me(s):typeof s=="object"?q(s):s):typeof r=="object"&&r!==null?e[t]=q(r):e[t]=r,e},{});var z=class extends E{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${Re(Y)}`},x=class extends u{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${Re(t)}`);}};var v=class extends f{code="BridgeError";message="Something went wrong. Please try again later."};var k=class extends L{constructor(e,t){super(`${J(e)} with id: \`${t}\` already exists. Please use a different id.`);}},I=class extends C{constructor(e,t){super(`${J(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},g=class extends f{constructor(e,t){super(`Failed to execute ${J(e)} with id: \`${t}\`. Please try again later.`);}};var Z=class extends I{code="ProviderNotFoundError";constructor(e){super("provider",e);}},Q=class extends g{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var H=class extends m{code="SignatureMismatchError";constructor(){super("Signature does not match the expected signature. Please ensure the signature provided in the `novu-signature` header is correct and try again.");}},ee=class extends m{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},te=class extends m{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},re=class extends m{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},oe=class extends m{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.secretKey`");}};var se=class extends I{code="StepNotFoundError";constructor(e){super("step",e);}};var U=class extends I{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},ie=class extends k{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var fe=o=>typeof structuredClone=="function"?structuredClone(o):JSON.parse(JSON.stringify(o));var ae=class{ajv;compiledSchemas;constructor(){this.ajv=new Ve__default.default({useDefaults:!0,removeAdditional:"failing"}),Me__default.default(this.ajv),this.compiledSchemas=new Map;}canHandle(e){return typeof e=="boolean"?!1:e.type==="object"||!!e.anyOf||!!e.allOf||!!e.oneOf}async validate(e,t){let r=this.compiledSchemas.get(t);r||(r=this.ajv.compile(t),this.compiledSchemas.set(t,r));let s=fe(e);return r(s)?{success:!0,data:s}:{success:!1,errors:r.errors.map(a=>({path:a.instancePath,message:a.message}))}}transformToJsonSchema(e){return e}};var ne=class{canHandle(e){return e.safeParseAsync!==void 0}async validate(e,t){let r=t.safeParse(e);return r.success?{success:!0,data:r.data}:{success:!1,errors:r.error.errors.map(s=>({path:`/${s.path.join("/")}`,message:s.message}))}}transformToJsonSchema(e){try{return zodToJsonSchema.zodToJsonSchema(e)}catch(t){throw t?.message?.includes("Cannot find module")&&console.error("Tried to use a zod schema in @novu/framework without `zod-to-json-schema` installed. Please install it by running `npm install zod-to-json-schema`."),t}}};var ce=new ne,de=new ae,Ne=async(o,e)=>{if(ce.canHandle(o))return ce.validate(e,o);if(de.canHandle(o))return de.validate(e,o);throw new Error("Invalid schema")},ve=o=>{if(ce.canHandle(o))return ce.transformToJsonSchema(o);if(de.canHandle(o))return de.transformToJsonSchema(o);throw new Error("Invalid schema")};jsonSchemaFaker.JSONSchemaFaker.random.shuffle=function(){return ["[placeholder]"]};jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});function Ce(){return ["development",void 0].includes(process.env.NODE_ENV)}var pe=class{discoveredWorkflows=[];templateEngine=new liquidjs.Liquid;secretKey;version=y;strictAuthentication;constructor(e){let t=this.buildOptions(e);this.secretKey=t.secretKey,this.strictAuthentication=t.strictAuthentication;}buildOptions(e){let t={secretKey:void 0,strictAuthentication:!Ce()};return t.secretKey=e?.secretKey||process.env.NOVU_SECRET_KEY||process.env.NOVU_API_KEY,e?.strictAuthentication!==void 0?t.strictAuthentication=e.strictAuthentication:process.env.NOVU_STRICT_AUTHENTICATION_ENABLED!==void 0&&(t.strictAuthentication=process.env.NOVU_STRICT_AUTHENTICATION_ENABLED==="true"),t}addWorkflows(e){for(let t of e){if(this.discoveredWorkflows.some(r=>r.workflowId===t.definition.workflowId))throw new ie(t.definition.workflowId);this.discoveredWorkflows.push(t.definition);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((r,s)=>r+s.steps.length,0);return {status:"ok",sdkVersion:y,frameworkVersion:F,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(r=>r.workflowId===e);if(t)return t;throw new U(e)}getStep(e,t){let s=this.getWorkflow(e).steps.find(i=>i.stepId===t);if(s)return s;throw new se(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(ve(e))}async validate(e,t,r,s,i,a,d){let c=await Ne(t,e);if(c.success)return c.data;switch(r){case"event":this.throwInvalidEvent(s,i,c.errors);case"step":this.throwInvalidStep(a,s,i,c.errors);case"provider":this.throwInvalidProvider(a,d,s,i,c.errors);default:throw new Error(`Invalid component: '${r}'`)}}throwInvalidProvider(e,t,r,s,i){if(!e)throw new Error("stepId is required");if(!t)throw new Error("providerId is required");switch(r){case"output":throw new B(s,e,t,i);default:throw new Error(`Invalid payload type: '${r}'`)}}throwInvalidStep(e,t,r,s){if(!e)throw new Error("stepId is required");switch(t){case"output":throw new G(r,e,s);case"result":throw new j(r,e,s);case"controls":throw new $(r,e,s);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(e,t,r){switch(e){case"controls":throw new W(t,r);case"payload":throw new P(t,r);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(r,s,i)=>{let a=this.getStep(e.workflowId,r),d=await this.createStepControls(a,e),c=e.action==="preview";if(!c&&await this.shouldSkip(i?.skip,d))return r===e.stepId&&t({options:{skip:!0},outputs:{},providers:{}}),{};let O=this.previewStep.bind(this),_=this.executeStep.bind(this),T=await(c?O:_)(e,{...a,providers:a.providers.map(S=>{let V=i?.providers?.[S.type];if(!V)throw new Z(S.type);return {...S,resolve:V}}),resolve:s});return Object.values(ue).includes(a.type)&&(T={...T,outputs:q(T.outputs)}),r===e.stepId&&t({...T,options:{skip:!1}}),T.outputs}}async shouldSkip(e,t){return e?e(t):!1}async executeWorkflow(e){let s=`${e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action"} workflowId:`;console.log(`
25
- ${l.bold(l.underline(s))} '${e.workflowId}'`);let i=this.getWorkflow(e.workflowId),a=process.hrtime(),d={outputs:{},providers:{},options:{skip:!1}},c,O=new Promise(h=>{c=h;}),_=h=>{c(),d=h;},w;try{if(e.action==="execute"&&!e.payload&&!e.data)throw new P(e.workflowId,{message:"Event `payload` is required"});let h=await this.createExecutionPayload(e,i),A={...e,payload:h};await Promise.race([O,i.execute({payload:h,environment:{},input:{},controls:{},subscriber:e.subscriber,step:{email:this.executeStepFactory(A,_),sms:this.executeStepFactory(A,_),inApp:this.executeStepFactory(A,_),digest:this.executeStepFactory(A,_),delay:this.executeStepFactory(A,_),push:this.executeStepFactory(A,_),chat:this.executeStepFactory(A,_),custom:this.executeStepFactory(A,_)}})]);}catch(h){w=h;}let T=process.hrtime(a),S=T[0],V=T[1],Oe=S*1e3+V/1e6,Se=w?p.ERROR:p.SUCCESS,De=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action";if(console.log(`${Se} ${De} workflowId: \`${e.workflowId}\``),this.prettyPrintExecute(e,Oe,w),w)throw w;return {outputs:d.outputs,providers:d.providers,options:d.options,metadata:{status:"success",error:!1,duration:Oe}}}async createExecutionPayload(e,t){let r=e.payload||e.data;if(e.action==="preview"){let i=this.mock(t.payload.schema);r=Object.assign(i,r);}return await this.validate(r,t.payload.unknownSchema,"event","payload",e.workflowId)}prettyPrintExecute(e,t,r){let s=r?p.ERROR:p.SUCCESS,i=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action",a=r?"Failed to execute":i,d=r?l.error:l.success,c=`${s} ${a} workflowId: '${e.workflowId}`;console.log(`
24
+ var D=(r=>(r.TRIGGER="trigger",r.EXECUTE="execute",r.PREVIEW="preview",r))(D||{}),V=(r=>(r.DISCOVER="discover",r.HEALTH_CHECK="health-check",r.CODE="code",r))(V||{});var u=(n=>(n.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",n.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",n.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",n.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",n.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",n.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",n.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",n.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",n.STEP_NOT_FOUND_ERROR="StepNotFoundError",n.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",n.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",n.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",n.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",n.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",n.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",n.STEP_CONTROL_COMPILATION_FAILED_ERROR="StepControlCompilationFailedError",n.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",n.INVALID_ACTION_ERROR="InvalidActionError",n.MISSING_SECRET_KEY_ERROR="MissingSecretKeyError",n.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",n.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",n.SIGNATURE_INVALID_ERROR="SignatureInvalidError",n.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",n.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",n.BRIDGE_ERROR="BridgeError",n.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",n.WORKFLOW_PAYLOAD_INVALID_ERROR="WorkflowPayloadInvalidError",n))(u||{});var Y=(r=>(r.POST="POST",r.GET="GET",r.OPTIONS="OPTIONS",r))(Y||{});var Re=(i=>(i.EMAIL="email",i.SMS="sms",i.PUSH="push",i.CHAT="chat",i.IN_APP="in_app",i))(Re||{});var Te="2.0.3";var y=Te,F="2024-06-26";var E=class extends Error{data},L=class extends E{statusCode=404},R=class extends E{statusCode=400},m=class extends E{statusCode=401},f=class extends E{statusCode=500},C=class extends E{statusCode=409};var b=class extends R{code="ExecutionStateCorruptError";constructor(e,t){super(`Workflow with id: \`${e}\` has a corrupt state. Step with id: \`${t}\` does not exist. Please provide the missing state.`),this.data={workflowId:e,stepId:t};}},P=class extends R{code="ExecutionEventPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct event payload.`),this.data=t;}},W=class extends R{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},$=class extends R{code="ExecutionStateControlInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid \`controls\`. Please provide the correct step controls.`),this.data=r;}},G=class extends R{code="ExecutionStateOutputInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid output. Please provide the correct step output.`),this.data=r;}},j=class extends R{code="ExecutionStateResultInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid result. Please provide the correct step result.`),this.data=r;}},K=class extends R{code="StepControlCompilationFailedError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has invalid controls syntax in step with id: \`${t}\`. Please correct step control syntax.`),this.data=r;}},B=class extends R{code="ExecutionProviderOutputInvalidError";constructor(e,t,r,s){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` and provider with id: \`${r}\` has invalid output. Please provide the correct provider output.`),this.data=s;}};var X=class extends E{statusCode;data;code;constructor(e,t,r){super(),this.data={message:r},this.statusCode=e,this.code=t;}};var l={info:o=>N__default.default.blue(o),warning:o=>N__default.default.yellow(o),error:o=>N__default.default.red(o),success:o=>N__default.default.green(o),underline:o=>N__default.default.underline(o),bold:o=>N__default.default.bold(o)},p={SUCCESS:l.success("\u2714"),ERROR:l.error("\u2717"),WARNING:l.warning("\u26A0"),INFO:l.info("\u2139"),ARROW:l.bold("\u2192"),MOCK:l.info("\u25CB"),HYDRATED:l.bold(l.info("\u2192")),STEP:l.info("\u03C3"),ACTION:l.info("\u03B1"),DURATION:l.info("\u0394"),PROVIDER:l.info("\u2699"),OUTPUT:l.info("\u21E2"),INPUT:l.info("\u21E0"),WORKFLOW:l.info("\u03C9"),STATE:l.info("\u03C3"),EXECUTE:l.info("\u03B5"),PREVIEW:l.info("\u03C1")};var ue=o=>Object.values(o).map(e=>`\`${e}\``).join(", "),J=o=>o.replaceAll(/(\w)(\w*)/g,(e,t,r)=>t.toUpperCase()+r.toLowerCase()).replaceAll(/[\s-]+/g,"");var Ae=(o,e="https://api.novu.co")=>{let t=process.env.NOVU_API_URL||e;return {post:async(r,s)=>{let i=await fetch(`${t}/v1${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${o}`},body:JSON.stringify(s)}),a=await i.json();if(i.ok)return a;throw shared.checkIsResponseError(a)?new X(a.statusCode,a.error,a.message):new v("Error processing API request to Novu Cloud from Bridge application.")},delete:async r=>(await fetch(`${t}/v1${r}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${o}`}})).json()}};var xe={allowedTags:Ie__default.default.defaults.allowedTags.concat(["style","img","html","head","body","link","meta","title"]),allowedAttributes:!1,allowVulnerableTags:!0,parseStyleAttributes:!1,parser:{lowerCaseAttributeNames:!0}},me=o=>{if(!o)return o;let e=/^<!DOCTYPE .*?>/,t=o.match(e),r=Ie__default.default(o,xe);return t?t[0]+r:r},q=o=>Object.keys(o).reduce((e,t)=>{let r=o[t];return typeof r=="string"?e[t]=me(r):Array.isArray(r)?e[t]=r.map(s=>typeof s=="string"?me(s):typeof s=="object"?q(s):s):typeof r=="object"&&r!==null?e[t]=q(r):e[t]=r,e},{});var z=class extends E{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${ue(Y)}`},x=class extends R{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${ue(t)}`);}};var v=class extends f{code="BridgeError";message="Something went wrong. Please try again later."};var U=class extends C{constructor(e,t){super(`${J(e)} with id: \`${t}\` already exists. Please use a different id.`);}},I=class extends L{constructor(e,t){super(`${J(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},g=class extends f{constructor(e,t){super(`Failed to execute ${J(e)} with id: \`${t}\`. Please try again later.`);}};var Z=class extends I{code="ProviderNotFoundError";constructor(e){super("provider",e);}},Q=class extends g{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var H=class extends m{code="SignatureMismatchError";constructor(){super("Signature does not match the expected signature. Please ensure the signature provided in the `novu-signature` header is correct and try again.");}},ee=class extends m{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},te=class extends m{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},re=class extends m{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},oe=class extends m{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.secretKey`");}};var se=class extends I{code="StepNotFoundError";constructor(e){super("step",e);}};var k=class extends I{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},ie=class extends U{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var fe=o=>typeof structuredClone=="function"?structuredClone(o):JSON.parse(JSON.stringify(o));var ae=class{ajv;compiledSchemas;constructor(){this.ajv=new Me__default.default({useDefaults:!0,removeAdditional:"failing"}),Ve__default.default(this.ajv),this.compiledSchemas=new Map;}canHandle(e){return typeof e=="boolean"?!1:e.type==="object"||!!e.anyOf||!!e.allOf||!!e.oneOf}async validate(e,t){let r=this.compiledSchemas.get(t);r||(r=this.ajv.compile(t),this.compiledSchemas.set(t,r));let s=fe(e);return r(s)?{success:!0,data:s}:{success:!1,errors:r.errors.map(a=>({path:a.instancePath,message:a.message}))}}transformToJsonSchema(e){return e}};var ne=class{canHandle(e){return e.safeParseAsync!==void 0}async validate(e,t){let r=t.safeParse(e);return r.success?{success:!0,data:r.data}:{success:!1,errors:r.error.errors.map(s=>({path:`/${s.path.join("/")}`,message:s.message}))}}transformToJsonSchema(e){try{return zodToJsonSchema.zodToJsonSchema(e)}catch(t){throw t?.message?.includes("Cannot find module")&&console.error("Tried to use a zod schema in @novu/framework without `zod-to-json-schema` installed. Please install it by running `npm install zod-to-json-schema`."),t}}};var ce=new ne,de=new ae,Ne=async(o,e)=>{if(ce.canHandle(o))return ce.validate(e,o);if(de.canHandle(o))return de.validate(e,o);throw new Error("Invalid schema")},ve=o=>{if(ce.canHandle(o))return ce.transformToJsonSchema(o);if(de.canHandle(o))return de.transformToJsonSchema(o);throw new Error("Invalid schema")};jsonSchemaFaker.JSONSchemaFaker.random.shuffle=function(){return ["[placeholder]"]};jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});function Le(){return ["development",void 0].includes(process.env.NODE_ENV)}var pe=class{discoveredWorkflows=[];templateEngine=new liquidjs.Liquid;secretKey;version=y;strictAuthentication;constructor(e){let t=this.buildOptions(e);this.secretKey=t.secretKey,this.strictAuthentication=t.strictAuthentication;}buildOptions(e){let t={secretKey:void 0,strictAuthentication:!Le()};return t.secretKey=e?.secretKey||process.env.NOVU_SECRET_KEY||process.env.NOVU_API_KEY,e?.strictAuthentication!==void 0?t.strictAuthentication=e.strictAuthentication:process.env.NOVU_STRICT_AUTHENTICATION_ENABLED!==void 0&&(t.strictAuthentication=process.env.NOVU_STRICT_AUTHENTICATION_ENABLED==="true"),t}addWorkflows(e){for(let t of e){if(this.discoveredWorkflows.some(r=>r.workflowId===t.definition.workflowId))throw new ie(t.definition.workflowId);this.discoveredWorkflows.push(t.definition);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((r,s)=>r+s.steps.length,0);return {status:"ok",sdkVersion:y,frameworkVersion:F,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(r=>r.workflowId===e);if(t)return t;throw new k(e)}getStep(e,t){let s=this.getWorkflow(e).steps.find(i=>i.stepId===t);if(s)return s;throw new se(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(ve(e))}async validate(e,t,r,s,i,a,d){let c=await Ne(t,e);if(c.success)return c.data;switch(r){case"event":this.throwInvalidEvent(s,i,c.errors);case"step":this.throwInvalidStep(a,s,i,c.errors);case"provider":this.throwInvalidProvider(a,d,s,i,c.errors);default:throw new Error(`Invalid component: '${r}'`)}}throwInvalidProvider(e,t,r,s,i){if(!e)throw new Error("stepId is required");if(!t)throw new Error("providerId is required");switch(r){case"output":throw new B(s,e,t,i);default:throw new Error(`Invalid payload type: '${r}'`)}}throwInvalidStep(e,t,r,s){if(!e)throw new Error("stepId is required");switch(t){case"output":throw new G(r,e,s);case"result":throw new j(r,e,s);case"controls":throw new $(r,e,s);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(e,t,r){switch(e){case"controls":throw new W(t,r);case"payload":throw new P(t,r);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(r,s,i)=>{let a=this.getStep(e.workflowId,r),d=await this.createStepControls(a,e),c=e.action==="preview";if(!c&&await this.shouldSkip(i?.skip,d))return r===e.stepId&&t({options:{skip:!0},outputs:{},providers:{}}),{};let O=this.previewStep.bind(this),_=this.executeStep.bind(this),T=await(c?O:_)(e,{...a,providers:a.providers.map(S=>{let M=i?.providers?.[S.type];if(!M)throw new Z(S.type);return {...S,resolve:M}}),resolve:s});return Object.values(Re).includes(a.type)&&(T={...T,outputs:q(T.outputs)}),r===e.stepId&&t({...T,options:{skip:!1}}),T.outputs}}async shouldSkip(e,t){return e?e(t):!1}async executeWorkflow(e){let s=`${e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action"} workflowId:`;console.log(`
25
+ ${l.bold(l.underline(s))} '${e.workflowId}'`);let i=this.getWorkflow(e.workflowId),a=process.hrtime(),d={outputs:{},providers:{},options:{skip:!1}},c,O=new Promise(h=>{c=h;}),_=h=>{c(),d=h;},w;try{if(e.action==="execute"&&!e.payload&&!e.data)throw new P(e.workflowId,{message:"Event `payload` is required"});let h=await this.createExecutionPayload(e,i),A={...e,payload:h};await Promise.race([O,i.execute({payload:h,environment:{},input:{},controls:{},subscriber:e.subscriber,step:{email:this.executeStepFactory(A,_),sms:this.executeStepFactory(A,_),inApp:this.executeStepFactory(A,_),digest:this.executeStepFactory(A,_),delay:this.executeStepFactory(A,_),push:this.executeStepFactory(A,_),chat:this.executeStepFactory(A,_),custom:this.executeStepFactory(A,_)}})]);}catch(h){w=h;}let T=process.hrtime(a),S=T[0],M=T[1],Oe=S*1e3+M/1e6,Se=w?p.ERROR:p.SUCCESS,De=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action";if(console.log(`${Se} ${De} workflowId: \`${e.workflowId}\``),this.prettyPrintExecute(e,Oe,w),w)throw w;return {outputs:d.outputs,providers:d.providers,options:d.options,metadata:{status:"success",error:!1,duration:Oe}}}async createExecutionPayload(e,t){let r=e.payload||e.data;if(e.action==="preview"){let i=this.mock(t.payload.schema);r=Object.assign(i,r);}return await this.validate(r,t.payload.unknownSchema,"event","payload",e.workflowId)}prettyPrintExecute(e,t,r){let s=r?p.ERROR:p.SUCCESS,i=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action",a=r?"Failed to execute":i,d=r?l.error:l.success,c=`${s} ${a} workflowId: '${e.workflowId}`;console.log(`
26
26
  ${l.bold(d(c))}'`),console.log(` \u251C ${p.STEP} stepId: '${e.stepId}'`),console.log(` \u251C ${p.ACTION} action: '${e.action}'`),console.log(` \u2514 ${p.DURATION} duration: '${t.toFixed(2)}ms'
27
27
  `);}async executeProviders(e,t,r){return t.providers.reduce(async(s,i)=>{let a=await s,d=this.previewProvider.bind(this),c=this.executeProvider.bind(this),_=await(e.action==="preview"?d:c)(e,t,i,r);return {...a,[i.type]:_}},Promise.resolve({}))}previewProvider(e,t,r,s){return console.log(` ${p.MOCK} Mocked provider: \`${r.type}\``),this.mock(r.outputs.schema)}async executeProvider(e,t,r,s){let i=le__default.default({indent:2}).start(`Executing provider: \`${r.type}\``);try{if(e.stepId===t.stepId){let a=await this.createStepControls(t,e),d=await r.resolve({controls:a,outputs:s}),c=await this.validate(d,r.outputs.unknownSchema,"step","output",e.workflowId,t.stepId,r.type);return i.succeed(`Executed provider: \`${r.type}\``),{...c,_passthrough:d._passthrough}}else return i.stopAndPersist({symbol:p.HYDRATED,text:`Hydrated provider: \`${r.type}\``}),{}}catch(a){throw i.stopAndPersist({symbol:p.ERROR,text:`Failed to execute provider: \`${r.type}\``}),new Q(`Failed to execute provider: '${r.type}'.
28
- ${a.message}`)}}async executeStep(e,t){if(e.stepId===t.stepId){let r=le__default.default({indent:1}).start(`Executing stepId: \`${t.stepId}\``);try{let s=await this.createStepControls(t,e),i=await this.compileControls(s,e),a=await t.resolve(i),d=await this.validate(a,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId),c=await this.executeProviders(e,t,d);return r.succeed(`Executed stepId: \`${t.stepId}\``),{outputs:d,providers:c}}catch(s){throw r.stopAndPersist({prefixText:"",symbol:p.ERROR,text:`Failed to execute stepId: \`${t.stepId}\``}),s}}else {let r=le__default.default({indent:1}).start(`Hydrating stepId: \`${t.stepId}\``);try{let s=e.state.find(i=>i.stepId===t.stepId);if(s){let i=await this.validate(s.outputs,t.results.unknownSchema,"step","result",e.workflowId,t.stepId);return r.stopAndPersist({symbol:p.HYDRATED,text:`Hydrated stepId: \`${t.stepId}\``}),{outputs:i,providers:await this.executeProviders(e,t,i)}}else throw new b(e.workflowId,t.stepId)}catch(s){throw r.stopAndPersist({symbol:p.ERROR,text:`Failed to hydrate stepId: \`${t.stepId}\``}),s}}}async compileControls(e,t){try{let r=this.templateEngine.parse(JSON.stringify(e)),s=await this.templateEngine.render(r,{payload:t.payload||t.data,subscriber:t.subscriber,...t.payload||t.data});return JSON.parse(s)}catch(r){throw new K(t.workflowId,t.stepId,r)}}async createStepControls(e,t){let r=t.controls||t.inputs;return await this.validate(r,e.controls.unknownSchema,"step","controls",t.workflowId,e.stepId)}async previewStep(e,t){let r=le__default.default({indent:1}).start(`Previewing stepId: \`${t.stepId}\``);try{if(e.stepId===t.stepId){let s=await this.createStepControls(t,e),i=await this.compileControls(s,e),a=await t.resolve(i),d=await this.validate(a,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId);return r.stopAndPersist({symbol:p.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:d,providers:await this.executeProviders(e,t,d)}}else {let s=this.mock(t.results.schema);return r.stopAndPersist({symbol:p.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:s,providers:await this.executeProviders(e,t,s)}}}catch(s){throw r.stopAndPersist({symbol:p.ERROR,text:`Failed to preview stepId: \`${t.stepId}\``}),s}}getStepCode(e,t){return {code:this.getStep(e,t).resolve.toString()}}getWorkflowCode(e){return {code:this.getWorkflow(e).execute.toString()}}getCode(e,t){let r;if(e)t?r=this.getStepCode(e,t):r=this.getWorkflowCode(e);else throw new U(e);return r}};var _e=class{frameworkName;handler;client;hmacEnabled;http;constructor(e){this.handler=e.handler,this.client=e.client?e.client:new pe,this.client.addWorkflows(e.workflows),this.http=Ae(this.client.secretKey),this.frameworkName=e.frameworkName,this.hmacEnabled=this.client.strictAuthentication;}createHandler(){return async(...e)=>{let t=await this.handler(...e),r=await this.handleAction({actions:t});return t.transformResponse(r)}}getStaticHeaders(){let e=`novu-framework:v${this.client.version}`;return {"content-type":"application/json","access-control-allow-origin":"*","access-control-allow-methods":"GET, POST","access-control-allow-headers":"*","access-control-max-age":"604800","novu-framework-version":F,"novu-framework-sdk":y,"novu-framework-server":this.frameworkName,"user-agent":e}}createResponse(e,t){return {status:e,body:JSON.stringify(t),headers:{...this.getStaticHeaders()}}}createError(e){return {status:e.statusCode,body:JSON.stringify({message:e.message,data:e.data,code:e.code}),headers:this.getStaticHeaders()}}async handleAction({actions:e}){let t=await e.url(),r=await e.method(),s=t.searchParams.get("action")||"",i=t.searchParams.get("workflowId")||"",a=t.searchParams.get("stepId")||"",d=await e.headers("novu-signature")||await e.headers("x-novu-signature")||"",c={};try{r==="POST"&&(c=await e.body());}catch{}try{s!=="health-check"&&this.validateHmac(c,d);let O=this.getPostActionMap(c,i,a,s),_=this.getGetActionMap(i,a);if(r==="POST")return await this.handlePostAction(s,O);if(r==="GET")return await this.handleGetAction(s,_);if(r==="OPTIONS")return this.createResponse(200,{})}catch(O){return this.handleError(O)}return this.createError(new z(r))}getPostActionMap(e,t,r,s){return {trigger:this.triggerAction({workflowId:t,...e}),execute:async()=>{let i=await this.client.executeWorkflow({...e,workflowId:t,stepId:r,action:s});return this.createResponse(200,i)},preview:async()=>{let i=await this.client.executeWorkflow({...e,workflowId:t,stepId:r,action:s});return this.createResponse(200,i)}}}triggerAction(e){return async()=>{let t={name:e.workflowId,to:e.to,payload:e?.payload||{},transactionId:e.transactionId,overrides:e.overrides||{},...e.actor&&{actor:e.actor},...e.bridgeUrl&&{bridgeUrl:e.bridgeUrl},...e.controls&&{controls:e.controls}},r=await this.http.post("/events/trigger",t);return this.createResponse(200,r)}}getGetActionMap(e,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(e,t);return this.createResponse(200,r)}}}async handlePostAction(e,t){if(Object.values(D).includes(e)){let r=t[e];return r()}else throw new x(e,D)}async handleGetAction(e,t){if(Object.values(M).includes(e)){let r=t[e];return r()}else throw new x(e,M)}isBridgeError(e){return Object.values(R).includes(e?.code)}isPlatformError(e){return e?.statusCode>=400&&e?.statusCode<500}handleError(e){return this.isBridgeError(e)?(e.statusCode===500&&console.error(e),this.createError(e)):this.isPlatformError(e)?this.createError(e):(console.error(e),this.createError(new v))}validateHmac(e,t){if(!this.hmacEnabled)return;if(!t)throw new ee;if(!this.client.secretKey)throw new oe;let[r,s]=t.split(",");if(!r||!s)throw new te;let[i,a]=r.split("="),[d,c]=s.split("=");if(Number(i)<Date.now()-1500)throw new re;if(!(this.hashHmac(this.client.secretKey,`${a}.${JSON.stringify(e)}`)===c))throw new H}hashHmac(e,t){return crypto.createHmac("sha256",e).update(t).digest("hex")}};var Ke="h3",Hr=o=>new _e({frameworkName:Ke,...o,handler:t=>({body:()=>h3.readBody(t),headers:r=>h3.getHeader(t,r),method:()=>t.method,url:()=>new URL(String(t.path),`${process.env.NODE_ENV==="development"?"http":"https"}://${String(h3.getHeader(t,"host"))}`),queryString:r=>String(h3.getQuery(t)[r]),transformResponse:r=>{let{res:s}=t.node;return s.statusCode=r.status,h3.setHeaders(t,r.headers),h3.send(t,r.body)}})}).createHandler();
28
+ ${a.message}`)}}async executeStep(e,t){if(e.stepId===t.stepId){let r=le__default.default({indent:1}).start(`Executing stepId: \`${t.stepId}\``);try{let s=await this.createStepControls(t,e),i=await this.compileControls(s,e),a=await t.resolve(i),d=await this.validate(a,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId),c=await this.executeProviders(e,t,d);return r.succeed(`Executed stepId: \`${t.stepId}\``),{outputs:d,providers:c}}catch(s){throw r.stopAndPersist({prefixText:"",symbol:p.ERROR,text:`Failed to execute stepId: \`${t.stepId}\``}),s}}else {let r=le__default.default({indent:1}).start(`Hydrating stepId: \`${t.stepId}\``);try{let s=e.state.find(i=>i.stepId===t.stepId);if(s){let i=await this.validate(s.outputs,t.results.unknownSchema,"step","result",e.workflowId,t.stepId);return r.stopAndPersist({symbol:p.HYDRATED,text:`Hydrated stepId: \`${t.stepId}\``}),{outputs:i,providers:await this.executeProviders(e,t,i)}}else throw new b(e.workflowId,t.stepId)}catch(s){throw r.stopAndPersist({symbol:p.ERROR,text:`Failed to hydrate stepId: \`${t.stepId}\``}),s}}}async compileControls(e,t){try{let r=this.templateEngine.parse(JSON.stringify(e)),s=await this.templateEngine.render(r,{payload:t.payload||t.data,subscriber:t.subscriber,...t.payload||t.data});return JSON.parse(s)}catch(r){throw new K(t.workflowId,t.stepId,r)}}async createStepControls(e,t){let r=t.controls||t.inputs;return await this.validate(r,e.controls.unknownSchema,"step","controls",t.workflowId,e.stepId)}async previewStep(e,t){let r=le__default.default({indent:1}).start(`Previewing stepId: \`${t.stepId}\``);try{if(e.stepId===t.stepId){let s=await this.createStepControls(t,e),i=await this.compileControls(s,e),a=await t.resolve(i),d=await this.validate(a,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId);return r.stopAndPersist({symbol:p.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:d,providers:await this.executeProviders(e,t,d)}}else {let s=this.mock(t.results.schema);return r.stopAndPersist({symbol:p.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:s,providers:await this.executeProviders(e,t,s)}}}catch(s){throw r.stopAndPersist({symbol:p.ERROR,text:`Failed to preview stepId: \`${t.stepId}\``}),s}}getStepCode(e,t){return {code:this.getStep(e,t).resolve.toString()}}getWorkflowCode(e){return {code:this.getWorkflow(e).execute.toString()}}getCode(e,t){let r;if(e)t?r=this.getStepCode(e,t):r=this.getWorkflowCode(e);else throw new k(e);return r}};var _e=class{frameworkName;handler;client;hmacEnabled;http;constructor(e){this.handler=e.handler,this.client=e.client?e.client:new pe,this.client.addWorkflows(e.workflows),this.http=Ae(this.client.secretKey),this.frameworkName=e.frameworkName,this.hmacEnabled=this.client.strictAuthentication;}createHandler(){return async(...e)=>{let t=await this.handler(...e),r=await this.handleAction({actions:t});return t.transformResponse(r)}}getStaticHeaders(){let e=`novu-framework:v${this.client.version}`;return {"content-type":"application/json","access-control-allow-origin":"*","access-control-allow-methods":"GET, POST","access-control-allow-headers":"*","access-control-max-age":"604800","novu-framework-version":F,"novu-framework-sdk":y,"novu-framework-server":this.frameworkName,"user-agent":e}}createResponse(e,t){return {status:e,body:JSON.stringify(t),headers:{...this.getStaticHeaders()}}}createError(e){return {status:e.statusCode,body:JSON.stringify({message:e.message,data:e.data,code:e.code}),headers:this.getStaticHeaders()}}async handleAction({actions:e}){let t=await e.url(),r=await e.method(),s=t.searchParams.get("action")||"",i=t.searchParams.get("workflowId")||"",a=t.searchParams.get("stepId")||"",d=await e.headers("novu-signature")||await e.headers("x-novu-signature")||"",c={};try{r==="POST"&&(c=await e.body());}catch{}try{s!=="health-check"&&this.validateHmac(c,d);let O=this.getPostActionMap(c,i,a,s),_=this.getGetActionMap(i,a);if(r==="POST")return await this.handlePostAction(s,O);if(r==="GET")return await this.handleGetAction(s,_);if(r==="OPTIONS")return this.createResponse(200,{})}catch(O){return this.handleError(O)}return this.createError(new z(r))}getPostActionMap(e,t,r,s){return {trigger:this.triggerAction({workflowId:t,...e}),execute:async()=>{let i=await this.client.executeWorkflow({...e,workflowId:t,stepId:r,action:s});return this.createResponse(200,i)},preview:async()=>{let i=await this.client.executeWorkflow({...e,workflowId:t,stepId:r,action:s});return this.createResponse(200,i)}}}triggerAction(e){return async()=>{let t={name:e.workflowId,to:e.to,payload:e?.payload||{},transactionId:e.transactionId,overrides:e.overrides||{},...e.actor&&{actor:e.actor},...e.bridgeUrl&&{bridgeUrl:e.bridgeUrl},...e.controls&&{controls:e.controls}},r=await this.http.post("/events/trigger",t);return this.createResponse(200,r)}}getGetActionMap(e,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(e,t);return this.createResponse(200,r)}}}async handlePostAction(e,t){if(Object.values(D).includes(e)){let r=t[e];return r()}else throw new x(e,D)}async handleGetAction(e,t){if(Object.values(V).includes(e)){let r=t[e];return r()}else throw new x(e,V)}isBridgeError(e){return Object.values(u).includes(e?.code)}isPlatformError(e){return e?.statusCode>=400&&e?.statusCode<500}handleError(e){return this.isBridgeError(e)?(e.statusCode===500&&console.error(e),this.createError(e)):this.isPlatformError(e)?this.createError(e):(console.error(e),this.createError(new v))}validateHmac(e,t){if(!this.hmacEnabled)return;if(!t)throw new ee;if(!this.client.secretKey)throw new oe;let[r,s]=t.split(",");if(!r||!s)throw new te;let[i,a]=r.split("="),[d,c]=s.split("=");if(Number(i)<Date.now()-1500)throw new re;if(!(this.hashHmac(this.client.secretKey,`${a}.${JSON.stringify(e)}`)===c))throw new H}hashHmac(e,t){return crypto.createHmac("sha256",e).update(t).digest("hex")}};var Ke="h3",to=o=>new _e({frameworkName:Ke,...o,handler:t=>({body:()=>h3.readBody(t),headers:r=>h3.getHeader(t,r),method:()=>t.method,url:()=>new URL(String(t.path),`${process.env.NODE_ENV==="development"?"http":"https"}://${String(h3.getHeader(t,"host"))}`),queryString:r=>String(h3.getQuery(t)[r]),transformResponse:r=>{let{res:s}=t.node;return s.statusCode=r.status,h3.setHeaders(t,r.headers),h3.send(t,r.body)}})}).createHandler();
29
29
 
30
30
  exports.frameworkName = Ke;
31
- exports.serve = Hr;
31
+ exports.serve = to;
@@ -1,6 +1,6 @@
1
1
  import * as aws_lambda from 'aws-lambda';
2
2
  import { APIGatewayProxyEventV2, APIGatewayProxyResult } from 'aws-lambda';
3
- import { v as SupportedFrameworkName, c as ServeHandlerOptions, af as Either } from '../handler-xDdUZXcL.js';
3
+ import { w as SupportedFrameworkName, c as ServeHandlerOptions, ag as Either } from '../handler-WKKD7ESp.js';
4
4
  import '@novu/shared';
5
5
  import 'json-schema-to-ts';
6
6
  import 'zod';
@@ -8,7 +8,7 @@ require('cross-fetch');
8
8
  var N = require('chalk');
9
9
  var shared = require('@novu/shared');
10
10
  var me = require('sanitize-html');
11
- var Ue = require('ajv');
11
+ var ke = require('ajv');
12
12
  var Ve = require('ajv-formats');
13
13
  var zodToJsonSchema = require('zod-to-json-schema');
14
14
 
@@ -17,14 +17,14 @@ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
17
17
  var le__default = /*#__PURE__*/_interopDefault(le);
18
18
  var N__default = /*#__PURE__*/_interopDefault(N);
19
19
  var me__default = /*#__PURE__*/_interopDefault(me);
20
- var Ue__default = /*#__PURE__*/_interopDefault(Ue);
20
+ var ke__default = /*#__PURE__*/_interopDefault(ke);
21
21
  var Ve__default = /*#__PURE__*/_interopDefault(Ve);
22
22
 
23
- var S=(r=>(r.TRIGGER="trigger",r.EXECUTE="execute",r.PREVIEW="preview",r))(S||{}),M=(r=>(r.DISCOVER="discover",r.HEALTH_CHECK="health-check",r.CODE="code",r))(M||{});var _=(c=>(c.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",c.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",c.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",c.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",c.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",c.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",c.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",c.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",c.STEP_NOT_FOUND_ERROR="StepNotFoundError",c.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",c.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",c.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",c.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",c.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",c.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",c.STEP_CONTROL_COMPILATION_FAILED_ERROR="StepControlCompilationFailedError",c.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",c.INVALID_ACTION_ERROR="InvalidActionError",c.MISSING_SECRET_KEY_ERROR="MissingSecretKeyError",c.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",c.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",c.SIGNATURE_INVALID_ERROR="SignatureInvalidError",c.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",c.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",c.BRIDGE_ERROR="BridgeError",c.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",c.WORKFLOW_PAYLOAD_INVALID_ERROR="WorkflowPayloadInvalidError",c))(_||{});var Y=(r=>(r.POST="POST",r.GET="GET",r.OPTIONS="OPTIONS",r))(Y||{});var Re=(i=>(i.EMAIL="email",i.SMS="sms",i.PUSH="push",i.CHAT="chat",i.IN_APP="in_app",i))(Re||{});var he="2.0.2";var P=he,F="2024-06-26";var E=class extends Error{data},C=class extends E{statusCode=404},R=class extends E{statusCode=400},I=class extends E{statusCode=401},f=class extends E{statusCode=500},b=class extends E{statusCode=409};var L=class extends R{code="ExecutionStateCorruptError";constructor(e,t){super(`Workflow with id: \`${e}\` has a corrupt state. Step with id: \`${t}\` does not exist. Please provide the missing state.`),this.data={workflowId:e,stepId:t};}},D=class extends R{code="ExecutionEventPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct event payload.`),this.data=t;}},W=class extends R{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},$=class extends R{code="ExecutionStateControlInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid \`controls\`. Please provide the correct step controls.`),this.data=r;}},G=class extends R{code="ExecutionStateOutputInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid output. Please provide the correct step output.`),this.data=r;}},j=class extends R{code="ExecutionStateResultInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid result. Please provide the correct step result.`),this.data=r;}},K=class extends R{code="StepControlCompilationFailedError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has invalid controls syntax in step with id: \`${t}\`. Please correct step control syntax.`),this.data=r;}},B=class extends R{code="ExecutionProviderOutputInvalidError";constructor(e,t,r,o){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` and provider with id: \`${r}\` has invalid output. Please provide the correct provider output.`),this.data=o;}};var X=class extends E{statusCode;data;code;constructor(e,t,r){super(),this.data={message:r},this.statusCode=e,this.code=t;}};var l={info:s=>N__default.default.blue(s),warning:s=>N__default.default.yellow(s),error:s=>N__default.default.red(s),success:s=>N__default.default.green(s),underline:s=>N__default.default.underline(s),bold:s=>N__default.default.bold(s)},p={SUCCESS:l.success("\u2714"),ERROR:l.error("\u2717"),WARNING:l.warning("\u26A0"),INFO:l.info("\u2139"),ARROW:l.bold("\u2192"),MOCK:l.info("\u25CB"),HYDRATED:l.bold(l.info("\u2192")),STEP:l.info("\u03C3"),ACTION:l.info("\u03B1"),DURATION:l.info("\u0394"),PROVIDER:l.info("\u2699"),OUTPUT:l.info("\u21E2"),INPUT:l.info("\u21E0"),WORKFLOW:l.info("\u03C9"),STATE:l.info("\u03C3"),EXECUTE:l.info("\u03B5"),PREVIEW:l.info("\u03C1")};var _e=s=>Object.values(s).map(e=>`\`${e}\``).join(", "),J=s=>s.replaceAll(/(\w)(\w*)/g,(e,t,r)=>t.toUpperCase()+r.toLowerCase()).replaceAll(/[\s-]+/g,"");var Ae=(s,e="https://api.novu.co")=>{let t=process.env.NOVU_API_URL||e;return {post:async(r,o)=>{let i=await fetch(`${t}/v1${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${s}`},body:JSON.stringify(o)}),a=await i.json();if(i.ok)return a;throw shared.checkIsResponseError(a)?new X(a.statusCode,a.error,a.message):new v("Error processing API request to Novu Cloud from Bridge application.")},delete:async r=>(await fetch(`${t}/v1${r}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${s}`}})).json()}};var De={allowedTags:me__default.default.defaults.allowedTags.concat(["style","img","html","head","body","link","meta","title"]),allowedAttributes:!1,allowVulnerableTags:!0,parseStyleAttributes:!1,parser:{lowerCaseAttributeNames:!0}},Ie=s=>{if(!s)return s;let e=/^<!DOCTYPE .*?>/,t=s.match(e),r=me__default.default(s,De);return t?t[0]+r:r},q=s=>Object.keys(s).reduce((e,t)=>{let r=s[t];return typeof r=="string"?e[t]=Ie(r):Array.isArray(r)?e[t]=r.map(o=>typeof o=="string"?Ie(o):typeof o=="object"?q(o):o):typeof r=="object"&&r!==null?e[t]=q(r):e[t]=r,e},{});var z=class extends E{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${_e(Y)}`},x=class extends R{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${_e(t)}`);}};var v=class extends f{code="BridgeError";message="Something went wrong. Please try again later."};var k=class extends b{constructor(e,t){super(`${J(e)} with id: \`${t}\` already exists. Please use a different id.`);}},m=class extends C{constructor(e,t){super(`${J(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},g=class extends f{constructor(e,t){super(`Failed to execute ${J(e)} with id: \`${t}\`. Please try again later.`);}};var Z=class extends m{code="ProviderNotFoundError";constructor(e){super("provider",e);}},Q=class extends g{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var H=class extends I{code="SignatureMismatchError";constructor(){super("Signature does not match the expected signature. Please ensure the signature provided in the `novu-signature` header is correct and try again.");}},ee=class extends I{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},te=class extends I{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},re=class extends I{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},oe=class extends I{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.secretKey`");}};var se=class extends m{code="StepNotFoundError";constructor(e){super("step",e);}};var U=class extends m{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},ie=class extends k{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var fe=s=>typeof structuredClone=="function"?structuredClone(s):JSON.parse(JSON.stringify(s));var ae=class{ajv;compiledSchemas;constructor(){this.ajv=new Ue__default.default({useDefaults:!0,removeAdditional:"failing"}),Ve__default.default(this.ajv),this.compiledSchemas=new Map;}canHandle(e){return typeof e=="boolean"?!1:e.type==="object"||!!e.anyOf||!!e.allOf||!!e.oneOf}async validate(e,t){let r=this.compiledSchemas.get(t);r||(r=this.ajv.compile(t),this.compiledSchemas.set(t,r));let o=fe(e);return r(o)?{success:!0,data:o}:{success:!1,errors:r.errors.map(a=>({path:a.instancePath,message:a.message}))}}transformToJsonSchema(e){return e}};var ne=class{canHandle(e){return e.safeParseAsync!==void 0}async validate(e,t){let r=t.safeParse(e);return r.success?{success:!0,data:r.data}:{success:!1,errors:r.error.errors.map(o=>({path:`/${o.path.join("/")}`,message:o.message}))}}transformToJsonSchema(e){try{return zodToJsonSchema.zodToJsonSchema(e)}catch(t){throw t?.message?.includes("Cannot find module")&&console.error("Tried to use a zod schema in @novu/framework without `zod-to-json-schema` installed. Please install it by running `npm install zod-to-json-schema`."),t}}};var ce=new ne,de=new ae,Ne=async(s,e)=>{if(ce.canHandle(s))return ce.validate(e,s);if(de.canHandle(s))return de.validate(e,s);throw new Error("Invalid schema")},ve=s=>{if(ce.canHandle(s))return ce.transformToJsonSchema(s);if(de.canHandle(s))return de.transformToJsonSchema(s);throw new Error("Invalid schema")};jsonSchemaFaker.JSONSchemaFaker.random.shuffle=function(){return ["[placeholder]"]};jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});function Fe(){return ["development",void 0].includes(process.env.NODE_ENV)}var pe=class{discoveredWorkflows=[];templateEngine=new liquidjs.Liquid;secretKey;version=P;strictAuthentication;constructor(e){let t=this.buildOptions(e);this.secretKey=t.secretKey,this.strictAuthentication=t.strictAuthentication;}buildOptions(e){let t={secretKey:void 0,strictAuthentication:!Fe()};return t.secretKey=e?.secretKey||process.env.NOVU_SECRET_KEY||process.env.NOVU_API_KEY,e?.strictAuthentication!==void 0?t.strictAuthentication=e.strictAuthentication:process.env.NOVU_STRICT_AUTHENTICATION_ENABLED!==void 0&&(t.strictAuthentication=process.env.NOVU_STRICT_AUTHENTICATION_ENABLED==="true"),t}addWorkflows(e){for(let t of e){if(this.discoveredWorkflows.some(r=>r.workflowId===t.definition.workflowId))throw new ie(t.definition.workflowId);this.discoveredWorkflows.push(t.definition);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((r,o)=>r+o.steps.length,0);return {status:"ok",sdkVersion:P,frameworkVersion:F,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(r=>r.workflowId===e);if(t)return t;throw new U(e)}getStep(e,t){let o=this.getWorkflow(e).steps.find(i=>i.stepId===t);if(o)return o;throw new se(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(ve(e))}async validate(e,t,r,o,i,a,n){let d=await Ne(t,e);if(d.success)return d.data;switch(r){case"event":this.throwInvalidEvent(o,i,d.errors);case"step":this.throwInvalidStep(a,o,i,d.errors);case"provider":this.throwInvalidProvider(a,n,o,i,d.errors);default:throw new Error(`Invalid component: '${r}'`)}}throwInvalidProvider(e,t,r,o,i){if(!e)throw new Error("stepId is required");if(!t)throw new Error("providerId is required");switch(r){case"output":throw new B(o,e,t,i);default:throw new Error(`Invalid payload type: '${r}'`)}}throwInvalidStep(e,t,r,o){if(!e)throw new Error("stepId is required");switch(t){case"output":throw new G(r,e,o);case"result":throw new j(r,e,o);case"controls":throw new $(r,e,o);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(e,t,r){switch(e){case"controls":throw new W(t,r);case"payload":throw new D(t,r);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(r,o,i)=>{let a=this.getStep(e.workflowId,r),n=await this.createStepControls(a,e),d=e.action==="preview";if(!d&&await this.shouldSkip(i?.skip,n))return r===e.stepId&&t({options:{skip:!0},outputs:{},providers:{}}),{};let O=this.previewStep.bind(this),u=this.executeStep.bind(this),h=await(d?O:u)(e,{...a,providers:a.providers.map(y=>{let V=i?.providers?.[y.type];if(!V)throw new Z(y.type);return {...y,resolve:V}}),resolve:o});return Object.values(Re).includes(a.type)&&(h={...h,outputs:q(h.outputs)}),r===e.stepId&&t({...h,options:{skip:!1}}),h.outputs}}async shouldSkip(e,t){return e?e(t):!1}async executeWorkflow(e){let o=`${e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action"} workflowId:`;console.log(`
23
+ var S=(r=>(r.TRIGGER="trigger",r.EXECUTE="execute",r.PREVIEW="preview",r))(S||{}),M=(r=>(r.DISCOVER="discover",r.HEALTH_CHECK="health-check",r.CODE="code",r))(M||{});var _=(c=>(c.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",c.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",c.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",c.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",c.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",c.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",c.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",c.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",c.STEP_NOT_FOUND_ERROR="StepNotFoundError",c.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",c.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",c.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",c.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",c.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",c.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",c.STEP_CONTROL_COMPILATION_FAILED_ERROR="StepControlCompilationFailedError",c.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",c.INVALID_ACTION_ERROR="InvalidActionError",c.MISSING_SECRET_KEY_ERROR="MissingSecretKeyError",c.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",c.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",c.SIGNATURE_INVALID_ERROR="SignatureInvalidError",c.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",c.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",c.BRIDGE_ERROR="BridgeError",c.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",c.WORKFLOW_PAYLOAD_INVALID_ERROR="WorkflowPayloadInvalidError",c))(_||{});var Y=(r=>(r.POST="POST",r.GET="GET",r.OPTIONS="OPTIONS",r))(Y||{});var Re=(i=>(i.EMAIL="email",i.SMS="sms",i.PUSH="push",i.CHAT="chat",i.IN_APP="in_app",i))(Re||{});var he="2.0.3";var P=he,F="2024-06-26";var E=class extends Error{data},C=class extends E{statusCode=404},R=class extends E{statusCode=400},I=class extends E{statusCode=401},f=class extends E{statusCode=500},L=class extends E{statusCode=409};var b=class extends R{code="ExecutionStateCorruptError";constructor(e,t){super(`Workflow with id: \`${e}\` has a corrupt state. Step with id: \`${t}\` does not exist. Please provide the missing state.`),this.data={workflowId:e,stepId:t};}},D=class extends R{code="ExecutionEventPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct event payload.`),this.data=t;}},W=class extends R{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},$=class extends R{code="ExecutionStateControlInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid \`controls\`. Please provide the correct step controls.`),this.data=r;}},G=class extends R{code="ExecutionStateOutputInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid output. Please provide the correct step output.`),this.data=r;}},j=class extends R{code="ExecutionStateResultInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid result. Please provide the correct step result.`),this.data=r;}},K=class extends R{code="StepControlCompilationFailedError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has invalid controls syntax in step with id: \`${t}\`. Please correct step control syntax.`),this.data=r;}},B=class extends R{code="ExecutionProviderOutputInvalidError";constructor(e,t,r,o){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` and provider with id: \`${r}\` has invalid output. Please provide the correct provider output.`),this.data=o;}};var X=class extends E{statusCode;data;code;constructor(e,t,r){super(),this.data={message:r},this.statusCode=e,this.code=t;}};var l={info:s=>N__default.default.blue(s),warning:s=>N__default.default.yellow(s),error:s=>N__default.default.red(s),success:s=>N__default.default.green(s),underline:s=>N__default.default.underline(s),bold:s=>N__default.default.bold(s)},p={SUCCESS:l.success("\u2714"),ERROR:l.error("\u2717"),WARNING:l.warning("\u26A0"),INFO:l.info("\u2139"),ARROW:l.bold("\u2192"),MOCK:l.info("\u25CB"),HYDRATED:l.bold(l.info("\u2192")),STEP:l.info("\u03C3"),ACTION:l.info("\u03B1"),DURATION:l.info("\u0394"),PROVIDER:l.info("\u2699"),OUTPUT:l.info("\u21E2"),INPUT:l.info("\u21E0"),WORKFLOW:l.info("\u03C9"),STATE:l.info("\u03C3"),EXECUTE:l.info("\u03B5"),PREVIEW:l.info("\u03C1")};var _e=s=>Object.values(s).map(e=>`\`${e}\``).join(", "),J=s=>s.replaceAll(/(\w)(\w*)/g,(e,t,r)=>t.toUpperCase()+r.toLowerCase()).replaceAll(/[\s-]+/g,"");var Ae=(s,e="https://api.novu.co")=>{let t=process.env.NOVU_API_URL||e;return {post:async(r,o)=>{let i=await fetch(`${t}/v1${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${s}`},body:JSON.stringify(o)}),a=await i.json();if(i.ok)return a;throw shared.checkIsResponseError(a)?new X(a.statusCode,a.error,a.message):new v("Error processing API request to Novu Cloud from Bridge application.")},delete:async r=>(await fetch(`${t}/v1${r}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${s}`}})).json()}};var De={allowedTags:me__default.default.defaults.allowedTags.concat(["style","img","html","head","body","link","meta","title"]),allowedAttributes:!1,allowVulnerableTags:!0,parseStyleAttributes:!1,parser:{lowerCaseAttributeNames:!0}},Ie=s=>{if(!s)return s;let e=/^<!DOCTYPE .*?>/,t=s.match(e),r=me__default.default(s,De);return t?t[0]+r:r},q=s=>Object.keys(s).reduce((e,t)=>{let r=s[t];return typeof r=="string"?e[t]=Ie(r):Array.isArray(r)?e[t]=r.map(o=>typeof o=="string"?Ie(o):typeof o=="object"?q(o):o):typeof r=="object"&&r!==null?e[t]=q(r):e[t]=r,e},{});var z=class extends E{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${_e(Y)}`},x=class extends R{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${_e(t)}`);}};var v=class extends f{code="BridgeError";message="Something went wrong. Please try again later."};var U=class extends L{constructor(e,t){super(`${J(e)} with id: \`${t}\` already exists. Please use a different id.`);}},m=class extends C{constructor(e,t){super(`${J(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},g=class extends f{constructor(e,t){super(`Failed to execute ${J(e)} with id: \`${t}\`. Please try again later.`);}};var Z=class extends m{code="ProviderNotFoundError";constructor(e){super("provider",e);}},Q=class extends g{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var H=class extends I{code="SignatureMismatchError";constructor(){super("Signature does not match the expected signature. Please ensure the signature provided in the `novu-signature` header is correct and try again.");}},ee=class extends I{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},te=class extends I{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},re=class extends I{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},oe=class extends I{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.secretKey`");}};var se=class extends m{code="StepNotFoundError";constructor(e){super("step",e);}};var k=class extends m{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},ie=class extends U{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var fe=s=>typeof structuredClone=="function"?structuredClone(s):JSON.parse(JSON.stringify(s));var ae=class{ajv;compiledSchemas;constructor(){this.ajv=new ke__default.default({useDefaults:!0,removeAdditional:"failing"}),Ve__default.default(this.ajv),this.compiledSchemas=new Map;}canHandle(e){return typeof e=="boolean"?!1:e.type==="object"||!!e.anyOf||!!e.allOf||!!e.oneOf}async validate(e,t){let r=this.compiledSchemas.get(t);r||(r=this.ajv.compile(t),this.compiledSchemas.set(t,r));let o=fe(e);return r(o)?{success:!0,data:o}:{success:!1,errors:r.errors.map(a=>({path:a.instancePath,message:a.message}))}}transformToJsonSchema(e){return e}};var ne=class{canHandle(e){return e.safeParseAsync!==void 0}async validate(e,t){let r=t.safeParse(e);return r.success?{success:!0,data:r.data}:{success:!1,errors:r.error.errors.map(o=>({path:`/${o.path.join("/")}`,message:o.message}))}}transformToJsonSchema(e){try{return zodToJsonSchema.zodToJsonSchema(e)}catch(t){throw t?.message?.includes("Cannot find module")&&console.error("Tried to use a zod schema in @novu/framework without `zod-to-json-schema` installed. Please install it by running `npm install zod-to-json-schema`."),t}}};var ce=new ne,de=new ae,Ne=async(s,e)=>{if(ce.canHandle(s))return ce.validate(e,s);if(de.canHandle(s))return de.validate(e,s);throw new Error("Invalid schema")},ve=s=>{if(ce.canHandle(s))return ce.transformToJsonSchema(s);if(de.canHandle(s))return de.transformToJsonSchema(s);throw new Error("Invalid schema")};jsonSchemaFaker.JSONSchemaFaker.random.shuffle=function(){return ["[placeholder]"]};jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});function Fe(){return ["development",void 0].includes(process.env.NODE_ENV)}var pe=class{discoveredWorkflows=[];templateEngine=new liquidjs.Liquid;secretKey;version=P;strictAuthentication;constructor(e){let t=this.buildOptions(e);this.secretKey=t.secretKey,this.strictAuthentication=t.strictAuthentication;}buildOptions(e){let t={secretKey:void 0,strictAuthentication:!Fe()};return t.secretKey=e?.secretKey||process.env.NOVU_SECRET_KEY||process.env.NOVU_API_KEY,e?.strictAuthentication!==void 0?t.strictAuthentication=e.strictAuthentication:process.env.NOVU_STRICT_AUTHENTICATION_ENABLED!==void 0&&(t.strictAuthentication=process.env.NOVU_STRICT_AUTHENTICATION_ENABLED==="true"),t}addWorkflows(e){for(let t of e){if(this.discoveredWorkflows.some(r=>r.workflowId===t.definition.workflowId))throw new ie(t.definition.workflowId);this.discoveredWorkflows.push(t.definition);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((r,o)=>r+o.steps.length,0);return {status:"ok",sdkVersion:P,frameworkVersion:F,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(r=>r.workflowId===e);if(t)return t;throw new k(e)}getStep(e,t){let o=this.getWorkflow(e).steps.find(i=>i.stepId===t);if(o)return o;throw new se(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(ve(e))}async validate(e,t,r,o,i,a,n){let d=await Ne(t,e);if(d.success)return d.data;switch(r){case"event":this.throwInvalidEvent(o,i,d.errors);case"step":this.throwInvalidStep(a,o,i,d.errors);case"provider":this.throwInvalidProvider(a,n,o,i,d.errors);default:throw new Error(`Invalid component: '${r}'`)}}throwInvalidProvider(e,t,r,o,i){if(!e)throw new Error("stepId is required");if(!t)throw new Error("providerId is required");switch(r){case"output":throw new B(o,e,t,i);default:throw new Error(`Invalid payload type: '${r}'`)}}throwInvalidStep(e,t,r,o){if(!e)throw new Error("stepId is required");switch(t){case"output":throw new G(r,e,o);case"result":throw new j(r,e,o);case"controls":throw new $(r,e,o);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(e,t,r){switch(e){case"controls":throw new W(t,r);case"payload":throw new D(t,r);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(r,o,i)=>{let a=this.getStep(e.workflowId,r),n=await this.createStepControls(a,e),d=e.action==="preview";if(!d&&await this.shouldSkip(i?.skip,n))return r===e.stepId&&t({options:{skip:!0},outputs:{},providers:{}}),{};let O=this.previewStep.bind(this),u=this.executeStep.bind(this),h=await(d?O:u)(e,{...a,providers:a.providers.map(y=>{let V=i?.providers?.[y.type];if(!V)throw new Z(y.type);return {...y,resolve:V}}),resolve:o});return Object.values(Re).includes(a.type)&&(h={...h,outputs:q(h.outputs)}),r===e.stepId&&t({...h,options:{skip:!1}}),h.outputs}}async shouldSkip(e,t){return e?e(t):!1}async executeWorkflow(e){let o=`${e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action"} workflowId:`;console.log(`
24
24
  ${l.bold(l.underline(o))} '${e.workflowId}'`);let i=this.getWorkflow(e.workflowId),a=process.hrtime(),n={outputs:{},providers:{},options:{skip:!1}},d,O=new Promise(T=>{d=T;}),u=T=>{d(),n=T;},w;try{if(e.action==="execute"&&!e.payload&&!e.data)throw new D(e.workflowId,{message:"Event `payload` is required"});let T=await this.createExecutionPayload(e,i),A={...e,payload:T};await Promise.race([O,i.execute({payload:T,environment:{},input:{},controls:{},subscriber:e.subscriber,step:{email:this.executeStepFactory(A,u),sms:this.executeStepFactory(A,u),inApp:this.executeStepFactory(A,u),digest:this.executeStepFactory(A,u),delay:this.executeStepFactory(A,u),push:this.executeStepFactory(A,u),chat:this.executeStepFactory(A,u),custom:this.executeStepFactory(A,u)}})]);}catch(T){w=T;}let h=process.hrtime(a),y=h[0],V=h[1],Oe=y*1e3+V/1e6,ge=w?p.ERROR:p.SUCCESS,ye=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action";if(console.log(`${ge} ${ye} workflowId: \`${e.workflowId}\``),this.prettyPrintExecute(e,Oe,w),w)throw w;return {outputs:n.outputs,providers:n.providers,options:n.options,metadata:{status:"success",error:!1,duration:Oe}}}async createExecutionPayload(e,t){let r=e.payload||e.data;if(e.action==="preview"){let i=this.mock(t.payload.schema);r=Object.assign(i,r);}return await this.validate(r,t.payload.unknownSchema,"event","payload",e.workflowId)}prettyPrintExecute(e,t,r){let o=r?p.ERROR:p.SUCCESS,i=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action",a=r?"Failed to execute":i,n=r?l.error:l.success,d=`${o} ${a} workflowId: '${e.workflowId}`;console.log(`
25
25
  ${l.bold(n(d))}'`),console.log(` \u251C ${p.STEP} stepId: '${e.stepId}'`),console.log(` \u251C ${p.ACTION} action: '${e.action}'`),console.log(` \u2514 ${p.DURATION} duration: '${t.toFixed(2)}ms'
26
26
  `);}async executeProviders(e,t,r){return t.providers.reduce(async(o,i)=>{let a=await o,n=this.previewProvider.bind(this),d=this.executeProvider.bind(this),u=await(e.action==="preview"?n:d)(e,t,i,r);return {...a,[i.type]:u}},Promise.resolve({}))}previewProvider(e,t,r,o){return console.log(` ${p.MOCK} Mocked provider: \`${r.type}\``),this.mock(r.outputs.schema)}async executeProvider(e,t,r,o){let i=le__default.default({indent:2}).start(`Executing provider: \`${r.type}\``);try{if(e.stepId===t.stepId){let a=await this.createStepControls(t,e),n=await r.resolve({controls:a,outputs:o}),d=await this.validate(n,r.outputs.unknownSchema,"step","output",e.workflowId,t.stepId,r.type);return i.succeed(`Executed provider: \`${r.type}\``),{...d,_passthrough:n._passthrough}}else return i.stopAndPersist({symbol:p.HYDRATED,text:`Hydrated provider: \`${r.type}\``}),{}}catch(a){throw i.stopAndPersist({symbol:p.ERROR,text:`Failed to execute provider: \`${r.type}\``}),new Q(`Failed to execute provider: '${r.type}'.
27
- ${a.message}`)}}async executeStep(e,t){if(e.stepId===t.stepId){let r=le__default.default({indent:1}).start(`Executing stepId: \`${t.stepId}\``);try{let o=await this.createStepControls(t,e),i=await this.compileControls(o,e),a=await t.resolve(i),n=await this.validate(a,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId),d=await this.executeProviders(e,t,n);return r.succeed(`Executed stepId: \`${t.stepId}\``),{outputs:n,providers:d}}catch(o){throw r.stopAndPersist({prefixText:"",symbol:p.ERROR,text:`Failed to execute stepId: \`${t.stepId}\``}),o}}else {let r=le__default.default({indent:1}).start(`Hydrating stepId: \`${t.stepId}\``);try{let o=e.state.find(i=>i.stepId===t.stepId);if(o){let i=await this.validate(o.outputs,t.results.unknownSchema,"step","result",e.workflowId,t.stepId);return r.stopAndPersist({symbol:p.HYDRATED,text:`Hydrated stepId: \`${t.stepId}\``}),{outputs:i,providers:await this.executeProviders(e,t,i)}}else throw new L(e.workflowId,t.stepId)}catch(o){throw r.stopAndPersist({symbol:p.ERROR,text:`Failed to hydrate stepId: \`${t.stepId}\``}),o}}}async compileControls(e,t){try{let r=this.templateEngine.parse(JSON.stringify(e)),o=await this.templateEngine.render(r,{payload:t.payload||t.data,subscriber:t.subscriber,...t.payload||t.data});return JSON.parse(o)}catch(r){throw new K(t.workflowId,t.stepId,r)}}async createStepControls(e,t){let r=t.controls||t.inputs;return await this.validate(r,e.controls.unknownSchema,"step","controls",t.workflowId,e.stepId)}async previewStep(e,t){let r=le__default.default({indent:1}).start(`Previewing stepId: \`${t.stepId}\``);try{if(e.stepId===t.stepId){let o=await this.createStepControls(t,e),i=await this.compileControls(o,e),a=await t.resolve(i),n=await this.validate(a,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId);return r.stopAndPersist({symbol:p.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:n,providers:await this.executeProviders(e,t,n)}}else {let o=this.mock(t.results.schema);return r.stopAndPersist({symbol:p.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:o,providers:await this.executeProviders(e,t,o)}}}catch(o){throw r.stopAndPersist({symbol:p.ERROR,text:`Failed to preview stepId: \`${t.stepId}\``}),o}}getStepCode(e,t){return {code:this.getStep(e,t).resolve.toString()}}getWorkflowCode(e){return {code:this.getWorkflow(e).execute.toString()}}getCode(e,t){let r;if(e)t?r=this.getStepCode(e,t):r=this.getWorkflowCode(e);else throw new U(e);return r}};var ue=class{frameworkName;handler;client;hmacEnabled;http;constructor(e){this.handler=e.handler,this.client=e.client?e.client:new pe,this.client.addWorkflows(e.workflows),this.http=Ae(this.client.secretKey),this.frameworkName=e.frameworkName,this.hmacEnabled=this.client.strictAuthentication;}createHandler(){return async(...e)=>{let t=await this.handler(...e),r=await this.handleAction({actions:t});return t.transformResponse(r)}}getStaticHeaders(){let e=`novu-framework:v${this.client.version}`;return {"content-type":"application/json","access-control-allow-origin":"*","access-control-allow-methods":"GET, POST","access-control-allow-headers":"*","access-control-max-age":"604800","novu-framework-version":F,"novu-framework-sdk":P,"novu-framework-server":this.frameworkName,"user-agent":e}}createResponse(e,t){return {status:e,body:JSON.stringify(t),headers:{...this.getStaticHeaders()}}}createError(e){return {status:e.statusCode,body:JSON.stringify({message:e.message,data:e.data,code:e.code}),headers:this.getStaticHeaders()}}async handleAction({actions:e}){let t=await e.url(),r=await e.method(),o=t.searchParams.get("action")||"",i=t.searchParams.get("workflowId")||"",a=t.searchParams.get("stepId")||"",n=await e.headers("novu-signature")||await e.headers("x-novu-signature")||"",d={};try{r==="POST"&&(d=await e.body());}catch{}try{o!=="health-check"&&this.validateHmac(d,n);let O=this.getPostActionMap(d,i,a,o),u=this.getGetActionMap(i,a);if(r==="POST")return await this.handlePostAction(o,O);if(r==="GET")return await this.handleGetAction(o,u);if(r==="OPTIONS")return this.createResponse(200,{})}catch(O){return this.handleError(O)}return this.createError(new z(r))}getPostActionMap(e,t,r,o){return {trigger:this.triggerAction({workflowId:t,...e}),execute:async()=>{let i=await this.client.executeWorkflow({...e,workflowId:t,stepId:r,action:o});return this.createResponse(200,i)},preview:async()=>{let i=await this.client.executeWorkflow({...e,workflowId:t,stepId:r,action:o});return this.createResponse(200,i)}}}triggerAction(e){return async()=>{let t={name:e.workflowId,to:e.to,payload:e?.payload||{},transactionId:e.transactionId,overrides:e.overrides||{},...e.actor&&{actor:e.actor},...e.bridgeUrl&&{bridgeUrl:e.bridgeUrl},...e.controls&&{controls:e.controls}},r=await this.http.post("/events/trigger",t);return this.createResponse(200,r)}}getGetActionMap(e,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(e,t);return this.createResponse(200,r)}}}async handlePostAction(e,t){if(Object.values(S).includes(e)){let r=t[e];return r()}else throw new x(e,S)}async handleGetAction(e,t){if(Object.values(M).includes(e)){let r=t[e];return r()}else throw new x(e,M)}isBridgeError(e){return Object.values(_).includes(e?.code)}isPlatformError(e){return e?.statusCode>=400&&e?.statusCode<500}handleError(e){return this.isBridgeError(e)?(e.statusCode===500&&console.error(e),this.createError(e)):this.isPlatformError(e)?this.createError(e):(console.error(e),this.createError(new v))}validateHmac(e,t){if(!this.hmacEnabled)return;if(!t)throw new ee;if(!this.client.secretKey)throw new oe;let[r,o]=t.split(",");if(!r||!o)throw new te;let[i,a]=r.split("="),[n,d]=o.split("=");if(Number(i)<Date.now()-1500)throw new re;if(!(this.hashHmac(this.client.secretKey,`${a}.${JSON.stringify(e)}`)===d))throw new H}hashHmac(e,t){return crypto.createHmac("sha256",e).update(t).digest("hex")}};var Le="lambda",Xr=s=>new ue({frameworkName:Le,...s,handler:t=>{let r=(o=>o.version==="2.0")(t);return {url:()=>{let o=r?t.requestContext.http.path:t.path,i=t.headers["x-forwarded-proto"]||"https",a=new URL(o,`${i}://${t.headers.host||t.headers.Host||""}`);for(let n in t.queryStringParameters)n&&a.searchParams.set(n,t.queryStringParameters[n]);return a},body:()=>{let o="{}";return t.body&&(o=t.isBase64Encoded?Buffer.from(t.body,"base64").toString():t.body),JSON.parse(o)},headers:o=>t.headers[o],queryString:o=>t.queryStringParameters?.[o],transformResponse:({body:o,status:i,headers:a})=>Promise.resolve({body:o,statusCode:i,headers:a}),method:()=>r?t.requestContext.http.method:t.httpMethod}}}).createHandler();
27
+ ${a.message}`)}}async executeStep(e,t){if(e.stepId===t.stepId){let r=le__default.default({indent:1}).start(`Executing stepId: \`${t.stepId}\``);try{let o=await this.createStepControls(t,e),i=await this.compileControls(o,e),a=await t.resolve(i),n=await this.validate(a,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId),d=await this.executeProviders(e,t,n);return r.succeed(`Executed stepId: \`${t.stepId}\``),{outputs:n,providers:d}}catch(o){throw r.stopAndPersist({prefixText:"",symbol:p.ERROR,text:`Failed to execute stepId: \`${t.stepId}\``}),o}}else {let r=le__default.default({indent:1}).start(`Hydrating stepId: \`${t.stepId}\``);try{let o=e.state.find(i=>i.stepId===t.stepId);if(o){let i=await this.validate(o.outputs,t.results.unknownSchema,"step","result",e.workflowId,t.stepId);return r.stopAndPersist({symbol:p.HYDRATED,text:`Hydrated stepId: \`${t.stepId}\``}),{outputs:i,providers:await this.executeProviders(e,t,i)}}else throw new b(e.workflowId,t.stepId)}catch(o){throw r.stopAndPersist({symbol:p.ERROR,text:`Failed to hydrate stepId: \`${t.stepId}\``}),o}}}async compileControls(e,t){try{let r=this.templateEngine.parse(JSON.stringify(e)),o=await this.templateEngine.render(r,{payload:t.payload||t.data,subscriber:t.subscriber,...t.payload||t.data});return JSON.parse(o)}catch(r){throw new K(t.workflowId,t.stepId,r)}}async createStepControls(e,t){let r=t.controls||t.inputs;return await this.validate(r,e.controls.unknownSchema,"step","controls",t.workflowId,e.stepId)}async previewStep(e,t){let r=le__default.default({indent:1}).start(`Previewing stepId: \`${t.stepId}\``);try{if(e.stepId===t.stepId){let o=await this.createStepControls(t,e),i=await this.compileControls(o,e),a=await t.resolve(i),n=await this.validate(a,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId);return r.stopAndPersist({symbol:p.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:n,providers:await this.executeProviders(e,t,n)}}else {let o=this.mock(t.results.schema);return r.stopAndPersist({symbol:p.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:o,providers:await this.executeProviders(e,t,o)}}}catch(o){throw r.stopAndPersist({symbol:p.ERROR,text:`Failed to preview stepId: \`${t.stepId}\``}),o}}getStepCode(e,t){return {code:this.getStep(e,t).resolve.toString()}}getWorkflowCode(e){return {code:this.getWorkflow(e).execute.toString()}}getCode(e,t){let r;if(e)t?r=this.getStepCode(e,t):r=this.getWorkflowCode(e);else throw new k(e);return r}};var ue=class{frameworkName;handler;client;hmacEnabled;http;constructor(e){this.handler=e.handler,this.client=e.client?e.client:new pe,this.client.addWorkflows(e.workflows),this.http=Ae(this.client.secretKey),this.frameworkName=e.frameworkName,this.hmacEnabled=this.client.strictAuthentication;}createHandler(){return async(...e)=>{let t=await this.handler(...e),r=await this.handleAction({actions:t});return t.transformResponse(r)}}getStaticHeaders(){let e=`novu-framework:v${this.client.version}`;return {"content-type":"application/json","access-control-allow-origin":"*","access-control-allow-methods":"GET, POST","access-control-allow-headers":"*","access-control-max-age":"604800","novu-framework-version":F,"novu-framework-sdk":P,"novu-framework-server":this.frameworkName,"user-agent":e}}createResponse(e,t){return {status:e,body:JSON.stringify(t),headers:{...this.getStaticHeaders()}}}createError(e){return {status:e.statusCode,body:JSON.stringify({message:e.message,data:e.data,code:e.code}),headers:this.getStaticHeaders()}}async handleAction({actions:e}){let t=await e.url(),r=await e.method(),o=t.searchParams.get("action")||"",i=t.searchParams.get("workflowId")||"",a=t.searchParams.get("stepId")||"",n=await e.headers("novu-signature")||await e.headers("x-novu-signature")||"",d={};try{r==="POST"&&(d=await e.body());}catch{}try{o!=="health-check"&&this.validateHmac(d,n);let O=this.getPostActionMap(d,i,a,o),u=this.getGetActionMap(i,a);if(r==="POST")return await this.handlePostAction(o,O);if(r==="GET")return await this.handleGetAction(o,u);if(r==="OPTIONS")return this.createResponse(200,{})}catch(O){return this.handleError(O)}return this.createError(new z(r))}getPostActionMap(e,t,r,o){return {trigger:this.triggerAction({workflowId:t,...e}),execute:async()=>{let i=await this.client.executeWorkflow({...e,workflowId:t,stepId:r,action:o});return this.createResponse(200,i)},preview:async()=>{let i=await this.client.executeWorkflow({...e,workflowId:t,stepId:r,action:o});return this.createResponse(200,i)}}}triggerAction(e){return async()=>{let t={name:e.workflowId,to:e.to,payload:e?.payload||{},transactionId:e.transactionId,overrides:e.overrides||{},...e.actor&&{actor:e.actor},...e.bridgeUrl&&{bridgeUrl:e.bridgeUrl},...e.controls&&{controls:e.controls}},r=await this.http.post("/events/trigger",t);return this.createResponse(200,r)}}getGetActionMap(e,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(e,t);return this.createResponse(200,r)}}}async handlePostAction(e,t){if(Object.values(S).includes(e)){let r=t[e];return r()}else throw new x(e,S)}async handleGetAction(e,t){if(Object.values(M).includes(e)){let r=t[e];return r()}else throw new x(e,M)}isBridgeError(e){return Object.values(_).includes(e?.code)}isPlatformError(e){return e?.statusCode>=400&&e?.statusCode<500}handleError(e){return this.isBridgeError(e)?(e.statusCode===500&&console.error(e),this.createError(e)):this.isPlatformError(e)?this.createError(e):(console.error(e),this.createError(new v))}validateHmac(e,t){if(!this.hmacEnabled)return;if(!t)throw new ee;if(!this.client.secretKey)throw new oe;let[r,o]=t.split(",");if(!r||!o)throw new te;let[i,a]=r.split("="),[n,d]=o.split("=");if(Number(i)<Date.now()-1500)throw new re;if(!(this.hashHmac(this.client.secretKey,`${a}.${JSON.stringify(e)}`)===d))throw new H}hashHmac(e,t){return crypto.createHmac("sha256",e).update(t).digest("hex")}};var be="lambda",qr=s=>new ue({frameworkName:be,...s,handler:t=>{let r=(o=>o.version==="2.0")(t);return {url:()=>{let o=r?t.requestContext.http.path:t.path,i=t.headers["x-forwarded-proto"]||"https",a=new URL(o,`${i}://${t.headers.host||t.headers.Host||""}`);for(let n in t.queryStringParameters)n&&a.searchParams.set(n,t.queryStringParameters[n]);return a},body:()=>{let o="{}";return t.body&&(o=t.isBase64Encoded?Buffer.from(t.body,"base64").toString():t.body),JSON.parse(o)},headers:o=>t.headers[o],queryString:o=>t.queryStringParameters?.[o],transformResponse:({body:o,status:i,headers:a})=>Promise.resolve({body:o,statusCode:i,headers:a}),method:()=>r?t.requestContext.http.method:t.httpMethod}}}).createHandler();
28
28
 
29
- exports.frameworkName = Le;
30
- exports.serve = Xr;
29
+ exports.frameworkName = be;
30
+ exports.serve = qr;
@@ -1,6 +1,6 @@
1
1
  import { NextApiResponse } from 'next';
2
2
  import { NextRequest } from 'next/server';
3
- import { v as SupportedFrameworkName, c as ServeHandlerOptions } from '../handler-xDdUZXcL.js';
3
+ import { w as SupportedFrameworkName, c as ServeHandlerOptions } from '../handler-WKKD7ESp.js';
4
4
  import '@novu/shared';
5
5
  import 'json-schema-to-ts';
6
6
  import 'zod';
@@ -7,8 +7,8 @@ var pe = require('ora');
7
7
  var crossFetch = require('cross-fetch');
8
8
  var S = require('chalk');
9
9
  var shared = require('@novu/shared');
10
- var Ie = require('sanitize-html');
11
- var Me = require('ajv');
10
+ var fe = require('sanitize-html');
11
+ var Ve = require('ajv');
12
12
  var Ye = require('ajv-formats');
13
13
  var zodToJsonSchema = require('zod-to-json-schema');
14
14
 
@@ -16,15 +16,15 @@ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
16
16
 
17
17
  var pe__default = /*#__PURE__*/_interopDefault(pe);
18
18
  var S__default = /*#__PURE__*/_interopDefault(S);
19
- var Ie__default = /*#__PURE__*/_interopDefault(Ie);
20
- var Me__default = /*#__PURE__*/_interopDefault(Me);
19
+ var fe__default = /*#__PURE__*/_interopDefault(fe);
20
+ var Ve__default = /*#__PURE__*/_interopDefault(Ve);
21
21
  var Ye__default = /*#__PURE__*/_interopDefault(Ye);
22
22
 
23
- var P=(r=>(r.TRIGGER="trigger",r.EXECUTE="execute",r.PREVIEW="preview",r))(P||{}),Y=(r=>(r.DISCOVER="discover",r.HEALTH_CHECK="health-check",r.CODE="code",r))(Y||{});var h=(l=>(l.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",l.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",l.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",l.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",l.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",l.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",l.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",l.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",l.STEP_NOT_FOUND_ERROR="StepNotFoundError",l.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",l.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",l.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",l.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",l.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",l.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",l.STEP_CONTROL_COMPILATION_FAILED_ERROR="StepControlCompilationFailedError",l.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",l.INVALID_ACTION_ERROR="InvalidActionError",l.MISSING_SECRET_KEY_ERROR="MissingSecretKeyError",l.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",l.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",l.SIGNATURE_INVALID_ERROR="SignatureInvalidError",l.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",l.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",l.BRIDGE_ERROR="BridgeError",l.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",l.WORKFLOW_PAYLOAD_INVALID_ERROR="WorkflowPayloadInvalidError",l))(h||{});var F=(r=>(r.POST="POST",r.GET="GET",r.OPTIONS="OPTIONS",r))(F||{});var _e=(i=>(i.EMAIL="email",i.SMS="sms",i.PUSH="push",i.CHAT="chat",i.IN_APP="in_app",i))(_e||{});var Te="2.0.2";var x=Te,C="2024-06-26";var A=class extends Error{data},L=class extends A{statusCode=404},E=class extends A{statusCode=400},N=class extends A{statusCode=401},g=class extends A{statusCode=500},b=class extends A{statusCode=409};var W=class extends E{code="ExecutionStateCorruptError";constructor(e,t){super(`Workflow with id: \`${e}\` has a corrupt state. Step with id: \`${t}\` does not exist. Please provide the missing state.`),this.data={workflowId:e,stepId:t};}},U=class extends E{code="ExecutionEventPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct event payload.`),this.data=t;}},$=class extends E{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},G=class extends E{code="ExecutionStateControlInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid \`controls\`. Please provide the correct step controls.`),this.data=r;}},j=class extends E{code="ExecutionStateOutputInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid output. Please provide the correct step output.`),this.data=r;}},K=class extends E{code="ExecutionStateResultInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid result. Please provide the correct step result.`),this.data=r;}},q=class extends E{code="StepControlCompilationFailedError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has invalid controls syntax in step with id: \`${t}\`. Please correct step control syntax.`),this.data=r;}},B=class extends E{code="ExecutionProviderOutputInvalidError";constructor(e,t,r,s){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` and provider with id: \`${r}\` has invalid output. Please provide the correct provider output.`),this.data=s;}};var X=class extends A{statusCode;data;code;constructor(e,t,r){super(),this.data={message:r},this.statusCode=e,this.code=t;}};var Ae=()=>typeof Response<"u"?Response:crossFetch.Response;var p={info:o=>S__default.default.blue(o),warning:o=>S__default.default.yellow(o),error:o=>S__default.default.red(o),success:o=>S__default.default.green(o),underline:o=>S__default.default.underline(o),bold:o=>S__default.default.bold(o)},_={SUCCESS:p.success("\u2714"),ERROR:p.error("\u2717"),WARNING:p.warning("\u26A0"),INFO:p.info("\u2139"),ARROW:p.bold("\u2192"),MOCK:p.info("\u25CB"),HYDRATED:p.bold(p.info("\u2192")),STEP:p.info("\u03C3"),ACTION:p.info("\u03B1"),DURATION:p.info("\u0394"),PROVIDER:p.info("\u2699"),OUTPUT:p.info("\u21E2"),INPUT:p.info("\u21E0"),WORKFLOW:p.info("\u03C9"),STATE:p.info("\u03C3"),EXECUTE:p.info("\u03B5"),PREVIEW:p.info("\u03C1")};var Oe=o=>Object.values(o).map(e=>`\`${e}\``).join(", "),J=o=>o.replaceAll(/(\w)(\w*)/g,(e,t,r)=>t.toUpperCase()+r.toLowerCase()).replaceAll(/[\s-]+/g,"");var me=(o,e="https://api.novu.co")=>{let t=process.env.NOVU_API_URL||e;return {post:async(r,s)=>{let i=await fetch(`${t}/v1${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${o}`},body:JSON.stringify(s)}),n=await i.json();if(i.ok)return n;throw shared.checkIsResponseError(n)?new X(n.statusCode,n.error,n.message):new y("Error processing API request to Novu Cloud from Bridge application.")},delete:async r=>(await fetch(`${t}/v1${r}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${o}`}})).json()}};var Ue={allowedTags:Ie__default.default.defaults.allowedTags.concat(["style","img","html","head","body","link","meta","title"]),allowedAttributes:!1,allowVulnerableTags:!0,parseStyleAttributes:!1,parser:{lowerCaseAttributeNames:!0}},fe=o=>{if(!o)return o;let e=/^<!DOCTYPE .*?>/,t=o.match(e),r=Ie__default.default(o,Ue);return t?t[0]+r:r},z=o=>Object.keys(o).reduce((e,t)=>{let r=o[t];return typeof r=="string"?e[t]=fe(r):Array.isArray(r)?e[t]=r.map(s=>typeof s=="string"?fe(s):typeof s=="object"?z(s):s):typeof r=="object"&&r!==null?e[t]=z(r):e[t]=r,e},{});var Z=class extends A{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${Oe(F)}`},k=class extends E{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${Oe(t)}`);}};var y=class extends g{code="BridgeError";message="Something went wrong. Please try again later."};var V=class extends b{constructor(e,t){super(`${J(e)} with id: \`${t}\` already exists. Please use a different id.`);}},v=class extends L{constructor(e,t){super(`${J(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},D=class extends g{constructor(e,t){super(`Failed to execute ${J(e)} with id: \`${t}\`. Please try again later.`);}};var Q=class extends v{code="ProviderNotFoundError";constructor(e){super("provider",e);}},H=class extends D{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var ee=class extends N{code="SignatureMismatchError";constructor(){super("Signature does not match the expected signature. Please ensure the signature provided in the `novu-signature` header is correct and try again.");}},te=class extends N{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},re=class extends N{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},oe=class extends N{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},se=class extends N{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.secretKey`");}};var ie=class extends v{code="StepNotFoundError";constructor(e){super("step",e);}};var M=class extends v{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},ne=class extends V{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var Ne=o=>typeof structuredClone=="function"?structuredClone(o):JSON.parse(JSON.stringify(o));var ae=class{ajv;compiledSchemas;constructor(){this.ajv=new Me__default.default({useDefaults:!0,removeAdditional:"failing"}),Ye__default.default(this.ajv),this.compiledSchemas=new Map;}canHandle(e){return typeof e=="boolean"?!1:e.type==="object"||!!e.anyOf||!!e.allOf||!!e.oneOf}async validate(e,t){let r=this.compiledSchemas.get(t);r||(r=this.ajv.compile(t),this.compiledSchemas.set(t,r));let s=Ne(e);return r(s)?{success:!0,data:s}:{success:!1,errors:r.errors.map(n=>({path:n.instancePath,message:n.message}))}}transformToJsonSchema(e){return e}};var ce=class{canHandle(e){return e.safeParseAsync!==void 0}async validate(e,t){let r=t.safeParse(e);return r.success?{success:!0,data:r.data}:{success:!1,errors:r.error.errors.map(s=>({path:`/${s.path.join("/")}`,message:s.message}))}}transformToJsonSchema(e){try{return zodToJsonSchema.zodToJsonSchema(e)}catch(t){throw t?.message?.includes("Cannot find module")&&console.error("Tried to use a zod schema in @novu/framework without `zod-to-json-schema` installed. Please install it by running `npm install zod-to-json-schema`."),t}}};var de=new ce,le=new ae,ve=async(o,e)=>{if(de.canHandle(o))return de.validate(e,o);if(le.canHandle(o))return le.validate(e,o);throw new Error("Invalid schema")},ge=o=>{if(de.canHandle(o))return de.transformToJsonSchema(o);if(le.canHandle(o))return le.transformToJsonSchema(o);throw new Error("Invalid schema")};jsonSchemaFaker.JSONSchemaFaker.random.shuffle=function(){return ["[placeholder]"]};jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});function Le(){return ["development",void 0].includes(process.env.NODE_ENV)}var ue=class{discoveredWorkflows=[];templateEngine=new liquidjs.Liquid;secretKey;version=x;strictAuthentication;constructor(e){let t=this.buildOptions(e);this.secretKey=t.secretKey,this.strictAuthentication=t.strictAuthentication;}buildOptions(e){let t={secretKey:void 0,strictAuthentication:!Le()};return t.secretKey=e?.secretKey||process.env.NOVU_SECRET_KEY||process.env.NOVU_API_KEY,e?.strictAuthentication!==void 0?t.strictAuthentication=e.strictAuthentication:process.env.NOVU_STRICT_AUTHENTICATION_ENABLED!==void 0&&(t.strictAuthentication=process.env.NOVU_STRICT_AUTHENTICATION_ENABLED==="true"),t}addWorkflows(e){for(let t of e){if(this.discoveredWorkflows.some(r=>r.workflowId===t.definition.workflowId))throw new ne(t.definition.workflowId);this.discoveredWorkflows.push(t.definition);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((r,s)=>r+s.steps.length,0);return {status:"ok",sdkVersion:x,frameworkVersion:C,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(r=>r.workflowId===e);if(t)return t;throw new M(e)}getStep(e,t){let s=this.getWorkflow(e).steps.find(i=>i.stepId===t);if(s)return s;throw new ie(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(ge(e))}async validate(e,t,r,s,i,n,d){let a=await ve(t,e);if(a.success)return a.data;switch(r){case"event":this.throwInvalidEvent(s,i,a.errors);case"step":this.throwInvalidStep(n,s,i,a.errors);case"provider":this.throwInvalidProvider(n,d,s,i,a.errors);default:throw new Error(`Invalid component: '${r}'`)}}throwInvalidProvider(e,t,r,s,i){if(!e)throw new Error("stepId is required");if(!t)throw new Error("providerId is required");switch(r){case"output":throw new B(s,e,t,i);default:throw new Error(`Invalid payload type: '${r}'`)}}throwInvalidStep(e,t,r,s){if(!e)throw new Error("stepId is required");switch(t){case"output":throw new j(r,e,s);case"result":throw new K(r,e,s);case"controls":throw new G(r,e,s);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(e,t,r){switch(e){case"controls":throw new $(t,r);case"payload":throw new U(t,r);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(r,s,i)=>{let n=this.getStep(e.workflowId,r),d=await this.createStepControls(n,e),a=e.action==="preview";if(!a&&await this.shouldSkip(i?.skip,d))return r===e.stepId&&t({options:{skip:!0},outputs:{},providers:{}}),{};let O=this.previewStep.bind(this),c=this.executeStep.bind(this),R=await(a?O:c)(e,{...n,providers:n.providers.map(f=>{let T=i?.providers?.[f.type];if(!T)throw new Q(f.type);return {...f,resolve:T}}),resolve:s});return Object.values(_e).includes(n.type)&&(R={...R,outputs:z(R.outputs)}),r===e.stepId&&t({...R,options:{skip:!1}}),R.outputs}}async shouldSkip(e,t){return e?e(t):!1}async executeWorkflow(e){let s=`${e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action"} workflowId:`;console.log(`
24
- ${p.bold(p.underline(s))} '${e.workflowId}'`);let i=this.getWorkflow(e.workflowId),n=process.hrtime(),d={outputs:{},providers:{},options:{skip:!1}},a,O=new Promise(I=>{a=I;}),c=I=>{a(),d=I;},u;try{if(e.action==="execute"&&!e.payload&&!e.data)throw new U(e.workflowId,{message:"Event `payload` is required"});let I=await this.createExecutionPayload(e,i),w={...e,payload:I};await Promise.race([O,i.execute({payload:I,environment:{},input:{},controls:{},subscriber:e.subscriber,step:{email:this.executeStepFactory(w,c),sms:this.executeStepFactory(w,c),inApp:this.executeStepFactory(w,c),digest:this.executeStepFactory(w,c),delay:this.executeStepFactory(w,c),push:this.executeStepFactory(w,c),chat:this.executeStepFactory(w,c),custom:this.executeStepFactory(w,c)}})]);}catch(I){u=I;}let R=process.hrtime(n),f=R[0],T=R[1],m=f*1e3+T/1e6,Se=u?_.ERROR:_.SUCCESS,ye=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action";if(console.log(`${Se} ${ye} workflowId: \`${e.workflowId}\``),this.prettyPrintExecute(e,m,u),u)throw u;return {outputs:d.outputs,providers:d.providers,options:d.options,metadata:{status:"success",error:!1,duration:m}}}async createExecutionPayload(e,t){let r=e.payload||e.data;if(e.action==="preview"){let i=this.mock(t.payload.schema);r=Object.assign(i,r);}return await this.validate(r,t.payload.unknownSchema,"event","payload",e.workflowId)}prettyPrintExecute(e,t,r){let s=r?_.ERROR:_.SUCCESS,i=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action",n=r?"Failed to execute":i,d=r?p.error:p.success,a=`${s} ${n} workflowId: '${e.workflowId}`;console.log(`
23
+ var D=(r=>(r.TRIGGER="trigger",r.EXECUTE="execute",r.PREVIEW="preview",r))(D||{}),Y=(r=>(r.DISCOVER="discover",r.HEALTH_CHECK="health-check",r.CODE="code",r))(Y||{});var h=(l=>(l.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",l.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",l.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",l.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",l.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",l.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",l.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",l.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",l.STEP_NOT_FOUND_ERROR="StepNotFoundError",l.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",l.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",l.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",l.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",l.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",l.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",l.STEP_CONTROL_COMPILATION_FAILED_ERROR="StepControlCompilationFailedError",l.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",l.INVALID_ACTION_ERROR="InvalidActionError",l.MISSING_SECRET_KEY_ERROR="MissingSecretKeyError",l.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",l.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",l.SIGNATURE_INVALID_ERROR="SignatureInvalidError",l.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",l.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",l.BRIDGE_ERROR="BridgeError",l.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",l.WORKFLOW_PAYLOAD_INVALID_ERROR="WorkflowPayloadInvalidError",l))(h||{});var F=(r=>(r.POST="POST",r.GET="GET",r.OPTIONS="OPTIONS",r))(F||{});var _e=(i=>(i.EMAIL="email",i.SMS="sms",i.PUSH="push",i.CHAT="chat",i.IN_APP="in_app",i))(_e||{});var Te="2.0.3";var x=Te,L="2024-06-26";var A=class extends Error{data},b=class extends A{statusCode=404},E=class extends A{statusCode=400},N=class extends A{statusCode=401},g=class extends A{statusCode=500},C=class extends A{statusCode=409};var W=class extends E{code="ExecutionStateCorruptError";constructor(e,t){super(`Workflow with id: \`${e}\` has a corrupt state. Step with id: \`${t}\` does not exist. Please provide the missing state.`),this.data={workflowId:e,stepId:t};}},U=class extends E{code="ExecutionEventPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct event payload.`),this.data=t;}},$=class extends E{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},G=class extends E{code="ExecutionStateControlInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid \`controls\`. Please provide the correct step controls.`),this.data=r;}},j=class extends E{code="ExecutionStateOutputInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid output. Please provide the correct step output.`),this.data=r;}},K=class extends E{code="ExecutionStateResultInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid result. Please provide the correct step result.`),this.data=r;}},q=class extends E{code="StepControlCompilationFailedError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has invalid controls syntax in step with id: \`${t}\`. Please correct step control syntax.`),this.data=r;}},B=class extends E{code="ExecutionProviderOutputInvalidError";constructor(e,t,r,s){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` and provider with id: \`${r}\` has invalid output. Please provide the correct provider output.`),this.data=s;}};var X=class extends A{statusCode;data;code;constructor(e,t,r){super(),this.data={message:r},this.statusCode=e,this.code=t;}};var Ae=()=>typeof Response<"u"?Response:crossFetch.Response;var p={info:o=>S__default.default.blue(o),warning:o=>S__default.default.yellow(o),error:o=>S__default.default.red(o),success:o=>S__default.default.green(o),underline:o=>S__default.default.underline(o),bold:o=>S__default.default.bold(o)},_={SUCCESS:p.success("\u2714"),ERROR:p.error("\u2717"),WARNING:p.warning("\u26A0"),INFO:p.info("\u2139"),ARROW:p.bold("\u2192"),MOCK:p.info("\u25CB"),HYDRATED:p.bold(p.info("\u2192")),STEP:p.info("\u03C3"),ACTION:p.info("\u03B1"),DURATION:p.info("\u0394"),PROVIDER:p.info("\u2699"),OUTPUT:p.info("\u21E2"),INPUT:p.info("\u21E0"),WORKFLOW:p.info("\u03C9"),STATE:p.info("\u03C3"),EXECUTE:p.info("\u03B5"),PREVIEW:p.info("\u03C1")};var Oe=o=>Object.values(o).map(e=>`\`${e}\``).join(", "),J=o=>o.replaceAll(/(\w)(\w*)/g,(e,t,r)=>t.toUpperCase()+r.toLowerCase()).replaceAll(/[\s-]+/g,"");var me=(o,e="https://api.novu.co")=>{let t=process.env.NOVU_API_URL||e;return {post:async(r,s)=>{let i=await fetch(`${t}/v1${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${o}`},body:JSON.stringify(s)}),n=await i.json();if(i.ok)return n;throw shared.checkIsResponseError(n)?new X(n.statusCode,n.error,n.message):new y("Error processing API request to Novu Cloud from Bridge application.")},delete:async r=>(await fetch(`${t}/v1${r}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${o}`}})).json()}};var Ue={allowedTags:fe__default.default.defaults.allowedTags.concat(["style","img","html","head","body","link","meta","title"]),allowedAttributes:!1,allowVulnerableTags:!0,parseStyleAttributes:!1,parser:{lowerCaseAttributeNames:!0}},Ie=o=>{if(!o)return o;let e=/^<!DOCTYPE .*?>/,t=o.match(e),r=fe__default.default(o,Ue);return t?t[0]+r:r},z=o=>Object.keys(o).reduce((e,t)=>{let r=o[t];return typeof r=="string"?e[t]=Ie(r):Array.isArray(r)?e[t]=r.map(s=>typeof s=="string"?Ie(s):typeof s=="object"?z(s):s):typeof r=="object"&&r!==null?e[t]=z(r):e[t]=r,e},{});var Z=class extends A{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${Oe(F)}`},k=class extends E{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${Oe(t)}`);}};var y=class extends g{code="BridgeError";message="Something went wrong. Please try again later."};var M=class extends C{constructor(e,t){super(`${J(e)} with id: \`${t}\` already exists. Please use a different id.`);}},v=class extends b{constructor(e,t){super(`${J(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},P=class extends g{constructor(e,t){super(`Failed to execute ${J(e)} with id: \`${t}\`. Please try again later.`);}};var Q=class extends v{code="ProviderNotFoundError";constructor(e){super("provider",e);}},H=class extends P{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var ee=class extends N{code="SignatureMismatchError";constructor(){super("Signature does not match the expected signature. Please ensure the signature provided in the `novu-signature` header is correct and try again.");}},te=class extends N{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},re=class extends N{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},oe=class extends N{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},se=class extends N{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.secretKey`");}};var ie=class extends v{code="StepNotFoundError";constructor(e){super("step",e);}};var V=class extends v{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},ne=class extends M{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var Ne=o=>typeof structuredClone=="function"?structuredClone(o):JSON.parse(JSON.stringify(o));var ae=class{ajv;compiledSchemas;constructor(){this.ajv=new Ve__default.default({useDefaults:!0,removeAdditional:"failing"}),Ye__default.default(this.ajv),this.compiledSchemas=new Map;}canHandle(e){return typeof e=="boolean"?!1:e.type==="object"||!!e.anyOf||!!e.allOf||!!e.oneOf}async validate(e,t){let r=this.compiledSchemas.get(t);r||(r=this.ajv.compile(t),this.compiledSchemas.set(t,r));let s=Ne(e);return r(s)?{success:!0,data:s}:{success:!1,errors:r.errors.map(n=>({path:n.instancePath,message:n.message}))}}transformToJsonSchema(e){return e}};var ce=class{canHandle(e){return e.safeParseAsync!==void 0}async validate(e,t){let r=t.safeParse(e);return r.success?{success:!0,data:r.data}:{success:!1,errors:r.error.errors.map(s=>({path:`/${s.path.join("/")}`,message:s.message}))}}transformToJsonSchema(e){try{return zodToJsonSchema.zodToJsonSchema(e)}catch(t){throw t?.message?.includes("Cannot find module")&&console.error("Tried to use a zod schema in @novu/framework without `zod-to-json-schema` installed. Please install it by running `npm install zod-to-json-schema`."),t}}};var de=new ce,le=new ae,ve=async(o,e)=>{if(de.canHandle(o))return de.validate(e,o);if(le.canHandle(o))return le.validate(e,o);throw new Error("Invalid schema")},ge=o=>{if(de.canHandle(o))return de.transformToJsonSchema(o);if(le.canHandle(o))return le.transformToJsonSchema(o);throw new Error("Invalid schema")};jsonSchemaFaker.JSONSchemaFaker.random.shuffle=function(){return ["[placeholder]"]};jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});function be(){return ["development",void 0].includes(process.env.NODE_ENV)}var ue=class{discoveredWorkflows=[];templateEngine=new liquidjs.Liquid;secretKey;version=x;strictAuthentication;constructor(e){let t=this.buildOptions(e);this.secretKey=t.secretKey,this.strictAuthentication=t.strictAuthentication;}buildOptions(e){let t={secretKey:void 0,strictAuthentication:!be()};return t.secretKey=e?.secretKey||process.env.NOVU_SECRET_KEY||process.env.NOVU_API_KEY,e?.strictAuthentication!==void 0?t.strictAuthentication=e.strictAuthentication:process.env.NOVU_STRICT_AUTHENTICATION_ENABLED!==void 0&&(t.strictAuthentication=process.env.NOVU_STRICT_AUTHENTICATION_ENABLED==="true"),t}addWorkflows(e){for(let t of e){if(this.discoveredWorkflows.some(r=>r.workflowId===t.definition.workflowId))throw new ne(t.definition.workflowId);this.discoveredWorkflows.push(t.definition);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((r,s)=>r+s.steps.length,0);return {status:"ok",sdkVersion:x,frameworkVersion:L,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(r=>r.workflowId===e);if(t)return t;throw new V(e)}getStep(e,t){let s=this.getWorkflow(e).steps.find(i=>i.stepId===t);if(s)return s;throw new ie(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(ge(e))}async validate(e,t,r,s,i,n,d){let a=await ve(t,e);if(a.success)return a.data;switch(r){case"event":this.throwInvalidEvent(s,i,a.errors);case"step":this.throwInvalidStep(n,s,i,a.errors);case"provider":this.throwInvalidProvider(n,d,s,i,a.errors);default:throw new Error(`Invalid component: '${r}'`)}}throwInvalidProvider(e,t,r,s,i){if(!e)throw new Error("stepId is required");if(!t)throw new Error("providerId is required");switch(r){case"output":throw new B(s,e,t,i);default:throw new Error(`Invalid payload type: '${r}'`)}}throwInvalidStep(e,t,r,s){if(!e)throw new Error("stepId is required");switch(t){case"output":throw new j(r,e,s);case"result":throw new K(r,e,s);case"controls":throw new G(r,e,s);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(e,t,r){switch(e){case"controls":throw new $(t,r);case"payload":throw new U(t,r);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(r,s,i)=>{let n=this.getStep(e.workflowId,r),d=await this.createStepControls(n,e),a=e.action==="preview";if(!a&&await this.shouldSkip(i?.skip,d))return r===e.stepId&&t({options:{skip:!0},outputs:{},providers:{}}),{};let O=this.previewStep.bind(this),c=this.executeStep.bind(this),R=await(a?O:c)(e,{...n,providers:n.providers.map(I=>{let T=i?.providers?.[I.type];if(!T)throw new Q(I.type);return {...I,resolve:T}}),resolve:s});return Object.values(_e).includes(n.type)&&(R={...R,outputs:z(R.outputs)}),r===e.stepId&&t({...R,options:{skip:!1}}),R.outputs}}async shouldSkip(e,t){return e?e(t):!1}async executeWorkflow(e){let s=`${e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action"} workflowId:`;console.log(`
24
+ ${p.bold(p.underline(s))} '${e.workflowId}'`);let i=this.getWorkflow(e.workflowId),n=process.hrtime(),d={outputs:{},providers:{},options:{skip:!1}},a,O=new Promise(f=>{a=f;}),c=f=>{a(),d=f;},u;try{if(e.action==="execute"&&!e.payload&&!e.data)throw new U(e.workflowId,{message:"Event `payload` is required"});let f=await this.createExecutionPayload(e,i),w={...e,payload:f};await Promise.race([O,i.execute({payload:f,environment:{},input:{},controls:{},subscriber:e.subscriber,step:{email:this.executeStepFactory(w,c),sms:this.executeStepFactory(w,c),inApp:this.executeStepFactory(w,c),digest:this.executeStepFactory(w,c),delay:this.executeStepFactory(w,c),push:this.executeStepFactory(w,c),chat:this.executeStepFactory(w,c),custom:this.executeStepFactory(w,c)}})]);}catch(f){u=f;}let R=process.hrtime(n),I=R[0],T=R[1],m=I*1e3+T/1e6,Se=u?_.ERROR:_.SUCCESS,ye=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action";if(console.log(`${Se} ${ye} workflowId: \`${e.workflowId}\``),this.prettyPrintExecute(e,m,u),u)throw u;return {outputs:d.outputs,providers:d.providers,options:d.options,metadata:{status:"success",error:!1,duration:m}}}async createExecutionPayload(e,t){let r=e.payload||e.data;if(e.action==="preview"){let i=this.mock(t.payload.schema);r=Object.assign(i,r);}return await this.validate(r,t.payload.unknownSchema,"event","payload",e.workflowId)}prettyPrintExecute(e,t,r){let s=r?_.ERROR:_.SUCCESS,i=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action",n=r?"Failed to execute":i,d=r?p.error:p.success,a=`${s} ${n} workflowId: '${e.workflowId}`;console.log(`
25
25
  ${p.bold(d(a))}'`),console.log(` \u251C ${_.STEP} stepId: '${e.stepId}'`),console.log(` \u251C ${_.ACTION} action: '${e.action}'`),console.log(` \u2514 ${_.DURATION} duration: '${t.toFixed(2)}ms'
26
26
  `);}async executeProviders(e,t,r){return t.providers.reduce(async(s,i)=>{let n=await s,d=this.previewProvider.bind(this),a=this.executeProvider.bind(this),c=await(e.action==="preview"?d:a)(e,t,i,r);return {...n,[i.type]:c}},Promise.resolve({}))}previewProvider(e,t,r,s){return console.log(` ${_.MOCK} Mocked provider: \`${r.type}\``),this.mock(r.outputs.schema)}async executeProvider(e,t,r,s){let i=pe__default.default({indent:2}).start(`Executing provider: \`${r.type}\``);try{if(e.stepId===t.stepId){let n=await this.createStepControls(t,e),d=await r.resolve({controls:n,outputs:s}),a=await this.validate(d,r.outputs.unknownSchema,"step","output",e.workflowId,t.stepId,r.type);return i.succeed(`Executed provider: \`${r.type}\``),{...a,_passthrough:d._passthrough}}else return i.stopAndPersist({symbol:_.HYDRATED,text:`Hydrated provider: \`${r.type}\``}),{}}catch(n){throw i.stopAndPersist({symbol:_.ERROR,text:`Failed to execute provider: \`${r.type}\``}),new H(`Failed to execute provider: '${r.type}'.
27
- ${n.message}`)}}async executeStep(e,t){if(e.stepId===t.stepId){let r=pe__default.default({indent:1}).start(`Executing stepId: \`${t.stepId}\``);try{let s=await this.createStepControls(t,e),i=await this.compileControls(s,e),n=await t.resolve(i),d=await this.validate(n,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId),a=await this.executeProviders(e,t,d);return r.succeed(`Executed stepId: \`${t.stepId}\``),{outputs:d,providers:a}}catch(s){throw r.stopAndPersist({prefixText:"",symbol:_.ERROR,text:`Failed to execute stepId: \`${t.stepId}\``}),s}}else {let r=pe__default.default({indent:1}).start(`Hydrating stepId: \`${t.stepId}\``);try{let s=e.state.find(i=>i.stepId===t.stepId);if(s){let i=await this.validate(s.outputs,t.results.unknownSchema,"step","result",e.workflowId,t.stepId);return r.stopAndPersist({symbol:_.HYDRATED,text:`Hydrated stepId: \`${t.stepId}\``}),{outputs:i,providers:await this.executeProviders(e,t,i)}}else throw new W(e.workflowId,t.stepId)}catch(s){throw r.stopAndPersist({symbol:_.ERROR,text:`Failed to hydrate stepId: \`${t.stepId}\``}),s}}}async compileControls(e,t){try{let r=this.templateEngine.parse(JSON.stringify(e)),s=await this.templateEngine.render(r,{payload:t.payload||t.data,subscriber:t.subscriber,...t.payload||t.data});return JSON.parse(s)}catch(r){throw new q(t.workflowId,t.stepId,r)}}async createStepControls(e,t){let r=t.controls||t.inputs;return await this.validate(r,e.controls.unknownSchema,"step","controls",t.workflowId,e.stepId)}async previewStep(e,t){let r=pe__default.default({indent:1}).start(`Previewing stepId: \`${t.stepId}\``);try{if(e.stepId===t.stepId){let s=await this.createStepControls(t,e),i=await this.compileControls(s,e),n=await t.resolve(i),d=await this.validate(n,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId);return r.stopAndPersist({symbol:_.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:d,providers:await this.executeProviders(e,t,d)}}else {let s=this.mock(t.results.schema);return r.stopAndPersist({symbol:_.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:s,providers:await this.executeProviders(e,t,s)}}}catch(s){throw r.stopAndPersist({symbol:_.ERROR,text:`Failed to preview stepId: \`${t.stepId}\``}),s}}getStepCode(e,t){return {code:this.getStep(e,t).resolve.toString()}}getWorkflowCode(e){return {code:this.getWorkflow(e).execute.toString()}}getCode(e,t){let r;if(e)t?r=this.getStepCode(e,t):r=this.getWorkflowCode(e);else throw new M(e);return r}};var Re=class{frameworkName;handler;client;hmacEnabled;http;constructor(e){this.handler=e.handler,this.client=e.client?e.client:new ue,this.client.addWorkflows(e.workflows),this.http=me(this.client.secretKey),this.frameworkName=e.frameworkName,this.hmacEnabled=this.client.strictAuthentication;}createHandler(){return async(...e)=>{let t=await this.handler(...e),r=await this.handleAction({actions:t});return t.transformResponse(r)}}getStaticHeaders(){let e=`novu-framework:v${this.client.version}`;return {"content-type":"application/json","access-control-allow-origin":"*","access-control-allow-methods":"GET, POST","access-control-allow-headers":"*","access-control-max-age":"604800","novu-framework-version":C,"novu-framework-sdk":x,"novu-framework-server":this.frameworkName,"user-agent":e}}createResponse(e,t){return {status:e,body:JSON.stringify(t),headers:{...this.getStaticHeaders()}}}createError(e){return {status:e.statusCode,body:JSON.stringify({message:e.message,data:e.data,code:e.code}),headers:this.getStaticHeaders()}}async handleAction({actions:e}){let t=await e.url(),r=await e.method(),s=t.searchParams.get("action")||"",i=t.searchParams.get("workflowId")||"",n=t.searchParams.get("stepId")||"",d=await e.headers("novu-signature")||await e.headers("x-novu-signature")||"",a={};try{r==="POST"&&(a=await e.body());}catch{}try{s!=="health-check"&&this.validateHmac(a,d);let O=this.getPostActionMap(a,i,n,s),c=this.getGetActionMap(i,n);if(r==="POST")return await this.handlePostAction(s,O);if(r==="GET")return await this.handleGetAction(s,c);if(r==="OPTIONS")return this.createResponse(200,{})}catch(O){return this.handleError(O)}return this.createError(new Z(r))}getPostActionMap(e,t,r,s){return {trigger:this.triggerAction({workflowId:t,...e}),execute:async()=>{let i=await this.client.executeWorkflow({...e,workflowId:t,stepId:r,action:s});return this.createResponse(200,i)},preview:async()=>{let i=await this.client.executeWorkflow({...e,workflowId:t,stepId:r,action:s});return this.createResponse(200,i)}}}triggerAction(e){return async()=>{let t={name:e.workflowId,to:e.to,payload:e?.payload||{},transactionId:e.transactionId,overrides:e.overrides||{},...e.actor&&{actor:e.actor},...e.bridgeUrl&&{bridgeUrl:e.bridgeUrl},...e.controls&&{controls:e.controls}},r=await this.http.post("/events/trigger",t);return this.createResponse(200,r)}}getGetActionMap(e,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(e,t);return this.createResponse(200,r)}}}async handlePostAction(e,t){if(Object.values(P).includes(e)){let r=t[e];return r()}else throw new k(e,P)}async handleGetAction(e,t){if(Object.values(Y).includes(e)){let r=t[e];return r()}else throw new k(e,Y)}isBridgeError(e){return Object.values(h).includes(e?.code)}isPlatformError(e){return e?.statusCode>=400&&e?.statusCode<500}handleError(e){return this.isBridgeError(e)?(e.statusCode===500&&console.error(e),this.createError(e)):this.isPlatformError(e)?this.createError(e):(console.error(e),this.createError(new y))}validateHmac(e,t){if(!this.hmacEnabled)return;if(!t)throw new te;if(!this.client.secretKey)throw new se;let[r,s]=t.split(",");if(!r||!s)throw new re;let[i,n]=r.split("="),[d,a]=s.split("=");if(Number(i)<Date.now()-1500)throw new oe;if(!(this.hashHmac(this.client.secretKey,`${n}.${JSON.stringify(e)}`)===a))throw new ee}hashHmac(e,t){return crypto.createHmac("sha256",e).update(t).digest("hex")}};var $e="next",Jr=o=>{let t=new Re({frameworkName:$e,...o,handler:(i,n,d)=>{let a=n,O=c=>{let u=typeof a.headers.get=="function"?a.headers.get(c):a.headers[c];return Array.isArray(u)?u[0]:u};return {body:()=>typeof a.json=="function"?a.json():a.body,headers:O,method:()=>i||a.method||"",queryString:(c,u)=>{let R=a.query?.[c]||u.searchParams.get(c);return Array.isArray(R)?R[0]:R},url:()=>{let c;try{c=new URL(a.url);}catch{}if(c){let T=O("host");if(T){let m=new URL(T.includes("://")?T:`${c.protocol}//${T}`);c.protocol=m.protocol,c.host=m.host,c.port=m.port,c.username=m.username,c.password=m.password;}return c}let u="https",R=O("host")||"";try{process.env.NODE_ENV==="development"&&(u="http");}catch{}return new URL(a.url,`${u}://${R}`)},transformResponse:({body:c,headers:u,status:R})=>{if(typeof d?.setHeader=="function"&&Object.entries(u).forEach(([T,m])=>{d.setHeader(T,m);}),typeof d?.status=="function"&&typeof d?.send=="function"){d.status(R).send(c);return}let f=Ae();return new f(c,{status:R,headers:u})}}}}).createHandler(),r=t.bind(null,void 0);return Object.defineProperties(r,{GET:{value:t.bind(null,"GET")},POST:{value:t.bind(null,"POST")},OPTIONS:{value:t.bind(null,"OPTIONS")}})};
27
+ ${n.message}`)}}async executeStep(e,t){if(e.stepId===t.stepId){let r=pe__default.default({indent:1}).start(`Executing stepId: \`${t.stepId}\``);try{let s=await this.createStepControls(t,e),i=await this.compileControls(s,e),n=await t.resolve(i),d=await this.validate(n,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId),a=await this.executeProviders(e,t,d);return r.succeed(`Executed stepId: \`${t.stepId}\``),{outputs:d,providers:a}}catch(s){throw r.stopAndPersist({prefixText:"",symbol:_.ERROR,text:`Failed to execute stepId: \`${t.stepId}\``}),s}}else {let r=pe__default.default({indent:1}).start(`Hydrating stepId: \`${t.stepId}\``);try{let s=e.state.find(i=>i.stepId===t.stepId);if(s){let i=await this.validate(s.outputs,t.results.unknownSchema,"step","result",e.workflowId,t.stepId);return r.stopAndPersist({symbol:_.HYDRATED,text:`Hydrated stepId: \`${t.stepId}\``}),{outputs:i,providers:await this.executeProviders(e,t,i)}}else throw new W(e.workflowId,t.stepId)}catch(s){throw r.stopAndPersist({symbol:_.ERROR,text:`Failed to hydrate stepId: \`${t.stepId}\``}),s}}}async compileControls(e,t){try{let r=this.templateEngine.parse(JSON.stringify(e)),s=await this.templateEngine.render(r,{payload:t.payload||t.data,subscriber:t.subscriber,...t.payload||t.data});return JSON.parse(s)}catch(r){throw new q(t.workflowId,t.stepId,r)}}async createStepControls(e,t){let r=t.controls||t.inputs;return await this.validate(r,e.controls.unknownSchema,"step","controls",t.workflowId,e.stepId)}async previewStep(e,t){let r=pe__default.default({indent:1}).start(`Previewing stepId: \`${t.stepId}\``);try{if(e.stepId===t.stepId){let s=await this.createStepControls(t,e),i=await this.compileControls(s,e),n=await t.resolve(i),d=await this.validate(n,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId);return r.stopAndPersist({symbol:_.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:d,providers:await this.executeProviders(e,t,d)}}else {let s=this.mock(t.results.schema);return r.stopAndPersist({symbol:_.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:s,providers:await this.executeProviders(e,t,s)}}}catch(s){throw r.stopAndPersist({symbol:_.ERROR,text:`Failed to preview stepId: \`${t.stepId}\``}),s}}getStepCode(e,t){return {code:this.getStep(e,t).resolve.toString()}}getWorkflowCode(e){return {code:this.getWorkflow(e).execute.toString()}}getCode(e,t){let r;if(e)t?r=this.getStepCode(e,t):r=this.getWorkflowCode(e);else throw new V(e);return r}};var Re=class{frameworkName;handler;client;hmacEnabled;http;constructor(e){this.handler=e.handler,this.client=e.client?e.client:new ue,this.client.addWorkflows(e.workflows),this.http=me(this.client.secretKey),this.frameworkName=e.frameworkName,this.hmacEnabled=this.client.strictAuthentication;}createHandler(){return async(...e)=>{let t=await this.handler(...e),r=await this.handleAction({actions:t});return t.transformResponse(r)}}getStaticHeaders(){let e=`novu-framework:v${this.client.version}`;return {"content-type":"application/json","access-control-allow-origin":"*","access-control-allow-methods":"GET, POST","access-control-allow-headers":"*","access-control-max-age":"604800","novu-framework-version":L,"novu-framework-sdk":x,"novu-framework-server":this.frameworkName,"user-agent":e}}createResponse(e,t){return {status:e,body:JSON.stringify(t),headers:{...this.getStaticHeaders()}}}createError(e){return {status:e.statusCode,body:JSON.stringify({message:e.message,data:e.data,code:e.code}),headers:this.getStaticHeaders()}}async handleAction({actions:e}){let t=await e.url(),r=await e.method(),s=t.searchParams.get("action")||"",i=t.searchParams.get("workflowId")||"",n=t.searchParams.get("stepId")||"",d=await e.headers("novu-signature")||await e.headers("x-novu-signature")||"",a={};try{r==="POST"&&(a=await e.body());}catch{}try{s!=="health-check"&&this.validateHmac(a,d);let O=this.getPostActionMap(a,i,n,s),c=this.getGetActionMap(i,n);if(r==="POST")return await this.handlePostAction(s,O);if(r==="GET")return await this.handleGetAction(s,c);if(r==="OPTIONS")return this.createResponse(200,{})}catch(O){return this.handleError(O)}return this.createError(new Z(r))}getPostActionMap(e,t,r,s){return {trigger:this.triggerAction({workflowId:t,...e}),execute:async()=>{let i=await this.client.executeWorkflow({...e,workflowId:t,stepId:r,action:s});return this.createResponse(200,i)},preview:async()=>{let i=await this.client.executeWorkflow({...e,workflowId:t,stepId:r,action:s});return this.createResponse(200,i)}}}triggerAction(e){return async()=>{let t={name:e.workflowId,to:e.to,payload:e?.payload||{},transactionId:e.transactionId,overrides:e.overrides||{},...e.actor&&{actor:e.actor},...e.bridgeUrl&&{bridgeUrl:e.bridgeUrl},...e.controls&&{controls:e.controls}},r=await this.http.post("/events/trigger",t);return this.createResponse(200,r)}}getGetActionMap(e,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(e,t);return this.createResponse(200,r)}}}async handlePostAction(e,t){if(Object.values(D).includes(e)){let r=t[e];return r()}else throw new k(e,D)}async handleGetAction(e,t){if(Object.values(Y).includes(e)){let r=t[e];return r()}else throw new k(e,Y)}isBridgeError(e){return Object.values(h).includes(e?.code)}isPlatformError(e){return e?.statusCode>=400&&e?.statusCode<500}handleError(e){return this.isBridgeError(e)?(e.statusCode===500&&console.error(e),this.createError(e)):this.isPlatformError(e)?this.createError(e):(console.error(e),this.createError(new y))}validateHmac(e,t){if(!this.hmacEnabled)return;if(!t)throw new te;if(!this.client.secretKey)throw new se;let[r,s]=t.split(",");if(!r||!s)throw new re;let[i,n]=r.split("="),[d,a]=s.split("=");if(Number(i)<Date.now()-1500)throw new oe;if(!(this.hashHmac(this.client.secretKey,`${n}.${JSON.stringify(e)}`)===a))throw new ee}hashHmac(e,t){return crypto.createHmac("sha256",e).update(t).digest("hex")}};var $e="next",Zr=o=>{let t=new Re({frameworkName:$e,...o,handler:(i,n,d)=>{let a=n,O=c=>{let u=typeof a.headers.get=="function"?a.headers.get(c):a.headers[c];return Array.isArray(u)?u[0]:u};return {body:()=>typeof a.json=="function"?a.json():a.body,headers:O,method:()=>i||a.method||"",queryString:(c,u)=>{let R=a.query?.[c]||u.searchParams.get(c);return Array.isArray(R)?R[0]:R},url:()=>{let c;try{c=new URL(a.url);}catch{}if(c){let T=O("host");if(T){let m=new URL(T.includes("://")?T:`${c.protocol}//${T}`);c.protocol=m.protocol,c.host=m.host,c.port=m.port,c.username=m.username,c.password=m.password;}return c}let u="https",R=O("host")||"";try{process.env.NODE_ENV==="development"&&(u="http");}catch{}return new URL(a.url,`${u}://${R}`)},transformResponse:({body:c,headers:u,status:R})=>{if(typeof d?.setHeader=="function"&&Object.entries(u).forEach(([T,m])=>{d.setHeader(T,m);}),typeof d?.status=="function"&&typeof d?.send=="function"){d.status(R).send(c);return}let I=Ae();return new I(c,{status:R,headers:u})}}}}).createHandler(),r=t.bind(null,void 0);return Object.defineProperties(r,{GET:{value:t.bind(null,"GET")},POST:{value:t.bind(null,"POST")},OPTIONS:{value:t.bind(null,"OPTIONS")}})};
28
28
 
29
29
  exports.frameworkName = $e;
30
- exports.serve = Jr;
30
+ exports.serve = Zr;