@novu/framework 0.24.3-alpha.5 → 0.24.3-alpha.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/express.d.ts +1 -1
- package/dist/express.js +15 -15
- package/dist/h3.d.ts +1 -1
- package/dist/h3.js +13 -13
- package/dist/{handler-58kccf2b.d.ts → handler-jSdMUIfN.d.ts} +0 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +18 -18
- package/dist/next.d.ts +1 -1
- package/dist/next.js +14 -14
- package/dist/nuxt.d.ts +1 -1
- package/dist/nuxt.js +13 -13
- package/dist/remix.d.ts +1 -1
- package/dist/remix.js +15 -15
- package/dist/sveltekit.d.ts +1 -1
- package/dist/sveltekit.js +14 -14
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,28 +1,28 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
4
|
-
var
|
|
5
|
-
var
|
|
3
|
+
var $e = require('ajv');
|
|
4
|
+
var Me = require('ajv-formats');
|
|
5
|
+
var Ue = require('better-ajv-errors');
|
|
6
6
|
var jsonSchemaFaker = require('json-schema-faker');
|
|
7
|
-
var
|
|
7
|
+
var oe = require('ora');
|
|
8
8
|
var v = require('chalk');
|
|
9
9
|
var liquidjs = require('liquidjs');
|
|
10
10
|
var crypto = require('crypto');
|
|
11
11
|
|
|
12
12
|
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
13
13
|
|
|
14
|
+
var $e__default = /*#__PURE__*/_interopDefault($e);
|
|
14
15
|
var Me__default = /*#__PURE__*/_interopDefault(Me);
|
|
15
16
|
var Ue__default = /*#__PURE__*/_interopDefault(Ue);
|
|
16
|
-
var
|
|
17
|
-
var se__default = /*#__PURE__*/_interopDefault(se);
|
|
17
|
+
var oe__default = /*#__PURE__*/_interopDefault(oe);
|
|
18
18
|
var v__default = /*#__PURE__*/_interopDefault(v);
|
|
19
19
|
|
|
20
|
-
var $=(n=>(n.EXECUTE="execute",n.PREVIEW="preview",n.SYNC="sync",n.DIFF="diff",n))($||{}),M=(i=>(i.DISCOVER="discover",i.HEALTH_CHECK="health-check",i.CODE="code",i))(M||{});var ue="https://api.novu.co";var y=(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_DATA_INVALID_ERROR="ExecutionEventDataInvalidError",c.EXECUTION_EVENT_INPUT_INVALID_ERROR="ExecutionEventInputInvalidError",c.EXECUTION_STATE_INPUT_INVALID_ERROR="ExecutionStateInputInvalidError",c.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",c.INVALID_ACTION_ERROR="InvalidActionError",c.MISSING_API_KEY_ERROR="MissingApiKeyError",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.PLATFORM_ERROR="PlatformError",c.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",c))(y||{});var S=(i=>(i.POST="POST",i.GET="GET",i.OPTIONS="OPTIONS",i))(S||{});var g=class extends Error{data},U=class extends g{statusCode=404},f=class extends g{statusCode=400},b=class extends g{statusCode=401},T=class extends g{statusCode=500},q=class extends g{statusCode=409};var L=class extends f{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};}},F=class extends f{code="ExecutionEventDataInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`data\`. Please provide the correct event data.`),this.data=t;}},A=class extends f{code="ExecutionEventInputInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`inputs\`. Please provide the correct event inputs.`),this.data=t;}},W=class extends f{code="ExecutionStateInputInvalidError";constructor(e,t,i){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid input. Please provide the correct step input.`),this.data=i;}},Y=class extends f{code="ExecutionStateOutputInvalidError";constructor(e,t,i){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid output. Please provide the correct step output.`),this.data=i;}},V=class extends f{code="ExecutionStateResultInvalidError";constructor(e,t,i){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid result. Please provide the correct step result.`),this.data=i;}},B=class extends f{code="ExecutionProviderOutputInvalidError";constructor(e,t,i,n){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` and provider with id: \`${i}\` has invalid output. Please provide the correct provider output.`),this.data=n;}};var l={info:o=>v__default.default.blue(o),warning:o=>v__default.default.yellow(o),error:o=>v__default.default.red(o),success:o=>v__default.default.green(o),underline:o=>v__default.default.underline(o),bold:o=>v__default.default.bold(o)},d={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 le=o=>Object.values(o).map(e=>`\`${e}\``).join(", "),G=o=>o.replaceAll(/(\w)(\w*)/g,(e,t,i)=>t.toUpperCase()+i.toLowerCase()).replaceAll(/[\s-]+/g,"");var K=class extends g{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${le(S)}`},P=class extends f{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${le(t)}`);}},C=class extends f{code="MissingApiKeyError";constructor(){super("API Key is missing. Please add the API Key during Client initialization.");}};var X=class extends T{code="PlatformError";message="Something went wrong. Please try again later."};var R=class extends q{constructor(e,t){super(`${G(e)} with id: \`${t}\` already exists. Please use a different id.`);}},w=class extends U{constructor(e,t){super(`${G(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},E=class extends T{constructor(e,t){super(`Failed to execute ${G(e)} with id: \`${t}\`. Please try again later.`);}};var z=class extends w{code="ProviderNotFoundError";constructor(e){super("provider",e);}},J=class extends E{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var Q=class extends b{code="SignatureMismatchError";constructor(){super("Signature does not match the expected signature. Please ensure the signature provided in the `x-novu-signature` header is correct and try again.");}},Z=class extends b{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `x-novu-signature` header");}},H=class extends b{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `x-novu-signature` header");}},ee=class extends b{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`x-novu-signature\` header`);}},te=class extends b{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.apiKey`");}};var ie=class extends w{code="StepNotFoundError";constructor(e){super("step",e);}},ne=class extends R{code="StepAlreadyExistsError";constructor(e){super("step",e);}};var D=class extends w{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},oe=class extends R{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var ge={name:"@novu/framework",version:"0.24.3-alpha.5",description:"The Code-First Notifications Workflow SDK.",main:"./dist/index.js",types:"./dist/index.d.ts",publishConfig:{registry:"https://registry.npmjs.org",access:"public"},private:!1,repository:{type:"git",url:"git+https://github.com/novuhq/novu.git"},files:["dist","README.md"],scripts:{preinstall:"npx only-allow pnpm",test:"vitest","test:watch":"vitest --watch",lint:"eslint src --ext .ts","lint:fix":"eslint src --ext .ts --fix",format:"prettier --check --ignore-path .gitignore .","format:fix":"prettier --write --ignore-path .gitignore .",build:"tsup","build:watch":"tsup --watch","$comment:bump:prerelease":"This is a workaround to support `npm version prerelease` with lerna","bump:prerelease":"npm version prerelease --preid=alpha & PID=$!; (sleep 1 && kill -9 $PID) & wait $PID","release:alpha":"pnpm bump:prerelease || pnpm build && npm publish --dry-run"},keywords:["novu","code-first","workflows","durable","sdk","notifications","email","sms","push","webhooks","next","nuxt","h3","express"],author:"Novu",license:"MIT",exports:{".":{require:"./dist/index.js",import:"./dist/index.js",types:"./dist/index.d.ts"},"./express":{require:"./dist/express.js",import:"./dist/express.js",types:"./dist/express.d.ts"},"./next":{require:"./dist/next.js",import:"./dist/next.js",types:"./dist/next.d.ts"},"./nuxt":{require:"./dist/nuxt.js",import:"./dist/nuxt.js",types:"./dist/nuxt.d.ts"},"./h3":{require:"./dist/h3.js",import:"./dist/h3.js",types:"./dist/h3.d.ts"},"./sveltekit":{require:"./dist/sveltekit.js",import:"./dist/sveltekit.js",types:"./dist/sveltekit.d.ts"},"./remix":{require:"./dist/remix.js",import:"./dist/remix.js",types:"./dist/remix.d.ts"}},devDependencies:{"@sveltejs/kit":"^2.5.10","@types/express":"^4.17.13","@types/json-schema":"^7.0.15","@types/node":"^20.11.20","@vercel/node":"^2.15.9",express:"^4.18.2",h3:"^1.11.1",next:"^13.5.4",prettier:"^3.2.5","ts-node":"^10.9.2",tsup:"^8.0.2",typescript:"^5.3.3",vitest:"^1.2.1"},dependencies:{ajv:"^8.12.0","ajv-formats":"^2.1.1","better-ajv-errors":"^1.2.0",chalk:"^4.1.2","cross-fetch":"^4.0.0","json-schema-faker":"^0.5.6","json-schema-to-ts":"^3.0.0",liquidjs:"^10.13.1",ora:"^5.4.1"}};var ce=ge.version;jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});var N=class{discoveredWorkflows=[];ajv;templateEngine=new liquidjs.Liquid;apiUrl;apiKey;version=ce;strictAuthentication;static NOVU_SIGNATURE_HEADER="x-novu-signature";constructor(e){let t=this.buildOptions(e);this.apiKey=t.apiKey,this.apiUrl=t.apiUrl,this.strictAuthentication=t.strictAuthentication;let i=new Me__default.default({useDefaults:!0});Ue__default.default(i),this.ajv=i;}buildOptions(e){let t={apiKey:void 0,apiUrl:ue,strictAuthentication:!0};return e?.apiKey!==void 0?t.apiKey=e.apiKey:process.env.NOVU_API_KEY!==void 0&&(t.apiKey=process.env.NOVU_API_KEY),e?.apiUrl!==void 0?t.apiUrl=e.apiUrl:process.env.NOVU_API_URL!==void 0&&(t.apiUrl=process.env.NOVU_API_URL),e?.strictAuthentication!==void 0?t.strictAuthentication=e.strictAuthentication:process.env.NOVU_STRICT_AUTHENTICATION!==void 0&&(t.strictAuthentication=process.env.NOVU_STRICT_AUTHENTICATION==="true"),t}addWorkflows(e){for(let t of e){if(this.discoveredWorkflows.some(i=>i.workflowId===t.workflowId))throw new oe(t.workflowId);this.discoveredWorkflows.push(t);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((i,n)=>i+n.steps.length,0);return {status:"ok",version:ce,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(i=>i.workflowId===e);if(t)return t;throw new D(e)}getStep(e,t){let n=this.getWorkflow(e).steps.find(s=>s.stepId===t);if(n)return n;throw new ie(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}getHeaders(e){let t={"content-type":"application/json",authorization:`ApiKey ${this.apiKey}`};return e&&(t["x-novu-anonymous"]=e),t}async diff(e,t){let i=this.discover()?.workflows||[];return (await fetch(this.apiUrl+"/v1/bridge/diff",{method:"POST",headers:this.getHeaders(t),body:JSON.stringify({workflows:i,bridgeUrl:e})})).json()}async sync(e,t,i){let{workflows:n}=this.discover();return (await fetch(`${this.apiUrl}/v1/bridge/sync?source=${i||"sdk"}`,{method:"POST",headers:this.getHeaders(t),body:JSON.stringify({workflows:n,bridgeUrl:e})})).json()}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(e)}validate(e,t,i,n,s,a,r,h){if(!t(e)){let u=qe__default.default(i,e,t.errors||[]);switch(console.error(`
|
|
21
|
-
${u}`),n){case"event":this.validateEvent(s,
|
|
22
|
-
${l.bold(l.underline(n))} '${e.workflowId}'`);let s=this.getWorkflow(e.workflowId),
|
|
23
|
-
${l.bold(
|
|
24
|
-
`);}async executeProviders(e,t){return t.providers.reduce(async(i,n)=>{let s=await i,
|
|
25
|
-
${s.message}`)}}async executeStep(e,t){if(e.stepId===t.stepId){let i=
|
|
20
|
+
var N=(t=>(t.EXECUTE="execute",t.PREVIEW="preview",t))(N||{}),j=(i=>(i.DISCOVER="discover",i.HEALTH_CHECK="health-check",i.CODE="code",i))(j||{});var he="https://api.novu.co";var y=(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_DATA_INVALID_ERROR="ExecutionEventDataInvalidError",c.EXECUTION_EVENT_INPUT_INVALID_ERROR="ExecutionEventInputInvalidError",c.EXECUTION_STATE_INPUT_INVALID_ERROR="ExecutionStateInputInvalidError",c.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",c.INVALID_ACTION_ERROR="InvalidActionError",c.MISSING_API_KEY_ERROR="MissingApiKeyError",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.PLATFORM_ERROR="PlatformError",c.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",c))(y||{});var $=(i=>(i.POST="POST",i.GET="GET",i.OPTIONS="OPTIONS",i))($||{});var g=class extends Error{data},M=class extends g{statusCode=404},m=class extends g{statusCode=400},b=class extends g{statusCode=401},T=class extends g{statusCode=500},U=class extends g{statusCode=409};var q=class extends m{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};}},L=class extends m{code="ExecutionEventDataInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`data\`. Please provide the correct event data.`),this.data=t;}},O=class extends m{code="ExecutionEventInputInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`inputs\`. Please provide the correct event inputs.`),this.data=t;}},F=class extends m{code="ExecutionStateInputInvalidError";constructor(e,t,i){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid input. Please provide the correct step input.`),this.data=i;}},W=class extends m{code="ExecutionStateOutputInvalidError";constructor(e,t,i){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid output. Please provide the correct step output.`),this.data=i;}},Y=class extends m{code="ExecutionStateResultInvalidError";constructor(e,t,i){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid result. Please provide the correct step result.`),this.data=i;}},V=class extends m{code="ExecutionProviderOutputInvalidError";constructor(e,t,i,n){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` and provider with id: \`${i}\` has invalid output. Please provide the correct provider output.`),this.data=n;}};var l={info:o=>v__default.default.blue(o),warning:o=>v__default.default.yellow(o),error:o=>v__default.default.red(o),success:o=>v__default.default.green(o),underline:o=>v__default.default.underline(o),bold:o=>v__default.default.bold(o)},d={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 ae=o=>Object.values(o).map(e=>`\`${e}\``).join(", "),B=o=>o.replaceAll(/(\w)(\w*)/g,(e,t,i)=>t.toUpperCase()+i.toLowerCase()).replaceAll(/[\s-]+/g,"");var G=class extends g{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${ae($)}`},S=class extends m{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${ae(t)}`);}};var K=class extends T{code="PlatformError";message="Something went wrong. Please try again later."};var R=class extends U{constructor(e,t){super(`${B(e)} with id: \`${t}\` already exists. Please use a different id.`);}},x=class extends M{constructor(e,t){super(`${B(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},E=class extends T{constructor(e,t){super(`Failed to execute ${B(e)} with id: \`${t}\`. Please try again later.`);}};var X=class extends x{code="ProviderNotFoundError";constructor(e){super("provider",e);}},z=class extends E{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var Q=class extends b{code="SignatureMismatchError";constructor(){super("Signature does not match the expected signature. Please ensure the signature provided in the `x-novu-signature` header is correct and try again.");}},J=class extends b{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `x-novu-signature` header");}},Z=class extends b{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `x-novu-signature` header");}},H=class extends b{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`x-novu-signature\` header`);}},ee=class extends b{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.apiKey`");}};var te=class extends x{code="StepNotFoundError";constructor(e){super("step",e);}},ie=class extends R{code="StepAlreadyExistsError";constructor(e){super("step",e);}};var P=class extends x{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},ne=class extends R{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var ye={name:"@novu/framework",version:"0.24.3-alpha.6",description:"The Code-First Notifications Workflow SDK.",main:"./dist/index.js",types:"./dist/index.d.ts",publishConfig:{registry:"https://registry.npmjs.org",access:"public"},private:!1,repository:{type:"git",url:"git+https://github.com/novuhq/novu.git"},files:["dist","README.md"],scripts:{preinstall:"npx only-allow pnpm",test:"vitest","test:watch":"vitest --watch",lint:"eslint src --ext .ts","lint:fix":"eslint src --ext .ts --fix",format:"prettier --check --ignore-path .gitignore .","format:fix":"prettier --write --ignore-path .gitignore .",build:"tsup","build:watch":"tsup --watch","$comment:bump:prerelease":"This is a workaround to support `npm version prerelease` with lerna","bump:prerelease":"npm version prerelease --preid=alpha & PID=$!; (sleep 1 && kill -9 $PID) & wait $PID","release:alpha":"pnpm bump:prerelease || pnpm build && npm publish"},keywords:["novu","code-first","workflows","durable","sdk","notifications","email","sms","push","webhooks","next","nuxt","h3","express"],author:"Novu",license:"MIT",exports:{".":{require:"./dist/index.js",import:"./dist/index.js",types:"./dist/index.d.ts"},"./express":{require:"./dist/express.js",import:"./dist/express.js",types:"./dist/express.d.ts"},"./next":{require:"./dist/next.js",import:"./dist/next.js",types:"./dist/next.d.ts"},"./nuxt":{require:"./dist/nuxt.js",import:"./dist/nuxt.js",types:"./dist/nuxt.d.ts"},"./h3":{require:"./dist/h3.js",import:"./dist/h3.js",types:"./dist/h3.d.ts"},"./sveltekit":{require:"./dist/sveltekit.js",import:"./dist/sveltekit.js",types:"./dist/sveltekit.d.ts"},"./remix":{require:"./dist/remix.js",import:"./dist/remix.js",types:"./dist/remix.d.ts"}},devDependencies:{"@sveltejs/kit":"^2.5.10","@types/express":"^4.17.13","@types/json-schema":"^7.0.15","@types/node":"^20.11.20","@vercel/node":"^2.15.9",express:"^4.18.2",h3:"^1.11.1",next:"^13.5.4",prettier:"^3.2.5","ts-node":"^10.9.2",tsup:"^8.0.2",typescript:"^5.3.3",vitest:"^1.2.1"},dependencies:{ajv:"^8.12.0","ajv-formats":"^2.1.1","better-ajv-errors":"^1.2.0",chalk:"^4.1.2","cross-fetch":"^4.0.0","json-schema-faker":"^0.5.6","json-schema-to-ts":"^3.0.0",liquidjs:"^10.13.1",ora:"^5.4.1"}};var le=ye.version;jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});var C=class{discoveredWorkflows=[];ajv;templateEngine=new liquidjs.Liquid;apiUrl;apiKey;version=le;strictAuthentication;static NOVU_SIGNATURE_HEADER="x-novu-signature";constructor(e){let t=this.buildOptions(e);this.apiKey=t.apiKey,this.apiUrl=t.apiUrl,this.strictAuthentication=t.strictAuthentication;let i=new $e__default.default({useDefaults:!0});Me__default.default(i),this.ajv=i;}buildOptions(e){let t={apiKey:void 0,apiUrl:he,strictAuthentication:!0};return e?.apiKey!==void 0?t.apiKey=e.apiKey:process.env.NOVU_API_KEY!==void 0&&(t.apiKey=process.env.NOVU_API_KEY),e?.apiUrl!==void 0?t.apiUrl=e.apiUrl:process.env.NOVU_API_URL!==void 0&&(t.apiUrl=process.env.NOVU_API_URL),e?.strictAuthentication!==void 0?t.strictAuthentication=e.strictAuthentication:process.env.NOVU_STRICT_AUTHENTICATION!==void 0&&(t.strictAuthentication=process.env.NOVU_STRICT_AUTHENTICATION==="true"),t}addWorkflows(e){for(let t of e){if(this.discoveredWorkflows.some(i=>i.workflowId===t.workflowId))throw new ne(t.workflowId);this.discoveredWorkflows.push(t);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((i,n)=>i+n.steps.length,0);return {status:"ok",version:le,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(i=>i.workflowId===e);if(t)return t;throw new P(e)}getStep(e,t){let n=this.getWorkflow(e).steps.find(s=>s.stepId===t);if(n)return n;throw new te(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}getHeaders(e){let t={"content-type":"application/json",authorization:`ApiKey ${this.apiKey}`};return e&&(t["x-novu-anonymous"]=e),t}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(e)}validate(e,t,i,n,s,r,a,h){if(!t(e)){let u=Ue__default.default(i,e,t.errors||[]);switch(console.error(`
|
|
21
|
+
${u}`),n){case"event":this.validateEvent(s,r,t);case"step":this.validateStep(a,s,r,t);case"provider":this.validateProvider(a,h,s,r,t);}}}validateProvider(e,t,i,n,s){if(!e)throw new Error("stepId is required");if(!t)throw new Error("providerId is required");switch(i){case"output":throw new V(n,e,t,s.errors);default:throw new Error(`Invalid payload type: '${i}'`)}}validateStep(e,t,i,n){if(!e)throw new Error("stepId is required");switch(t){case"output":throw new W(i,e,n.errors);case"result":throw new Y(i,e,n.errors);case"input":throw new F(i,e,n.errors);default:throw new Error(`Invalid payload type: '${t}'`)}}validateEvent(e,t,i){switch(e){case"input":throw new O(t,i.errors);case"data":throw new L(t,i.errors);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(i,n,s)=>{let r=this.getStep(e.workflowId,i),a=Le(e),h=this.createStepInputs(r,a),p=e.action==="preview";if(!p&&await this.shouldSkip(s?.skip,h))return t({options:{skip:!0}}),{};let u=this.previewStep.bind(this),f=this.executeStep.bind(this),D=await(p?u:f)(e,{...r,providers:r.providers.map(k=>{let A=s?.providers?.[k.type];if(!A)throw new X(k.type);return {...k,resolve:A}}),resolve:n});return i===e.stepId&&t(D),D.outputs}}async shouldSkip(e,t){return e?e(t):!1}async executeWorkflow(e){let n=`${{execute:"Executing",preview:"Previewing"}[e.action]} workflowId:`;console.log(`
|
|
22
|
+
${l.bold(l.underline(n))} '${e.workflowId}'`);let s=this.getWorkflow(e.workflowId),r=process.hrtime(),a={outputs:{},providers:{},options:{}},h,p=new Promise(_=>{h=_;}),u=_=>{h(),a=_;},f;try{if(e.action==="execute"&&!e.data)throw new O(e.workflowId,{message:"Event `data` is required"});let _=this.createExecutionInputs(e,s);await Promise.race([p,s.execute({payload:_,environment:{},input:{},subscriber:e.subscriber,step:{email:this.executeStepFactory(e,u),sms:this.executeStepFactory(e,u),inApp:this.executeStepFactory(e,u),digest:this.executeStepFactory(e,u),delay:this.executeStepFactory(e,u),push:this.executeStepFactory(e,u),chat:this.executeStepFactory(e,u),custom:this.executeStepFactory(e,u)}})]);}catch(_){f=_;}let I=process.hrtime(r),D=I[0],k=I[1],A=D*1e3+k/1e6,Ce=f?d.ERROR:d.SUCCESS,De=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action";if(console.log(`${Ce} ${De} workflowId: \`${e.workflowId}\``),this.prettyPrintExecute(e,A,f),f)throw f;return {outputs:a.outputs,providers:a.providers,options:a.options,metadata:{status:"success",error:!1,duration:A}}}createExecutionInputs(e,t){let i=e.data;return this.validate(e.data,t.data.validate,t.data.schema,"event","input",e.workflowId),i}prettyPrintExecute(e,t,i){let n=i?d.ERROR:d.SUCCESS,s=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action",r=i?"Failed to execute":s,a=i?l.error:l.success,h=`${n} ${r} workflowId: '${e.workflowId}`;console.log(`
|
|
23
|
+
${l.bold(a(h))}'`),console.log(` \u251C ${d.STEP} stepId: '${e.stepId}'`),console.log(` \u251C ${d.ACTION} action: '${e.action}'`),console.log(` \u2514 ${d.DURATION} duration: '${t.toFixed(2)}ms'
|
|
24
|
+
`);}async executeProviders(e,t){return t.providers.reduce(async(i,n)=>{let s=await i,r=this.previewProvider.bind(this),a=this.executeProvider.bind(this),p=await(e.action==="preview"?r:a)(e,t,n);return {...s,[n.type]:p}},Promise.resolve({}))}previewProvider(e,t,i){return console.log(` ${d.MOCK} Mocked provider: \`${i.type}\``),this.mock(i.outputs.schema)}async executeProvider(e,t,i){let n=oe__default.default({indent:2}).start(`Executing provider: \`${i.type}\``);try{if(e.stepId===t.stepId){let s=this.createStepInputs(t,e),r=await i.resolve({inputs:s});return this.validate(r,i.outputs.validate,i.outputs.schema,"step","output",e.workflowId,t.stepId,i.type),n.succeed(`Executed provider: \`${i.type}\``),r}else n.stopAndPersist({symbol:d.HYDRATED,text:`Hydrated provider: \`${i.type}\``});}catch(s){throw n.stopAndPersist({symbol:d.ERROR,text:`Failed to execute provider: \`${i.type}\``}),new z(`Failed to execute provider: '${i.type}'.
|
|
25
|
+
${s.message}`)}}async executeStep(e,t){if(e.stepId===t.stepId){let i=oe__default.default({indent:1}).start(`Executing stepId: \`${t.stepId}\``);try{let n=this.createStepInputs(t,e),s=await this.compileInputs(n,e),r=await t.resolve(s);this.validate(r,t.outputs.validate,t.outputs.schema,"step","output",e.workflowId,t.stepId);let a=await this.executeProviders(e,t);return i.succeed(`Executed stepId: \`${t.stepId}\``),{outputs:r,providers:a}}catch(n){throw i.stopAndPersist({prefixText:"",symbol:d.ERROR,text:`Failed to execute stepId: \`${t.stepId}\``}),n}}else {let i=oe__default.default({indent:1}).start(`Hydrating stepId: \`${t.stepId}\``);try{let n=e.state.find(s=>s.stepId===t.stepId);if(n)return this.validate(n.outputs,t.results.validate,t.results.schema,"step","result",e.workflowId,t.stepId),i.stopAndPersist({symbol:d.HYDRATED,text:`Hydrated stepId: \`${t.stepId}\``}),{outputs:n.outputs,providers:await this.executeProviders(e,t)};throw new q(e.workflowId,t.stepId)}catch(n){throw i.stopAndPersist({symbol:d.ERROR,text:`Failed to hydrate stepId: \`${t.stepId}\``}),n}}}async compileInputs(e,t){let i=this.templateEngine.parse(JSON.stringify(e)),n=await this.templateEngine.render(i,{...t.data,subscriber:t.subscriber});return JSON.parse(n)}createStepInputs(e,t){let i=t.inputs;return this.validate(i,e.inputs.validate,e.inputs.schema,"step","input",t.workflowId,e.stepId),i}async previewStep(e,t){let i=oe__default.default({indent:1}).start(`Previewing stepId: \`${t.stepId}\``);try{if(e.stepId===t.stepId){let n=this.createStepInputs(t,e),s=await this.compileInputs(n,e),r=await t.resolve(s);return this.validate(r,t.outputs.validate,t.outputs.schema,"step","output",e.workflowId,t.stepId),i.stopAndPersist({symbol:d.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:r,providers:await this.executeProviders(e,t)}}else {let n=this.mock(t.results.schema);return i.stopAndPersist({symbol:d.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:n,providers:await this.executeProviders(e,t)}}}catch(n){throw i.stopAndPersist({symbol:d.ERROR,text:`Failed to preview stepId: \`${t.stepId}\``}),n}}getStepCode(e,t){return {code:this.getStep(e,t).resolve.toString()}}getWorkflowCode(e){return {code:this.getWorkflow(e).execute.toString()}}getCode(e,t){let i;if(e)t?i=this.getStepCode(e,t):i=this.getWorkflowCode(e);else throw new P(e);return i}};function Le(o){return JSON.parse(JSON.stringify(o))}var Fe=(p=>(p.PENDING="pending",p.QUEUED="queued",p.RUNNING="running",p.COMPLETED="completed",p.FAILED="failed",p.DELAYED="delayed",p.CANCELED="canceled",p.MERGED="merged",p.SKIPPED="skipped",p))(Fe||{});var ce=class{frameworkName;handler;client;hmacEnabled;constructor(e){this.handler=e.handler,this.client=e.client?e.client:new C,this.client.addWorkflows(e.workflows),this.frameworkName=e.frameworkName,this.hmacEnabled=this.client.strictAuthentication;}createHandler(){return async(...e)=>{let t=await this.handler(...e),i=await this.handleAction({actions:t});return t.transformResponse(i)}}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","x-novu-framework":this.frameworkName,"user-agent":e,"x-novu-sdk":e}}createResponse(e,t,i={}){return {status:e,body:JSON.stringify(t),headers:{...this.getStaticHeaders(),...i}}}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(),i=await e.method(),n=t.searchParams.get("action")||"",s=t.searchParams.get("workflowId")||"",r=t.searchParams.get("stepId")||"",a=await e.headers("x-novu-signature")||"",h=await e.headers("x-novu-anonymous")||"",p=t.searchParams.get("source")||"",u={};try{i==="POST"&&(u=await e.body());}catch{}try{n!=="health-check"&&this.validateHmac(u,a);let f=this.getPostActionMap(u,s,r,n,h,p),I=this.getGetActionMap(s,r);if(i==="POST")return await this.handlePostAction(n,f);if(i==="GET")return await this.handleGetAction(n,I);if(i==="OPTIONS")return this.createResponse(200,{},{...this.getStaticHeaders()})}catch(f){return this.handleError(f)}return this.createError(new G(i))}getPostActionMap(e,t,i,n,s,r){return {execute:async()=>{let a=await this.client.executeWorkflow({...e,workflowId:t,stepId:i,action:n});return this.createResponse(200,a,{"x-novu-execution-duration":a.metadata.duration.toString()})},preview:async()=>{let a=await this.client.executeWorkflow({...e,workflowId:t,stepId:i,action:n});return this.createResponse(200,a,{"x-novu-execution-duration":a.metadata.duration.toString()})}}}getGetActionMap(e,t){return {discover:async()=>{let i=await this.client.discover();return this.createResponse(200,i)},"health-check":async()=>{let i=await this.client.healthCheck();return this.createResponse(200,i)},code:async()=>{let i=await this.client.getCode(e,t);return this.createResponse(200,i)}}}async handlePostAction(e,t){if(Object.values(N).includes(e)){let i=t[e];return i()}else throw new S(e,N)}async handleGetAction(e,t){if(Object.values(j).includes(e)){let i=t[e];return i()}else throw new S(e,j)}isClientError(e){return Object.values(y).includes(e.code)}handleError(e){return this.isClientError(e)?(e.statusCode===500&&console.error(e),this.createError(e)):(console.error(e),this.createError(new K))}validateHmac(e,t){if(!this.hmacEnabled)return;if(!t)throw new J;if(!this.client.apiKey)throw new ee;let[i,n]=t.split(",");if(!i||!n)throw new Z;let[s,r]=i.split("="),[a,h]=n.split("=");if(Number(s)<Date.now()-1500)throw new H;if(!(this.hashHmac(this.client.apiKey,`${r}.${JSON.stringify(e)}`)===h))throw new Q}hashHmac(e,t){return crypto.createHmac("sha256",e).update(t).digest("hex")}};var Ve={type:"object",properties:{webhookUrl:{type:"string",format:"uri"},text:{type:"string"},blocks:{type:"array",items:{type:"object",properties:{type:{enum:["image","context","actions","divider","section","input","file","header","video","rich_text"]}},required:["type"],additionalProperties:!0,allOf:[{if:{properties:{type:{const:"image"}}},then:{$ref:"#/definitions/ImageBlock"}},{if:{properties:{type:{const:"context"}}},then:{$ref:"#/definitions/ContextBlock"}},{if:{properties:{type:{const:"actions"}}},then:{$ref:"#/definitions/ActionsBlock"}},{if:{properties:{type:{const:"divider"}}},then:{$ref:"#/definitions/DividerBlock"}},{if:{properties:{type:{const:"section"}}},then:{$ref:"#/definitions/SectionBlock"}},{if:{properties:{type:{const:"Input"}}},then:{$ref:"#/definitions/InputBlock"}},{if:{properties:{type:{const:"Video"}}},then:{$ref:"#/definitions/VideoBlock"}},{if:{properties:{type:{const:"rich_text"}}},then:{$ref:"#/definitions/RichTextBlock"}}]}}},definitions:{KnownBlock:{oneOf:[{$ref:"#/definitions/ImageBlock"},{$ref:"#/definitions/ContextBlock"},{$ref:"#/definitions/ActionsBlock"},{$ref:"#/definitions/DividerBlock"},{$ref:"#/definitions/SectionBlock"},{$ref:"#/definitions/InputBlock"},{$ref:"#/definitions/FileBlock"},{$ref:"#/definitions/HeaderBlock"},{$ref:"#/definitions/VideoBlock"},{$ref:"#/definitions/RichTextBlock"}]},ImageBlock:{type:"object",properties:{type:{type:"string",const:"image",description:"The type of block. For an image block, `type` is always `image`."},block_id:{type:"string"},image_url:{type:"string",description:"The URL of the image to be displayed. Maximum length for this field is 3000 characters."},alt_text:{type:"string",description:`A plain-text summary of the image. This should not contain any markup.
|
|
26
26
|
Maximum length for this field is 2000 characters.`},title:{$ref:"#/definitions/PlainTextElement",description:`An optional title for the image in the form of a {@link PlainTextElement } object.
|
|
27
27
|
Maximum length for the text in this field is 2000 characters.`}},required:["alt_text","image_url","type"],additionalProperties:!1,description:"Displays an image. A simple image block, designed to make those cat photos really pop."},PlainTextElement:{type:"object",properties:{type:{type:"string",const:"plain_text",description:"The formatting to use for this text object."},text:{type:"string",description:"The text for the block. The minimum length is 1 and maximum length is 3000 characters."},emoji:{type:"boolean",description:"Indicates whether emojis in a text field should be escaped into the colon emoji format."}},required:["type","text"],additionalProperties:!1,description:"Defines an object containing some text."},ContextBlock:{type:"object",properties:{type:{type:"string",const:"context",description:"The type of block. For a context block, `type` is always `context`."},block_id:{type:"string"},elements:{type:"array",items:{anyOf:[{$ref:"#/definitions/ImageElement"},{$ref:"#/definitions/PlainTextElement"},{$ref:"#/definitions/MrkdwnElement"}]},description:`An array of {@link ImageElement }, {@link PlainTextElement } or {@link MrkdwnElement } objects.
|
|
28
28
|
Maximum number of items is 10.`}},required:["elements","type"],additionalProperties:!1,description:"Displays contextual info, which can include both images and text."},ImageElement:{type:"object",properties:{type:{type:"string",const:"image",description:"The type of element. In this case `type` is always `image`."},image_url:{type:"string",description:"The URL of the image to be displayed."},alt_text:{type:"string",description:"A plain-text summary of the image. This should not contain any markup."}},required:["type","image_url","alt_text"],additionalProperties:!1,description:"Displays an image as part of a larger block of content. Use this `image` block if you want a block with\nonly an image in it."},MrkdwnElement:{type:"object",properties:{type:{type:"string",const:"mrkdwn",description:"The formatting to use for this text object."},text:{type:"string",description:`The text for the block. This field accepts any of the standard text formatting markup.
|
|
@@ -103,10 +103,10 @@ that contain remote files. If you want to add remote files to messages,
|
|
|
103
103
|
Maximum length for the text in this field is 150 characters.`}},required:["text","type"],additionalProperties:!1,description:"Displays a larger-sized text block. A `header` is a plain-text block that displays in a larger, bold\nfont. Use it to delineate between different groups of content in your app's surfaces."},VideoBlock:{type:"object",properties:{type:{type:"string",const:"video",description:"The type of block. For a video block, `type` is always `video`."},block_id:{type:"string",description:"A string acting as a unique identifier for a block. If not specified, a `block_id` will be generated.\nYou can use this `block_id` when you receive an interaction payload to\n{@link https://api.slack.com/interactivity/handling#payloads identify the source of the action}.\nMaximum length for this field is 255 characters. `block_id` should be unique for each message and each iteration of\na message. If a message is updated, use a new `block_id`."},video_url:{type:"string",description:`The URL to be embedded. Must match any existing
|
|
104
104
|
{@link https://api.slack.com/reference/messaging/link-unfurling#configuring_domains unfurl domains} within the app
|
|
105
105
|
and point to a HTTPS URL.`},thumbnail_url:{type:"string",description:"The thumbnail image URL."},alt_text:{type:"string",description:"A tooltip for the video. Required for accessibility."},title:{$ref:"#/definitions/PlainTextElement",description:"Video title as a {@link PlainTextElement } object. `text` within must be less than 200 characters."},title_url:{type:"string",description:`Hyperlink for the title text. Must correspond to the non-embeddable URL for the video.
|
|
106
|
-
Must go to an HTTPS URL.`},author_name:{type:"string",description:"Author name to be displayed. Must be less than 50 characters."},provider_name:{type:"string",description:"The originating application or domain of the video, e.g. YouTube."},provider_icon_url:{type:"string",description:"Icon for the video provider, e.g. YouTube icon."},description:{$ref:"#/definitions/PlainTextElement",description:"Description for video using a {@link PlainTextElement } object."}},required:["alt_text","thumbnail_url","title","type","video_url"],additionalProperties:!1,description:"Displays an embedded video player. A video block is designed to embed videos in all app surfaces (e.g.\nlink unfurls, messages, modals, App Home) \u2014 anywhere you can put blocks! To use the video block within your app, you\nmust have the {@link https://api.slack.com/scopes/links.embed:write `links.embed:write` scope}."}},additionalProperties:!1},
|
|
107
|
-
${l.bold(l.underline("Discovered workflowId:"))} '${o.workflowId}'`),o.steps.forEach((e,t)=>{let i=t===o.steps.length-1?"\u2514":"\u251C";console.log(`${i} ${d.STEP} Discovered stepId: '${e.stepId}' Type: '${e.type}'`),e.providers.forEach((n,s)=>{let
|
|
106
|
+
Must go to an HTTPS URL.`},author_name:{type:"string",description:"Author name to be displayed. Must be less than 50 characters."},provider_name:{type:"string",description:"The originating application or domain of the video, e.g. YouTube."},provider_icon_url:{type:"string",description:"Icon for the video provider, e.g. YouTube icon."},description:{$ref:"#/definitions/PlainTextElement",description:"Description for video using a {@link PlainTextElement } object."}},required:["alt_text","thumbnail_url","title","type","video_url"],additionalProperties:!1,description:"Displays an embedded video player. A video block is designed to embed videos in all app surfaces (e.g.\nlink unfurls, messages, modals, App Home) \u2014 anywhere you can put blocks! To use the video block within your app, you\nmust have the {@link https://api.slack.com/scopes/links.embed:write `links.embed:write` scope}."}},additionalProperties:!1},be={output:Ve};var xe={slack:be};var Be={type:"object",properties:{ipPoolName:{type:"string"}},required:["ipPoolName"],additionalProperties:!1},we={output:Be};var _e={sendgrid:we};var ke={};var Te={};var ve={};var Re={chat:xe,sms:ve,email:_e,push:Te,in_app:ke};var Ge={type:"object",properties:{type:{enum:["regular"],default:"regular"},amount:{type:"number"},unit:{type:"string",enum:["seconds","minutes","hours","days","weeks","months"]}},required:["amount","unit"],additionalProperties:!1},Ke={type:"object",properties:{duration:{type:"number"}},required:["duration"],additionalProperties:!1},pe={output:Ge,result:Ke};var Xe={type:"object",properties:{amount:{type:"number"},unit:{type:"string",enum:["seconds","minutes","hours","days","weeks","months"]}},required:["amount","unit"],additionalProperties:!1},ze={type:"object",properties:{events:{type:"array",items:{type:"object",properties:{id:{type:"string"},time:{type:"string"},payload:{type:"object"}},required:["id","time","payload"],additionalProperties:!1}}},required:["events"],additionalProperties:!1},de={output:Xe,result:ze};var Qe={type:"object",properties:{body:{type:"string"}},required:["body"],additionalProperties:!1},Je={type:"object",properties:{},required:[],additionalProperties:!1},Ee={output:Qe,result:Je};var Ze={type:"object",properties:{subject:{type:"string"},body:{type:"string"}},required:["subject","body"],additionalProperties:!1},He={type:"object",properties:{},required:[],additionalProperties:!1},Ie={output:Ze,result:He};var et={type:"object",properties:{body:{type:"string"}},required:["body"],additionalProperties:!1},tt={type:"object",properties:{seen:{type:"boolean"},read:{type:"boolean"},lastSeenDate:{type:"string",format:"date-time",nullable:!0},lastReadDate:{type:"string",format:"date-time",nullable:!0}},required:["seen","read","lastSeenDate","lastReadDate"],additionalProperties:!1},Ae={output:et,result:tt};var it={type:"object",properties:{subject:{type:"string"},body:{type:"string"}},required:["subject","body"],additionalProperties:!1},nt={type:"object",properties:{},required:[],additionalProperties:!1},Oe={output:it,result:nt};var ot={type:"object",properties:{body:{type:"string"}},required:["body"],additionalProperties:!1},st={type:"object",properties:{},required:[],additionalProperties:!1},Se={output:ot,result:st};var se={chat:Ee,sms:Se,push:Oe,email:Ie,in_app:Ae};var w={type:"object",properties:{},required:[],additionalProperties:!1};function lt(o,e,t){let i=t||{},n=new $e__default.default({useDefaults:!0});Me__default.default(n);let s={workflowId:o,options:i,steps:[],code:e.toString(),data:{schema:i.payloadSchema||w,validate:n.compile(i.payloadSchema||w)},inputs:{schema:i.inputSchema||w,validate:n.compile(i.inputSchema||w)},execute:e};return e({payload:{},subscriber:{},environment:{},input:{},step:{...Object.entries(se).reduce((r,[a,h])=>(r[a]=re(s,a,n,h.output,h.result),r),{}),inApp:re(s,"in_app",n,se.in_app.output,se.in_app.result),digest:re(s,"digest",n,de.output,de.result),delay:re(s,"delay",n,pe.output,pe.result),custom:pt(s,"custom",n)}}),dt(s),s}function re(o,e,t,i,n){return async(s,r,a={})=>{let h=a?.inputSchema||w,p={stepId:s,type:e,inputs:{schema:h,validate:t.compile(h)},outputs:{schema:i,validate:t.compile(i)},results:{schema:n,validate:t.compile(n)},resolve:r,code:r.toString(),options:a,providers:[]};Pe(o,s,p),Object.keys(a.providers||{}).length>0&&ct(p,t,e,a.providers||{});}}function Pe(o,e,t){if(o.steps.some(i=>i.stepId===e))throw new ie(e);o.steps.push(t);}function ct(o,e,t,i){let n=Re[t];Object.entries(i).forEach(([s,r])=>{let a=n[s];o.providers.push({type:s,code:r.toString(),resolve:r,outputs:{schema:a.output,validate:e.compile(a.output)}});});}function pt(o,e,t){return async(i,n,s={})=>{let r=s?.inputSchema||w,a=s?.outputSchema||w;Pe(o,i,{stepId:i,type:e,inputs:{schema:r,validate:t.compile(r)},outputs:{schema:a,validate:t.compile(a)},results:{schema:a,validate:t.compile(a)},resolve:n,code:n.toString(),options:s,providers:[]});}}function dt(o){console.log(`
|
|
107
|
+
${l.bold(l.underline("Discovered workflowId:"))} '${o.workflowId}'`),o.steps.forEach((e,t)=>{let i=t===o.steps.length-1?"\u2514":"\u251C";console.log(`${i} ${d.STEP} Discovered stepId: '${e.stepId}' Type: '${e.type}'`),e.providers.forEach((n,s)=>{let r=s===e.providers.length-1?"\u2514":"\u251C";console.log(` ${r} ${d.PROVIDER} Discovered provider: '${n.type}'`);});});}
|
|
108
108
|
|
|
109
|
-
exports.Client =
|
|
110
|
-
exports.JobStatusEnum =
|
|
111
|
-
exports.NovuRequestHandler =
|
|
112
|
-
exports.workflow =
|
|
109
|
+
exports.Client = C;
|
|
110
|
+
exports.JobStatusEnum = Fe;
|
|
111
|
+
exports.NovuRequestHandler = ce;
|
|
112
|
+
exports.workflow = lt;
|
package/dist/next.d.ts
CHANGED
package/dist/next.js
CHANGED
|
@@ -1,28 +1,28 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var crypto = require('crypto');
|
|
4
|
-
var
|
|
5
|
-
var
|
|
6
|
-
var
|
|
4
|
+
var Te = require('ajv');
|
|
5
|
+
var _e = require('ajv-formats');
|
|
6
|
+
var fe = require('better-ajv-errors');
|
|
7
7
|
var jsonSchemaFaker = require('json-schema-faker');
|
|
8
|
-
var
|
|
8
|
+
var te = require('ora');
|
|
9
9
|
var v = require('chalk');
|
|
10
10
|
var liquidjs = require('liquidjs');
|
|
11
11
|
|
|
12
12
|
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
13
13
|
|
|
14
|
-
var
|
|
15
|
-
var we__default = /*#__PURE__*/_interopDefault(we);
|
|
14
|
+
var Te__default = /*#__PURE__*/_interopDefault(Te);
|
|
16
15
|
var _e__default = /*#__PURE__*/_interopDefault(_e);
|
|
17
|
-
var
|
|
16
|
+
var fe__default = /*#__PURE__*/_interopDefault(fe);
|
|
17
|
+
var te__default = /*#__PURE__*/_interopDefault(te);
|
|
18
18
|
var v__default = /*#__PURE__*/_interopDefault(v);
|
|
19
19
|
|
|
20
|
-
var he=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var k=(s=>(s.EXECUTE="execute",s.PREVIEW="preview",s.SYNC="sync",s.DIFF="diff",s))(k||{}),L=(r=>(r.DISCOVER="discover",r.HEALTH_CHECK="health-check",r.CODE="code",r))(L||{});var ae="https://api.novu.co";var f=(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_DATA_INVALID_ERROR="ExecutionEventDataInvalidError",d.EXECUTION_EVENT_INPUT_INVALID_ERROR="ExecutionEventInputInvalidError",d.EXECUTION_STATE_INPUT_INVALID_ERROR="ExecutionStateInputInvalidError",d.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",d.INVALID_ACTION_ERROR="InvalidActionError",d.MISSING_API_KEY_ERROR="MissingApiKeyError",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.PLATFORM_ERROR="PlatformError",d.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",d))(f||{});var m=(r=>(r.POST="POST",r.GET="GET",r.OPTIONS="OPTIONS",r))(m||{});var w=class extends Error{data},b=class extends w{statusCode=404},T=class extends w{statusCode=400},_=class extends w{statusCode=401},x=class extends w{statusCode=500},F=class extends w{statusCode=409};var W=class extends T{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};}},$=class extends T{code="ExecutionEventDataInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`data\`. Please provide the correct event data.`),this.data=t;}},y=class extends T{code="ExecutionEventInputInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`inputs\`. Please provide the correct event inputs.`),this.data=t;}},M=class extends T{code="ExecutionStateInputInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid input. Please provide the correct step input.`),this.data=r;}},V=class extends T{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 T{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 T{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 de=()=>typeof Response<"u"?Response:he("cross-fetch").Response;var u={info:o=>v__default.default.blue(o),warning:o=>v__default.default.yellow(o),error:o=>v__default.default.red(o),success:o=>v__default.default.green(o),underline:o=>v__default.default.underline(o),bold:o=>v__default.default.bold(o)},R={SUCCESS:u.success("\u2714"),ERROR:u.error("\u2717"),WARNING:u.warning("\u26A0"),INFO:u.info("\u2139"),ARROW:u.bold("\u2192"),MOCK:u.info("\u25CB"),HYDRATED:u.bold(u.info("\u2192")),STEP:u.info("\u03C3"),ACTION:u.info("\u03B1"),DURATION:u.info("\u0394"),PROVIDER:u.info("\u2699"),OUTPUT:u.info("\u21E2"),INPUT:u.info("\u21E0"),WORKFLOW:u.info("\u03C9"),STATE:u.info("\u03C3"),EXECUTE:u.info("\u03B5"),PREVIEW:u.info("\u03C1")};var ie=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 Y=class extends w{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${ie(m)}`},S=class extends T{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${ie(t)}`);}},C=class extends T{code="MissingApiKeyError";constructor(){super("API Key is missing. Please add the API Key during Client initialization.");}};var X=class extends x{code="PlatformError";message="Something went wrong. Please try again later."};var U=class extends F{constructor(e,t){super(`${j(e)} with id: \`${t}\` already exists. Please use a different id.`);}},N=class extends b{constructor(e,t){super(`${j(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},P=class extends x{constructor(e,t){super(`Failed to execute ${j(e)} with id: \`${t}\`. Please try again later.`);}};var q=class extends N{code="ProviderNotFoundError";constructor(e){super("provider",e);}},B=class extends P{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var J=class extends _{code="SignatureMismatchError";constructor(){super("Signature does not match the expected signature. Please ensure the signature provided in the `x-novu-signature` header is correct and try again.");}},Q=class extends _{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `x-novu-signature` header");}},z=class extends _{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `x-novu-signature` header");}},Z=class extends _{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`x-novu-signature\` header`);}},H=class extends _{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.apiKey`");}};var ee=class extends N{code="StepNotFoundError";constructor(e){super("step",e);}};var D=class extends N{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},te=class extends U{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var ue={name:"@novu/framework",version:"0.24.3-alpha.5",description:"The Code-First Notifications Workflow SDK.",main:"./dist/index.js",types:"./dist/index.d.ts",publishConfig:{registry:"https://registry.npmjs.org",access:"public"},private:!1,repository:{type:"git",url:"git+https://github.com/novuhq/novu.git"},files:["dist","README.md"],scripts:{preinstall:"npx only-allow pnpm",test:"vitest","test:watch":"vitest --watch",lint:"eslint src --ext .ts","lint:fix":"eslint src --ext .ts --fix",format:"prettier --check --ignore-path .gitignore .","format:fix":"prettier --write --ignore-path .gitignore .",build:"tsup","build:watch":"tsup --watch","$comment:bump:prerelease":"This is a workaround to support `npm version prerelease` with lerna","bump:prerelease":"npm version prerelease --preid=alpha & PID=$!; (sleep 1 && kill -9 $PID) & wait $PID","release:alpha":"pnpm bump:prerelease || pnpm build && npm publish --dry-run"},keywords:["novu","code-first","workflows","durable","sdk","notifications","email","sms","push","webhooks","next","nuxt","h3","express"],author:"Novu",license:"MIT",exports:{".":{require:"./dist/index.js",import:"./dist/index.js",types:"./dist/index.d.ts"},"./express":{require:"./dist/express.js",import:"./dist/express.js",types:"./dist/express.d.ts"},"./next":{require:"./dist/next.js",import:"./dist/next.js",types:"./dist/next.d.ts"},"./nuxt":{require:"./dist/nuxt.js",import:"./dist/nuxt.js",types:"./dist/nuxt.d.ts"},"./h3":{require:"./dist/h3.js",import:"./dist/h3.js",types:"./dist/h3.d.ts"},"./sveltekit":{require:"./dist/sveltekit.js",import:"./dist/sveltekit.js",types:"./dist/sveltekit.d.ts"},"./remix":{require:"./dist/remix.js",import:"./dist/remix.js",types:"./dist/remix.d.ts"}},devDependencies:{"@sveltejs/kit":"^2.5.10","@types/express":"^4.17.13","@types/json-schema":"^7.0.15","@types/node":"^20.11.20","@vercel/node":"^2.15.9",express:"^4.18.2",h3:"^1.11.1",next:"^13.5.4",prettier:"^3.2.5","ts-node":"^10.9.2",tsup:"^8.0.2",typescript:"^5.3.3",vitest:"^1.2.1"},dependencies:{ajv:"^8.12.0","ajv-formats":"^2.1.1","better-ajv-errors":"^1.2.0",chalk:"^4.1.2","cross-fetch":"^4.0.0","json-schema-faker":"^0.5.6","json-schema-to-ts":"^3.0.0",liquidjs:"^10.13.1",ora:"^5.4.1"}};var ne=ue.version;jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});var se=class{discoveredWorkflows=[];ajv;templateEngine=new liquidjs.Liquid;apiUrl;apiKey;version=ne;strictAuthentication;static NOVU_SIGNATURE_HEADER="x-novu-signature";constructor(e){let t=this.buildOptions(e);this.apiKey=t.apiKey,this.apiUrl=t.apiUrl,this.strictAuthentication=t.strictAuthentication;let r=new fe__default.default({useDefaults:!0});we__default.default(r),this.ajv=r;}buildOptions(e){let t={apiKey:void 0,apiUrl:ae,strictAuthentication:!0};return e?.apiKey!==void 0?t.apiKey=e.apiKey:process.env.NOVU_API_KEY!==void 0&&(t.apiKey=process.env.NOVU_API_KEY),e?.apiUrl!==void 0?t.apiUrl=e.apiUrl:process.env.NOVU_API_URL!==void 0&&(t.apiUrl=process.env.NOVU_API_URL),e?.strictAuthentication!==void 0?t.strictAuthentication=e.strictAuthentication:process.env.NOVU_STRICT_AUTHENTICATION!==void 0&&(t.strictAuthentication=process.env.NOVU_STRICT_AUTHENTICATION==="true"),t}addWorkflows(e){for(let t of e){if(this.discoveredWorkflows.some(r=>r.workflowId===t.workflowId))throw new te(t.workflowId);this.discoveredWorkflows.push(t);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((r,s)=>r+s.steps.length,0);return {status:"ok",version:ne,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(r=>r.workflowId===e);if(t)return t;throw new D(e)}getStep(e,t){let s=this.getWorkflow(e).steps.find(i=>i.stepId===t);if(s)return s;throw new ee(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}getHeaders(e){let t={"content-type":"application/json",authorization:`ApiKey ${this.apiKey}`};return e&&(t["x-novu-anonymous"]=e),t}async diff(e,t){let r=this.discover()?.workflows||[];return (await fetch(this.apiUrl+"/v1/bridge/diff",{method:"POST",headers:this.getHeaders(t),body:JSON.stringify({workflows:r,bridgeUrl:e})})).json()}async sync(e,t,r){let{workflows:s}=this.discover();return (await fetch(`${this.apiUrl}/v1/bridge/sync?source=${r||"sdk"}`,{method:"POST",headers:this.getHeaders(t),body:JSON.stringify({workflows:s,bridgeUrl:e})})).json()}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(e)}validate(e,t,r,s,i,c,a,l){if(!t(e)){let n=_e__default.default(r,e,t.errors||[]);switch(console.error(`
|
|
21
|
-
${
|
|
22
|
-
${u.bold(u.underline(s))} '${e.workflowId}'`);let
|
|
23
|
-
${u.bold(
|
|
24
|
-
`);}async executeProviders(e,t){return t.providers.reduce(async(r,s)=>{let
|
|
25
|
-
${
|
|
20
|
+
var Oe=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var U=(t=>(t.EXECUTE="execute",t.PREVIEW="preview",t))(U||{}),D=(r=>(r.DISCOVER="discover",r.HEALTH_CHECK="health-check",r.CODE="code",r))(D||{});var ne="https://api.novu.co";var _=(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_DATA_INVALID_ERROR="ExecutionEventDataInvalidError",d.EXECUTION_EVENT_INPUT_INVALID_ERROR="ExecutionEventInputInvalidError",d.EXECUTION_STATE_INPUT_INVALID_ERROR="ExecutionStateInputInvalidError",d.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",d.INVALID_ACTION_ERROR="InvalidActionError",d.MISSING_API_KEY_ERROR="MissingApiKeyError",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.PLATFORM_ERROR="PlatformError",d.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",d))(_||{});var k=(r=>(r.POST="POST",r.GET="GET",r.OPTIONS="OPTIONS",r))(k||{});var f=class extends Error{data},L=class extends f{statusCode=404},T=class extends f{statusCode=400},w=class extends f{statusCode=401},x=class extends f{statusCode=500},b=class extends f{statusCode=409};var F=class extends T{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};}},W=class extends T{code="ExecutionEventDataInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`data\`. Please provide the correct event data.`),this.data=t;}},m=class extends T{code="ExecutionEventInputInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`inputs\`. Please provide the correct event inputs.`),this.data=t;}},$=class extends T{code="ExecutionStateInputInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid input. Please provide the correct step input.`),this.data=r;}},M=class extends T{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;}},V=class extends T{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;}},G=class extends T{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 ce=()=>typeof Response<"u"?Response:Oe("cross-fetch").Response;var u={info:o=>v__default.default.blue(o),warning:o=>v__default.default.yellow(o),error:o=>v__default.default.red(o),success:o=>v__default.default.green(o),underline:o=>v__default.default.underline(o),bold:o=>v__default.default.bold(o)},R={SUCCESS:u.success("\u2714"),ERROR:u.error("\u2717"),WARNING:u.warning("\u26A0"),INFO:u.info("\u2139"),ARROW:u.bold("\u2192"),MOCK:u.info("\u25CB"),HYDRATED:u.bold(u.info("\u2192")),STEP:u.info("\u03C3"),ACTION:u.info("\u03B1"),DURATION:u.info("\u0394"),PROVIDER:u.info("\u2699"),OUTPUT:u.info("\u21E2"),INPUT:u.info("\u21E0"),WORKFLOW:u.info("\u03C9"),STATE:u.info("\u03C3"),EXECUTE:u.info("\u03B5"),PREVIEW:u.info("\u03C1")};var oe=o=>Object.values(o).map(e=>`\`${e}\``).join(", "),K=o=>o.replaceAll(/(\w)(\w*)/g,(e,t,r)=>t.toUpperCase()+r.toLowerCase()).replaceAll(/[\s-]+/g,"");var j=class extends f{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${oe(k)}`},S=class extends T{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${oe(t)}`);}};var X=class extends x{code="PlatformError";message="Something went wrong. Please try again later."};var y=class extends b{constructor(e,t){super(`${K(e)} with id: \`${t}\` already exists. Please use a different id.`);}},A=class extends L{constructor(e,t){super(`${K(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},P=class extends x{constructor(e,t){super(`Failed to execute ${K(e)} with id: \`${t}\`. Please try again later.`);}};var Y=class extends A{code="ProviderNotFoundError";constructor(e){super("provider",e);}},q=class extends P{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var B=class extends w{code="SignatureMismatchError";constructor(){super("Signature does not match the expected signature. Please ensure the signature provided in the `x-novu-signature` header is correct and try again.");}},J=class extends w{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `x-novu-signature` header");}},Q=class extends w{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `x-novu-signature` header");}},z=class extends w{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`x-novu-signature\` header`);}},Z=class extends w{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.apiKey`");}};var H=class extends A{code="StepNotFoundError";constructor(e){super("step",e);}};var C=class extends A{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},ee=class extends y{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var le={name:"@novu/framework",version:"0.24.3-alpha.6",description:"The Code-First Notifications Workflow SDK.",main:"./dist/index.js",types:"./dist/index.d.ts",publishConfig:{registry:"https://registry.npmjs.org",access:"public"},private:!1,repository:{type:"git",url:"git+https://github.com/novuhq/novu.git"},files:["dist","README.md"],scripts:{preinstall:"npx only-allow pnpm",test:"vitest","test:watch":"vitest --watch",lint:"eslint src --ext .ts","lint:fix":"eslint src --ext .ts --fix",format:"prettier --check --ignore-path .gitignore .","format:fix":"prettier --write --ignore-path .gitignore .",build:"tsup","build:watch":"tsup --watch","$comment:bump:prerelease":"This is a workaround to support `npm version prerelease` with lerna","bump:prerelease":"npm version prerelease --preid=alpha & PID=$!; (sleep 1 && kill -9 $PID) & wait $PID","release:alpha":"pnpm bump:prerelease || pnpm build && npm publish"},keywords:["novu","code-first","workflows","durable","sdk","notifications","email","sms","push","webhooks","next","nuxt","h3","express"],author:"Novu",license:"MIT",exports:{".":{require:"./dist/index.js",import:"./dist/index.js",types:"./dist/index.d.ts"},"./express":{require:"./dist/express.js",import:"./dist/express.js",types:"./dist/express.d.ts"},"./next":{require:"./dist/next.js",import:"./dist/next.js",types:"./dist/next.d.ts"},"./nuxt":{require:"./dist/nuxt.js",import:"./dist/nuxt.js",types:"./dist/nuxt.d.ts"},"./h3":{require:"./dist/h3.js",import:"./dist/h3.js",types:"./dist/h3.d.ts"},"./sveltekit":{require:"./dist/sveltekit.js",import:"./dist/sveltekit.js",types:"./dist/sveltekit.d.ts"},"./remix":{require:"./dist/remix.js",import:"./dist/remix.js",types:"./dist/remix.d.ts"}},devDependencies:{"@sveltejs/kit":"^2.5.10","@types/express":"^4.17.13","@types/json-schema":"^7.0.15","@types/node":"^20.11.20","@vercel/node":"^2.15.9",express:"^4.18.2",h3:"^1.11.1",next:"^13.5.4",prettier:"^3.2.5","ts-node":"^10.9.2",tsup:"^8.0.2",typescript:"^5.3.3",vitest:"^1.2.1"},dependencies:{ajv:"^8.12.0","ajv-formats":"^2.1.1","better-ajv-errors":"^1.2.0",chalk:"^4.1.2","cross-fetch":"^4.0.0","json-schema-faker":"^0.5.6","json-schema-to-ts":"^3.0.0",liquidjs:"^10.13.1",ora:"^5.4.1"}};var ie=le.version;jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});var re=class{discoveredWorkflows=[];ajv;templateEngine=new liquidjs.Liquid;apiUrl;apiKey;version=ie;strictAuthentication;static NOVU_SIGNATURE_HEADER="x-novu-signature";constructor(e){let t=this.buildOptions(e);this.apiKey=t.apiKey,this.apiUrl=t.apiUrl,this.strictAuthentication=t.strictAuthentication;let r=new Te__default.default({useDefaults:!0});_e__default.default(r),this.ajv=r;}buildOptions(e){let t={apiKey:void 0,apiUrl:ne,strictAuthentication:!0};return e?.apiKey!==void 0?t.apiKey=e.apiKey:process.env.NOVU_API_KEY!==void 0&&(t.apiKey=process.env.NOVU_API_KEY),e?.apiUrl!==void 0?t.apiUrl=e.apiUrl:process.env.NOVU_API_URL!==void 0&&(t.apiUrl=process.env.NOVU_API_URL),e?.strictAuthentication!==void 0?t.strictAuthentication=e.strictAuthentication:process.env.NOVU_STRICT_AUTHENTICATION!==void 0&&(t.strictAuthentication=process.env.NOVU_STRICT_AUTHENTICATION==="true"),t}addWorkflows(e){for(let t of e){if(this.discoveredWorkflows.some(r=>r.workflowId===t.workflowId))throw new ee(t.workflowId);this.discoveredWorkflows.push(t);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((r,s)=>r+s.steps.length,0);return {status:"ok",version:ie,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(r=>r.workflowId===e);if(t)return t;throw new C(e)}getStep(e,t){let s=this.getWorkflow(e).steps.find(n=>n.stepId===t);if(s)return s;throw new H(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}getHeaders(e){let t={"content-type":"application/json",authorization:`ApiKey ${this.apiKey}`};return e&&(t["x-novu-anonymous"]=e),t}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(e)}validate(e,t,r,s,n,a,c,p){if(!t(e)){let i=fe__default.default(r,e,t.errors||[]);switch(console.error(`
|
|
21
|
+
${i}`),s){case"event":this.validateEvent(n,a,t);case"step":this.validateStep(c,n,a,t);case"provider":this.validateProvider(c,p,n,a,t);}}}validateProvider(e,t,r,s,n){if(!e)throw new Error("stepId is required");if(!t)throw new Error("providerId is required");switch(r){case"output":throw new G(s,e,t,n.errors);default:throw new Error(`Invalid payload type: '${r}'`)}}validateStep(e,t,r,s){if(!e)throw new Error("stepId is required");switch(t){case"output":throw new M(r,e,s.errors);case"result":throw new V(r,e,s.errors);case"input":throw new $(r,e,s.errors);default:throw new Error(`Invalid payload type: '${t}'`)}}validateEvent(e,t,r){switch(e){case"input":throw new m(t,r.errors);case"data":throw new W(t,r.errors);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(r,s,n)=>{let a=this.getStep(e.workflowId,r),c=Ae(e),p=this.createStepInputs(a,c),E=e.action==="preview";if(!E&&await this.shouldSkip(n?.skip,p))return t({options:{skip:!0}}),{};let i=this.previewStep.bind(this),l=this.executeStep.bind(this),N=await(E?i:l)(e,{...a,providers:a.providers.map(h=>{let I=n?.providers?.[h.type];if(!I)throw new Y(h.type);return {...h,resolve:I}}),resolve:s});return r===e.stepId&&t(N),N.outputs}}async shouldSkip(e,t){return e?e(t):!1}async executeWorkflow(e){let s=`${{execute:"Executing",preview:"Previewing"}[e.action]} workflowId:`;console.log(`
|
|
22
|
+
${u.bold(u.underline(s))} '${e.workflowId}'`);let n=this.getWorkflow(e.workflowId),a=process.hrtime(),c={outputs:{},providers:{},options:{}},p,E=new Promise(g=>{p=g;}),i=g=>{p(),c=g;},l;try{if(e.action==="execute"&&!e.data)throw new m(e.workflowId,{message:"Event `data` is required"});let g=this.createExecutionInputs(e,n);await Promise.race([E,n.execute({payload:g,environment:{},input:{},subscriber:e.subscriber,step:{email:this.executeStepFactory(e,i),sms:this.executeStepFactory(e,i),inApp:this.executeStepFactory(e,i),digest:this.executeStepFactory(e,i),delay:this.executeStepFactory(e,i),push:this.executeStepFactory(e,i),chat:this.executeStepFactory(e,i),custom:this.executeStepFactory(e,i)}})]);}catch(g){l=g;}let O=process.hrtime(a),N=O[0],h=O[1],I=N*1e3+h/1e6,Re=l?R.ERROR:R.SUCCESS,Ee=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action";if(console.log(`${Re} ${Ee} workflowId: \`${e.workflowId}\``),this.prettyPrintExecute(e,I,l),l)throw l;return {outputs:c.outputs,providers:c.providers,options:c.options,metadata:{status:"success",error:!1,duration:I}}}createExecutionInputs(e,t){let r=e.data;return this.validate(e.data,t.data.validate,t.data.schema,"event","input",e.workflowId),r}prettyPrintExecute(e,t,r){let s=r?R.ERROR:R.SUCCESS,n=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action",a=r?"Failed to execute":n,c=r?u.error:u.success,p=`${s} ${a} workflowId: '${e.workflowId}`;console.log(`
|
|
23
|
+
${u.bold(c(p))}'`),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'
|
|
24
|
+
`);}async executeProviders(e,t){return t.providers.reduce(async(r,s)=>{let n=await r,a=this.previewProvider.bind(this),c=this.executeProvider.bind(this),E=await(e.action==="preview"?a:c)(e,t,s);return {...n,[s.type]:E}},Promise.resolve({}))}previewProvider(e,t,r){return console.log(` ${R.MOCK} Mocked provider: \`${r.type}\``),this.mock(r.outputs.schema)}async executeProvider(e,t,r){let s=te__default.default({indent:2}).start(`Executing provider: \`${r.type}\``);try{if(e.stepId===t.stepId){let n=this.createStepInputs(t,e),a=await r.resolve({inputs:n});return this.validate(a,r.outputs.validate,r.outputs.schema,"step","output",e.workflowId,t.stepId,r.type),s.succeed(`Executed provider: \`${r.type}\``),a}else s.stopAndPersist({symbol:R.HYDRATED,text:`Hydrated provider: \`${r.type}\``});}catch(n){throw s.stopAndPersist({symbol:R.ERROR,text:`Failed to execute provider: \`${r.type}\``}),new q(`Failed to execute provider: '${r.type}'.
|
|
25
|
+
${n.message}`)}}async executeStep(e,t){if(e.stepId===t.stepId){let r=te__default.default({indent:1}).start(`Executing stepId: \`${t.stepId}\``);try{let s=this.createStepInputs(t,e),n=await this.compileInputs(s,e),a=await t.resolve(n);this.validate(a,t.outputs.validate,t.outputs.schema,"step","output",e.workflowId,t.stepId);let c=await this.executeProviders(e,t);return r.succeed(`Executed stepId: \`${t.stepId}\``),{outputs:a,providers:c}}catch(s){throw r.stopAndPersist({prefixText:"",symbol:R.ERROR,text:`Failed to execute stepId: \`${t.stepId}\``}),s}}else {let r=te__default.default({indent:1}).start(`Hydrating stepId: \`${t.stepId}\``);try{let s=e.state.find(n=>n.stepId===t.stepId);if(s)return this.validate(s.outputs,t.results.validate,t.results.schema,"step","result",e.workflowId,t.stepId),r.stopAndPersist({symbol:R.HYDRATED,text:`Hydrated stepId: \`${t.stepId}\``}),{outputs:s.outputs,providers:await this.executeProviders(e,t)};throw new F(e.workflowId,t.stepId)}catch(s){throw r.stopAndPersist({symbol:R.ERROR,text:`Failed to hydrate stepId: \`${t.stepId}\``}),s}}}async compileInputs(e,t){let r=this.templateEngine.parse(JSON.stringify(e)),s=await this.templateEngine.render(r,{...t.data,subscriber:t.subscriber});return JSON.parse(s)}createStepInputs(e,t){let r=t.inputs;return this.validate(r,e.inputs.validate,e.inputs.schema,"step","input",t.workflowId,e.stepId),r}async previewStep(e,t){let r=te__default.default({indent:1}).start(`Previewing stepId: \`${t.stepId}\``);try{if(e.stepId===t.stepId){let s=this.createStepInputs(t,e),n=await this.compileInputs(s,e),a=await t.resolve(n);return this.validate(a,t.outputs.validate,t.outputs.schema,"step","output",e.workflowId,t.stepId),r.stopAndPersist({symbol:R.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:a,providers:await this.executeProviders(e,t)}}else {let s=this.mock(t.results.schema);return r.stopAndPersist({symbol:R.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:s,providers:await this.executeProviders(e,t)}}}catch(s){throw r.stopAndPersist({symbol:R.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 C(e);return r}};function Ae(o){return JSON.parse(JSON.stringify(o))}var se=class{frameworkName;handler;client;hmacEnabled;constructor(e){this.handler=e.handler,this.client=e.client?e.client:new re,this.client.addWorkflows(e.workflows),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","x-novu-framework":this.frameworkName,"user-agent":e,"x-novu-sdk":e}}createResponse(e,t,r={}){return {status:e,body:JSON.stringify(t),headers:{...this.getStaticHeaders(),...r}}}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")||"",n=t.searchParams.get("workflowId")||"",a=t.searchParams.get("stepId")||"",c=await e.headers("x-novu-signature")||"",p=await e.headers("x-novu-anonymous")||"",E=t.searchParams.get("source")||"",i={};try{r==="POST"&&(i=await e.body());}catch{}try{s!=="health-check"&&this.validateHmac(i,c);let l=this.getPostActionMap(i,n,a,s,p,E),O=this.getGetActionMap(n,a);if(r==="POST")return await this.handlePostAction(s,l);if(r==="GET")return await this.handleGetAction(s,O);if(r==="OPTIONS")return this.createResponse(200,{},{...this.getStaticHeaders()})}catch(l){return this.handleError(l)}return this.createError(new j(r))}getPostActionMap(e,t,r,s,n,a){return {execute:async()=>{let c=await this.client.executeWorkflow({...e,workflowId:t,stepId:r,action:s});return this.createResponse(200,c,{"x-novu-execution-duration":c.metadata.duration.toString()})},preview:async()=>{let c=await this.client.executeWorkflow({...e,workflowId:t,stepId:r,action:s});return this.createResponse(200,c,{"x-novu-execution-duration":c.metadata.duration.toString()})}}}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(U).includes(e)){let r=t[e];return r()}else throw new S(e,U)}async handleGetAction(e,t){if(Object.values(D).includes(e)){let r=t[e];return r()}else throw new S(e,D)}isClientError(e){return Object.values(_).includes(e.code)}handleError(e){return this.isClientError(e)?(e.statusCode===500&&console.error(e),this.createError(e)):(console.error(e),this.createError(new X))}validateHmac(e,t){if(!this.hmacEnabled)return;if(!t)throw new J;if(!this.client.apiKey)throw new Z;let[r,s]=t.split(",");if(!r||!s)throw new Q;let[n,a]=r.split("="),[c,p]=s.split("=");if(Number(n)<Date.now()-1500)throw new z;if(!(this.hashHmac(this.client.apiKey,`${a}.${JSON.stringify(e)}`)===p))throw new B}hashHmac(e,t){return crypto.createHmac("sha256",e).update(t).digest("hex")}};var xe="next",Or=o=>{let t=new se({frameworkName:xe,...o,handler:(n,a,c)=>{let p=a,E=i=>{let l=typeof p.headers.get=="function"?p.headers.get(i):p.headers[i];return Array.isArray(l)?l[0]:l};return {body:()=>typeof p.json=="function"?p.json():p.body,headers:E,method:()=>n||p.method||"",queryString:(i,l)=>{let O=p.query?.[i]||l.searchParams.get(i);return Array.isArray(O)?O[0]:O},url:()=>{let i;try{i=new URL(p.url);}catch{}if(i){let h=E("host");if(h){let I=new URL(h.includes("://")?h:`${i.protocol}//${h}`);i.protocol=I.protocol,i.host=I.host,i.port=I.port,i.username=I.username,i.password=I.password;}return i}let l="https",O=E("host")||"";try{process.env.NODE_ENV==="development"&&(l="http");}catch{}return new URL(p.url,`${l}://${O}`)},transformResponse:({body:i,headers:l,status:O})=>{if(typeof c?.setHeader=="function"&&Object.entries(l).forEach(([h,I])=>{c.setHeader(h,I);}),typeof c?.status=="function"&&typeof c?.send=="function"){c.status(O).send(i);return}let N=ce();return new N(i,{status:O,headers:l})}}}}).createHandler(),r=t.bind(null,void 0);return Object.defineProperties(r,{GET:{value:t.bind(null,"GET")},POST:{value:t.bind(null,"POST")},PUT:{value:t.bind(null,"PUT")},OPTIONS:{value:t.bind(null,"OPTIONS")}})};
|
|
26
26
|
|
|
27
|
-
exports.frameworkName =
|
|
27
|
+
exports.frameworkName = xe;
|
|
28
28
|
exports.serve = Or;
|
package/dist/nuxt.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as h3 from 'h3';
|
|
2
2
|
import { H3Event } from 'h3';
|
|
3
|
-
import { i as SupportedFrameworkName, S as ServeHandlerOptions } from './handler-
|
|
3
|
+
import { i as SupportedFrameworkName, S as ServeHandlerOptions } from './handler-jSdMUIfN.js';
|
|
4
4
|
import 'ajv';
|
|
5
5
|
import 'json-schema-to-ts';
|
|
6
6
|
|