@novu/framework 2.0.0-canary.4 → 2.0.0-canary.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/dist/handler-kv_Ed8ly.d.ts +4421 -0
- package/dist/index.d.ts +4 -4
- package/dist/index.js +447 -118
- package/dist/servers/express.d.ts +1 -1
- package/dist/servers/express.js +16 -16
- package/dist/servers/h3.d.ts +1 -1
- package/dist/servers/h3.js +17 -17
- package/dist/servers/lambda.d.ts +1 -1
- package/dist/servers/lambda.js +15 -15
- package/dist/servers/next.d.ts +1 -1
- package/dist/servers/next.js +15 -15
- package/dist/servers/nuxt.d.ts +1 -1
- package/dist/servers/nuxt.js +17 -17
- package/dist/servers/remix.d.ts +1 -1
- package/dist/servers/remix.js +16 -16
- package/dist/servers/sveltekit.d.ts +1 -1
- package/dist/servers/sveltekit.js +16 -16
- package/package.json +1 -2
- package/dist/handler-RA4Feq8s.d.ts +0 -3912
|
@@ -3,28 +3,28 @@
|
|
|
3
3
|
var crypto = require('crypto');
|
|
4
4
|
var jsonSchemaFaker = require('json-schema-faker');
|
|
5
5
|
var liquidjs = require('liquidjs');
|
|
6
|
-
var
|
|
6
|
+
var ce = require('ora');
|
|
7
7
|
var crossFetch = require('cross-fetch');
|
|
8
|
-
var
|
|
8
|
+
var v = require('chalk');
|
|
9
9
|
var shared = require('@novu/shared');
|
|
10
|
-
var
|
|
11
|
-
var
|
|
12
|
-
var
|
|
10
|
+
var Ie = require('sanitize-html');
|
|
11
|
+
var Ue = require('ajv');
|
|
12
|
+
var Me = require('ajv-formats');
|
|
13
13
|
var zodToJsonSchema = require('zod-to-json-schema');
|
|
14
14
|
|
|
15
15
|
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
16
16
|
|
|
17
|
-
var
|
|
18
|
-
var
|
|
19
|
-
var
|
|
20
|
-
var xe__default = /*#__PURE__*/_interopDefault(xe);
|
|
17
|
+
var ce__default = /*#__PURE__*/_interopDefault(ce);
|
|
18
|
+
var v__default = /*#__PURE__*/_interopDefault(v);
|
|
19
|
+
var Ie__default = /*#__PURE__*/_interopDefault(Ie);
|
|
21
20
|
var Ue__default = /*#__PURE__*/_interopDefault(Ue);
|
|
21
|
+
var Me__default = /*#__PURE__*/_interopDefault(Me);
|
|
22
22
|
|
|
23
|
-
var D=(r=>(r.TRIGGER="trigger",r.EXECUTE="execute",r.PREVIEW="preview",r))(D||{}),k=(r=>(r.DISCOVER="discover",r.HEALTH_CHECK="health-check",r.CODE="code",r))(k||{});var E=(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.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))(E||{});var V=(r=>(r.POST="POST",r.GET="GET",r.OPTIONS="OPTIONS",r))(V||{});var de=(i=>(i.EMAIL="email",i.SMS="sms",i.PUSH="push",i.CHAT="chat",i.IN_APP="in_app",i))(de||{});var ue="2.0.0-canary.4";var S=ue,Y="2024-06-26";var O=class extends Error{data},F=class extends O{statusCode=404},_=class extends O{statusCode=400},T=class extends O{statusCode=401},N=class extends O{statusCode=500},b=class extends O{statusCode=409};var C=class extends _{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 _{code="ExecutionEventPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct event payload.`),this.data=t;}},L=class extends _{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},W=class extends _{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;}},$=class extends _{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;}},G=class extends _{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;}},j=class extends _{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 K=class extends O{statusCode;data;code;constructor(e,t,r){super(),this.data={message:r},this.statusCode=e,this.code=t;}};var Ee=()=>typeof Response<"u"?Response:crossFetch.Response;var d={info:s=>m__default.default.blue(s),warning:s=>m__default.default.yellow(s),error:s=>m__default.default.red(s),success:s=>m__default.default.green(s),underline:s=>m__default.default.underline(s),bold:s=>m__default.default.bold(s)},R={SUCCESS:d.success("\u2714"),ERROR:d.error("\u2717"),WARNING:d.warning("\u26A0"),INFO:d.info("\u2139"),ARROW:d.bold("\u2192"),MOCK:d.info("\u25CB"),HYDRATED:d.bold(d.info("\u2192")),STEP:d.info("\u03C3"),ACTION:d.info("\u03B1"),DURATION:d.info("\u0394"),PROVIDER:d.info("\u2699"),OUTPUT:d.info("\u21E2"),INPUT:d.info("\u21E0"),WORKFLOW:d.info("\u03C9"),STATE:d.info("\u03C3"),EXECUTE:d.info("\u03B5"),PREVIEW:d.info("\u03C1")};var pe=s=>Object.values(s).map(e=>`\`${e}\``).join(", "),B=s=>s.replaceAll(/(\w)(\w*)/g,(e,t,r)=>t.toUpperCase()+r.toLowerCase()).replaceAll(/[\s-]+/g,"");var Oe=(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 K(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:Ae__default.default.defaults.allowedTags.concat(["style","img","html","head","body","link","meta","title"]),allowedAttributes:!1,allowVulnerableTags:!0,parseStyleAttributes:!1,parser:{lowerCaseAttributeNames:!0}},Te=s=>{if(!s)return s;let e=new RegExp("^<!DOCTYPE .*?>"),t=s.match(e),r=Ae__default.default(s,De);return t?t[0]+r:r},X=s=>Object.keys(s).reduce((e,t)=>{let r=s[t];return typeof r=="string"?e[t]=Te(r):Array.isArray(r)?e[t]=r.map(o=>typeof o=="string"?Te(o):typeof o=="object"?X(o):o):typeof r=="object"&&r!==null?e[t]=X(r):e[t]=r,e},{});var q=class extends O{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${pe(V)}`},x=class extends _{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${pe(t)}`);}};var v=class extends N{code="BridgeError";message="Something went wrong. Please try again later."};var U=class extends b{constructor(e,t){super(`${B(e)} with id: \`${t}\` already exists. Please use a different id.`);}},A=class extends F{constructor(e,t){super(`${B(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},g=class extends N{constructor(e,t){super(`Failed to execute ${B(e)} with id: \`${t}\`. Please try again later.`);}};var J=class extends A{code="ProviderNotFoundError";constructor(e){super("provider",e);}},z=class extends g{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var Z=class extends T{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.");}},Q=class extends T{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},H=class extends T{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},ee=class extends T{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},te=class extends T{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.secretKey`");}};var re=class extends A{code="StepNotFoundError";constructor(e){super("step",e);}};var M=class extends A{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},oe=class extends U{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var se=class{ajv;compiledSchemas;constructor(){this.ajv=new xe__default.default({useDefaults:!0,removeAdditional:"all"}),Ue__default.default(this.ajv),this.compiledSchemas=new Map;}isSchema(e){return typeof e=="boolean"?!1:e.type==="object"||!!e.anyOf||!!e.oneOf}async validate(e,t){let r=this.compiledSchemas.get(t);return r||(r=this.ajv.compile(t),this.compiledSchemas.set(t,r)),r(e)?{success:!0,data:e}:{success:!1,errors:r.errors.map(i=>({path:i.instancePath,message:i.message}))}}transformToJsonSchema(e){return e}};var ie=class{isSchema(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 Ie=[new ie,new se],fe=async(s,e)=>{for(let t of Ie)if(t.isSchema(s))return t.validate(e,s);throw new Error("Invalid schema")},we=s=>{for(let e of Ie)if(e.isSchema(s))return e.transformToJsonSchema(s);throw new Error("Invalid schema")};jsonSchemaFaker.JSONSchemaFaker.random.shuffle=function(){return ["[placeholder]"]};jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});function Ve(){return ["development",void 0].includes(process.env.NODE_ENV)}var ne=class{discoveredWorkflows=[];templateEngine=new liquidjs.Liquid;secretKey;version=S;strictAuthentication;constructor(e){let t=this.buildOptions(e);this.secretKey=t.secretKey,this.strictAuthentication=t.strictAuthentication;}buildOptions(e){let t={secretKey:void 0,strictAuthentication:!Ve()};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 oe(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:S,frameworkVersion:Y,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 o=this.getWorkflow(e).steps.find(i=>i.stepId===t);if(o)return o;throw new re(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(we(e))}async validate(e,t,r,o,i,a,n){let c=await fe(t,e);if(c.success)return c.data;switch(r){case"event":this.throwInvalidEvent(o,i,c.errors);case"step":this.throwInvalidStep(a,o,i,c.errors);case"provider":this.throwInvalidProvider(a,n,o,i,c.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 j(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 $(r,e,o);case"result":throw new G(r,e,o);case"controls":throw new W(r,e,o);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(e,t,r){switch(e){case"controls":throw new L(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),n=Ye(e),c=await this.createStepControls(a,n),u=e.action==="preview";if(!u&&await this.shouldSkip(i?.skip,c))return t({options:{skip:!0}}),{};let p=this.previewStep.bind(this),h=this.executeStep.bind(this),I=await(u?p:h)(e,{...a,providers:a.providers.map(w=>{let y=i?.providers?.[w.type];if(!y)throw new J(w.type);return {...w,resolve:y}}),resolve:o});return Object.values(de).includes(a.type)&&(I={...I,outputs:X(I.outputs)}),r===e.stepId&&t(I),I.outputs}}async shouldSkip(e,t){return e?e(t):!1}async executeWorkflow(e){let o=`${{execute:"Executing",preview:"Previewing"}[e.action]} workflowId:`;console.log(`
|
|
24
|
-
${
|
|
25
|
-
${
|
|
26
|
-
`);}async executeProviders(e,t,r){return t.providers.reduce(async(o,i)=>{let
|
|
27
|
-
${
|
|
23
|
+
var S=(r=>(r.TRIGGER="trigger",r.EXECUTE="execute",r.PREVIEW="preview",r))(S||{}),V=(r=>(r.DISCOVER="discover",r.HEALTH_CHECK="health-check",r.CODE="code",r))(V||{});var O=(d=>(d.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",d.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",d.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",d.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",d.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",d.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",d.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",d.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",d.STEP_NOT_FOUND_ERROR="StepNotFoundError",d.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",d.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",d.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",d.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",d.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",d.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",d.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",d.INVALID_ACTION_ERROR="InvalidActionError",d.MISSING_SECRET_KEY_ERROR="MissingSecretKeyError",d.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",d.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",d.SIGNATURE_INVALID_ERROR="SignatureInvalidError",d.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",d.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",d.BRIDGE_ERROR="BridgeError",d.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",d.WORKFLOW_PAYLOAD_INVALID_ERROR="WorkflowPayloadInvalidError",d))(O||{});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 Oe="2.0.0-canary.5";var P=Oe,F="2024-06-26";var E=class extends Error{data},b=class extends E{statusCode=404},_=class extends E{statusCode=400},A=class extends E{statusCode=401},N=class extends E{statusCode=500},C=class extends E{statusCode=409};var L=class extends _{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};}},x=class extends _{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 _{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},$=class extends _{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 _{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 _{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 _{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 B=class extends E{statusCode;data;code;constructor(e,t,r){super(),this.data={message:r},this.statusCode=e,this.code=t;}};var Te=()=>typeof Response<"u"?Response:crossFetch.Response;var l={info:s=>v__default.default.blue(s),warning:s=>v__default.default.yellow(s),error:s=>v__default.default.red(s),success:s=>v__default.default.green(s),underline:s=>v__default.default.underline(s),bold:s=>v__default.default.bold(s)},R={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(", "),X=s=>s.replaceAll(/(\w)(\w*)/g,(e,t,r)=>t.toUpperCase()+r.toLowerCase()).replaceAll(/[\s-]+/g,"");var he=(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)}),n=await i.json();if(i.ok)return n;throw shared.checkIsResponseError(n)?new B(n.statusCode,n.error,n.message):new g("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}},Ae=s=>{if(!s)return s;let e=new RegExp("^<!DOCTYPE .*?>"),t=s.match(e),r=Ie__default.default(s,Pe);return t?t[0]+r:r},q=s=>Object.keys(s).reduce((e,t)=>{let r=s[t];return typeof r=="string"?e[t]=Ae(r):Array.isArray(r)?e[t]=r.map(o=>typeof o=="string"?Ae(o):typeof o=="object"?q(o):o):typeof r=="object"&&r!==null?e[t]=q(r):e[t]=r,e},{});var J=class extends E{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${ue(Y)}`},k=class extends _{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${ue(t)}`);}};var g=class extends N{code="BridgeError";message="Something went wrong. Please try again later."};var U=class extends C{constructor(e,t){super(`${X(e)} with id: \`${t}\` already exists. Please use a different id.`);}},I=class extends b{constructor(e,t){super(`${X(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},D=class extends N{constructor(e,t){super(`Failed to execute ${X(e)} with id: \`${t}\`. Please try again later.`);}};var z=class extends I{code="ProviderNotFoundError";constructor(e){super("provider",e);}},Z=class extends D{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var Q=class extends A{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.");}},H=class extends A{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},ee=class extends A{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},te=class extends A{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},re=class extends A{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.secretKey`");}};var oe=class extends I{code="StepNotFoundError";constructor(e){super("step",e);}};var M=class extends I{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},se=class extends U{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var ie=s=>typeof structuredClone=="function"?structuredClone(s):JSON.parse(JSON.stringify(s));var ne=class{ajv;compiledSchemas;constructor(){this.ajv=new Ue__default.default({useDefaults:!0,removeAdditional:"failing"}),Me__default.default(this.ajv),this.compiledSchemas=new Map;}isSchema(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=ie(e);return r(o)?{success:!0,data:o}:{success:!1,errors:r.errors.map(n=>({path:n.instancePath,message:n.message}))}}transformToJsonSchema(e){return e}};var ae=class{isSchema(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 fe=[new ae,new ne],me=async(s,e)=>{for(let t of fe)if(t.isSchema(s))return t.validate(e,s);throw new Error("Invalid schema")},Ne=s=>{for(let e of fe)if(e.isSchema(s))return e.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 de=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 se(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 M(e)}getStep(e,t){let o=this.getWorkflow(e).steps.find(i=>i.stepId===t);if(o)return o;throw new oe(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(Ne(e))}async validate(e,t,r,o,i,n,a){let c=await me(t,e);if(c.success)return c.data;switch(r){case"event":this.throwInvalidEvent(o,i,c.errors);case"step":this.throwInvalidStep(n,o,i,c.errors);case"provider":this.throwInvalidProvider(n,a,o,i,c.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 K(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 x(t,r);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(r,o,i)=>{let n=this.getStep(e.workflowId,r),a=ie(e),c=await this.createStepControls(n,a),u=e.action==="preview";if(!u&&await this.shouldSkip(i?.skip,c))return t({options:{skip:!0},outputs:{},providers:{}}),{};let p=this.previewStep.bind(this),w=this.executeStep.bind(this),f=await(u?p:w)(e,{...n,providers:n.providers.map(m=>{let y=i?.providers?.[m.type];if(!y)throw new z(m.type);return {...m,resolve:y}}),resolve:o});return Object.values(Re).includes(n.type)&&(f={...f,outputs:q(f.outputs)}),r===e.stepId&&t({...f,options:{skip:!1}}),f.outputs}}async shouldSkip(e,t){return e?e(t):!1}async executeWorkflow(e){let o=`${{execute:"Executing",preview:"Previewing"}[e.action]} workflowId:`;console.log(`
|
|
24
|
+
${l.bold(l.underline(o))} '${e.workflowId}'`);let i=this.getWorkflow(e.workflowId),n=process.hrtime(),a={outputs:{},providers:{},options:{skip:!1}},c,u=new Promise(T=>{c=T;}),p=T=>{c(),a=T;},w;try{if(e.action==="execute"&&!e.payload&&!e.data)throw new x(e.workflowId,{message:"Event `payload` is required"});let T=await this.createExecutionPayload(e,i),h={...e,payload:T};await Promise.race([u,i.execute({payload:T,environment:{},input:{},controls:{},subscriber:e.subscriber,step:{email:this.executeStepFactory(h,p),sms:this.executeStepFactory(h,p),inApp:this.executeStepFactory(h,p),digest:this.executeStepFactory(h,p),delay:this.executeStepFactory(h,p),push:this.executeStepFactory(h,p),chat:this.executeStepFactory(h,p),custom:this.executeStepFactory(h,p)}})]);}catch(T){w=T;}let pe=process.hrtime(n),f=pe[0],m=pe[1],y=f*1e3+m/1e6,ve=w?R.ERROR:R.SUCCESS,ge=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action";if(console.log(`${ve} ${ge} workflowId: \`${e.workflowId}\``),this.prettyPrintExecute(e,y,w),w)throw w;return {outputs:a.outputs,providers:a.providers,options:a.options,metadata:{status:"success",error:!1,duration:y}}}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?R.ERROR:R.SUCCESS,i=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action",n=r?"Failed to execute":i,a=r?l.error:l.success,c=`${o} ${n} workflowId: '${e.workflowId}`;console.log(`
|
|
25
|
+
${l.bold(a(c))}'`),console.log(` \u251C ${R.STEP} stepId: '${e.stepId}'`),console.log(` \u251C ${R.ACTION} action: '${e.action}'`),console.log(` \u2514 ${R.DURATION} duration: '${t.toFixed(2)}ms'
|
|
26
|
+
`);}async executeProviders(e,t,r){return t.providers.reduce(async(o,i)=>{let n=await o,a=this.previewProvider.bind(this),c=this.executeProvider.bind(this),p=await(e.action==="preview"?a:c)(e,t,i,r);return {...n,[i.type]:p}},Promise.resolve({}))}previewProvider(e,t,r,o){return console.log(` ${R.MOCK} Mocked provider: \`${r.type}\``),this.mock(r.outputs.schema)}async executeProvider(e,t,r,o){let i=ce__default.default({indent:2}).start(`Executing provider: \`${r.type}\``);try{if(e.stepId===t.stepId){let n=await this.createStepControls(t,e),a=await r.resolve({controls:n,outputs:o}),c=await this.validate(a,r.outputs.unknownSchema,"step","output",e.workflowId,t.stepId,r.type);return i.succeed(`Executed provider: \`${r.type}\``),{...c,_passthrough:a._passthrough}}else return i.stopAndPersist({symbol:R.HYDRATED,text:`Hydrated provider: \`${r.type}\``}),{}}catch(n){throw i.stopAndPersist({symbol:R.ERROR,text:`Failed to execute provider: \`${r.type}\``}),new Z(`Failed to execute provider: '${r.type}'.
|
|
27
|
+
${n.message}`)}}async executeStep(e,t){if(e.stepId===t.stepId){let r=ce__default.default({indent:1}).start(`Executing stepId: \`${t.stepId}\``);try{let o=await this.createStepControls(t,e),i=await this.compileControls(o,e),n=await t.resolve(i),a=await this.validate(n,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId),c=await this.executeProviders(e,t,a);return r.succeed(`Executed stepId: \`${t.stepId}\``),{outputs:a,providers:c}}catch(o){throw r.stopAndPersist({prefixText:"",symbol:R.ERROR,text:`Failed to execute stepId: \`${t.stepId}\``}),o}}else {let r=ce__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:R.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:R.ERROR,text:`Failed to hydrate stepId: \`${t.stepId}\``}),o}}}async compileControls(e,t){let r=this.templateEngine.parse(JSON.stringify(e)),o=await this.templateEngine.render(r,{...t.payload||t.data,subscriber:t.subscriber});return JSON.parse(o)}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=ce__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),n=await t.resolve(i),a=await this.validate(n,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId);return r.stopAndPersist({symbol:R.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:a,providers:await this.executeProviders(e,t,a)}}else {let o=this.mock(t.results.schema);return r.stopAndPersist({symbol:R.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:o,providers:await this.executeProviders(e,t,o)}}}catch(o){throw r.stopAndPersist({symbol:R.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 M(e);return r}};var le=class{frameworkName;handler;client;hmacEnabled;http;constructor(e){this.handler=e.handler,this.client=e.client?e.client:new de,this.client.addWorkflows(e.workflows),this.http=he(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")||"",n=t.searchParams.get("stepId")||"",a=await e.headers("novu-signature")||await e.headers("x-novu-signature")||"",c={};try{r==="POST"&&(c=await e.body());}catch{}try{o!=="health-check"&&this.validateHmac(c,a);let u=this.getPostActionMap(c,i,n,o),p=this.getGetActionMap(i,n);if(r==="POST")return await this.handlePostAction(o,u);if(r==="GET")return await this.handleGetAction(o,p);if(r==="OPTIONS")return this.createResponse(200,{})}catch(u){return this.handleError(u)}return this.createError(new J(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.tenant&&{tenant:e.tenant},...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 k(e,S)}async handleGetAction(e,t){if(Object.values(V).includes(e)){let r=t[e];return r()}else throw new k(e,V)}isBridgeError(e){return Object.values(O).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 g))}validateHmac(e,t){if(!this.hmacEnabled)return;if(!t)throw new H;if(!this.client.secretKey)throw new re;let[r,o]=t.split(",");if(!r||!o)throw new ee;let[i,n]=r.split("="),[a,c]=o.split("=");if(Number(i)<Date.now()-1500)throw new te;if(!(this.hashHmac(this.client.secretKey,`${n}.${JSON.stringify(e)}`)===c))throw new Q}hashHmac(e,t){return crypto.createHmac("sha256",e).update(t).digest("hex")}};var Le="sveltekit",qr=s=>{let t=new le({frameworkName:Le,...s,handler:(i,n)=>({method:()=>i||n.request.method||"",body:()=>n.request.json(),headers:a=>n.request.headers.get(a),url:()=>{let a=process.env.NODE_ENV==="development"?"http":"https";return new URL(n.request.url,`${a}://${n.request.headers.get("host")||""}`)},transformResponse:({body:a,headers:c,status:u})=>{let p=Te();return new p(a,{status:u,headers:c})}})}).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
|
-
exports.frameworkName =
|
|
30
|
-
exports.serve =
|
|
29
|
+
exports.frameworkName = Le;
|
|
30
|
+
exports.serve = qr;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@novu/framework",
|
|
3
|
-
"version": "2.0.0-canary.
|
|
3
|
+
"version": "2.0.0-canary.5",
|
|
4
4
|
"description": "The Code-First Notifications Workflow SDK.",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -18,7 +18,6 @@
|
|
|
18
18
|
"README.md"
|
|
19
19
|
],
|
|
20
20
|
"scripts": {
|
|
21
|
-
"preinstall": "npx only-allow pnpm",
|
|
22
21
|
"test": "vitest",
|
|
23
22
|
"test:watch": "vitest --watch",
|
|
24
23
|
"lint": "eslint src --ext .ts --config .eslintrc.js",
|