@novu/framework 0.24.3-alpha.10 → 0.24.3-alpha.11
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.js +1 -1
- package/dist/h3.js +1 -1
- package/dist/index.js +1 -1
- package/dist/next.js +2 -2
- package/dist/nuxt.js +1 -1
- package/dist/remix.js +1 -1
- package/dist/sveltekit.js +1 -1
- package/package.json +1 -1
package/dist/express.js
CHANGED
|
@@ -19,7 +19,7 @@ var _=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var Rt=_(F=>{Objec
|
|
|
19
19
|
]))`;continue}else if(s[c]==="$"){n+=`($|(?=[\r
|
|
20
20
|
]))`;continue}}if(t.s&&s[c]==="."){n+=i?`${s[c]}\r
|
|
21
21
|
`:`[${s[c]}\r
|
|
22
|
-
]`;continue}n+=s[c],s[c]==="\\"?a=!0:i&&s[c]==="]"?i=!1:!i&&s[c]==="["&&(i=!0);}try{let c=new RegExp(n);}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return n};});var Yt=_(Gt=>{Object.defineProperty(Gt,"__esModule",{value:!0});Gt.parseRecordDef=void 0;var Lr=Dt(),js=P(),Ka=Bt();function za(r,e){if(e.target==="openApi3"&&r.keyType?._def.typeName===Lr.ZodFirstPartyTypeKind.ZodEnum)return {type:"object",required:r.keyType._def.values,properties:r.keyType._def.values.reduce((s,n)=>({...s,[n]:(0, js.parseDef)(r.valueType._def,{...e,currentPath:[...e.currentPath,"properties",n]})??{}}),{}),additionalProperties:!1};let t={type:"object",additionalProperties:(0, js.parseDef)(r.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return t;if(r.keyType?._def.typeName===Lr.ZodFirstPartyTypeKind.ZodString&&r.keyType._def.checks?.length){let s=Object.entries((0, Ka.parseStringDef)(r.keyType._def,e)).reduce((n,[a,i])=>a==="type"?n:{...n,[a]:i},{});return {...t,propertyNames:s}}else if(r.keyType?._def.typeName===Lr.ZodFirstPartyTypeKind.ZodEnum)return {...t,propertyNames:{enum:r.keyType._def.values}};return t}Gt.parseRecordDef=za;});var $r=_(Jt=>{Object.defineProperty(Jt,"__esModule",{value:!0});Jt.parseMapDef=void 0;var Ms=P(),Ba=Yt();function Ga(r,e){if(e.mapStrategy==="record")return (0, Ba.parseRecordDef)(r,e);let t=(0, Ms.parseDef)(r.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},s=(0, Ms.parseDef)(r.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return {type:"array",maxItems:125,items:{type:"array",items:[t,s],minItems:2,maxItems:2}}}Jt.parseMapDef=Ga;});var qr=_(Xt=>{Object.defineProperty(Xt,"__esModule",{value:!0});Xt.parseNativeEnumDef=void 0;function Ya(r){let e=r.values,s=Object.keys(r.values).filter(a=>typeof e[e[a]]!="number").map(a=>e[a]),n=Array.from(new Set(s.map(a=>typeof a)));return {type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:s}}Xt.parseNativeEnumDef=Ya;});var Fr=_(Qt=>{Object.defineProperty(Qt,"__esModule",{value:!0});Qt.parseNeverDef=void 0;function Ja(){return {not:{}}}Qt.parseNeverDef=Ja;});var Wr=_(Ht=>{Object.defineProperty(Ht,"__esModule",{value:!0});Ht.parseNullDef=void 0;function Xa(r){return r.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}Ht.parseNullDef=Xa;});var er=_(ie=>{Object.defineProperty(ie,"__esModule",{value:!0});ie.parseUnionDef=ie.primitiveMappings=void 0;var Qa=P();ie.primitiveMappings={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Ha(r,e){if(e.target==="openApi3")return Us(r,e);let t=r.options instanceof Map?Array.from(r.options.values()):r.options;if(t.every(s=>s._def.typeName in ie.primitiveMappings&&(!s._def.checks||!s._def.checks.length))){let s=t.reduce((n,a)=>{let i=ie.primitiveMappings[a._def.typeName];return i&&!n.includes(i)?[...n,i]:n},[]);return {type:s.length>1?s:s[0]}}else if(t.every(s=>s._def.typeName==="ZodLiteral"&&!s.description)){let s=t.reduce((n,a)=>{let i=typeof a._def.value;switch(i){case"string":case"number":case"boolean":return [...n,i];case"bigint":return [...n,"integer"];case"object":if(a._def.value===null)return [...n,"null"];case"symbol":case"undefined":case"function":default:return n}},[]);if(s.length===t.length){let n=s.filter((a,i,d)=>d.indexOf(a)===i);return {type:n.length>1?n:n[0],enum:t.reduce((a,i)=>a.includes(i._def.value)?a:[...a,i._def.value],[])}}}else if(t.every(s=>s._def.typeName==="ZodEnum"))return {type:"string",enum:t.reduce((s,n)=>[...s,...n._def.values.filter(a=>!s.includes(a))],[])};return Us(r,e)}ie.parseUnionDef=Ha;var Us=(r,e)=>{let t=(r.options instanceof Map?Array.from(r.options.values()):r.options).map((s,n)=>(0, Qa.parseDef)(s._def,{...e,currentPath:[...e.currentPath,"anyOf",`${n}`]})).filter(s=>!!s&&(!e.strictUnions||typeof s=="object"&&Object.keys(s).length>0));return t.length?{anyOf:t}:void 0};});var Kr=_(tr=>{Object.defineProperty(tr,"__esModule",{value:!0});tr.parseNullableDef=void 0;var Vs=P(),Ls=er();function ei(r,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(r.innerType._def.typeName)&&(!r.innerType._def.checks||!r.innerType._def.checks.length))return e.target==="openApi3"?{type:Ls.primitiveMappings[r.innerType._def.typeName],nullable:!0}:{type:[Ls.primitiveMappings[r.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let s=(0, Vs.parseDef)(r.innerType._def,{...e,currentPath:[...e.currentPath]});return s&&"$ref"in s?{allOf:[s],nullable:!0}:s&&{...s,nullable:!0}}let t=(0, Vs.parseDef)(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}tr.parseNullableDef=ei;});var zr=_(rr=>{Object.defineProperty(rr,"__esModule",{value:!0});rr.parseNumberDef=void 0;var oe=te();function ti(r,e){let t={type:"number"};if(!r.checks)return t;for(let s of r.checks)switch(s.kind){case"int":t.type="integer",(0, oe.addErrorMessage)(t,"type",s.message,e);break;case"min":e.target==="jsonSchema7"?s.inclusive?(0, oe.setResponseValueAndErrors)(t,"minimum",s.value,s.message,e):(0, oe.setResponseValueAndErrors)(t,"exclusiveMinimum",s.value,s.message,e):(s.inclusive||(t.exclusiveMinimum=!0),(0, oe.setResponseValueAndErrors)(t,"minimum",s.value,s.message,e));break;case"max":e.target==="jsonSchema7"?s.inclusive?(0, oe.setResponseValueAndErrors)(t,"maximum",s.value,s.message,e):(0, oe.setResponseValueAndErrors)(t,"exclusiveMaximum",s.value,s.message,e):(s.inclusive||(t.exclusiveMaximum=!0),(0, oe.setResponseValueAndErrors)(t,"maximum",s.value,s.message,e));break;case"multipleOf":(0, oe.setResponseValueAndErrors)(t,"multipleOf",s.value,s.message,e);break}return t}rr.parseNumberDef=ti;});var Gr=_(Ve=>{Object.defineProperty(Ve,"__esModule",{value:!0});Ve.parseObjectDef=Ve.parseObjectDefX=void 0;var Qe=P();function Br(r,e){return e.removeAdditionalStrategy==="strict"?r.catchall._def.typeName==="ZodNever"?r.unknownKeys!=="strict":(0, Qe.parseDef)(r.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:r.catchall._def.typeName==="ZodNever"?r.unknownKeys==="passthrough":(0, Qe.parseDef)(r.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function ri(r,e){Object.keys(r.shape()).reduce((s,n)=>{let a=r.shape()[n],i=a.isOptional();i||(a={...a._def.innerSchema});let d=(0, Qe.parseDef)(a._def,{...e,currentPath:[...e.currentPath,"properties",n],propertyPath:[...e.currentPath,"properties",n]});return d!==void 0&&(s.properties[n]=d,i||(s.required||(s.required=[]),s.required.push(n))),s},{type:"object",properties:{},additionalProperties:Br(r,e)});let t={type:"object",...Object.entries(r.shape()).reduce((s,[n,a])=>{if(a===void 0||a._def===void 0)return s;let i=(0, Qe.parseDef)(a._def,{...e,currentPath:[...e.currentPath,"properties",n],propertyPath:[...e.currentPath,"properties",n]});return i===void 0?s:{properties:{...s.properties,[n]:i},required:a.isOptional()?s.required:[...s.required,n]}},{properties:{},required:[]}),additionalProperties:Br(r,e)};return t.required.length||delete t.required,t}Ve.parseObjectDefX=ri;function si(r,e){let t={type:"object",...Object.entries(r.shape()).reduce((s,[n,a])=>{if(a===void 0||a._def===void 0)return s;let i=(0, Qe.parseDef)(a._def,{...e,currentPath:[...e.currentPath,"properties",n],propertyPath:[...e.currentPath,"properties",n]});return i===void 0?s:{properties:{...s.properties,[n]:i},required:a.isOptional()?s.required:[...s.required,n]}},{properties:{},required:[]}),additionalProperties:Br(r,e)};return t.required.length||delete t.required,t}Ve.parseObjectDef=si;});var Yr=_(sr=>{Object.defineProperty(sr,"__esModule",{value:!0});sr.parseOptionalDef=void 0;var $s=P(),ni=(r,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return (0, $s.parseDef)(r.innerType._def,e);let t=(0, $s.parseDef)(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:{}},t]}:{}};sr.parseOptionalDef=ni;});var Jr=_(ar=>{Object.defineProperty(ar,"__esModule",{value:!0});ar.parsePipelineDef=void 0;var nr=P(),ai=(r,e)=>{if(e.pipeStrategy==="input")return (0, nr.parseDef)(r.in._def,e);if(e.pipeStrategy==="output")return (0, nr.parseDef)(r.out._def,e);let t=(0, nr.parseDef)(r.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),s=(0, nr.parseDef)(r.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return {allOf:[t,s].filter(n=>n!==void 0)}};ar.parsePipelineDef=ai;});var Xr=_(ir=>{Object.defineProperty(ir,"__esModule",{value:!0});ir.parsePromiseDef=void 0;var ii=P();function oi(r,e){return (0, ii.parseDef)(r.type._def,e)}ir.parsePromiseDef=oi;});var Qr=_(or=>{Object.defineProperty(or,"__esModule",{value:!0});or.parseSetDef=void 0;var qs=te(),di=P();function ui(r,e){let s={type:"array",uniqueItems:!0,items:(0, di.parseDef)(r.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return r.minSize&&(0, qs.setResponseValueAndErrors)(s,"minItems",r.minSize.value,r.minSize.message,e),r.maxSize&&(0, qs.setResponseValueAndErrors)(s,"maxItems",r.maxSize.value,r.maxSize.message,e),s}or.parseSetDef=ui;});var es=_(dr=>{Object.defineProperty(dr,"__esModule",{value:!0});dr.parseTupleDef=void 0;var Hr=P();function ci(r,e){return r.rest?{type:"array",minItems:r.items.length,items:r.items.map((t,s)=>(0, Hr.parseDef)(t._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((t,s)=>s===void 0?t:[...t,s],[]),additionalItems:(0, Hr.parseDef)(r.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:r.items.length,maxItems:r.items.length,items:r.items.map((t,s)=>(0, Hr.parseDef)(t._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((t,s)=>s===void 0?t:[...t,s],[])}}dr.parseTupleDef=ci;});var ts=_(ur=>{Object.defineProperty(ur,"__esModule",{value:!0});ur.parseUndefinedDef=void 0;function li(){return {not:{}}}ur.parseUndefinedDef=li;});var rs=_(cr=>{Object.defineProperty(cr,"__esModule",{value:!0});cr.parseUnknownDef=void 0;function pi(){return {}}cr.parseUnknownDef=pi;});var ss=_(lr=>{Object.defineProperty(lr,"__esModule",{value:!0});lr.parseReadonlyDef=void 0;var fi=P(),hi=(r,e)=>(0, fi.parseDef)(r.innerType._def,e);lr.parseReadonlyDef=hi;});var P=_(pr=>{Object.defineProperty(pr,"__esModule",{value:!0});pr.parseDef=void 0;var I=Dt(),mi=Pr(),yi=Ar(),_i=kr(),gi=Cr(),vi=Nr(),Ti=Dr(),Ii=Sr(),Oi=Zr(),xi=jr(),Ri=Mr(),Ei=Ur(),wi=Vr(),bi=$r(),Pi=qr(),Ai=Fr(),ki=Wr(),Ci=Kr(),Ni=zr(),Di=Gr(),Si=Yr(),Zi=Jr(),ji=Xr(),Mi=Yt(),Ui=Qr(),Vi=Bt(),Li=es(),$i=ts(),qi=er(),Fi=rs(),Wi=ss(),Ki=Rt();function Fs(r,e,t=!1){let s=e.seen.get(r);if(e.override){let i=e.override?.(r,e,s,t);if(i!==Ki.ignoreOverride)return i}if(s&&!t){let i=zi(s,e);if(i!==void 0)return i}let n={def:r,path:e.currentPath,jsonSchema:void 0};e.seen.set(r,n);let a=Gi(r,r.typeName,e);return a&&Yi(r,e,a),n.jsonSchema=a,a}pr.parseDef=Fs;var zi=(r,e)=>{switch(e.$refStrategy){case"root":return {$ref:r.path.join("/")};case"relative":return {$ref:Bi(e.currentPath,r.path)};case"none":case"seen":return r.path.length<e.currentPath.length&&r.path.every((t,s)=>e.currentPath[s]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},Bi=(r,e)=>{let t=0;for(;t<r.length&&t<e.length&&r[t]===e[t];t++);return [(r.length-t).toString(),...e.slice(t)].join("/")},Gi=(r,e,t)=>{switch(e){case I.ZodFirstPartyTypeKind.ZodString:return (0, Vi.parseStringDef)(r,t);case I.ZodFirstPartyTypeKind.ZodNumber:return (0, Ni.parseNumberDef)(r,t);case I.ZodFirstPartyTypeKind.ZodObject:return (0, Di.parseObjectDef)(r,t);case I.ZodFirstPartyTypeKind.ZodBigInt:return (0, _i.parseBigintDef)(r,t);case I.ZodFirstPartyTypeKind.ZodBoolean:return (0, gi.parseBooleanDef)();case I.ZodFirstPartyTypeKind.ZodDate:return (0, Ii.parseDateDef)(r,t);case I.ZodFirstPartyTypeKind.ZodUndefined:return (0, $i.parseUndefinedDef)();case I.ZodFirstPartyTypeKind.ZodNull:return (0, ki.parseNullDef)(t);case I.ZodFirstPartyTypeKind.ZodArray:return (0, yi.parseArrayDef)(r,t);case I.ZodFirstPartyTypeKind.ZodUnion:case I.ZodFirstPartyTypeKind.ZodDiscriminatedUnion:return (0, qi.parseUnionDef)(r,t);case I.ZodFirstPartyTypeKind.ZodIntersection:return (0, Ei.parseIntersectionDef)(r,t);case I.ZodFirstPartyTypeKind.ZodTuple:return (0, Li.parseTupleDef)(r,t);case I.ZodFirstPartyTypeKind.ZodRecord:return (0, Mi.parseRecordDef)(r,t);case I.ZodFirstPartyTypeKind.ZodLiteral:return (0, wi.parseLiteralDef)(r,t);case I.ZodFirstPartyTypeKind.ZodEnum:return (0, Ri.parseEnumDef)(r);case I.ZodFirstPartyTypeKind.ZodNativeEnum:return (0, Pi.parseNativeEnumDef)(r);case I.ZodFirstPartyTypeKind.ZodNullable:return (0, Ci.parseNullableDef)(r,t);case I.ZodFirstPartyTypeKind.ZodOptional:return (0, Si.parseOptionalDef)(r,t);case I.ZodFirstPartyTypeKind.ZodMap:return (0, bi.parseMapDef)(r,t);case I.ZodFirstPartyTypeKind.ZodSet:return (0, Ui.parseSetDef)(r,t);case I.ZodFirstPartyTypeKind.ZodLazy:return Fs(r.getter()._def,t);case I.ZodFirstPartyTypeKind.ZodPromise:return (0, ji.parsePromiseDef)(r,t);case I.ZodFirstPartyTypeKind.ZodNaN:case I.ZodFirstPartyTypeKind.ZodNever:return (0, Ai.parseNeverDef)();case I.ZodFirstPartyTypeKind.ZodEffects:return (0, xi.parseEffectsDef)(r,t);case I.ZodFirstPartyTypeKind.ZodAny:return (0, mi.parseAnyDef)();case I.ZodFirstPartyTypeKind.ZodUnknown:return (0, Fi.parseUnknownDef)();case I.ZodFirstPartyTypeKind.ZodDefault:return (0, Oi.parseDefaultDef)(r,t);case I.ZodFirstPartyTypeKind.ZodBranded:return (0, vi.parseBrandedDef)(r,t);case I.ZodFirstPartyTypeKind.ZodReadonly:return (0, Wi.parseReadonlyDef)(r,t);case I.ZodFirstPartyTypeKind.ZodCatch:return (0, Ti.parseCatchDef)(r,t);case I.ZodFirstPartyTypeKind.ZodPipeline:return (0, Zi.parsePipelineDef)(r,t);case I.ZodFirstPartyTypeKind.ZodFunction:case I.ZodFirstPartyTypeKind.ZodVoid:case I.ZodFirstPartyTypeKind.ZodSymbol:return;default:return (s=>{})()}},Yi=(r,e,t)=>(r.description&&(t.description=r.description,e.markdownDescription&&(t.markdownDescription=r.description)),t);});var ns=_(fr=>{Object.defineProperty(fr,"__esModule",{value:!0});fr.zodToJsonSchema=void 0;var Ws=P(),Ji=Tr(),Xi=(r,e)=>{let t=(0, Ji.getRefs)(e),s=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,h])=>({...c,[l]:(0, Ws.parseDef)(h._def,{...t,currentPath:[...t.basePath,t.definitionPath,l]},!0)??{}}),{}):void 0,n=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,a=(0, Ws.parseDef)(r._def,n===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,n]},!1)??{},i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(a.title=i);let d=n===void 0?s?{...a,[t.definitionPath]:s}:a:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,n].join("/"),[t.definitionPath]:{...s,[n]:a}};return t.target==="jsonSchema7"?d.$schema="http://json-schema.org/draft-07/schema#":t.target==="jsonSchema2019-09"&&(d.$schema="https://json-schema.org/draft/2019-09/schema#"),d};fr.zodToJsonSchema=Xi;});var Ks=_(T=>{var Qi=T&&T.__createBinding||(Object.create?function(r,e,t,s){s===void 0&&(s=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,s,n);}:function(r,e,t,s){s===void 0&&(s=t),r[s]=e[t];}),O=T&&T.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Qi(e,r,t);};Object.defineProperty(T,"__esModule",{value:!0});O(Rt(),T);O(Tr(),T);O(te(),T);O(P(),T);O(Pr(),T);O(Ar(),T);O(kr(),T);O(Cr(),T);O(Nr(),T);O(Dr(),T);O(Sr(),T);O(Zr(),T);O(jr(),T);O(Mr(),T);O(Ur(),T);O(Vr(),T);O($r(),T);O(qr(),T);O(Fr(),T);O(Wr(),T);O(Kr(),T);O(zr(),T);O(Gr(),T);O(Yr(),T);O(Jr(),T);O(Xr(),T);O(ss(),T);O(Yt(),T);O(Qr(),T);O(Bt(),T);O(es(),T);O(ts(),T);O(er(),T);O(rs(),T);O(ns(),T);var Hi=ns();T.default=Hi.zodToJsonSchema;});var et=(s=>(s.TRIGGER="trigger",s.EXECUTE="execute",s.PREVIEW="preview",s))(et||{}),tt=(s=>(s.DISCOVER="discover",s.HEALTH_CHECK="health-check",s.CODE="code",s))(tt||{});var V=(w=>(w.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",w.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",w.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",w.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",w.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",w.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",w.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",w.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",w.STEP_NOT_FOUND_ERROR="StepNotFoundError",w.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",w.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",w.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",w.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",w.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",w.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",w.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",w.INVALID_ACTION_ERROR="InvalidActionError",w.MISSING_API_KEY_ERROR="MissingApiKeyError",w.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",w.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",w.SIGNATURE_INVALID_ERROR="SignatureInvalidError",w.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",w.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",w.PLATFORM_ERROR="PlatformError",w.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",w))(V||{});var rt=(s=>(s.POST="POST",s.GET="GET",s.OPTIONS="OPTIONS",s))(rt||{});var B=class extends Error{data},st=class extends B{statusCode=404},Z=class extends B{statusCode=400},H=class extends B{statusCode=401},Pe=class extends B{statusCode=500},nt=class extends B{statusCode=409};var at=class extends Z{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};}},$e=class extends Z{code="ExecutionEventPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct event payload.`),this.data=t;}},it=class extends Z{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},ot=class extends Z{code="ExecutionStateControlInvalidError";constructor(e,t,s){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid \`controls\`. Please provide the correct step controls.`),this.data=s;}},dt=class extends Z{code="ExecutionStateOutputInvalidError";constructor(e,t,s){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid output. Please provide the correct step output.`),this.data=s;}},ut=class extends Z{code="ExecutionStateResultInvalidError";constructor(e,t,s){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid result. Please provide the correct step result.`),this.data=s;}},ct=class extends Z{code="ExecutionProviderOutputInvalidError";constructor(e,t,s,n){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` and provider with id: \`${s}\` has invalid output. Please provide the correct provider output.`),this.data=n;}};var b={info:r=>Ae__default.default.blue(r),warning:r=>Ae__default.default.yellow(r),error:r=>Ae__default.default.red(r),success:r=>Ae__default.default.green(r),underline:r=>Ae__default.default.underline(r),bold:r=>Ae__default.default.bold(r)},A={SUCCESS:b.success("\u2714"),ERROR:b.error("\u2717"),WARNING:b.warning("\u26A0"),INFO:b.info("\u2139"),ARROW:b.bold("\u2192"),MOCK:b.info("\u25CB"),HYDRATED:b.bold(b.info("\u2192")),STEP:b.info("\u03C3"),ACTION:b.info("\u03B1"),DURATION:b.info("\u0394"),PROVIDER:b.info("\u2699"),OUTPUT:b.info("\u21E2"),INPUT:b.info("\u21E0"),WORKFLOW:b.info("\u03C9"),STATE:b.info("\u03C3"),EXECUTE:b.info("\u03B5"),PREVIEW:b.info("\u03C1")};var vr=r=>Object.values(r).map(e=>`\`${e}\``).join(", "),lt=r=>r.replaceAll(/(\w)(\w*)/g,(e,t,s)=>t.toUpperCase()+s.toLowerCase()).replaceAll(/[\s-]+/g,"");var os=(r,e="https://api.novu.co/v1")=>({post:async(t,s)=>await fetch(e+t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${r}`},body:JSON.stringify(s)})});var pt=class extends B{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${vr(rt)}`},qe=class extends Z{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${vr(t)}`);}};var ft=class extends Pe{code="PlatformError";message="Something went wrong. Please try again later."};var Fe=class extends nt{constructor(e,t){super(`${lt(e)} with id: \`${t}\` already exists. Please use a different id.`);}},ee=class extends st{constructor(e,t){super(`${lt(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},ke=class extends Pe{constructor(e,t){super(`Failed to execute ${lt(e)} with id: \`${t}\`. Please try again later.`);}};var ht=class extends ee{code="ProviderNotFoundError";constructor(e){super("provider",e);}},mt=class extends ke{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var yt=class extends H{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.");}},_t=class extends H{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},gt=class extends H{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},vt=class extends H{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},Tt=class extends H{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.apiKey`");}};var It=class extends ee{code="StepNotFoundError";constructor(e){super("step",e);}};var We=class extends ee{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},Ot=class extends Fe{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var xt=class{ajv;compiledSchemas;constructor(){this.ajv=new en__default.default({useDefaults:!0,removeAdditional:"all"}),tn__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 s=this.compiledSchemas.get(t);return s||(s=this.ajv.compile(t),this.compiledSchemas.set(t,s)),s(e)?{success:!0,data:e}:{success:!1,errors:s.errors.map(a=>({path:a.instancePath,message:a.message}))}}transformToJsonSchema(e){return e}};var hr=class{isSchema(e){return e.safeParseAsync!==void 0}async validate(e,t){let s=t.safeParse(e);return s.success?{success:!0,data:s.data}:{success:!1,errors:s.error.errors.map(n=>({path:`/${n.path.join("/")}`,message:n.message}))}}transformToJsonSchema(e){try{return Ks().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 zs=[new hr,new xt],Bs=async(r,e)=>{for(let t of zs)if(t.isSchema(r))return t.validate(e,r);throw new Error("Invalid schema")},Gs=r=>{for(let e of zs)if(e.isSchema(r))return e.transformToJsonSchema(r);throw new Error("Invalid schema")};var Ys={name:"@novu/framework",version:"0.24.3-alpha.10",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",zod:"^3.23.0","zod-to-json-schema":"^3.23.0"},dependencies:{"@novu/shared":"0.24.2",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 He=Ys.version,mr="2024-06-26";jsonSchemaFaker.JSONSchemaFaker.random.shuffle=function(){return ["[placeholder]"]};jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});var _r=class{discoveredWorkflows=[];templateEngine=new liquidjs.Liquid;apiKey;version=He;strictAuthentication;constructor(e){let t=this.buildOptions(e);this.apiKey=t.apiKey,this.strictAuthentication=t.strictAuthentication;}buildOptions(e){let t={apiKey:void 0,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?.strictAuthentication!==void 0?t.strictAuthentication=e.strictAuthentication:process.env.NODE_ENV==="development"&&(t.strictAuthentication=!1),t}addWorkflows(e){for(let t of e){if(this.discoveredWorkflows.some(s=>s.workflowId===t.workflowId))throw new Ot(t.workflowId);this.discoveredWorkflows.push(t);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((s,n)=>s+n.steps.length,0);return {status:"ok",sdkVersion:He,frameworkVersion:mr,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(s=>s.workflowId===e);if(t)return t;throw new We(e)}getStep(e,t){let n=this.getWorkflow(e).steps.find(a=>a.stepId===t);if(n)return n;throw new It(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(Gs(e))}async validate(e,t,s,n,a,i,d){let c=await Bs(t,e);if(c.success)return c.data;switch(s){case"event":this.throwInvalidEvent(n,a,c.errors);case"step":this.throwInvalidStep(i,n,a,c.errors);case"provider":this.throwInvalidProvider(i,d,n,a,c.errors);default:throw new Error(`Invalid component: '${s}'`)}}throwInvalidProvider(e,t,s,n,a){if(!e)throw new Error("stepId is required");if(!t)throw new Error("providerId is required");switch(s){case"output":throw new ct(n,e,t,a);default:throw new Error(`Invalid payload type: '${s}'`)}}throwInvalidStep(e,t,s,n){if(!e)throw new Error("stepId is required");switch(t){case"output":throw new dt(s,e,n);case"result":throw new ut(s,e,n);case"controls":throw new ot(s,e,n);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(e,t,s){switch(e){case"controls":throw new it(t,s);case"payload":throw new $e(t,s);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(s,n,a)=>{let i=this.getStep(e.workflowId,s),d=ro(e),c=await this.createStepControls(i,d),l=e.action==="preview";if(!l&&await this.shouldSkip(a?.skip,c))return t({options:{skip:!0}}),{};let h=this.previewStep.bind(this),E=this.executeStep.bind(this),Q=await(l?h:E)(e,{...i,providers:i.providers.map(be=>{let Le=a?.providers?.[be.type];if(!Le)throw new ht(be.type);return {...be,resolve:Le}}),resolve:n});return s===e.stepId&&t(Q),Q.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
|
+
]`;continue}n+=s[c],s[c]==="\\"?a=!0:i&&s[c]==="]"?i=!1:!i&&s[c]==="["&&(i=!0);}try{let c=new RegExp(n);}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return n};});var Yt=_(Gt=>{Object.defineProperty(Gt,"__esModule",{value:!0});Gt.parseRecordDef=void 0;var Lr=Dt(),js=P(),Ka=Bt();function za(r,e){if(e.target==="openApi3"&&r.keyType?._def.typeName===Lr.ZodFirstPartyTypeKind.ZodEnum)return {type:"object",required:r.keyType._def.values,properties:r.keyType._def.values.reduce((s,n)=>({...s,[n]:(0, js.parseDef)(r.valueType._def,{...e,currentPath:[...e.currentPath,"properties",n]})??{}}),{}),additionalProperties:!1};let t={type:"object",additionalProperties:(0, js.parseDef)(r.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return t;if(r.keyType?._def.typeName===Lr.ZodFirstPartyTypeKind.ZodString&&r.keyType._def.checks?.length){let s=Object.entries((0, Ka.parseStringDef)(r.keyType._def,e)).reduce((n,[a,i])=>a==="type"?n:{...n,[a]:i},{});return {...t,propertyNames:s}}else if(r.keyType?._def.typeName===Lr.ZodFirstPartyTypeKind.ZodEnum)return {...t,propertyNames:{enum:r.keyType._def.values}};return t}Gt.parseRecordDef=za;});var $r=_(Jt=>{Object.defineProperty(Jt,"__esModule",{value:!0});Jt.parseMapDef=void 0;var Ms=P(),Ba=Yt();function Ga(r,e){if(e.mapStrategy==="record")return (0, Ba.parseRecordDef)(r,e);let t=(0, Ms.parseDef)(r.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},s=(0, Ms.parseDef)(r.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return {type:"array",maxItems:125,items:{type:"array",items:[t,s],minItems:2,maxItems:2}}}Jt.parseMapDef=Ga;});var qr=_(Xt=>{Object.defineProperty(Xt,"__esModule",{value:!0});Xt.parseNativeEnumDef=void 0;function Ya(r){let e=r.values,s=Object.keys(r.values).filter(a=>typeof e[e[a]]!="number").map(a=>e[a]),n=Array.from(new Set(s.map(a=>typeof a)));return {type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:s}}Xt.parseNativeEnumDef=Ya;});var Fr=_(Qt=>{Object.defineProperty(Qt,"__esModule",{value:!0});Qt.parseNeverDef=void 0;function Ja(){return {not:{}}}Qt.parseNeverDef=Ja;});var Wr=_(Ht=>{Object.defineProperty(Ht,"__esModule",{value:!0});Ht.parseNullDef=void 0;function Xa(r){return r.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}Ht.parseNullDef=Xa;});var er=_(ie=>{Object.defineProperty(ie,"__esModule",{value:!0});ie.parseUnionDef=ie.primitiveMappings=void 0;var Qa=P();ie.primitiveMappings={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Ha(r,e){if(e.target==="openApi3")return Us(r,e);let t=r.options instanceof Map?Array.from(r.options.values()):r.options;if(t.every(s=>s._def.typeName in ie.primitiveMappings&&(!s._def.checks||!s._def.checks.length))){let s=t.reduce((n,a)=>{let i=ie.primitiveMappings[a._def.typeName];return i&&!n.includes(i)?[...n,i]:n},[]);return {type:s.length>1?s:s[0]}}else if(t.every(s=>s._def.typeName==="ZodLiteral"&&!s.description)){let s=t.reduce((n,a)=>{let i=typeof a._def.value;switch(i){case"string":case"number":case"boolean":return [...n,i];case"bigint":return [...n,"integer"];case"object":if(a._def.value===null)return [...n,"null"];case"symbol":case"undefined":case"function":default:return n}},[]);if(s.length===t.length){let n=s.filter((a,i,d)=>d.indexOf(a)===i);return {type:n.length>1?n:n[0],enum:t.reduce((a,i)=>a.includes(i._def.value)?a:[...a,i._def.value],[])}}}else if(t.every(s=>s._def.typeName==="ZodEnum"))return {type:"string",enum:t.reduce((s,n)=>[...s,...n._def.values.filter(a=>!s.includes(a))],[])};return Us(r,e)}ie.parseUnionDef=Ha;var Us=(r,e)=>{let t=(r.options instanceof Map?Array.from(r.options.values()):r.options).map((s,n)=>(0, Qa.parseDef)(s._def,{...e,currentPath:[...e.currentPath,"anyOf",`${n}`]})).filter(s=>!!s&&(!e.strictUnions||typeof s=="object"&&Object.keys(s).length>0));return t.length?{anyOf:t}:void 0};});var Kr=_(tr=>{Object.defineProperty(tr,"__esModule",{value:!0});tr.parseNullableDef=void 0;var Vs=P(),Ls=er();function ei(r,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(r.innerType._def.typeName)&&(!r.innerType._def.checks||!r.innerType._def.checks.length))return e.target==="openApi3"?{type:Ls.primitiveMappings[r.innerType._def.typeName],nullable:!0}:{type:[Ls.primitiveMappings[r.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let s=(0, Vs.parseDef)(r.innerType._def,{...e,currentPath:[...e.currentPath]});return s&&"$ref"in s?{allOf:[s],nullable:!0}:s&&{...s,nullable:!0}}let t=(0, Vs.parseDef)(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}tr.parseNullableDef=ei;});var zr=_(rr=>{Object.defineProperty(rr,"__esModule",{value:!0});rr.parseNumberDef=void 0;var oe=te();function ti(r,e){let t={type:"number"};if(!r.checks)return t;for(let s of r.checks)switch(s.kind){case"int":t.type="integer",(0, oe.addErrorMessage)(t,"type",s.message,e);break;case"min":e.target==="jsonSchema7"?s.inclusive?(0, oe.setResponseValueAndErrors)(t,"minimum",s.value,s.message,e):(0, oe.setResponseValueAndErrors)(t,"exclusiveMinimum",s.value,s.message,e):(s.inclusive||(t.exclusiveMinimum=!0),(0, oe.setResponseValueAndErrors)(t,"minimum",s.value,s.message,e));break;case"max":e.target==="jsonSchema7"?s.inclusive?(0, oe.setResponseValueAndErrors)(t,"maximum",s.value,s.message,e):(0, oe.setResponseValueAndErrors)(t,"exclusiveMaximum",s.value,s.message,e):(s.inclusive||(t.exclusiveMaximum=!0),(0, oe.setResponseValueAndErrors)(t,"maximum",s.value,s.message,e));break;case"multipleOf":(0, oe.setResponseValueAndErrors)(t,"multipleOf",s.value,s.message,e);break}return t}rr.parseNumberDef=ti;});var Gr=_(Ve=>{Object.defineProperty(Ve,"__esModule",{value:!0});Ve.parseObjectDef=Ve.parseObjectDefX=void 0;var Qe=P();function Br(r,e){return e.removeAdditionalStrategy==="strict"?r.catchall._def.typeName==="ZodNever"?r.unknownKeys!=="strict":(0, Qe.parseDef)(r.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:r.catchall._def.typeName==="ZodNever"?r.unknownKeys==="passthrough":(0, Qe.parseDef)(r.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function ri(r,e){Object.keys(r.shape()).reduce((s,n)=>{let a=r.shape()[n],i=a.isOptional();i||(a={...a._def.innerSchema});let d=(0, Qe.parseDef)(a._def,{...e,currentPath:[...e.currentPath,"properties",n],propertyPath:[...e.currentPath,"properties",n]});return d!==void 0&&(s.properties[n]=d,i||(s.required||(s.required=[]),s.required.push(n))),s},{type:"object",properties:{},additionalProperties:Br(r,e)});let t={type:"object",...Object.entries(r.shape()).reduce((s,[n,a])=>{if(a===void 0||a._def===void 0)return s;let i=(0, Qe.parseDef)(a._def,{...e,currentPath:[...e.currentPath,"properties",n],propertyPath:[...e.currentPath,"properties",n]});return i===void 0?s:{properties:{...s.properties,[n]:i},required:a.isOptional()?s.required:[...s.required,n]}},{properties:{},required:[]}),additionalProperties:Br(r,e)};return t.required.length||delete t.required,t}Ve.parseObjectDefX=ri;function si(r,e){let t={type:"object",...Object.entries(r.shape()).reduce((s,[n,a])=>{if(a===void 0||a._def===void 0)return s;let i=(0, Qe.parseDef)(a._def,{...e,currentPath:[...e.currentPath,"properties",n],propertyPath:[...e.currentPath,"properties",n]});return i===void 0?s:{properties:{...s.properties,[n]:i},required:a.isOptional()?s.required:[...s.required,n]}},{properties:{},required:[]}),additionalProperties:Br(r,e)};return t.required.length||delete t.required,t}Ve.parseObjectDef=si;});var Yr=_(sr=>{Object.defineProperty(sr,"__esModule",{value:!0});sr.parseOptionalDef=void 0;var $s=P(),ni=(r,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return (0, $s.parseDef)(r.innerType._def,e);let t=(0, $s.parseDef)(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:{}},t]}:{}};sr.parseOptionalDef=ni;});var Jr=_(ar=>{Object.defineProperty(ar,"__esModule",{value:!0});ar.parsePipelineDef=void 0;var nr=P(),ai=(r,e)=>{if(e.pipeStrategy==="input")return (0, nr.parseDef)(r.in._def,e);if(e.pipeStrategy==="output")return (0, nr.parseDef)(r.out._def,e);let t=(0, nr.parseDef)(r.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),s=(0, nr.parseDef)(r.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return {allOf:[t,s].filter(n=>n!==void 0)}};ar.parsePipelineDef=ai;});var Xr=_(ir=>{Object.defineProperty(ir,"__esModule",{value:!0});ir.parsePromiseDef=void 0;var ii=P();function oi(r,e){return (0, ii.parseDef)(r.type._def,e)}ir.parsePromiseDef=oi;});var Qr=_(or=>{Object.defineProperty(or,"__esModule",{value:!0});or.parseSetDef=void 0;var qs=te(),di=P();function ui(r,e){let s={type:"array",uniqueItems:!0,items:(0, di.parseDef)(r.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return r.minSize&&(0, qs.setResponseValueAndErrors)(s,"minItems",r.minSize.value,r.minSize.message,e),r.maxSize&&(0, qs.setResponseValueAndErrors)(s,"maxItems",r.maxSize.value,r.maxSize.message,e),s}or.parseSetDef=ui;});var es=_(dr=>{Object.defineProperty(dr,"__esModule",{value:!0});dr.parseTupleDef=void 0;var Hr=P();function ci(r,e){return r.rest?{type:"array",minItems:r.items.length,items:r.items.map((t,s)=>(0, Hr.parseDef)(t._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((t,s)=>s===void 0?t:[...t,s],[]),additionalItems:(0, Hr.parseDef)(r.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:r.items.length,maxItems:r.items.length,items:r.items.map((t,s)=>(0, Hr.parseDef)(t._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((t,s)=>s===void 0?t:[...t,s],[])}}dr.parseTupleDef=ci;});var ts=_(ur=>{Object.defineProperty(ur,"__esModule",{value:!0});ur.parseUndefinedDef=void 0;function li(){return {not:{}}}ur.parseUndefinedDef=li;});var rs=_(cr=>{Object.defineProperty(cr,"__esModule",{value:!0});cr.parseUnknownDef=void 0;function pi(){return {}}cr.parseUnknownDef=pi;});var ss=_(lr=>{Object.defineProperty(lr,"__esModule",{value:!0});lr.parseReadonlyDef=void 0;var fi=P(),hi=(r,e)=>(0, fi.parseDef)(r.innerType._def,e);lr.parseReadonlyDef=hi;});var P=_(pr=>{Object.defineProperty(pr,"__esModule",{value:!0});pr.parseDef=void 0;var I=Dt(),mi=Pr(),yi=Ar(),_i=kr(),gi=Cr(),vi=Nr(),Ti=Dr(),Ii=Sr(),Oi=Zr(),xi=jr(),Ri=Mr(),Ei=Ur(),wi=Vr(),bi=$r(),Pi=qr(),Ai=Fr(),ki=Wr(),Ci=Kr(),Ni=zr(),Di=Gr(),Si=Yr(),Zi=Jr(),ji=Xr(),Mi=Yt(),Ui=Qr(),Vi=Bt(),Li=es(),$i=ts(),qi=er(),Fi=rs(),Wi=ss(),Ki=Rt();function Fs(r,e,t=!1){let s=e.seen.get(r);if(e.override){let i=e.override?.(r,e,s,t);if(i!==Ki.ignoreOverride)return i}if(s&&!t){let i=zi(s,e);if(i!==void 0)return i}let n={def:r,path:e.currentPath,jsonSchema:void 0};e.seen.set(r,n);let a=Gi(r,r.typeName,e);return a&&Yi(r,e,a),n.jsonSchema=a,a}pr.parseDef=Fs;var zi=(r,e)=>{switch(e.$refStrategy){case"root":return {$ref:r.path.join("/")};case"relative":return {$ref:Bi(e.currentPath,r.path)};case"none":case"seen":return r.path.length<e.currentPath.length&&r.path.every((t,s)=>e.currentPath[s]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},Bi=(r,e)=>{let t=0;for(;t<r.length&&t<e.length&&r[t]===e[t];t++);return [(r.length-t).toString(),...e.slice(t)].join("/")},Gi=(r,e,t)=>{switch(e){case I.ZodFirstPartyTypeKind.ZodString:return (0, Vi.parseStringDef)(r,t);case I.ZodFirstPartyTypeKind.ZodNumber:return (0, Ni.parseNumberDef)(r,t);case I.ZodFirstPartyTypeKind.ZodObject:return (0, Di.parseObjectDef)(r,t);case I.ZodFirstPartyTypeKind.ZodBigInt:return (0, _i.parseBigintDef)(r,t);case I.ZodFirstPartyTypeKind.ZodBoolean:return (0, gi.parseBooleanDef)();case I.ZodFirstPartyTypeKind.ZodDate:return (0, Ii.parseDateDef)(r,t);case I.ZodFirstPartyTypeKind.ZodUndefined:return (0, $i.parseUndefinedDef)();case I.ZodFirstPartyTypeKind.ZodNull:return (0, ki.parseNullDef)(t);case I.ZodFirstPartyTypeKind.ZodArray:return (0, yi.parseArrayDef)(r,t);case I.ZodFirstPartyTypeKind.ZodUnion:case I.ZodFirstPartyTypeKind.ZodDiscriminatedUnion:return (0, qi.parseUnionDef)(r,t);case I.ZodFirstPartyTypeKind.ZodIntersection:return (0, Ei.parseIntersectionDef)(r,t);case I.ZodFirstPartyTypeKind.ZodTuple:return (0, Li.parseTupleDef)(r,t);case I.ZodFirstPartyTypeKind.ZodRecord:return (0, Mi.parseRecordDef)(r,t);case I.ZodFirstPartyTypeKind.ZodLiteral:return (0, wi.parseLiteralDef)(r,t);case I.ZodFirstPartyTypeKind.ZodEnum:return (0, Ri.parseEnumDef)(r);case I.ZodFirstPartyTypeKind.ZodNativeEnum:return (0, Pi.parseNativeEnumDef)(r);case I.ZodFirstPartyTypeKind.ZodNullable:return (0, Ci.parseNullableDef)(r,t);case I.ZodFirstPartyTypeKind.ZodOptional:return (0, Si.parseOptionalDef)(r,t);case I.ZodFirstPartyTypeKind.ZodMap:return (0, bi.parseMapDef)(r,t);case I.ZodFirstPartyTypeKind.ZodSet:return (0, Ui.parseSetDef)(r,t);case I.ZodFirstPartyTypeKind.ZodLazy:return Fs(r.getter()._def,t);case I.ZodFirstPartyTypeKind.ZodPromise:return (0, ji.parsePromiseDef)(r,t);case I.ZodFirstPartyTypeKind.ZodNaN:case I.ZodFirstPartyTypeKind.ZodNever:return (0, Ai.parseNeverDef)();case I.ZodFirstPartyTypeKind.ZodEffects:return (0, xi.parseEffectsDef)(r,t);case I.ZodFirstPartyTypeKind.ZodAny:return (0, mi.parseAnyDef)();case I.ZodFirstPartyTypeKind.ZodUnknown:return (0, Fi.parseUnknownDef)();case I.ZodFirstPartyTypeKind.ZodDefault:return (0, Oi.parseDefaultDef)(r,t);case I.ZodFirstPartyTypeKind.ZodBranded:return (0, vi.parseBrandedDef)(r,t);case I.ZodFirstPartyTypeKind.ZodReadonly:return (0, Wi.parseReadonlyDef)(r,t);case I.ZodFirstPartyTypeKind.ZodCatch:return (0, Ti.parseCatchDef)(r,t);case I.ZodFirstPartyTypeKind.ZodPipeline:return (0, Zi.parsePipelineDef)(r,t);case I.ZodFirstPartyTypeKind.ZodFunction:case I.ZodFirstPartyTypeKind.ZodVoid:case I.ZodFirstPartyTypeKind.ZodSymbol:return;default:return (s=>{})()}},Yi=(r,e,t)=>(r.description&&(t.description=r.description,e.markdownDescription&&(t.markdownDescription=r.description)),t);});var ns=_(fr=>{Object.defineProperty(fr,"__esModule",{value:!0});fr.zodToJsonSchema=void 0;var Ws=P(),Ji=Tr(),Xi=(r,e)=>{let t=(0, Ji.getRefs)(e),s=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,h])=>({...c,[l]:(0, Ws.parseDef)(h._def,{...t,currentPath:[...t.basePath,t.definitionPath,l]},!0)??{}}),{}):void 0,n=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,a=(0, Ws.parseDef)(r._def,n===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,n]},!1)??{},i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(a.title=i);let d=n===void 0?s?{...a,[t.definitionPath]:s}:a:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,n].join("/"),[t.definitionPath]:{...s,[n]:a}};return t.target==="jsonSchema7"?d.$schema="http://json-schema.org/draft-07/schema#":t.target==="jsonSchema2019-09"&&(d.$schema="https://json-schema.org/draft/2019-09/schema#"),d};fr.zodToJsonSchema=Xi;});var Ks=_(T=>{var Qi=T&&T.__createBinding||(Object.create?function(r,e,t,s){s===void 0&&(s=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,s,n);}:function(r,e,t,s){s===void 0&&(s=t),r[s]=e[t];}),O=T&&T.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Qi(e,r,t);};Object.defineProperty(T,"__esModule",{value:!0});O(Rt(),T);O(Tr(),T);O(te(),T);O(P(),T);O(Pr(),T);O(Ar(),T);O(kr(),T);O(Cr(),T);O(Nr(),T);O(Dr(),T);O(Sr(),T);O(Zr(),T);O(jr(),T);O(Mr(),T);O(Ur(),T);O(Vr(),T);O($r(),T);O(qr(),T);O(Fr(),T);O(Wr(),T);O(Kr(),T);O(zr(),T);O(Gr(),T);O(Yr(),T);O(Jr(),T);O(Xr(),T);O(ss(),T);O(Yt(),T);O(Qr(),T);O(Bt(),T);O(es(),T);O(ts(),T);O(er(),T);O(rs(),T);O(ns(),T);var Hi=ns();T.default=Hi.zodToJsonSchema;});var et=(s=>(s.TRIGGER="trigger",s.EXECUTE="execute",s.PREVIEW="preview",s))(et||{}),tt=(s=>(s.DISCOVER="discover",s.HEALTH_CHECK="health-check",s.CODE="code",s))(tt||{});var V=(w=>(w.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",w.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",w.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",w.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",w.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",w.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",w.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",w.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",w.STEP_NOT_FOUND_ERROR="StepNotFoundError",w.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",w.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",w.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",w.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",w.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",w.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",w.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",w.INVALID_ACTION_ERROR="InvalidActionError",w.MISSING_API_KEY_ERROR="MissingApiKeyError",w.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",w.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",w.SIGNATURE_INVALID_ERROR="SignatureInvalidError",w.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",w.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",w.PLATFORM_ERROR="PlatformError",w.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",w))(V||{});var rt=(s=>(s.POST="POST",s.GET="GET",s.OPTIONS="OPTIONS",s))(rt||{});var B=class extends Error{data},st=class extends B{statusCode=404},Z=class extends B{statusCode=400},H=class extends B{statusCode=401},Pe=class extends B{statusCode=500},nt=class extends B{statusCode=409};var at=class extends Z{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};}},$e=class extends Z{code="ExecutionEventPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct event payload.`),this.data=t;}},it=class extends Z{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},ot=class extends Z{code="ExecutionStateControlInvalidError";constructor(e,t,s){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid \`controls\`. Please provide the correct step controls.`),this.data=s;}},dt=class extends Z{code="ExecutionStateOutputInvalidError";constructor(e,t,s){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid output. Please provide the correct step output.`),this.data=s;}},ut=class extends Z{code="ExecutionStateResultInvalidError";constructor(e,t,s){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid result. Please provide the correct step result.`),this.data=s;}},ct=class extends Z{code="ExecutionProviderOutputInvalidError";constructor(e,t,s,n){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` and provider with id: \`${s}\` has invalid output. Please provide the correct provider output.`),this.data=n;}};var b={info:r=>Ae__default.default.blue(r),warning:r=>Ae__default.default.yellow(r),error:r=>Ae__default.default.red(r),success:r=>Ae__default.default.green(r),underline:r=>Ae__default.default.underline(r),bold:r=>Ae__default.default.bold(r)},A={SUCCESS:b.success("\u2714"),ERROR:b.error("\u2717"),WARNING:b.warning("\u26A0"),INFO:b.info("\u2139"),ARROW:b.bold("\u2192"),MOCK:b.info("\u25CB"),HYDRATED:b.bold(b.info("\u2192")),STEP:b.info("\u03C3"),ACTION:b.info("\u03B1"),DURATION:b.info("\u0394"),PROVIDER:b.info("\u2699"),OUTPUT:b.info("\u21E2"),INPUT:b.info("\u21E0"),WORKFLOW:b.info("\u03C9"),STATE:b.info("\u03C3"),EXECUTE:b.info("\u03B5"),PREVIEW:b.info("\u03C1")};var vr=r=>Object.values(r).map(e=>`\`${e}\``).join(", "),lt=r=>r.replaceAll(/(\w)(\w*)/g,(e,t,s)=>t.toUpperCase()+s.toLowerCase()).replaceAll(/[\s-]+/g,"");var os=(r,e="https://api.novu.co")=>{let t=process.env.NOVU_API_URL||e;return {post:async(s,n)=>(await fetch(t+"/v1"+s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${r}`},body:JSON.stringify(n)})).json()}};var pt=class extends B{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${vr(rt)}`},qe=class extends Z{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${vr(t)}`);}};var ft=class extends Pe{code="PlatformError";message="Something went wrong. Please try again later."};var Fe=class extends nt{constructor(e,t){super(`${lt(e)} with id: \`${t}\` already exists. Please use a different id.`);}},ee=class extends st{constructor(e,t){super(`${lt(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},ke=class extends Pe{constructor(e,t){super(`Failed to execute ${lt(e)} with id: \`${t}\`. Please try again later.`);}};var ht=class extends ee{code="ProviderNotFoundError";constructor(e){super("provider",e);}},mt=class extends ke{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var yt=class extends H{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.");}},_t=class extends H{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},gt=class extends H{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},vt=class extends H{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},Tt=class extends H{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.apiKey`");}};var It=class extends ee{code="StepNotFoundError";constructor(e){super("step",e);}};var We=class extends ee{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},Ot=class extends Fe{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var xt=class{ajv;compiledSchemas;constructor(){this.ajv=new en__default.default({useDefaults:!0,removeAdditional:"all"}),tn__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 s=this.compiledSchemas.get(t);return s||(s=this.ajv.compile(t),this.compiledSchemas.set(t,s)),s(e)?{success:!0,data:e}:{success:!1,errors:s.errors.map(a=>({path:a.instancePath,message:a.message}))}}transformToJsonSchema(e){return e}};var hr=class{isSchema(e){return e.safeParseAsync!==void 0}async validate(e,t){let s=t.safeParse(e);return s.success?{success:!0,data:s.data}:{success:!1,errors:s.error.errors.map(n=>({path:`/${n.path.join("/")}`,message:n.message}))}}transformToJsonSchema(e){try{return Ks().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 zs=[new hr,new xt],Bs=async(r,e)=>{for(let t of zs)if(t.isSchema(r))return t.validate(e,r);throw new Error("Invalid schema")},Gs=r=>{for(let e of zs)if(e.isSchema(r))return e.transformToJsonSchema(r);throw new Error("Invalid schema")};var Ys={name:"@novu/framework",version:"0.24.3-alpha.11",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",zod:"^3.23.0","zod-to-json-schema":"^3.23.0"},dependencies:{"@novu/shared":"0.24.2",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 He=Ys.version,mr="2024-06-26";jsonSchemaFaker.JSONSchemaFaker.random.shuffle=function(){return ["[placeholder]"]};jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});var _r=class{discoveredWorkflows=[];templateEngine=new liquidjs.Liquid;apiKey;version=He;strictAuthentication;constructor(e){let t=this.buildOptions(e);this.apiKey=t.apiKey,this.strictAuthentication=t.strictAuthentication;}buildOptions(e){let t={apiKey:void 0,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?.strictAuthentication!==void 0?t.strictAuthentication=e.strictAuthentication:process.env.NODE_ENV==="development"&&(t.strictAuthentication=!1),t}addWorkflows(e){for(let t of e){if(this.discoveredWorkflows.some(s=>s.workflowId===t.workflowId))throw new Ot(t.workflowId);this.discoveredWorkflows.push(t);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((s,n)=>s+n.steps.length,0);return {status:"ok",sdkVersion:He,frameworkVersion:mr,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(s=>s.workflowId===e);if(t)return t;throw new We(e)}getStep(e,t){let n=this.getWorkflow(e).steps.find(a=>a.stepId===t);if(n)return n;throw new It(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(Gs(e))}async validate(e,t,s,n,a,i,d){let c=await Bs(t,e);if(c.success)return c.data;switch(s){case"event":this.throwInvalidEvent(n,a,c.errors);case"step":this.throwInvalidStep(i,n,a,c.errors);case"provider":this.throwInvalidProvider(i,d,n,a,c.errors);default:throw new Error(`Invalid component: '${s}'`)}}throwInvalidProvider(e,t,s,n,a){if(!e)throw new Error("stepId is required");if(!t)throw new Error("providerId is required");switch(s){case"output":throw new ct(n,e,t,a);default:throw new Error(`Invalid payload type: '${s}'`)}}throwInvalidStep(e,t,s,n){if(!e)throw new Error("stepId is required");switch(t){case"output":throw new dt(s,e,n);case"result":throw new ut(s,e,n);case"controls":throw new ot(s,e,n);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(e,t,s){switch(e){case"controls":throw new it(t,s);case"payload":throw new $e(t,s);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(s,n,a)=>{let i=this.getStep(e.workflowId,s),d=ro(e),c=await this.createStepControls(i,d),l=e.action==="preview";if(!l&&await this.shouldSkip(a?.skip,c))return t({options:{skip:!0}}),{};let h=this.previewStep.bind(this),E=this.executeStep.bind(this),Q=await(l?h:E)(e,{...i,providers:i.providers.map(be=>{let Le=a?.providers?.[be.type];if(!Le)throw new ht(be.type);return {...be,resolve:Le}}),resolve:n});return s===e.stepId&&t(Q),Q.outputs}}async shouldSkip(e,t){return e?e(t):!1}async executeWorkflow(e){let n=`${{execute:"Executing",preview:"Previewing"}[e.action]} workflowId:`;console.log(`
|
|
23
23
|
${b.bold(b.underline(n))} '${e.workflowId}'`);let a=this.getWorkflow(e.workflowId),i=process.hrtime(),d={outputs:{},providers:{},options:{}},c,l=new Promise(de=>{c=de;}),h=de=>{c(),d=de;},E;try{if(e.action==="execute"&&!e.payload&&!e.data)throw new $e(e.workflowId,{message:"Event `payload` is required"});let de=await this.createExecutionPayload(e,a);await Promise.race([l,a.execute({payload:de,environment:{},inputs:{},controls:{},subscriber:e.subscriber,step:{email:this.executeStepFactory(e,h),sms:this.executeStepFactory(e,h),inApp:this.executeStepFactory(e,h),digest:this.executeStepFactory(e,h),delay:this.executeStepFactory(e,h),push:this.executeStepFactory(e,h),chat:this.executeStepFactory(e,h),custom:this.executeStepFactory(e,h)}})]);}catch(de){E=de;}let X=process.hrtime(i),Q=X[0],be=X[1],Le=Q*1e3+be/1e6,Js=E?A.ERROR:A.SUCCESS,Xs=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action";if(console.log(`${Js} ${Xs} workflowId: \`${e.workflowId}\``),this.prettyPrintExecute(e,Le,E),E)throw E;return {outputs:d.outputs,providers:d.providers,options:d.options,metadata:{status:"success",error:!1,duration:Le}}}async createExecutionPayload(e,t){let s=e.payload||e.data;if(e.action==="preview"){let a=this.mock(t.payload.schema);s=Object.assign(a,s);}return await this.validate(s,t.payload.unknownSchema,"event","payload",e.workflowId)}prettyPrintExecute(e,t,s){let n=s?A.ERROR:A.SUCCESS,a=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action",i=s?"Failed to execute":a,d=s?b.error:b.success,c=`${n} ${i} workflowId: '${e.workflowId}`;console.log(`
|
|
24
24
|
${b.bold(d(c))}'`),console.log(` \u251C ${A.STEP} stepId: '${e.stepId}'`),console.log(` \u251C ${A.ACTION} action: '${e.action}'`),console.log(` \u2514 ${A.DURATION} duration: '${t.toFixed(2)}ms'
|
|
25
25
|
`);}async executeProviders(e,t,s){return t.providers.reduce(async(n,a)=>{let i=await n,d=this.previewProvider.bind(this),c=this.executeProvider.bind(this),h=await(e.action==="preview"?d:c)(e,t,a,s);return {...i,[a.type]:h}},Promise.resolve({}))}previewProvider(e,t,s,n){return console.log(` ${A.MOCK} Mocked provider: \`${s.type}\``),this.mock(s.outputs.schema)}async executeProvider(e,t,s,n){let a=yr__default.default({indent:2}).start(`Executing provider: \`${s.type}\``);try{if(e.stepId===t.stepId){let i=await this.createStepControls(t,e),d=await s.resolve({controls:i,outputs:n}),c=await this.validate(d,s.outputs.unknownSchema,"step","output",e.workflowId,t.stepId,s.type);return a.succeed(`Executed provider: \`${s.type}\``),c}else a.stopAndPersist({symbol:A.HYDRATED,text:`Hydrated provider: \`${s.type}\``});}catch(i){throw a.stopAndPersist({symbol:A.ERROR,text:`Failed to execute provider: \`${s.type}\``}),new mt(`Failed to execute provider: '${s.type}'.
|
package/dist/h3.js
CHANGED
|
@@ -19,7 +19,7 @@ var _=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var Et=_(W=>{Objec
|
|
|
19
19
|
]))`;continue}else if(s[u]==="$"){n+=`($|(?=[\r
|
|
20
20
|
]))`;continue}}if(t.s&&s[u]==="."){n+=a?`${s[u]}\r
|
|
21
21
|
`:`[${s[u]}\r
|
|
22
|
-
]`;continue}n+=s[u],s[u]==="\\"?o=!0:a&&s[u]==="]"?a=!1:!a&&s[u]==="["&&(a=!0);}try{let u=new RegExp(n);}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return n};});var Yt=_(Jt=>{Object.defineProperty(Jt,"__esModule",{value:!0});Jt.parseRecordDef=void 0;var Yr=Zt(),on=P(),Fa=Gt();function Wa(r,e){if(e.target==="openApi3"&&r.keyType?._def.typeName===Yr.ZodFirstPartyTypeKind.ZodEnum)return {type:"object",required:r.keyType._def.values,properties:r.keyType._def.values.reduce((s,n)=>({...s,[n]:(0, on.parseDef)(r.valueType._def,{...e,currentPath:[...e.currentPath,"properties",n]})??{}}),{}),additionalProperties:!1};let t={type:"object",additionalProperties:(0, on.parseDef)(r.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return t;if(r.keyType?._def.typeName===Yr.ZodFirstPartyTypeKind.ZodString&&r.keyType._def.checks?.length){let s=Object.entries((0, Fa.parseStringDef)(r.keyType._def,e)).reduce((n,[o,a])=>o==="type"?n:{...n,[o]:a},{});return {...t,propertyNames:s}}else if(r.keyType?._def.typeName===Yr.ZodFirstPartyTypeKind.ZodEnum)return {...t,propertyNames:{enum:r.keyType._def.values}};return t}Jt.parseRecordDef=Wa;});var Xr=_(Xt=>{Object.defineProperty(Xt,"__esModule",{value:!0});Xt.parseMapDef=void 0;var an=P(),Ba=Yt();function Ka(r,e){if(e.mapStrategy==="record")return (0, Ba.parseRecordDef)(r,e);let t=(0, an.parseDef)(r.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},s=(0, an.parseDef)(r.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return {type:"array",maxItems:125,items:{type:"array",items:[t,s],minItems:2,maxItems:2}}}Xt.parseMapDef=Ka;});var Qr=_(Qt=>{Object.defineProperty(Qt,"__esModule",{value:!0});Qt.parseNativeEnumDef=void 0;function za(r){let e=r.values,s=Object.keys(r.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),n=Array.from(new Set(s.map(o=>typeof o)));return {type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:s}}Qt.parseNativeEnumDef=za;});var es=_(er=>{Object.defineProperty(er,"__esModule",{value:!0});er.parseNeverDef=void 0;function Ha(){return {not:{}}}er.parseNeverDef=Ha;});var ts=_(tr=>{Object.defineProperty(tr,"__esModule",{value:!0});tr.parseNullDef=void 0;function Ga(r){return r.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}tr.parseNullDef=Ga;});var rr=_(ae=>{Object.defineProperty(ae,"__esModule",{value:!0});ae.parseUnionDef=ae.primitiveMappings=void 0;var Ja=P();ae.primitiveMappings={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Ya(r,e){if(e.target==="openApi3")return dn(r,e);let t=r.options instanceof Map?Array.from(r.options.values()):r.options;if(t.every(s=>s._def.typeName in ae.primitiveMappings&&(!s._def.checks||!s._def.checks.length))){let s=t.reduce((n,o)=>{let a=ae.primitiveMappings[o._def.typeName];return a&&!n.includes(a)?[...n,a]:n},[]);return {type:s.length>1?s:s[0]}}else if(t.every(s=>s._def.typeName==="ZodLiteral"&&!s.description)){let s=t.reduce((n,o)=>{let a=typeof o._def.value;switch(a){case"string":case"number":case"boolean":return [...n,a];case"bigint":return [...n,"integer"];case"object":if(o._def.value===null)return [...n,"null"];case"symbol":case"undefined":case"function":default:return n}},[]);if(s.length===t.length){let n=s.filter((o,a,i)=>i.indexOf(o)===a);return {type:n.length>1?n:n[0],enum:t.reduce((o,a)=>o.includes(a._def.value)?o:[...o,a._def.value],[])}}}else if(t.every(s=>s._def.typeName==="ZodEnum"))return {type:"string",enum:t.reduce((s,n)=>[...s,...n._def.values.filter(o=>!s.includes(o))],[])};return dn(r,e)}ae.parseUnionDef=Ya;var dn=(r,e)=>{let t=(r.options instanceof Map?Array.from(r.options.values()):r.options).map((s,n)=>(0, Ja.parseDef)(s._def,{...e,currentPath:[...e.currentPath,"anyOf",`${n}`]})).filter(s=>!!s&&(!e.strictUnions||typeof s=="object"&&Object.keys(s).length>0));return t.length?{anyOf:t}:void 0};});var rs=_(sr=>{Object.defineProperty(sr,"__esModule",{value:!0});sr.parseNullableDef=void 0;var cn=P(),un=rr();function Xa(r,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(r.innerType._def.typeName)&&(!r.innerType._def.checks||!r.innerType._def.checks.length))return e.target==="openApi3"?{type:un.primitiveMappings[r.innerType._def.typeName],nullable:!0}:{type:[un.primitiveMappings[r.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let s=(0, cn.parseDef)(r.innerType._def,{...e,currentPath:[...e.currentPath]});return s&&"$ref"in s?{allOf:[s],nullable:!0}:s&&{...s,nullable:!0}}let t=(0, cn.parseDef)(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}sr.parseNullableDef=Xa;});var ss=_(nr=>{Object.defineProperty(nr,"__esModule",{value:!0});nr.parseNumberDef=void 0;var ie=te();function Qa(r,e){let t={type:"number"};if(!r.checks)return t;for(let s of r.checks)switch(s.kind){case"int":t.type="integer",(0, ie.addErrorMessage)(t,"type",s.message,e);break;case"min":e.target==="jsonSchema7"?s.inclusive?(0, ie.setResponseValueAndErrors)(t,"minimum",s.value,s.message,e):(0, ie.setResponseValueAndErrors)(t,"exclusiveMinimum",s.value,s.message,e):(s.inclusive||(t.exclusiveMinimum=!0),(0, ie.setResponseValueAndErrors)(t,"minimum",s.value,s.message,e));break;case"max":e.target==="jsonSchema7"?s.inclusive?(0, ie.setResponseValueAndErrors)(t,"maximum",s.value,s.message,e):(0, ie.setResponseValueAndErrors)(t,"exclusiveMaximum",s.value,s.message,e):(s.inclusive||(t.exclusiveMaximum=!0),(0, ie.setResponseValueAndErrors)(t,"maximum",s.value,s.message,e));break;case"multipleOf":(0, ie.setResponseValueAndErrors)(t,"multipleOf",s.value,s.message,e);break}return t}nr.parseNumberDef=Qa;});var os=_(qe=>{Object.defineProperty(qe,"__esModule",{value:!0});qe.parseObjectDef=qe.parseObjectDefX=void 0;var et=P();function ns(r,e){return e.removeAdditionalStrategy==="strict"?r.catchall._def.typeName==="ZodNever"?r.unknownKeys!=="strict":(0, et.parseDef)(r.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:r.catchall._def.typeName==="ZodNever"?r.unknownKeys==="passthrough":(0, et.parseDef)(r.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function ei(r,e){Object.keys(r.shape()).reduce((s,n)=>{let o=r.shape()[n],a=o.isOptional();a||(o={...o._def.innerSchema});let i=(0, et.parseDef)(o._def,{...e,currentPath:[...e.currentPath,"properties",n],propertyPath:[...e.currentPath,"properties",n]});return i!==void 0&&(s.properties[n]=i,a||(s.required||(s.required=[]),s.required.push(n))),s},{type:"object",properties:{},additionalProperties:ns(r,e)});let t={type:"object",...Object.entries(r.shape()).reduce((s,[n,o])=>{if(o===void 0||o._def===void 0)return s;let a=(0, et.parseDef)(o._def,{...e,currentPath:[...e.currentPath,"properties",n],propertyPath:[...e.currentPath,"properties",n]});return a===void 0?s:{properties:{...s.properties,[n]:a},required:o.isOptional()?s.required:[...s.required,n]}},{properties:{},required:[]}),additionalProperties:ns(r,e)};return t.required.length||delete t.required,t}qe.parseObjectDefX=ei;function ti(r,e){let t={type:"object",...Object.entries(r.shape()).reduce((s,[n,o])=>{if(o===void 0||o._def===void 0)return s;let a=(0, et.parseDef)(o._def,{...e,currentPath:[...e.currentPath,"properties",n],propertyPath:[...e.currentPath,"properties",n]});return a===void 0?s:{properties:{...s.properties,[n]:a},required:o.isOptional()?s.required:[...s.required,n]}},{properties:{},required:[]}),additionalProperties:ns(r,e)};return t.required.length||delete t.required,t}qe.parseObjectDef=ti;});var as=_(or=>{Object.defineProperty(or,"__esModule",{value:!0});or.parseOptionalDef=void 0;var ln=P(),ri=(r,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return (0, ln.parseDef)(r.innerType._def,e);let t=(0, ln.parseDef)(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:{}},t]}:{}};or.parseOptionalDef=ri;});var is=_(ir=>{Object.defineProperty(ir,"__esModule",{value:!0});ir.parsePipelineDef=void 0;var ar=P(),si=(r,e)=>{if(e.pipeStrategy==="input")return (0, ar.parseDef)(r.in._def,e);if(e.pipeStrategy==="output")return (0, ar.parseDef)(r.out._def,e);let t=(0, ar.parseDef)(r.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),s=(0, ar.parseDef)(r.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return {allOf:[t,s].filter(n=>n!==void 0)}};ir.parsePipelineDef=si;});var ds=_(dr=>{Object.defineProperty(dr,"__esModule",{value:!0});dr.parsePromiseDef=void 0;var ni=P();function oi(r,e){return (0, ni.parseDef)(r.type._def,e)}dr.parsePromiseDef=oi;});var cs=_(cr=>{Object.defineProperty(cr,"__esModule",{value:!0});cr.parseSetDef=void 0;var fn=te(),ai=P();function ii(r,e){let s={type:"array",uniqueItems:!0,items:(0, ai.parseDef)(r.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return r.minSize&&(0, fn.setResponseValueAndErrors)(s,"minItems",r.minSize.value,r.minSize.message,e),r.maxSize&&(0, fn.setResponseValueAndErrors)(s,"maxItems",r.maxSize.value,r.maxSize.message,e),s}cr.parseSetDef=ii;});var ls=_(ur=>{Object.defineProperty(ur,"__esModule",{value:!0});ur.parseTupleDef=void 0;var us=P();function di(r,e){return r.rest?{type:"array",minItems:r.items.length,items:r.items.map((t,s)=>(0, us.parseDef)(t._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((t,s)=>s===void 0?t:[...t,s],[]),additionalItems:(0, us.parseDef)(r.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:r.items.length,maxItems:r.items.length,items:r.items.map((t,s)=>(0, us.parseDef)(t._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((t,s)=>s===void 0?t:[...t,s],[])}}ur.parseTupleDef=di;});var fs=_(lr=>{Object.defineProperty(lr,"__esModule",{value:!0});lr.parseUndefinedDef=void 0;function ci(){return {not:{}}}lr.parseUndefinedDef=ci;});var ps=_(fr=>{Object.defineProperty(fr,"__esModule",{value:!0});fr.parseUnknownDef=void 0;function ui(){return {}}fr.parseUnknownDef=ui;});var hs=_(pr=>{Object.defineProperty(pr,"__esModule",{value:!0});pr.parseReadonlyDef=void 0;var li=P(),fi=(r,e)=>(0, li.parseDef)(r.innerType._def,e);pr.parseReadonlyDef=fi;});var P=_(hr=>{Object.defineProperty(hr,"__esModule",{value:!0});hr.parseDef=void 0;var T=Zt(),pi=Lr(),hi=qr(),mi=Vr(),yi=$r(),_i=Fr(),gi=Wr(),vi=Br(),wi=Kr(),Ti=zr(),Ri=Hr(),Oi=Gr(),xi=Jr(),Ii=Xr(),Ei=Qr(),bi=es(),Pi=ts(),Ai=rs(),Ci=ss(),Si=os(),Ni=as(),ki=is(),Di=ds(),Zi=Yt(),ji=cs(),Mi=Gt(),Ui=ls(),Li=fs(),qi=rr(),Vi=ps(),$i=hs(),Fi=Et();function pn(r,e,t=!1){let s=e.seen.get(r);if(e.override){let a=e.override?.(r,e,s,t);if(a!==Fi.ignoreOverride)return a}if(s&&!t){let a=Wi(s,e);if(a!==void 0)return a}let n={def:r,path:e.currentPath,jsonSchema:void 0};e.seen.set(r,n);let o=Ki(r,r.typeName,e);return o&&zi(r,e,o),n.jsonSchema=o,o}hr.parseDef=pn;var Wi=(r,e)=>{switch(e.$refStrategy){case"root":return {$ref:r.path.join("/")};case"relative":return {$ref:Bi(e.currentPath,r.path)};case"none":case"seen":return r.path.length<e.currentPath.length&&r.path.every((t,s)=>e.currentPath[s]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},Bi=(r,e)=>{let t=0;for(;t<r.length&&t<e.length&&r[t]===e[t];t++);return [(r.length-t).toString(),...e.slice(t)].join("/")},Ki=(r,e,t)=>{switch(e){case T.ZodFirstPartyTypeKind.ZodString:return (0, Mi.parseStringDef)(r,t);case T.ZodFirstPartyTypeKind.ZodNumber:return (0, Ci.parseNumberDef)(r,t);case T.ZodFirstPartyTypeKind.ZodObject:return (0, Si.parseObjectDef)(r,t);case T.ZodFirstPartyTypeKind.ZodBigInt:return (0, mi.parseBigintDef)(r,t);case T.ZodFirstPartyTypeKind.ZodBoolean:return (0, yi.parseBooleanDef)();case T.ZodFirstPartyTypeKind.ZodDate:return (0, vi.parseDateDef)(r,t);case T.ZodFirstPartyTypeKind.ZodUndefined:return (0, Li.parseUndefinedDef)();case T.ZodFirstPartyTypeKind.ZodNull:return (0, Pi.parseNullDef)(t);case T.ZodFirstPartyTypeKind.ZodArray:return (0, hi.parseArrayDef)(r,t);case T.ZodFirstPartyTypeKind.ZodUnion:case T.ZodFirstPartyTypeKind.ZodDiscriminatedUnion:return (0, qi.parseUnionDef)(r,t);case T.ZodFirstPartyTypeKind.ZodIntersection:return (0, Oi.parseIntersectionDef)(r,t);case T.ZodFirstPartyTypeKind.ZodTuple:return (0, Ui.parseTupleDef)(r,t);case T.ZodFirstPartyTypeKind.ZodRecord:return (0, Zi.parseRecordDef)(r,t);case T.ZodFirstPartyTypeKind.ZodLiteral:return (0, xi.parseLiteralDef)(r,t);case T.ZodFirstPartyTypeKind.ZodEnum:return (0, Ri.parseEnumDef)(r);case T.ZodFirstPartyTypeKind.ZodNativeEnum:return (0, Ei.parseNativeEnumDef)(r);case T.ZodFirstPartyTypeKind.ZodNullable:return (0, Ai.parseNullableDef)(r,t);case T.ZodFirstPartyTypeKind.ZodOptional:return (0, Ni.parseOptionalDef)(r,t);case T.ZodFirstPartyTypeKind.ZodMap:return (0, Ii.parseMapDef)(r,t);case T.ZodFirstPartyTypeKind.ZodSet:return (0, ji.parseSetDef)(r,t);case T.ZodFirstPartyTypeKind.ZodLazy:return pn(r.getter()._def,t);case T.ZodFirstPartyTypeKind.ZodPromise:return (0, Di.parsePromiseDef)(r,t);case T.ZodFirstPartyTypeKind.ZodNaN:case T.ZodFirstPartyTypeKind.ZodNever:return (0, bi.parseNeverDef)();case T.ZodFirstPartyTypeKind.ZodEffects:return (0, Ti.parseEffectsDef)(r,t);case T.ZodFirstPartyTypeKind.ZodAny:return (0, pi.parseAnyDef)();case T.ZodFirstPartyTypeKind.ZodUnknown:return (0, Vi.parseUnknownDef)();case T.ZodFirstPartyTypeKind.ZodDefault:return (0, wi.parseDefaultDef)(r,t);case T.ZodFirstPartyTypeKind.ZodBranded:return (0, _i.parseBrandedDef)(r,t);case T.ZodFirstPartyTypeKind.ZodReadonly:return (0, $i.parseReadonlyDef)(r,t);case T.ZodFirstPartyTypeKind.ZodCatch:return (0, gi.parseCatchDef)(r,t);case T.ZodFirstPartyTypeKind.ZodPipeline:return (0, ki.parsePipelineDef)(r,t);case T.ZodFirstPartyTypeKind.ZodFunction:case T.ZodFirstPartyTypeKind.ZodVoid:case T.ZodFirstPartyTypeKind.ZodSymbol:return;default:return (s=>{})()}},zi=(r,e,t)=>(r.description&&(t.description=r.description,e.markdownDescription&&(t.markdownDescription=r.description)),t);});var ms=_(mr=>{Object.defineProperty(mr,"__esModule",{value:!0});mr.zodToJsonSchema=void 0;var hn=P(),Hi=Sr(),Gi=(r,e)=>{let t=(0, Hi.getRefs)(e),s=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((u,[l,h])=>({...u,[l]:(0, hn.parseDef)(h._def,{...t,currentPath:[...t.basePath,t.definitionPath,l]},!0)??{}}),{}):void 0,n=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=(0, hn.parseDef)(r._def,n===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,n]},!1)??{},a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(o.title=a);let i=n===void 0?s?{...o,[t.definitionPath]:s}:o:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,n].join("/"),[t.definitionPath]:{...s,[n]:o}};return t.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":t.target==="jsonSchema2019-09"&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),i};mr.zodToJsonSchema=Gi;});var mn=_(w=>{var Ji=w&&w.__createBinding||(Object.create?function(r,e,t,s){s===void 0&&(s=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,s,n);}:function(r,e,t,s){s===void 0&&(s=t),r[s]=e[t];}),R=w&&w.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Ji(e,r,t);};Object.defineProperty(w,"__esModule",{value:!0});R(Et(),w);R(Sr(),w);R(te(),w);R(P(),w);R(Lr(),w);R(qr(),w);R(Vr(),w);R($r(),w);R(Fr(),w);R(Wr(),w);R(Br(),w);R(Kr(),w);R(zr(),w);R(Hr(),w);R(Gr(),w);R(Jr(),w);R(Xr(),w);R(Qr(),w);R(es(),w);R(ts(),w);R(rs(),w);R(ss(),w);R(os(),w);R(as(),w);R(is(),w);R(ds(),w);R(hs(),w);R(Yt(),w);R(cs(),w);R(Gt(),w);R(ls(),w);R(fs(),w);R(rr(),w);R(ps(),w);R(ms(),w);var Yi=ms();w.default=Yi.zodToJsonSchema;});var gs=/\+/g;function Tr(r=""){try{return decodeURIComponent(""+r)}catch{return ""+r}}function Rn(r){return Tr(r.replace(gs," "))}function On(r){return Tr(r.replace(gs," "))}function xn(r=""){let e={};r[0]==="?"&&(r=r.slice(1));for(let t of r.split("&")){let s=t.match(/([^=]+)=?(.*)/)||[];if(s.length<2)continue;let n=Rn(s[1]);if(n==="__proto__"||n==="constructor")continue;let o=On(s[2]||"");e[n]===void 0?e[n]=o:Array.isArray(e[n])?e[n].push(o):e[n]=[e[n],o];}return e}var In=/^[\s\w\0+.-]{2,}:([/\\]{1,2})/,En=/^[\s\w\0+.-]{2,}:([/\\]{2})?/,bn=/^([/\\]\s*){2,}[^/\\]/;function Pn(r,e={}){return typeof e=="boolean"&&(e={acceptRelative:e}),e.strict?In.test(r):En.test(r)||(e.acceptRelative?bn.test(r):!1)}function vs(r){return xn(Rr(r).search)}var An=Symbol.for("ufo:protocolRelative");function Rr(r="",e){let t=r.match(/^[\s\0]*(blob:|data:|javascript:|vbscript:)(.*)/i);if(t){let[,x,L=""]=t;return {protocol:x.toLowerCase(),pathname:L,href:x+L,auth:"",host:"",search:"",hash:""}}if(!Pn(r,{acceptRelative:!0}))return e?Rr(e+r):_s(r);let[,s="",n,o=""]=r.replace(/\\/g,"/").match(/^[\s\0]*([\w+.-]{2,}:)?\/\/([^/@]+@)?(.*)/)||[],[,a="",i=""]=o.match(/([^#/?]*)(.*)?/)||[],{pathname:u,search:l,hash:h}=_s(i.replace(/\/(?=[A-Za-z]:)/,""));return {protocol:s.toLowerCase(),auth:n?n.slice(0,Math.max(0,n.length-1)):"",host:a,pathname:u,search:l,hash:h,[An]:!s}}function _s(r=""){let[e="",t="",s=""]=(r.match(/([^#?]*)(\?[^#]*)?(#.*)?/)||[]).splice(1);return {pathname:e,search:t,hash:s}}var Cn=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,Sn=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,Nn=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function kn(r,e){if(r==="__proto__"||r==="constructor"&&e&&typeof e=="object"&&"prototype"in e){Dn(r);return}return e}function Dn(r){console.warn(`[destr] Dropping "${r}" key to prevent prototype pollution.`);}function ws(r,e={}){if(typeof r!="string")return r;let t=r.trim();if(r[0]==='"'&&r.endsWith('"')&&!r.includes("\\"))return t.slice(1,-1);if(t.length<=9){let s=t.toLowerCase();if(s==="true")return !0;if(s==="false")return !1;if(s==="undefined")return;if(s==="null")return null;if(s==="nan")return Number.NaN;if(s==="infinity")return Number.POSITIVE_INFINITY;if(s==="-infinity")return Number.NEGATIVE_INFINITY}if(!Nn.test(r)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return r}try{if(Cn.test(r)||Sn.test(r)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(r,kn)}return JSON.parse(r)}catch(s){if(e.strict)throw s;return r}}function Pr(r,e){try{return e in r}catch{return !1}}var jn=Object.defineProperty,Mn=(r,e,t)=>e in r?jn(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ce=(r,e,t)=>(Mn(r,typeof e!="symbol"?e+"":e,t),t),$e=class extends Error{constructor(e,t={}){super(e,t),ce(this,"statusCode",500),ce(this,"fatal",!1),ce(this,"unhandled",!1),ce(this,"statusMessage"),ce(this,"data"),ce(this,"cause"),t.cause&&!this.cause&&(this.cause=t.cause);}toJSON(){let e={message:this.message,statusCode:br(this.statusCode,500)};return this.statusMessage&&(e.statusMessage=Es(this.statusMessage)),this.data!==void 0&&(e.data=this.data),e}};ce($e,"__h3_error__",!0);function Os(r){if(typeof r=="string")return new $e(r);if(Un(r))return r;let e=new $e(r.message??r.statusMessage??"",{cause:r.cause||r});if(Pr(r,"stack"))try{Object.defineProperty(e,"stack",{get(){return r.stack}});}catch{try{e.stack=r.stack;}catch{}}if(r.data&&(e.data=r.data),r.statusCode?e.statusCode=br(r.statusCode,e.statusCode):r.status&&(e.statusCode=br(r.status,e.statusCode)),r.statusMessage?e.statusMessage=r.statusMessage:r.statusText&&(e.statusMessage=r.statusText),e.statusMessage){let t=e.statusMessage;Es(e.statusMessage)!==t&&console.warn("[h3] Please prefer using `message` for longer error messages instead of `statusMessage`. In the future, `statusMessage` will be sanitized by default.");}return r.fatal!==void 0&&(e.fatal=r.fatal),r.unhandled!==void 0&&(e.unhandled=r.unhandled),e}function Un(r){return r?.constructor?.__h3_error__===!0}function xs(r){return vs(r.path||"")}function Ln(r,e,t){if(t&&r.method==="HEAD")return !0;if(typeof e=="string"){if(r.method===e)return !0}else if(e.includes(r.method))return !0;return !1}function qn(r,e,t){if(!Ln(r,e,t))throw Os({statusCode:405,statusMessage:"HTTP method is not allowed."})}function Vn(r){let e={};for(let t in r.node.req.headers){let s=r.node.req.headers[t];e[t]=Array.isArray(s)?s.filter(Boolean).join(", "):s;}return e}function $n(r,e){return Vn(r)[e.toLowerCase()]}var Ar=$n;var Ts=Symbol.for("h3RawBody"),Er=Symbol.for("h3ParsedBody"),Fn=["PATCH","POST","PUT","DELETE"];function Wn(r,e="utf8"){qn(r,Fn);let t=r._requestBody||r.web?.request?.body||r.node.req[Ts]||r.node.req.rawBody||r.node.req.body;if(t){let o=Promise.resolve(t).then(a=>Buffer.isBuffer(a)?a:typeof a.pipeTo=="function"?new Promise((i,u)=>{let l=[];a.pipeTo(new WritableStream({write(h){l.push(h);},close(){i(Buffer.concat(l));},abort(h){u(h);}})).catch(u);}):typeof a.pipe=="function"?new Promise((i,u)=>{let l=[];a.on("data",h=>{l.push(h);}).on("end",()=>{i(Buffer.concat(l));}).on("error",u);}):a.constructor===Object?Buffer.from(JSON.stringify(a)):Buffer.from(a));return e?o.then(a=>a.toString(e)):o}if(!Number.parseInt(r.node.req.headers["content-length"]||""))return Promise.resolve(void 0);let s=r.node.req[Ts]=new Promise((o,a)=>{let i=[];r.node.req.on("error",u=>{a(u);}).on("data",u=>{i.push(u);}).on("end",()=>{o(Buffer.concat(i));});});return e?s.then(o=>o.toString(e)):s}async function Is(r,e={}){let t=r.node.req;if(Pr(t,Er))return t[Er];let s=t.headers["content-type"]||"",n=await Wn(r),o;return s==="application/json"?o=Rs(n,e.strict??!0):s.startsWith("application/x-www-form-urlencoded")?o=Bn(n):s.startsWith("text/")?o=n:o=Rs(n,e.strict??!1),t[Er]=o,o}function Rs(r="",e){if(r)try{return ws(r,{strict:e})}catch{throw Os({statusCode:400,statusMessage:"Bad Request",message:"Invalid JSON body"})}}function Bn(r){let e=new URLSearchParams(r),t=Object.create(null);for(let[s,n]of e.entries())Pr(t,s)?(Array.isArray(t[s])||(t[s]=[t[s]]),t[s].push(n)):t[s]=n;return t}var Kn=/[^\u0009\u0020-\u007E]/g;function Es(r=""){return r.replace(Kn,"")}function br(r,e=200){return !r||(typeof r=="string"&&(r=Number.parseInt(r,10)),r<100||r>999)?e:r}var zn=typeof setImmediate>"u"?r=>r():setImmediate;function bs(r,e,t){return t&&Hn(r,t),new Promise(s=>{zn(()=>{r.handled||r.node.res.end(e),s();});})}function Hn(r,e){e&&r.node.res.statusCode!==304&&!r.node.res.getHeader("content-type")&&r.node.res.setHeader("content-type",e);}function Gn(r,e){for(let[t,s]of Object.entries(e))r.node.res.setHeader(t,s);}var Ps=Gn;var rt=(s=>(s.TRIGGER="trigger",s.EXECUTE="execute",s.PREVIEW="preview",s))(rt||{}),st=(s=>(s.DISCOVER="discover",s.HEALTH_CHECK="health-check",s.CODE="code",s))(st||{});var q=(E=>(E.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",E.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",E.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",E.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",E.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",E.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",E.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",E.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",E.STEP_NOT_FOUND_ERROR="StepNotFoundError",E.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",E.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",E.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",E.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",E.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",E.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",E.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",E.INVALID_ACTION_ERROR="InvalidActionError",E.MISSING_API_KEY_ERROR="MissingApiKeyError",E.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",E.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",E.SIGNATURE_INVALID_ERROR="SignatureInvalidError",E.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",E.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",E.PLATFORM_ERROR="PlatformError",E.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",E))(q||{});var nt=(s=>(s.POST="POST",s.GET="GET",s.OPTIONS="OPTIONS",s))(nt||{});var H=class extends Error{data},ot=class extends H{statusCode=404},Z=class extends H{statusCode=400},Q=class extends H{statusCode=401},Ae=class extends H{statusCode=500},at=class extends H{statusCode=409};var it=class extends Z{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};}},Fe=class extends Z{code="ExecutionEventPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct event payload.`),this.data=t;}},dt=class extends Z{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},ct=class extends Z{code="ExecutionStateControlInvalidError";constructor(e,t,s){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid \`controls\`. Please provide the correct step controls.`),this.data=s;}},ut=class extends Z{code="ExecutionStateOutputInvalidError";constructor(e,t,s){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid output. Please provide the correct step output.`),this.data=s;}},lt=class extends Z{code="ExecutionStateResultInvalidError";constructor(e,t,s){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid result. Please provide the correct step result.`),this.data=s;}},ft=class extends Z{code="ExecutionProviderOutputInvalidError";constructor(e,t,s,n){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` and provider with id: \`${s}\` has invalid output. Please provide the correct provider output.`),this.data=n;}};var b={info:r=>Ce__default.default.blue(r),warning:r=>Ce__default.default.yellow(r),error:r=>Ce__default.default.red(r),success:r=>Ce__default.default.green(r),underline:r=>Ce__default.default.underline(r),bold:r=>Ce__default.default.bold(r)},A={SUCCESS:b.success("\u2714"),ERROR:b.error("\u2717"),WARNING:b.warning("\u26A0"),INFO:b.info("\u2139"),ARROW:b.bold("\u2192"),MOCK:b.info("\u25CB"),HYDRATED:b.bold(b.info("\u2192")),STEP:b.info("\u03C3"),ACTION:b.info("\u03B1"),DURATION:b.info("\u0394"),PROVIDER:b.info("\u2699"),OUTPUT:b.info("\u21E2"),INPUT:b.info("\u21E0"),WORKFLOW:b.info("\u03C9"),STATE:b.info("\u03C3"),EXECUTE:b.info("\u03B5"),PREVIEW:b.info("\u03C1")};var Cr=r=>Object.values(r).map(e=>`\`${e}\``).join(", "),pt=r=>r.replaceAll(/(\w)(\w*)/g,(e,t,s)=>t.toUpperCase()+s.toLowerCase()).replaceAll(/[\s-]+/g,"");var Cs=(r,e="https://api.novu.co/v1")=>({post:async(t,s)=>await fetch(e+t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${r}`},body:JSON.stringify(s)})});var ht=class extends H{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${Cr(nt)}`},We=class extends Z{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${Cr(t)}`);}};var mt=class extends Ae{code="PlatformError";message="Something went wrong. Please try again later."};var Be=class extends at{constructor(e,t){super(`${pt(e)} with id: \`${t}\` already exists. Please use a different id.`);}},ee=class extends ot{constructor(e,t){super(`${pt(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},Se=class extends Ae{constructor(e,t){super(`Failed to execute ${pt(e)} with id: \`${t}\`. Please try again later.`);}};var yt=class extends ee{code="ProviderNotFoundError";constructor(e){super("provider",e);}},_t=class extends Se{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var gt=class extends Q{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.");}},vt=class extends Q{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},wt=class extends Q{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},Tt=class extends Q{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},Rt=class extends Q{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.apiKey`");}};var Ot=class extends ee{code="StepNotFoundError";constructor(e){super("step",e);}};var Ke=class extends ee{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},xt=class extends Be{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var It=class{ajv;compiledSchemas;constructor(){this.ajv=new Xn__default.default({useDefaults:!0,removeAdditional:"all"}),Qn__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 s=this.compiledSchemas.get(t);return s||(s=this.ajv.compile(t),this.compiledSchemas.set(t,s)),s(e)?{success:!0,data:e}:{success:!1,errors:s.errors.map(o=>({path:o.instancePath,message:o.message}))}}transformToJsonSchema(e){return e}};var yr=class{isSchema(e){return e.safeParseAsync!==void 0}async validate(e,t){let s=t.safeParse(e);return s.success?{success:!0,data:s.data}:{success:!1,errors:s.error.errors.map(n=>({path:`/${n.path.join("/")}`,message:n.message}))}}transformToJsonSchema(e){try{return mn().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 yn=[new yr,new It],_n=async(r,e)=>{for(let t of yn)if(t.isSchema(r))return t.validate(e,r);throw new Error("Invalid schema")},gn=r=>{for(let e of yn)if(e.isSchema(r))return e.transformToJsonSchema(r);throw new Error("Invalid schema")};var vn={name:"@novu/framework",version:"0.24.3-alpha.10",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",zod:"^3.23.0","zod-to-json-schema":"^3.23.0"},dependencies:{"@novu/shared":"0.24.2",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 tt=vn.version,_r="2024-06-26";jsonSchemaFaker.JSONSchemaFaker.random.shuffle=function(){return ["[placeholder]"]};jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});var vr=class{discoveredWorkflows=[];templateEngine=new liquidjs.Liquid;apiKey;version=tt;strictAuthentication;constructor(e){let t=this.buildOptions(e);this.apiKey=t.apiKey,this.strictAuthentication=t.strictAuthentication;}buildOptions(e){let t={apiKey:void 0,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?.strictAuthentication!==void 0?t.strictAuthentication=e.strictAuthentication:process.env.NODE_ENV==="development"&&(t.strictAuthentication=!1),t}addWorkflows(e){for(let t of e){if(this.discoveredWorkflows.some(s=>s.workflowId===t.workflowId))throw new xt(t.workflowId);this.discoveredWorkflows.push(t);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((s,n)=>s+n.steps.length,0);return {status:"ok",sdkVersion:tt,frameworkVersion:_r,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(s=>s.workflowId===e);if(t)return t;throw new Ke(e)}getStep(e,t){let n=this.getWorkflow(e).steps.find(o=>o.stepId===t);if(n)return n;throw new Ot(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(gn(e))}async validate(e,t,s,n,o,a,i){let u=await _n(t,e);if(u.success)return u.data;switch(s){case"event":this.throwInvalidEvent(n,o,u.errors);case"step":this.throwInvalidStep(a,n,o,u.errors);case"provider":this.throwInvalidProvider(a,i,n,o,u.errors);default:throw new Error(`Invalid component: '${s}'`)}}throwInvalidProvider(e,t,s,n,o){if(!e)throw new Error("stepId is required");if(!t)throw new Error("providerId is required");switch(s){case"output":throw new ft(n,e,t,o);default:throw new Error(`Invalid payload type: '${s}'`)}}throwInvalidStep(e,t,s,n){if(!e)throw new Error("stepId is required");switch(t){case"output":throw new ut(s,e,n);case"result":throw new lt(s,e,n);case"controls":throw new ct(s,e,n);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(e,t,s){switch(e){case"controls":throw new dt(t,s);case"payload":throw new Fe(t,s);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(s,n,o)=>{let a=this.getStep(e.workflowId,s),i=ed(e),u=await this.createStepControls(a,i),l=e.action==="preview";if(!l&&await this.shouldSkip(o?.skip,u))return t({options:{skip:!0}}),{};let h=this.previewStep.bind(this),x=this.executeStep.bind(this),X=await(l?h:x)(e,{...a,providers:a.providers.map(Pe=>{let Ve=o?.providers?.[Pe.type];if(!Ve)throw new yt(Pe.type);return {...Pe,resolve:Ve}}),resolve:n});return s===e.stepId&&t(X),X.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
|
+
]`;continue}n+=s[u],s[u]==="\\"?o=!0:a&&s[u]==="]"?a=!1:!a&&s[u]==="["&&(a=!0);}try{let u=new RegExp(n);}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return n};});var Yt=_(Jt=>{Object.defineProperty(Jt,"__esModule",{value:!0});Jt.parseRecordDef=void 0;var Yr=Zt(),on=P(),Fa=Gt();function Wa(r,e){if(e.target==="openApi3"&&r.keyType?._def.typeName===Yr.ZodFirstPartyTypeKind.ZodEnum)return {type:"object",required:r.keyType._def.values,properties:r.keyType._def.values.reduce((s,n)=>({...s,[n]:(0, on.parseDef)(r.valueType._def,{...e,currentPath:[...e.currentPath,"properties",n]})??{}}),{}),additionalProperties:!1};let t={type:"object",additionalProperties:(0, on.parseDef)(r.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return t;if(r.keyType?._def.typeName===Yr.ZodFirstPartyTypeKind.ZodString&&r.keyType._def.checks?.length){let s=Object.entries((0, Fa.parseStringDef)(r.keyType._def,e)).reduce((n,[o,a])=>o==="type"?n:{...n,[o]:a},{});return {...t,propertyNames:s}}else if(r.keyType?._def.typeName===Yr.ZodFirstPartyTypeKind.ZodEnum)return {...t,propertyNames:{enum:r.keyType._def.values}};return t}Jt.parseRecordDef=Wa;});var Xr=_(Xt=>{Object.defineProperty(Xt,"__esModule",{value:!0});Xt.parseMapDef=void 0;var an=P(),Ba=Yt();function Ka(r,e){if(e.mapStrategy==="record")return (0, Ba.parseRecordDef)(r,e);let t=(0, an.parseDef)(r.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},s=(0, an.parseDef)(r.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return {type:"array",maxItems:125,items:{type:"array",items:[t,s],minItems:2,maxItems:2}}}Xt.parseMapDef=Ka;});var Qr=_(Qt=>{Object.defineProperty(Qt,"__esModule",{value:!0});Qt.parseNativeEnumDef=void 0;function za(r){let e=r.values,s=Object.keys(r.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),n=Array.from(new Set(s.map(o=>typeof o)));return {type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:s}}Qt.parseNativeEnumDef=za;});var es=_(er=>{Object.defineProperty(er,"__esModule",{value:!0});er.parseNeverDef=void 0;function Ha(){return {not:{}}}er.parseNeverDef=Ha;});var ts=_(tr=>{Object.defineProperty(tr,"__esModule",{value:!0});tr.parseNullDef=void 0;function Ga(r){return r.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}tr.parseNullDef=Ga;});var rr=_(ae=>{Object.defineProperty(ae,"__esModule",{value:!0});ae.parseUnionDef=ae.primitiveMappings=void 0;var Ja=P();ae.primitiveMappings={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Ya(r,e){if(e.target==="openApi3")return dn(r,e);let t=r.options instanceof Map?Array.from(r.options.values()):r.options;if(t.every(s=>s._def.typeName in ae.primitiveMappings&&(!s._def.checks||!s._def.checks.length))){let s=t.reduce((n,o)=>{let a=ae.primitiveMappings[o._def.typeName];return a&&!n.includes(a)?[...n,a]:n},[]);return {type:s.length>1?s:s[0]}}else if(t.every(s=>s._def.typeName==="ZodLiteral"&&!s.description)){let s=t.reduce((n,o)=>{let a=typeof o._def.value;switch(a){case"string":case"number":case"boolean":return [...n,a];case"bigint":return [...n,"integer"];case"object":if(o._def.value===null)return [...n,"null"];case"symbol":case"undefined":case"function":default:return n}},[]);if(s.length===t.length){let n=s.filter((o,a,i)=>i.indexOf(o)===a);return {type:n.length>1?n:n[0],enum:t.reduce((o,a)=>o.includes(a._def.value)?o:[...o,a._def.value],[])}}}else if(t.every(s=>s._def.typeName==="ZodEnum"))return {type:"string",enum:t.reduce((s,n)=>[...s,...n._def.values.filter(o=>!s.includes(o))],[])};return dn(r,e)}ae.parseUnionDef=Ya;var dn=(r,e)=>{let t=(r.options instanceof Map?Array.from(r.options.values()):r.options).map((s,n)=>(0, Ja.parseDef)(s._def,{...e,currentPath:[...e.currentPath,"anyOf",`${n}`]})).filter(s=>!!s&&(!e.strictUnions||typeof s=="object"&&Object.keys(s).length>0));return t.length?{anyOf:t}:void 0};});var rs=_(sr=>{Object.defineProperty(sr,"__esModule",{value:!0});sr.parseNullableDef=void 0;var cn=P(),un=rr();function Xa(r,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(r.innerType._def.typeName)&&(!r.innerType._def.checks||!r.innerType._def.checks.length))return e.target==="openApi3"?{type:un.primitiveMappings[r.innerType._def.typeName],nullable:!0}:{type:[un.primitiveMappings[r.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let s=(0, cn.parseDef)(r.innerType._def,{...e,currentPath:[...e.currentPath]});return s&&"$ref"in s?{allOf:[s],nullable:!0}:s&&{...s,nullable:!0}}let t=(0, cn.parseDef)(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}sr.parseNullableDef=Xa;});var ss=_(nr=>{Object.defineProperty(nr,"__esModule",{value:!0});nr.parseNumberDef=void 0;var ie=te();function Qa(r,e){let t={type:"number"};if(!r.checks)return t;for(let s of r.checks)switch(s.kind){case"int":t.type="integer",(0, ie.addErrorMessage)(t,"type",s.message,e);break;case"min":e.target==="jsonSchema7"?s.inclusive?(0, ie.setResponseValueAndErrors)(t,"minimum",s.value,s.message,e):(0, ie.setResponseValueAndErrors)(t,"exclusiveMinimum",s.value,s.message,e):(s.inclusive||(t.exclusiveMinimum=!0),(0, ie.setResponseValueAndErrors)(t,"minimum",s.value,s.message,e));break;case"max":e.target==="jsonSchema7"?s.inclusive?(0, ie.setResponseValueAndErrors)(t,"maximum",s.value,s.message,e):(0, ie.setResponseValueAndErrors)(t,"exclusiveMaximum",s.value,s.message,e):(s.inclusive||(t.exclusiveMaximum=!0),(0, ie.setResponseValueAndErrors)(t,"maximum",s.value,s.message,e));break;case"multipleOf":(0, ie.setResponseValueAndErrors)(t,"multipleOf",s.value,s.message,e);break}return t}nr.parseNumberDef=Qa;});var os=_(qe=>{Object.defineProperty(qe,"__esModule",{value:!0});qe.parseObjectDef=qe.parseObjectDefX=void 0;var et=P();function ns(r,e){return e.removeAdditionalStrategy==="strict"?r.catchall._def.typeName==="ZodNever"?r.unknownKeys!=="strict":(0, et.parseDef)(r.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:r.catchall._def.typeName==="ZodNever"?r.unknownKeys==="passthrough":(0, et.parseDef)(r.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function ei(r,e){Object.keys(r.shape()).reduce((s,n)=>{let o=r.shape()[n],a=o.isOptional();a||(o={...o._def.innerSchema});let i=(0, et.parseDef)(o._def,{...e,currentPath:[...e.currentPath,"properties",n],propertyPath:[...e.currentPath,"properties",n]});return i!==void 0&&(s.properties[n]=i,a||(s.required||(s.required=[]),s.required.push(n))),s},{type:"object",properties:{},additionalProperties:ns(r,e)});let t={type:"object",...Object.entries(r.shape()).reduce((s,[n,o])=>{if(o===void 0||o._def===void 0)return s;let a=(0, et.parseDef)(o._def,{...e,currentPath:[...e.currentPath,"properties",n],propertyPath:[...e.currentPath,"properties",n]});return a===void 0?s:{properties:{...s.properties,[n]:a},required:o.isOptional()?s.required:[...s.required,n]}},{properties:{},required:[]}),additionalProperties:ns(r,e)};return t.required.length||delete t.required,t}qe.parseObjectDefX=ei;function ti(r,e){let t={type:"object",...Object.entries(r.shape()).reduce((s,[n,o])=>{if(o===void 0||o._def===void 0)return s;let a=(0, et.parseDef)(o._def,{...e,currentPath:[...e.currentPath,"properties",n],propertyPath:[...e.currentPath,"properties",n]});return a===void 0?s:{properties:{...s.properties,[n]:a},required:o.isOptional()?s.required:[...s.required,n]}},{properties:{},required:[]}),additionalProperties:ns(r,e)};return t.required.length||delete t.required,t}qe.parseObjectDef=ti;});var as=_(or=>{Object.defineProperty(or,"__esModule",{value:!0});or.parseOptionalDef=void 0;var ln=P(),ri=(r,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return (0, ln.parseDef)(r.innerType._def,e);let t=(0, ln.parseDef)(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:{}},t]}:{}};or.parseOptionalDef=ri;});var is=_(ir=>{Object.defineProperty(ir,"__esModule",{value:!0});ir.parsePipelineDef=void 0;var ar=P(),si=(r,e)=>{if(e.pipeStrategy==="input")return (0, ar.parseDef)(r.in._def,e);if(e.pipeStrategy==="output")return (0, ar.parseDef)(r.out._def,e);let t=(0, ar.parseDef)(r.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),s=(0, ar.parseDef)(r.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return {allOf:[t,s].filter(n=>n!==void 0)}};ir.parsePipelineDef=si;});var ds=_(dr=>{Object.defineProperty(dr,"__esModule",{value:!0});dr.parsePromiseDef=void 0;var ni=P();function oi(r,e){return (0, ni.parseDef)(r.type._def,e)}dr.parsePromiseDef=oi;});var cs=_(cr=>{Object.defineProperty(cr,"__esModule",{value:!0});cr.parseSetDef=void 0;var fn=te(),ai=P();function ii(r,e){let s={type:"array",uniqueItems:!0,items:(0, ai.parseDef)(r.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return r.minSize&&(0, fn.setResponseValueAndErrors)(s,"minItems",r.minSize.value,r.minSize.message,e),r.maxSize&&(0, fn.setResponseValueAndErrors)(s,"maxItems",r.maxSize.value,r.maxSize.message,e),s}cr.parseSetDef=ii;});var ls=_(ur=>{Object.defineProperty(ur,"__esModule",{value:!0});ur.parseTupleDef=void 0;var us=P();function di(r,e){return r.rest?{type:"array",minItems:r.items.length,items:r.items.map((t,s)=>(0, us.parseDef)(t._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((t,s)=>s===void 0?t:[...t,s],[]),additionalItems:(0, us.parseDef)(r.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:r.items.length,maxItems:r.items.length,items:r.items.map((t,s)=>(0, us.parseDef)(t._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((t,s)=>s===void 0?t:[...t,s],[])}}ur.parseTupleDef=di;});var fs=_(lr=>{Object.defineProperty(lr,"__esModule",{value:!0});lr.parseUndefinedDef=void 0;function ci(){return {not:{}}}lr.parseUndefinedDef=ci;});var ps=_(fr=>{Object.defineProperty(fr,"__esModule",{value:!0});fr.parseUnknownDef=void 0;function ui(){return {}}fr.parseUnknownDef=ui;});var hs=_(pr=>{Object.defineProperty(pr,"__esModule",{value:!0});pr.parseReadonlyDef=void 0;var li=P(),fi=(r,e)=>(0, li.parseDef)(r.innerType._def,e);pr.parseReadonlyDef=fi;});var P=_(hr=>{Object.defineProperty(hr,"__esModule",{value:!0});hr.parseDef=void 0;var T=Zt(),pi=Lr(),hi=qr(),mi=Vr(),yi=$r(),_i=Fr(),gi=Wr(),vi=Br(),wi=Kr(),Ti=zr(),Ri=Hr(),Oi=Gr(),xi=Jr(),Ii=Xr(),Ei=Qr(),bi=es(),Pi=ts(),Ai=rs(),Ci=ss(),Si=os(),Ni=as(),ki=is(),Di=ds(),Zi=Yt(),ji=cs(),Mi=Gt(),Ui=ls(),Li=fs(),qi=rr(),Vi=ps(),$i=hs(),Fi=Et();function pn(r,e,t=!1){let s=e.seen.get(r);if(e.override){let a=e.override?.(r,e,s,t);if(a!==Fi.ignoreOverride)return a}if(s&&!t){let a=Wi(s,e);if(a!==void 0)return a}let n={def:r,path:e.currentPath,jsonSchema:void 0};e.seen.set(r,n);let o=Ki(r,r.typeName,e);return o&&zi(r,e,o),n.jsonSchema=o,o}hr.parseDef=pn;var Wi=(r,e)=>{switch(e.$refStrategy){case"root":return {$ref:r.path.join("/")};case"relative":return {$ref:Bi(e.currentPath,r.path)};case"none":case"seen":return r.path.length<e.currentPath.length&&r.path.every((t,s)=>e.currentPath[s]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},Bi=(r,e)=>{let t=0;for(;t<r.length&&t<e.length&&r[t]===e[t];t++);return [(r.length-t).toString(),...e.slice(t)].join("/")},Ki=(r,e,t)=>{switch(e){case T.ZodFirstPartyTypeKind.ZodString:return (0, Mi.parseStringDef)(r,t);case T.ZodFirstPartyTypeKind.ZodNumber:return (0, Ci.parseNumberDef)(r,t);case T.ZodFirstPartyTypeKind.ZodObject:return (0, Si.parseObjectDef)(r,t);case T.ZodFirstPartyTypeKind.ZodBigInt:return (0, mi.parseBigintDef)(r,t);case T.ZodFirstPartyTypeKind.ZodBoolean:return (0, yi.parseBooleanDef)();case T.ZodFirstPartyTypeKind.ZodDate:return (0, vi.parseDateDef)(r,t);case T.ZodFirstPartyTypeKind.ZodUndefined:return (0, Li.parseUndefinedDef)();case T.ZodFirstPartyTypeKind.ZodNull:return (0, Pi.parseNullDef)(t);case T.ZodFirstPartyTypeKind.ZodArray:return (0, hi.parseArrayDef)(r,t);case T.ZodFirstPartyTypeKind.ZodUnion:case T.ZodFirstPartyTypeKind.ZodDiscriminatedUnion:return (0, qi.parseUnionDef)(r,t);case T.ZodFirstPartyTypeKind.ZodIntersection:return (0, Oi.parseIntersectionDef)(r,t);case T.ZodFirstPartyTypeKind.ZodTuple:return (0, Ui.parseTupleDef)(r,t);case T.ZodFirstPartyTypeKind.ZodRecord:return (0, Zi.parseRecordDef)(r,t);case T.ZodFirstPartyTypeKind.ZodLiteral:return (0, xi.parseLiteralDef)(r,t);case T.ZodFirstPartyTypeKind.ZodEnum:return (0, Ri.parseEnumDef)(r);case T.ZodFirstPartyTypeKind.ZodNativeEnum:return (0, Ei.parseNativeEnumDef)(r);case T.ZodFirstPartyTypeKind.ZodNullable:return (0, Ai.parseNullableDef)(r,t);case T.ZodFirstPartyTypeKind.ZodOptional:return (0, Ni.parseOptionalDef)(r,t);case T.ZodFirstPartyTypeKind.ZodMap:return (0, Ii.parseMapDef)(r,t);case T.ZodFirstPartyTypeKind.ZodSet:return (0, ji.parseSetDef)(r,t);case T.ZodFirstPartyTypeKind.ZodLazy:return pn(r.getter()._def,t);case T.ZodFirstPartyTypeKind.ZodPromise:return (0, Di.parsePromiseDef)(r,t);case T.ZodFirstPartyTypeKind.ZodNaN:case T.ZodFirstPartyTypeKind.ZodNever:return (0, bi.parseNeverDef)();case T.ZodFirstPartyTypeKind.ZodEffects:return (0, Ti.parseEffectsDef)(r,t);case T.ZodFirstPartyTypeKind.ZodAny:return (0, pi.parseAnyDef)();case T.ZodFirstPartyTypeKind.ZodUnknown:return (0, Vi.parseUnknownDef)();case T.ZodFirstPartyTypeKind.ZodDefault:return (0, wi.parseDefaultDef)(r,t);case T.ZodFirstPartyTypeKind.ZodBranded:return (0, _i.parseBrandedDef)(r,t);case T.ZodFirstPartyTypeKind.ZodReadonly:return (0, $i.parseReadonlyDef)(r,t);case T.ZodFirstPartyTypeKind.ZodCatch:return (0, gi.parseCatchDef)(r,t);case T.ZodFirstPartyTypeKind.ZodPipeline:return (0, ki.parsePipelineDef)(r,t);case T.ZodFirstPartyTypeKind.ZodFunction:case T.ZodFirstPartyTypeKind.ZodVoid:case T.ZodFirstPartyTypeKind.ZodSymbol:return;default:return (s=>{})()}},zi=(r,e,t)=>(r.description&&(t.description=r.description,e.markdownDescription&&(t.markdownDescription=r.description)),t);});var ms=_(mr=>{Object.defineProperty(mr,"__esModule",{value:!0});mr.zodToJsonSchema=void 0;var hn=P(),Hi=Sr(),Gi=(r,e)=>{let t=(0, Hi.getRefs)(e),s=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((u,[l,h])=>({...u,[l]:(0, hn.parseDef)(h._def,{...t,currentPath:[...t.basePath,t.definitionPath,l]},!0)??{}}),{}):void 0,n=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=(0, hn.parseDef)(r._def,n===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,n]},!1)??{},a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(o.title=a);let i=n===void 0?s?{...o,[t.definitionPath]:s}:o:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,n].join("/"),[t.definitionPath]:{...s,[n]:o}};return t.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":t.target==="jsonSchema2019-09"&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),i};mr.zodToJsonSchema=Gi;});var mn=_(w=>{var Ji=w&&w.__createBinding||(Object.create?function(r,e,t,s){s===void 0&&(s=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,s,n);}:function(r,e,t,s){s===void 0&&(s=t),r[s]=e[t];}),R=w&&w.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Ji(e,r,t);};Object.defineProperty(w,"__esModule",{value:!0});R(Et(),w);R(Sr(),w);R(te(),w);R(P(),w);R(Lr(),w);R(qr(),w);R(Vr(),w);R($r(),w);R(Fr(),w);R(Wr(),w);R(Br(),w);R(Kr(),w);R(zr(),w);R(Hr(),w);R(Gr(),w);R(Jr(),w);R(Xr(),w);R(Qr(),w);R(es(),w);R(ts(),w);R(rs(),w);R(ss(),w);R(os(),w);R(as(),w);R(is(),w);R(ds(),w);R(hs(),w);R(Yt(),w);R(cs(),w);R(Gt(),w);R(ls(),w);R(fs(),w);R(rr(),w);R(ps(),w);R(ms(),w);var Yi=ms();w.default=Yi.zodToJsonSchema;});var gs=/\+/g;function Tr(r=""){try{return decodeURIComponent(""+r)}catch{return ""+r}}function Rn(r){return Tr(r.replace(gs," "))}function On(r){return Tr(r.replace(gs," "))}function xn(r=""){let e={};r[0]==="?"&&(r=r.slice(1));for(let t of r.split("&")){let s=t.match(/([^=]+)=?(.*)/)||[];if(s.length<2)continue;let n=Rn(s[1]);if(n==="__proto__"||n==="constructor")continue;let o=On(s[2]||"");e[n]===void 0?e[n]=o:Array.isArray(e[n])?e[n].push(o):e[n]=[e[n],o];}return e}var In=/^[\s\w\0+.-]{2,}:([/\\]{1,2})/,En=/^[\s\w\0+.-]{2,}:([/\\]{2})?/,bn=/^([/\\]\s*){2,}[^/\\]/;function Pn(r,e={}){return typeof e=="boolean"&&(e={acceptRelative:e}),e.strict?In.test(r):En.test(r)||(e.acceptRelative?bn.test(r):!1)}function vs(r){return xn(Rr(r).search)}var An=Symbol.for("ufo:protocolRelative");function Rr(r="",e){let t=r.match(/^[\s\0]*(blob:|data:|javascript:|vbscript:)(.*)/i);if(t){let[,x,L=""]=t;return {protocol:x.toLowerCase(),pathname:L,href:x+L,auth:"",host:"",search:"",hash:""}}if(!Pn(r,{acceptRelative:!0}))return e?Rr(e+r):_s(r);let[,s="",n,o=""]=r.replace(/\\/g,"/").match(/^[\s\0]*([\w+.-]{2,}:)?\/\/([^/@]+@)?(.*)/)||[],[,a="",i=""]=o.match(/([^#/?]*)(.*)?/)||[],{pathname:u,search:l,hash:h}=_s(i.replace(/\/(?=[A-Za-z]:)/,""));return {protocol:s.toLowerCase(),auth:n?n.slice(0,Math.max(0,n.length-1)):"",host:a,pathname:u,search:l,hash:h,[An]:!s}}function _s(r=""){let[e="",t="",s=""]=(r.match(/([^#?]*)(\?[^#]*)?(#.*)?/)||[]).splice(1);return {pathname:e,search:t,hash:s}}var Cn=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,Sn=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,Nn=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function kn(r,e){if(r==="__proto__"||r==="constructor"&&e&&typeof e=="object"&&"prototype"in e){Dn(r);return}return e}function Dn(r){console.warn(`[destr] Dropping "${r}" key to prevent prototype pollution.`);}function ws(r,e={}){if(typeof r!="string")return r;let t=r.trim();if(r[0]==='"'&&r.endsWith('"')&&!r.includes("\\"))return t.slice(1,-1);if(t.length<=9){let s=t.toLowerCase();if(s==="true")return !0;if(s==="false")return !1;if(s==="undefined")return;if(s==="null")return null;if(s==="nan")return Number.NaN;if(s==="infinity")return Number.POSITIVE_INFINITY;if(s==="-infinity")return Number.NEGATIVE_INFINITY}if(!Nn.test(r)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return r}try{if(Cn.test(r)||Sn.test(r)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(r,kn)}return JSON.parse(r)}catch(s){if(e.strict)throw s;return r}}function Pr(r,e){try{return e in r}catch{return !1}}var jn=Object.defineProperty,Mn=(r,e,t)=>e in r?jn(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ce=(r,e,t)=>(Mn(r,typeof e!="symbol"?e+"":e,t),t),$e=class extends Error{constructor(e,t={}){super(e,t),ce(this,"statusCode",500),ce(this,"fatal",!1),ce(this,"unhandled",!1),ce(this,"statusMessage"),ce(this,"data"),ce(this,"cause"),t.cause&&!this.cause&&(this.cause=t.cause);}toJSON(){let e={message:this.message,statusCode:br(this.statusCode,500)};return this.statusMessage&&(e.statusMessage=Es(this.statusMessage)),this.data!==void 0&&(e.data=this.data),e}};ce($e,"__h3_error__",!0);function Os(r){if(typeof r=="string")return new $e(r);if(Un(r))return r;let e=new $e(r.message??r.statusMessage??"",{cause:r.cause||r});if(Pr(r,"stack"))try{Object.defineProperty(e,"stack",{get(){return r.stack}});}catch{try{e.stack=r.stack;}catch{}}if(r.data&&(e.data=r.data),r.statusCode?e.statusCode=br(r.statusCode,e.statusCode):r.status&&(e.statusCode=br(r.status,e.statusCode)),r.statusMessage?e.statusMessage=r.statusMessage:r.statusText&&(e.statusMessage=r.statusText),e.statusMessage){let t=e.statusMessage;Es(e.statusMessage)!==t&&console.warn("[h3] Please prefer using `message` for longer error messages instead of `statusMessage`. In the future, `statusMessage` will be sanitized by default.");}return r.fatal!==void 0&&(e.fatal=r.fatal),r.unhandled!==void 0&&(e.unhandled=r.unhandled),e}function Un(r){return r?.constructor?.__h3_error__===!0}function xs(r){return vs(r.path||"")}function Ln(r,e,t){if(t&&r.method==="HEAD")return !0;if(typeof e=="string"){if(r.method===e)return !0}else if(e.includes(r.method))return !0;return !1}function qn(r,e,t){if(!Ln(r,e,t))throw Os({statusCode:405,statusMessage:"HTTP method is not allowed."})}function Vn(r){let e={};for(let t in r.node.req.headers){let s=r.node.req.headers[t];e[t]=Array.isArray(s)?s.filter(Boolean).join(", "):s;}return e}function $n(r,e){return Vn(r)[e.toLowerCase()]}var Ar=$n;var Ts=Symbol.for("h3RawBody"),Er=Symbol.for("h3ParsedBody"),Fn=["PATCH","POST","PUT","DELETE"];function Wn(r,e="utf8"){qn(r,Fn);let t=r._requestBody||r.web?.request?.body||r.node.req[Ts]||r.node.req.rawBody||r.node.req.body;if(t){let o=Promise.resolve(t).then(a=>Buffer.isBuffer(a)?a:typeof a.pipeTo=="function"?new Promise((i,u)=>{let l=[];a.pipeTo(new WritableStream({write(h){l.push(h);},close(){i(Buffer.concat(l));},abort(h){u(h);}})).catch(u);}):typeof a.pipe=="function"?new Promise((i,u)=>{let l=[];a.on("data",h=>{l.push(h);}).on("end",()=>{i(Buffer.concat(l));}).on("error",u);}):a.constructor===Object?Buffer.from(JSON.stringify(a)):Buffer.from(a));return e?o.then(a=>a.toString(e)):o}if(!Number.parseInt(r.node.req.headers["content-length"]||""))return Promise.resolve(void 0);let s=r.node.req[Ts]=new Promise((o,a)=>{let i=[];r.node.req.on("error",u=>{a(u);}).on("data",u=>{i.push(u);}).on("end",()=>{o(Buffer.concat(i));});});return e?s.then(o=>o.toString(e)):s}async function Is(r,e={}){let t=r.node.req;if(Pr(t,Er))return t[Er];let s=t.headers["content-type"]||"",n=await Wn(r),o;return s==="application/json"?o=Rs(n,e.strict??!0):s.startsWith("application/x-www-form-urlencoded")?o=Bn(n):s.startsWith("text/")?o=n:o=Rs(n,e.strict??!1),t[Er]=o,o}function Rs(r="",e){if(r)try{return ws(r,{strict:e})}catch{throw Os({statusCode:400,statusMessage:"Bad Request",message:"Invalid JSON body"})}}function Bn(r){let e=new URLSearchParams(r),t=Object.create(null);for(let[s,n]of e.entries())Pr(t,s)?(Array.isArray(t[s])||(t[s]=[t[s]]),t[s].push(n)):t[s]=n;return t}var Kn=/[^\u0009\u0020-\u007E]/g;function Es(r=""){return r.replace(Kn,"")}function br(r,e=200){return !r||(typeof r=="string"&&(r=Number.parseInt(r,10)),r<100||r>999)?e:r}var zn=typeof setImmediate>"u"?r=>r():setImmediate;function bs(r,e,t){return t&&Hn(r,t),new Promise(s=>{zn(()=>{r.handled||r.node.res.end(e),s();});})}function Hn(r,e){e&&r.node.res.statusCode!==304&&!r.node.res.getHeader("content-type")&&r.node.res.setHeader("content-type",e);}function Gn(r,e){for(let[t,s]of Object.entries(e))r.node.res.setHeader(t,s);}var Ps=Gn;var rt=(s=>(s.TRIGGER="trigger",s.EXECUTE="execute",s.PREVIEW="preview",s))(rt||{}),st=(s=>(s.DISCOVER="discover",s.HEALTH_CHECK="health-check",s.CODE="code",s))(st||{});var q=(E=>(E.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",E.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",E.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",E.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",E.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",E.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",E.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",E.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",E.STEP_NOT_FOUND_ERROR="StepNotFoundError",E.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",E.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",E.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",E.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",E.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",E.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",E.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",E.INVALID_ACTION_ERROR="InvalidActionError",E.MISSING_API_KEY_ERROR="MissingApiKeyError",E.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",E.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",E.SIGNATURE_INVALID_ERROR="SignatureInvalidError",E.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",E.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",E.PLATFORM_ERROR="PlatformError",E.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",E))(q||{});var nt=(s=>(s.POST="POST",s.GET="GET",s.OPTIONS="OPTIONS",s))(nt||{});var H=class extends Error{data},ot=class extends H{statusCode=404},Z=class extends H{statusCode=400},Q=class extends H{statusCode=401},Ae=class extends H{statusCode=500},at=class extends H{statusCode=409};var it=class extends Z{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};}},Fe=class extends Z{code="ExecutionEventPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct event payload.`),this.data=t;}},dt=class extends Z{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},ct=class extends Z{code="ExecutionStateControlInvalidError";constructor(e,t,s){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid \`controls\`. Please provide the correct step controls.`),this.data=s;}},ut=class extends Z{code="ExecutionStateOutputInvalidError";constructor(e,t,s){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid output. Please provide the correct step output.`),this.data=s;}},lt=class extends Z{code="ExecutionStateResultInvalidError";constructor(e,t,s){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid result. Please provide the correct step result.`),this.data=s;}},ft=class extends Z{code="ExecutionProviderOutputInvalidError";constructor(e,t,s,n){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` and provider with id: \`${s}\` has invalid output. Please provide the correct provider output.`),this.data=n;}};var b={info:r=>Ce__default.default.blue(r),warning:r=>Ce__default.default.yellow(r),error:r=>Ce__default.default.red(r),success:r=>Ce__default.default.green(r),underline:r=>Ce__default.default.underline(r),bold:r=>Ce__default.default.bold(r)},A={SUCCESS:b.success("\u2714"),ERROR:b.error("\u2717"),WARNING:b.warning("\u26A0"),INFO:b.info("\u2139"),ARROW:b.bold("\u2192"),MOCK:b.info("\u25CB"),HYDRATED:b.bold(b.info("\u2192")),STEP:b.info("\u03C3"),ACTION:b.info("\u03B1"),DURATION:b.info("\u0394"),PROVIDER:b.info("\u2699"),OUTPUT:b.info("\u21E2"),INPUT:b.info("\u21E0"),WORKFLOW:b.info("\u03C9"),STATE:b.info("\u03C3"),EXECUTE:b.info("\u03B5"),PREVIEW:b.info("\u03C1")};var Cr=r=>Object.values(r).map(e=>`\`${e}\``).join(", "),pt=r=>r.replaceAll(/(\w)(\w*)/g,(e,t,s)=>t.toUpperCase()+s.toLowerCase()).replaceAll(/[\s-]+/g,"");var Cs=(r,e="https://api.novu.co")=>{let t=process.env.NOVU_API_URL||e;return {post:async(s,n)=>(await fetch(t+"/v1"+s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${r}`},body:JSON.stringify(n)})).json()}};var ht=class extends H{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${Cr(nt)}`},We=class extends Z{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${Cr(t)}`);}};var mt=class extends Ae{code="PlatformError";message="Something went wrong. Please try again later."};var Be=class extends at{constructor(e,t){super(`${pt(e)} with id: \`${t}\` already exists. Please use a different id.`);}},ee=class extends ot{constructor(e,t){super(`${pt(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},Se=class extends Ae{constructor(e,t){super(`Failed to execute ${pt(e)} with id: \`${t}\`. Please try again later.`);}};var yt=class extends ee{code="ProviderNotFoundError";constructor(e){super("provider",e);}},_t=class extends Se{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var gt=class extends Q{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.");}},vt=class extends Q{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},wt=class extends Q{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},Tt=class extends Q{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},Rt=class extends Q{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.apiKey`");}};var Ot=class extends ee{code="StepNotFoundError";constructor(e){super("step",e);}};var Ke=class extends ee{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},xt=class extends Be{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var It=class{ajv;compiledSchemas;constructor(){this.ajv=new Xn__default.default({useDefaults:!0,removeAdditional:"all"}),Qn__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 s=this.compiledSchemas.get(t);return s||(s=this.ajv.compile(t),this.compiledSchemas.set(t,s)),s(e)?{success:!0,data:e}:{success:!1,errors:s.errors.map(o=>({path:o.instancePath,message:o.message}))}}transformToJsonSchema(e){return e}};var yr=class{isSchema(e){return e.safeParseAsync!==void 0}async validate(e,t){let s=t.safeParse(e);return s.success?{success:!0,data:s.data}:{success:!1,errors:s.error.errors.map(n=>({path:`/${n.path.join("/")}`,message:n.message}))}}transformToJsonSchema(e){try{return mn().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 yn=[new yr,new It],_n=async(r,e)=>{for(let t of yn)if(t.isSchema(r))return t.validate(e,r);throw new Error("Invalid schema")},gn=r=>{for(let e of yn)if(e.isSchema(r))return e.transformToJsonSchema(r);throw new Error("Invalid schema")};var vn={name:"@novu/framework",version:"0.24.3-alpha.11",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",zod:"^3.23.0","zod-to-json-schema":"^3.23.0"},dependencies:{"@novu/shared":"0.24.2",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 tt=vn.version,_r="2024-06-26";jsonSchemaFaker.JSONSchemaFaker.random.shuffle=function(){return ["[placeholder]"]};jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});var vr=class{discoveredWorkflows=[];templateEngine=new liquidjs.Liquid;apiKey;version=tt;strictAuthentication;constructor(e){let t=this.buildOptions(e);this.apiKey=t.apiKey,this.strictAuthentication=t.strictAuthentication;}buildOptions(e){let t={apiKey:void 0,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?.strictAuthentication!==void 0?t.strictAuthentication=e.strictAuthentication:process.env.NODE_ENV==="development"&&(t.strictAuthentication=!1),t}addWorkflows(e){for(let t of e){if(this.discoveredWorkflows.some(s=>s.workflowId===t.workflowId))throw new xt(t.workflowId);this.discoveredWorkflows.push(t);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((s,n)=>s+n.steps.length,0);return {status:"ok",sdkVersion:tt,frameworkVersion:_r,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(s=>s.workflowId===e);if(t)return t;throw new Ke(e)}getStep(e,t){let n=this.getWorkflow(e).steps.find(o=>o.stepId===t);if(n)return n;throw new Ot(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(gn(e))}async validate(e,t,s,n,o,a,i){let u=await _n(t,e);if(u.success)return u.data;switch(s){case"event":this.throwInvalidEvent(n,o,u.errors);case"step":this.throwInvalidStep(a,n,o,u.errors);case"provider":this.throwInvalidProvider(a,i,n,o,u.errors);default:throw new Error(`Invalid component: '${s}'`)}}throwInvalidProvider(e,t,s,n,o){if(!e)throw new Error("stepId is required");if(!t)throw new Error("providerId is required");switch(s){case"output":throw new ft(n,e,t,o);default:throw new Error(`Invalid payload type: '${s}'`)}}throwInvalidStep(e,t,s,n){if(!e)throw new Error("stepId is required");switch(t){case"output":throw new ut(s,e,n);case"result":throw new lt(s,e,n);case"controls":throw new ct(s,e,n);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(e,t,s){switch(e){case"controls":throw new dt(t,s);case"payload":throw new Fe(t,s);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(s,n,o)=>{let a=this.getStep(e.workflowId,s),i=ed(e),u=await this.createStepControls(a,i),l=e.action==="preview";if(!l&&await this.shouldSkip(o?.skip,u))return t({options:{skip:!0}}),{};let h=this.previewStep.bind(this),x=this.executeStep.bind(this),X=await(l?h:x)(e,{...a,providers:a.providers.map(Pe=>{let Ve=o?.providers?.[Pe.type];if(!Ve)throw new yt(Pe.type);return {...Pe,resolve:Ve}}),resolve:n});return s===e.stepId&&t(X),X.outputs}}async shouldSkip(e,t){return e?e(t):!1}async executeWorkflow(e){let n=`${{execute:"Executing",preview:"Previewing"}[e.action]} workflowId:`;console.log(`
|
|
23
23
|
${b.bold(b.underline(n))} '${e.workflowId}'`);let o=this.getWorkflow(e.workflowId),a=process.hrtime(),i={outputs:{},providers:{},options:{}},u,l=new Promise(de=>{u=de;}),h=de=>{u(),i=de;},x;try{if(e.action==="execute"&&!e.payload&&!e.data)throw new Fe(e.workflowId,{message:"Event `payload` is required"});let de=await this.createExecutionPayload(e,o);await Promise.race([l,o.execute({payload:de,environment:{},inputs:{},controls:{},subscriber:e.subscriber,step:{email:this.executeStepFactory(e,h),sms:this.executeStepFactory(e,h),inApp:this.executeStepFactory(e,h),digest:this.executeStepFactory(e,h),delay:this.executeStepFactory(e,h),push:this.executeStepFactory(e,h),chat:this.executeStepFactory(e,h),custom:this.executeStepFactory(e,h)}})]);}catch(de){x=de;}let L=process.hrtime(a),X=L[0],Pe=L[1],Ve=X*1e3+Pe/1e6,wn=x?A.ERROR:A.SUCCESS,Tn=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action";if(console.log(`${wn} ${Tn} workflowId: \`${e.workflowId}\``),this.prettyPrintExecute(e,Ve,x),x)throw x;return {outputs:i.outputs,providers:i.providers,options:i.options,metadata:{status:"success",error:!1,duration:Ve}}}async createExecutionPayload(e,t){let s=e.payload||e.data;if(e.action==="preview"){let o=this.mock(t.payload.schema);s=Object.assign(o,s);}return await this.validate(s,t.payload.unknownSchema,"event","payload",e.workflowId)}prettyPrintExecute(e,t,s){let n=s?A.ERROR:A.SUCCESS,o=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action",a=s?"Failed to execute":o,i=s?b.error:b.success,u=`${n} ${a} workflowId: '${e.workflowId}`;console.log(`
|
|
24
24
|
${b.bold(i(u))}'`),console.log(` \u251C ${A.STEP} stepId: '${e.stepId}'`),console.log(` \u251C ${A.ACTION} action: '${e.action}'`),console.log(` \u2514 ${A.DURATION} duration: '${t.toFixed(2)}ms'
|
|
25
25
|
`);}async executeProviders(e,t,s){return t.providers.reduce(async(n,o)=>{let a=await n,i=this.previewProvider.bind(this),u=this.executeProvider.bind(this),h=await(e.action==="preview"?i:u)(e,t,o,s);return {...a,[o.type]:h}},Promise.resolve({}))}previewProvider(e,t,s,n){return console.log(` ${A.MOCK} Mocked provider: \`${s.type}\``),this.mock(s.outputs.schema)}async executeProvider(e,t,s,n){let o=gr__default.default({indent:2}).start(`Executing provider: \`${s.type}\``);try{if(e.stepId===t.stepId){let a=await this.createStepControls(t,e),i=await s.resolve({controls:a,outputs:n}),u=await this.validate(i,s.outputs.unknownSchema,"step","output",e.workflowId,t.stepId,s.type);return o.succeed(`Executed provider: \`${s.type}\``),u}else o.stopAndPersist({symbol:A.HYDRATED,text:`Hydrated provider: \`${s.type}\``});}catch(a){throw o.stopAndPersist({symbol:A.ERROR,text:`Failed to execute provider: \`${s.type}\``}),new _t(`Failed to execute provider: '${s.type}'.
|
package/dist/index.js
CHANGED
|
@@ -19,7 +19,7 @@ var b=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var Nt=b(G=>{Objec
|
|
|
19
19
|
]))`;continue}else if(n[d]==="$"){r+=`($|(?=[\r
|
|
20
20
|
]))`;continue}}if(t.s&&n[d]==="."){r+=o?`${n[d]}\r
|
|
21
21
|
`:`[${n[d]}\r
|
|
22
|
-
]`;continue}r+=n[d],n[d]==="\\"?s=!0:o&&n[d]==="]"?o=!1:!o&&n[d]==="["&&(o=!0);}try{let d=new RegExp(r);}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),i.source}return r};});var oi=b(si=>{Object.defineProperty(si,"__esModule",{value:!0});si.parseRecordDef=void 0;var Ji=Ft(),Xn=D(),bo=ri();function vo(i,e){if(e.target==="openApi3"&&i.keyType?._def.typeName===Ji.ZodFirstPartyTypeKind.ZodEnum)return {type:"object",required:i.keyType._def.values,properties:i.keyType._def.values.reduce((n,r)=>({...n,[r]:(0, Xn.parseDef)(i.valueType._def,{...e,currentPath:[...e.currentPath,"properties",r]})??{}}),{}),additionalProperties:!1};let t={type:"object",additionalProperties:(0, Xn.parseDef)(i.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return t;if(i.keyType?._def.typeName===Ji.ZodFirstPartyTypeKind.ZodString&&i.keyType._def.checks?.length){let n=Object.entries((0, bo.parseStringDef)(i.keyType._def,e)).reduce((r,[s,o])=>s==="type"?r:{...r,[s]:o},{});return {...t,propertyNames:n}}else if(i.keyType?._def.typeName===Ji.ZodFirstPartyTypeKind.ZodEnum)return {...t,propertyNames:{enum:i.keyType._def.values}};return t}si.parseRecordDef=vo;});var Xi=b(ai=>{Object.defineProperty(ai,"__esModule",{value:!0});ai.parseMapDef=void 0;var Qn=D(),To=oi();function xo(i,e){if(e.mapStrategy==="record")return (0, To.parseRecordDef)(i,e);let t=(0, Qn.parseDef)(i.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=(0, Qn.parseDef)(i.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return {type:"array",maxItems:125,items:{type:"array",items:[t,n],minItems:2,maxItems:2}}}ai.parseMapDef=xo;});var Qi=b(ci=>{Object.defineProperty(ci,"__esModule",{value:!0});ci.parseNativeEnumDef=void 0;function wo(i){let e=i.values,n=Object.keys(i.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),r=Array.from(new Set(n.map(s=>typeof s)));return {type:r.length===1?r[0]==="string"?"string":"number":["string","number"],enum:n}}ci.parseNativeEnumDef=wo;});var Hi=b(li=>{Object.defineProperty(li,"__esModule",{value:!0});li.parseNeverDef=void 0;function ko(){return {not:{}}}li.parseNeverDef=ko;});var en=b(di=>{Object.defineProperty(di,"__esModule",{value:!0});di.parseNullDef=void 0;function Oo(i){return i.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}di.parseNullDef=Oo;});var ui=b(ue=>{Object.defineProperty(ue,"__esModule",{value:!0});ue.parseUnionDef=ue.primitiveMappings=void 0;var So=D();ue.primitiveMappings={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Ao(i,e){if(e.target==="openApi3")return Hn(i,e);let t=i.options instanceof Map?Array.from(i.options.values()):i.options;if(t.every(n=>n._def.typeName in ue.primitiveMappings&&(!n._def.checks||!n._def.checks.length))){let n=t.reduce((r,s)=>{let o=ue.primitiveMappings[s._def.typeName];return o&&!r.includes(o)?[...r,o]:r},[]);return {type:n.length>1?n:n[0]}}else if(t.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=t.reduce((r,s)=>{let o=typeof s._def.value;switch(o){case"string":case"number":case"boolean":return [...r,o];case"bigint":return [...r,"integer"];case"object":if(s._def.value===null)return [...r,"null"];case"symbol":case"undefined":case"function":default:return r}},[]);if(n.length===t.length){let r=n.filter((s,o,a)=>a.indexOf(s)===o);return {type:r.length>1?r:r[0],enum:t.reduce((s,o)=>s.includes(o._def.value)?s:[...s,o._def.value],[])}}}else if(t.every(n=>n._def.typeName==="ZodEnum"))return {type:"string",enum:t.reduce((n,r)=>[...n,...r._def.values.filter(s=>!n.includes(s))],[])};return Hn(i,e)}ue.parseUnionDef=Ao;var Hn=(i,e)=>{let t=(i.options instanceof Map?Array.from(i.options.values()):i.options).map((n,r)=>(0, So.parseDef)(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${r}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return t.length?{anyOf:t}:void 0};});var tn=b(pi=>{Object.defineProperty(pi,"__esModule",{value:!0});pi.parseNullableDef=void 0;var er=D(),tr=ui();function Io(i,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(i.innerType._def.typeName)&&(!i.innerType._def.checks||!i.innerType._def.checks.length))return e.target==="openApi3"?{type:tr.primitiveMappings[i.innerType._def.typeName],nullable:!0}:{type:[tr.primitiveMappings[i.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=(0, er.parseDef)(i.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let t=(0, er.parseDef)(i.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}pi.parseNullableDef=Io;});var nn=b(hi=>{Object.defineProperty(hi,"__esModule",{value:!0});hi.parseNumberDef=void 0;var pe=oe();function Po(i,e){let t={type:"number"};if(!i.checks)return t;for(let n of i.checks)switch(n.kind){case"int":t.type="integer",(0, pe.addErrorMessage)(t,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?(0, pe.setResponseValueAndErrors)(t,"minimum",n.value,n.message,e):(0, pe.setResponseValueAndErrors)(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),(0, pe.setResponseValueAndErrors)(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?(0, pe.setResponseValueAndErrors)(t,"maximum",n.value,n.message,e):(0, pe.setResponseValueAndErrors)(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),(0, pe.setResponseValueAndErrors)(t,"maximum",n.value,n.message,e));break;case"multipleOf":(0, pe.setResponseValueAndErrors)(t,"multipleOf",n.value,n.message,e);break}return t}hi.parseNumberDef=Po;});var sn=b(Be=>{Object.defineProperty(Be,"__esModule",{value:!0});Be.parseObjectDef=Be.parseObjectDefX=void 0;var rt=D();function rn(i,e){return e.removeAdditionalStrategy==="strict"?i.catchall._def.typeName==="ZodNever"?i.unknownKeys!=="strict":(0, rt.parseDef)(i.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:i.catchall._def.typeName==="ZodNever"?i.unknownKeys==="passthrough":(0, rt.parseDef)(i.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function Ro(i,e){Object.keys(i.shape()).reduce((n,r)=>{let s=i.shape()[r],o=s.isOptional();o||(s={...s._def.innerSchema});let a=(0, rt.parseDef)(s._def,{...e,currentPath:[...e.currentPath,"properties",r],propertyPath:[...e.currentPath,"properties",r]});return a!==void 0&&(n.properties[r]=a,o||(n.required||(n.required=[]),n.required.push(r))),n},{type:"object",properties:{},additionalProperties:rn(i,e)});let t={type:"object",...Object.entries(i.shape()).reduce((n,[r,s])=>{if(s===void 0||s._def===void 0)return n;let o=(0, rt.parseDef)(s._def,{...e,currentPath:[...e.currentPath,"properties",r],propertyPath:[...e.currentPath,"properties",r]});return o===void 0?n:{properties:{...n.properties,[r]:o},required:s.isOptional()?n.required:[...n.required,r]}},{properties:{},required:[]}),additionalProperties:rn(i,e)};return t.required.length||delete t.required,t}Be.parseObjectDefX=Ro;function Eo(i,e){let t={type:"object",...Object.entries(i.shape()).reduce((n,[r,s])=>{if(s===void 0||s._def===void 0)return n;let o=(0, rt.parseDef)(s._def,{...e,currentPath:[...e.currentPath,"properties",r],propertyPath:[...e.currentPath,"properties",r]});return o===void 0?n:{properties:{...n.properties,[r]:o},required:s.isOptional()?n.required:[...n.required,r]}},{properties:{},required:[]}),additionalProperties:rn(i,e)};return t.required.length||delete t.required,t}Be.parseObjectDef=Eo;});var on=b(fi=>{Object.defineProperty(fi,"__esModule",{value:!0});fi.parseOptionalDef=void 0;var ir=D(),Do=(i,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return (0, ir.parseDef)(i.innerType._def,e);let t=(0, ir.parseDef)(i.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:{}},t]}:{}};fi.parseOptionalDef=Do;});var an=b(yi=>{Object.defineProperty(yi,"__esModule",{value:!0});yi.parsePipelineDef=void 0;var mi=D(),Co=(i,e)=>{if(e.pipeStrategy==="input")return (0, mi.parseDef)(i.in._def,e);if(e.pipeStrategy==="output")return (0, mi.parseDef)(i.out._def,e);let t=(0, mi.parseDef)(i.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=(0, mi.parseDef)(i.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return {allOf:[t,n].filter(r=>r!==void 0)}};yi.parsePipelineDef=Co;});var cn=b(_i=>{Object.defineProperty(_i,"__esModule",{value:!0});_i.parsePromiseDef=void 0;var jo=D();function No(i,e){return (0, jo.parseDef)(i.type._def,e)}_i.parsePromiseDef=No;});var ln=b(gi=>{Object.defineProperty(gi,"__esModule",{value:!0});gi.parseSetDef=void 0;var nr=oe(),Mo=D();function Zo(i,e){let n={type:"array",uniqueItems:!0,items:(0, Mo.parseDef)(i.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return i.minSize&&(0, nr.setResponseValueAndErrors)(n,"minItems",i.minSize.value,i.minSize.message,e),i.maxSize&&(0, nr.setResponseValueAndErrors)(n,"maxItems",i.maxSize.value,i.maxSize.message,e),n}gi.parseSetDef=Zo;});var un=b(bi=>{Object.defineProperty(bi,"__esModule",{value:!0});bi.parseTupleDef=void 0;var dn=D();function $o(i,e){return i.rest?{type:"array",minItems:i.items.length,items:i.items.map((t,n)=>(0, dn.parseDef)(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[]),additionalItems:(0, dn.parseDef)(i.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:i.items.length,maxItems:i.items.length,items:i.items.map((t,n)=>(0, dn.parseDef)(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[])}}bi.parseTupleDef=$o;});var pn=b(vi=>{Object.defineProperty(vi,"__esModule",{value:!0});vi.parseUndefinedDef=void 0;function Uo(){return {not:{}}}vi.parseUndefinedDef=Uo;});var hn=b(Ti=>{Object.defineProperty(Ti,"__esModule",{value:!0});Ti.parseUnknownDef=void 0;function qo(){return {}}Ti.parseUnknownDef=qo;});var fn=b(xi=>{Object.defineProperty(xi,"__esModule",{value:!0});xi.parseReadonlyDef=void 0;var Vo=D(),Lo=(i,e)=>(0, Vo.parseDef)(i.innerType._def,e);xi.parseReadonlyDef=Lo;});var D=b(wi=>{Object.defineProperty(wi,"__esModule",{value:!0});wi.parseDef=void 0;var w=Ft(),Yo=$i(),Fo=Ui(),Wo=qi(),Bo=Vi(),Ko=Li(),zo=Yi(),Go=Fi(),Jo=Wi(),Xo=Bi(),Qo=Ki(),Ho=zi(),ea=Gi(),ta=Xi(),ia=Qi(),na=Hi(),ra=en(),sa=tn(),oa=nn(),aa=sn(),ca=on(),la=an(),da=cn(),ua=oi(),pa=ln(),ha=ri(),fa=un(),ma=pn(),ya=ui(),_a=hn(),ga=fn(),ba=Nt();function rr(i,e,t=!1){let n=e.seen.get(i);if(e.override){let o=e.override?.(i,e,n,t);if(o!==ba.ignoreOverride)return o}if(n&&!t){let o=va(n,e);if(o!==void 0)return o}let r={def:i,path:e.currentPath,jsonSchema:void 0};e.seen.set(i,r);let s=xa(i,i.typeName,e);return s&&wa(i,e,s),r.jsonSchema=s,s}wi.parseDef=rr;var va=(i,e)=>{switch(e.$refStrategy){case"root":return {$ref:i.path.join("/")};case"relative":return {$ref:Ta(e.currentPath,i.path)};case"none":case"seen":return i.path.length<e.currentPath.length&&i.path.every((t,n)=>e.currentPath[n]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},Ta=(i,e)=>{let t=0;for(;t<i.length&&t<e.length&&i[t]===e[t];t++);return [(i.length-t).toString(),...e.slice(t)].join("/")},xa=(i,e,t)=>{switch(e){case w.ZodFirstPartyTypeKind.ZodString:return (0, ha.parseStringDef)(i,t);case w.ZodFirstPartyTypeKind.ZodNumber:return (0, oa.parseNumberDef)(i,t);case w.ZodFirstPartyTypeKind.ZodObject:return (0, aa.parseObjectDef)(i,t);case w.ZodFirstPartyTypeKind.ZodBigInt:return (0, Wo.parseBigintDef)(i,t);case w.ZodFirstPartyTypeKind.ZodBoolean:return (0, Bo.parseBooleanDef)();case w.ZodFirstPartyTypeKind.ZodDate:return (0, Go.parseDateDef)(i,t);case w.ZodFirstPartyTypeKind.ZodUndefined:return (0, ma.parseUndefinedDef)();case w.ZodFirstPartyTypeKind.ZodNull:return (0, ra.parseNullDef)(t);case w.ZodFirstPartyTypeKind.ZodArray:return (0, Fo.parseArrayDef)(i,t);case w.ZodFirstPartyTypeKind.ZodUnion:case w.ZodFirstPartyTypeKind.ZodDiscriminatedUnion:return (0, ya.parseUnionDef)(i,t);case w.ZodFirstPartyTypeKind.ZodIntersection:return (0, Ho.parseIntersectionDef)(i,t);case w.ZodFirstPartyTypeKind.ZodTuple:return (0, fa.parseTupleDef)(i,t);case w.ZodFirstPartyTypeKind.ZodRecord:return (0, ua.parseRecordDef)(i,t);case w.ZodFirstPartyTypeKind.ZodLiteral:return (0, ea.parseLiteralDef)(i,t);case w.ZodFirstPartyTypeKind.ZodEnum:return (0, Qo.parseEnumDef)(i);case w.ZodFirstPartyTypeKind.ZodNativeEnum:return (0, ia.parseNativeEnumDef)(i);case w.ZodFirstPartyTypeKind.ZodNullable:return (0, sa.parseNullableDef)(i,t);case w.ZodFirstPartyTypeKind.ZodOptional:return (0, ca.parseOptionalDef)(i,t);case w.ZodFirstPartyTypeKind.ZodMap:return (0, ta.parseMapDef)(i,t);case w.ZodFirstPartyTypeKind.ZodSet:return (0, pa.parseSetDef)(i,t);case w.ZodFirstPartyTypeKind.ZodLazy:return rr(i.getter()._def,t);case w.ZodFirstPartyTypeKind.ZodPromise:return (0, da.parsePromiseDef)(i,t);case w.ZodFirstPartyTypeKind.ZodNaN:case w.ZodFirstPartyTypeKind.ZodNever:return (0, na.parseNeverDef)();case w.ZodFirstPartyTypeKind.ZodEffects:return (0, Xo.parseEffectsDef)(i,t);case w.ZodFirstPartyTypeKind.ZodAny:return (0, Yo.parseAnyDef)();case w.ZodFirstPartyTypeKind.ZodUnknown:return (0, _a.parseUnknownDef)();case w.ZodFirstPartyTypeKind.ZodDefault:return (0, Jo.parseDefaultDef)(i,t);case w.ZodFirstPartyTypeKind.ZodBranded:return (0, Ko.parseBrandedDef)(i,t);case w.ZodFirstPartyTypeKind.ZodReadonly:return (0, ga.parseReadonlyDef)(i,t);case w.ZodFirstPartyTypeKind.ZodCatch:return (0, zo.parseCatchDef)(i,t);case w.ZodFirstPartyTypeKind.ZodPipeline:return (0, la.parsePipelineDef)(i,t);case w.ZodFirstPartyTypeKind.ZodFunction:case w.ZodFirstPartyTypeKind.ZodVoid:case w.ZodFirstPartyTypeKind.ZodSymbol:return;default:return (n=>{})()}},wa=(i,e,t)=>(i.description&&(t.description=i.description,e.markdownDescription&&(t.markdownDescription=i.description)),t);});var mn=b(ki=>{Object.defineProperty(ki,"__esModule",{value:!0});ki.zodToJsonSchema=void 0;var sr=D(),ka=Ri(),Oa=(i,e)=>{let t=(0, ka.getRefs)(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((d,[p,y])=>({...d,[p]:(0, sr.parseDef)(y._def,{...t,currentPath:[...t.basePath,t.definitionPath,p]},!0)??{}}),{}):void 0,r=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=(0, sr.parseDef)(i._def,r===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,r]},!1)??{},o=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;o!==void 0&&(s.title=o);let a=r===void 0?n?{...s,[t.definitionPath]:n}:s:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,r].join("/"),[t.definitionPath]:{...n,[r]:s}};return t.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":t.target==="jsonSchema2019-09"&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),a};ki.zodToJsonSchema=Oa;});var or=b(x=>{var Sa=x&&x.__createBinding||(Object.create?function(i,e,t,n){n===void 0&&(n=t);var r=Object.getOwnPropertyDescriptor(e,t);(!r||("get"in r?!e.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(i,n,r);}:function(i,e,t,n){n===void 0&&(n=t),i[n]=e[t];}),k=x&&x.__exportStar||function(i,e){for(var t in i)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Sa(e,i,t);};Object.defineProperty(x,"__esModule",{value:!0});k(Nt(),x);k(Ri(),x);k(oe(),x);k(D(),x);k($i(),x);k(Ui(),x);k(qi(),x);k(Vi(),x);k(Li(),x);k(Yi(),x);k(Fi(),x);k(Wi(),x);k(Bi(),x);k(Ki(),x);k(zi(),x);k(Gi(),x);k(Xi(),x);k(Qi(),x);k(Hi(),x);k(en(),x);k(tn(),x);k(nn(),x);k(sn(),x);k(on(),x);k(an(),x);k(cn(),x);k(fn(),x);k(oi(),x);k(ln(),x);k(ri(),x);k(un(),x);k(pn(),x);k(ui(),x);k(hn(),x);k(mn(),x);var Aa=mn();x.default=Aa.zodToJsonSchema;});var at=(n=>(n.TRIGGER="trigger",n.EXECUTE="execute",n.PREVIEW="preview",n))(at||{}),ct=(n=>(n.DISCOVER="discover",n.HEALTH_CHECK="health-check",n.CODE="code",n))(ct||{});var Sr=(t=>(t.SYNC="/v1/bridge/sync",t.DIFF="/v1/bridge/diff",t))(Sr||{}),vn=5,Tn=1500;var F=(P=>(P.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",P.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",P.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",P.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",P.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",P.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",P.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",P.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",P.STEP_NOT_FOUND_ERROR="StepNotFoundError",P.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",P.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",P.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",P.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",P.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",P.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",P.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",P.INVALID_ACTION_ERROR="InvalidActionError",P.MISSING_API_KEY_ERROR="MissingApiKeyError",P.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",P.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",P.SIGNATURE_INVALID_ERROR="SignatureInvalidError",P.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",P.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",P.PLATFORM_ERROR="PlatformError",P.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",P))(F||{});var Ii=(R=>(R.NOVU_SIGNATURE="novu-signature",R.NOVU_ANONYMOUS="novu-anonymous",R.NOVU_SIGNATURE_DEPRECATED="x-novu-signature",R.NOVU_ANONYMOUS_DEPRECATED="x-novu-anonymous",R.NOVU_FRAMEWORK_SDK="novu-framework-sdk",R.NOVU_FRAMEWORK_API="novu-framework-api",R.NOVU_FRAMEWORK_VERSION="novu-framework-version",R.USER_AGENT="user-agent",R.CONTENT_TYPE="content-type",R.ACCESS_CONTROL_ALLOW_ORIGIN="access-control-allow-origin",R.ACCESS_CONTROL_ALLOW_METHODS="access-control-allow-methods",R.ACCESS_CONTROL_ALLOW_HEADERS="access-control-allow-headers",R.ACCESS_CONTROL_MAX_AGE="access-control-max-age",R))(Ii||{});var lt=(n=>(n.POST="POST",n.GET="GET",n.OPTIONS="OPTIONS",n))(lt||{});var xn=(r=>(r.WORKFLOW_ID="workflowId",r.STEP_ID="stepId",r.ACTION="action",r.SOURCE="source",r))(xn||{});var dt=(u=>(u[u.CONTINUE=100]="CONTINUE",u[u.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",u[u.PROCESSING=102]="PROCESSING",u[u.EARLYHINTS=103]="EARLYHINTS",u[u.OK=200]="OK",u[u.CREATED=201]="CREATED",u[u.ACCEPTED=202]="ACCEPTED",u[u.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",u[u.NO_CONTENT=204]="NO_CONTENT",u[u.RESET_CONTENT=205]="RESET_CONTENT",u[u.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",u[u.AMBIGUOUS=300]="AMBIGUOUS",u[u.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",u[u.FOUND=302]="FOUND",u[u.SEE_OTHER=303]="SEE_OTHER",u[u.NOT_MODIFIED=304]="NOT_MODIFIED",u[u.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",u[u.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",u[u.BAD_REQUEST=400]="BAD_REQUEST",u[u.UNAUTHORIZED=401]="UNAUTHORIZED",u[u.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",u[u.FORBIDDEN=403]="FORBIDDEN",u[u.NOT_FOUND=404]="NOT_FOUND",u[u.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",u[u.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",u[u.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",u[u.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",u[u.CONFLICT=409]="CONFLICT",u[u.GONE=410]="GONE",u[u.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",u[u.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",u[u.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",u[u.URI_TOO_LONG=414]="URI_TOO_LONG",u[u.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",u[u.REQUESTED_RANGE_NOT_SATISFIABLE=416]="REQUESTED_RANGE_NOT_SATISFIABLE",u[u.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",u[u.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",u[u.MISDIRECTED=421]="MISDIRECTED",u[u.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",u[u.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",u[u.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",u[u.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",u[u.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",u[u.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",u[u.BAD_GATEWAY=502]="BAD_GATEWAY",u[u.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",u[u.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",u[u.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",u))(dt||{}),pc=[500];var ut=(n=>(n.WORKFLOW="workflow",n.PROVIDER="provider",n.STEP="step",n))(ut||{});var pt=(s=>(s.EMAIL="email",s.SMS="sms",s.PUSH="push",s.CHAT="chat",s.IN_APP="in_app",s))(pt||{}),Ar=(n=>(n.DIGEST="digest",n.DELAY="delay",n.CUSTOM="custom",n))(Ar||{});var H=class extends Error{data},ht=class extends H{statusCode=404},q=class extends H{statusCode=400},re=class extends H{statusCode=401},je=class extends H{statusCode=500},ft=class extends H{statusCode=409};var mt=class extends q{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};}},ze=class extends q{code="ExecutionEventPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct event payload.`),this.data=t;}},yt=class extends q{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},_t=class extends q{code="ExecutionStateControlInvalidError";constructor(e,t,n){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid \`controls\`. Please provide the correct step controls.`),this.data=n;}},gt=class extends q{code="ExecutionStateOutputInvalidError";constructor(e,t,n){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid output. Please provide the correct step output.`),this.data=n;}},bt=class extends q{code="ExecutionStateResultInvalidError";constructor(e,t,n){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid result. Please provide the correct step result.`),this.data=n;}},vt=class extends q{code="ExecutionProviderOutputInvalidError";constructor(e,t,n,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` and provider with id: \`${n}\` has invalid output. Please provide the correct provider output.`),this.data=r;}};var A={info:i=>Ne__default.default.blue(i),warning:i=>Ne__default.default.yellow(i),error:i=>Ne__default.default.red(i),success:i=>Ne__default.default.green(i),underline:i=>Ne__default.default.underline(i),bold:i=>Ne__default.default.bold(i)},E={SUCCESS:A.success("\u2714"),ERROR:A.error("\u2717"),WARNING:A.warning("\u26A0"),INFO:A.info("\u2139"),ARROW:A.bold("\u2192"),MOCK:A.info("\u25CB"),HYDRATED:A.bold(A.info("\u2192")),STEP:A.info("\u03C3"),ACTION:A.info("\u03B1"),DURATION:A.info("\u0394"),PROVIDER:A.info("\u2699"),OUTPUT:A.info("\u21E2"),INPUT:A.info("\u21E0"),WORKFLOW:A.info("\u03C9"),STATE:A.info("\u03C3"),EXECUTE:A.info("\u03B5"),PREVIEW:A.info("\u03C1")};var Pi=i=>Object.values(i).map(e=>`\`${e}\``).join(", "),Tt=i=>i.replaceAll(/(\w)(\w*)/g,(e,t,n)=>t.toUpperCase()+n.toLowerCase()).replaceAll(/[\s-]+/g,"");var wn=(i,e="https://api.novu.co/v1")=>({post:async(t,n)=>await fetch(e+t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${i}`},body:JSON.stringify(n)})});var xt=class extends H{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${Pi(lt)}`},Ge=class extends q{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${Pi(t)}`);}};var wt=class extends je{code="PlatformError";message="Something went wrong. Please try again later."};var Me=class extends ft{constructor(e,t){super(`${Tt(e)} with id: \`${t}\` already exists. Please use a different id.`);}},se=class extends ht{constructor(e,t){super(`${Tt(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},Ze=class extends je{constructor(e,t){super(`Failed to execute ${Tt(e)} with id: \`${t}\`. Please try again later.`);}};var kt=class extends se{code="ProviderNotFoundError";constructor(e){super("provider",e);}},Ot=class extends Ze{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var St=class extends re{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.");}},At=class extends re{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},It=class extends re{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},Pt=class extends re{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},Rt=class extends re{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.apiKey`");}};var Et=class extends se{code="StepNotFoundError";constructor(e){super("step",e);}},Dt=class extends Me{code="StepAlreadyExistsError";constructor(e){super("step",e);}};var Je=class extends se{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},Ct=class extends Me{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var jt=class{ajv;compiledSchemas;constructor(){this.ajv=new Ir__default.default({useDefaults:!0,removeAdditional:"all"}),Pr__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 n=this.compiledSchemas.get(t);return n||(n=this.ajv.compile(t),this.compiledSchemas.set(t,n)),n(e)?{success:!0,data:e}:{success:!1,errors:n.errors.map(s=>({path:s.instancePath,message:s.message}))}}transformToJsonSchema(e){return e}};var Oi=class{isSchema(e){return e.safeParseAsync!==void 0}async validate(e,t){let n=t.safeParse(e);return n.success?{success:!0,data:n.data}:{success:!1,errors:n.error.errors.map(r=>({path:`/${r.path.join("/")}`,message:r.message}))}}transformToJsonSchema(e){try{return or().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 ar=[new Oi,new jt],cr=async(i,e)=>{for(let t of ar)if(t.isSchema(i))return t.validate(e,i);throw new Error("Invalid schema")},C=i=>{for(let e of ar)if(e.isSchema(i))return e.transformToJsonSchema(i);throw new Error("Invalid schema")};var lr={name:"@novu/framework",version:"0.24.3-alpha.10",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",zod:"^3.23.0","zod-to-json-schema":"^3.23.0"},dependencies:{"@novu/shared":"0.24.2",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 st=lr.version,Si="2024-06-26";jsonSchemaFaker.JSONSchemaFaker.random.shuffle=function(){return ["[placeholder]"]};jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});var ot=class{discoveredWorkflows=[];templateEngine=new liquidjs.Liquid;apiKey;version=st;strictAuthentication;constructor(e){let t=this.buildOptions(e);this.apiKey=t.apiKey,this.strictAuthentication=t.strictAuthentication;}buildOptions(e){let t={apiKey:void 0,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?.strictAuthentication!==void 0?t.strictAuthentication=e.strictAuthentication:process.env.NODE_ENV==="development"&&(t.strictAuthentication=!1),t}addWorkflows(e){for(let t of e){if(this.discoveredWorkflows.some(n=>n.workflowId===t.workflowId))throw new Ct(t.workflowId);this.discoveredWorkflows.push(t);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((n,r)=>n+r.steps.length,0);return {status:"ok",sdkVersion:st,frameworkVersion:Si,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(n=>n.workflowId===e);if(t)return t;throw new Je(e)}getStep(e,t){let r=this.getWorkflow(e).steps.find(s=>s.stepId===t);if(r)return r;throw new Et(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(C(e))}async validate(e,t,n,r,s,o,a){let d=await cr(t,e);if(d.success)return d.data;switch(n){case"event":this.throwInvalidEvent(r,s,d.errors);case"step":this.throwInvalidStep(o,r,s,d.errors);case"provider":this.throwInvalidProvider(o,a,r,s,d.errors);default:throw new Error(`Invalid component: '${n}'`)}}throwInvalidProvider(e,t,n,r,s){if(!e)throw new Error("stepId is required");if(!t)throw new Error("providerId is required");switch(n){case"output":throw new vt(r,e,t,s);default:throw new Error(`Invalid payload type: '${n}'`)}}throwInvalidStep(e,t,n,r){if(!e)throw new Error("stepId is required");switch(t){case"output":throw new gt(n,e,r);case"result":throw new bt(n,e,r);case"controls":throw new _t(n,e,r);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(e,t,n){switch(e){case"controls":throw new yt(t,n);case"payload":throw new ze(t,n);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(n,r,s)=>{let o=this.getStep(e.workflowId,n),a=Ra(e),d=await this.createStepControls(o,a),p=e.action==="preview";if(!p&&await this.shouldSkip(s?.skip,d))return t({options:{skip:!0}}),{};let y=this.previewStep.bind(this),I=this.executeStep.bind(this),R=await(p?y:I)(e,{...o,providers:o.providers.map(Ce=>{let Ke=s?.providers?.[Ce.type];if(!Ke)throw new kt(Ce.type);return {...Ce,resolve:Ke}}),resolve:r});return n===e.stepId&&t(R),R.outputs}}async shouldSkip(e,t){return e?e(t):!1}async executeWorkflow(e){let r=`${{execute:"Executing",preview:"Previewing"}[e.action]} workflowId:`;console.log(`
|
|
22
|
+
]`;continue}r+=n[d],n[d]==="\\"?s=!0:o&&n[d]==="]"?o=!1:!o&&n[d]==="["&&(o=!0);}try{let d=new RegExp(r);}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),i.source}return r};});var oi=b(si=>{Object.defineProperty(si,"__esModule",{value:!0});si.parseRecordDef=void 0;var Ji=Ft(),Xn=D(),bo=ri();function vo(i,e){if(e.target==="openApi3"&&i.keyType?._def.typeName===Ji.ZodFirstPartyTypeKind.ZodEnum)return {type:"object",required:i.keyType._def.values,properties:i.keyType._def.values.reduce((n,r)=>({...n,[r]:(0, Xn.parseDef)(i.valueType._def,{...e,currentPath:[...e.currentPath,"properties",r]})??{}}),{}),additionalProperties:!1};let t={type:"object",additionalProperties:(0, Xn.parseDef)(i.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return t;if(i.keyType?._def.typeName===Ji.ZodFirstPartyTypeKind.ZodString&&i.keyType._def.checks?.length){let n=Object.entries((0, bo.parseStringDef)(i.keyType._def,e)).reduce((r,[s,o])=>s==="type"?r:{...r,[s]:o},{});return {...t,propertyNames:n}}else if(i.keyType?._def.typeName===Ji.ZodFirstPartyTypeKind.ZodEnum)return {...t,propertyNames:{enum:i.keyType._def.values}};return t}si.parseRecordDef=vo;});var Xi=b(ai=>{Object.defineProperty(ai,"__esModule",{value:!0});ai.parseMapDef=void 0;var Qn=D(),To=oi();function xo(i,e){if(e.mapStrategy==="record")return (0, To.parseRecordDef)(i,e);let t=(0, Qn.parseDef)(i.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=(0, Qn.parseDef)(i.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return {type:"array",maxItems:125,items:{type:"array",items:[t,n],minItems:2,maxItems:2}}}ai.parseMapDef=xo;});var Qi=b(ci=>{Object.defineProperty(ci,"__esModule",{value:!0});ci.parseNativeEnumDef=void 0;function wo(i){let e=i.values,n=Object.keys(i.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),r=Array.from(new Set(n.map(s=>typeof s)));return {type:r.length===1?r[0]==="string"?"string":"number":["string","number"],enum:n}}ci.parseNativeEnumDef=wo;});var Hi=b(li=>{Object.defineProperty(li,"__esModule",{value:!0});li.parseNeverDef=void 0;function ko(){return {not:{}}}li.parseNeverDef=ko;});var en=b(di=>{Object.defineProperty(di,"__esModule",{value:!0});di.parseNullDef=void 0;function Oo(i){return i.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}di.parseNullDef=Oo;});var ui=b(ue=>{Object.defineProperty(ue,"__esModule",{value:!0});ue.parseUnionDef=ue.primitiveMappings=void 0;var So=D();ue.primitiveMappings={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Ao(i,e){if(e.target==="openApi3")return Hn(i,e);let t=i.options instanceof Map?Array.from(i.options.values()):i.options;if(t.every(n=>n._def.typeName in ue.primitiveMappings&&(!n._def.checks||!n._def.checks.length))){let n=t.reduce((r,s)=>{let o=ue.primitiveMappings[s._def.typeName];return o&&!r.includes(o)?[...r,o]:r},[]);return {type:n.length>1?n:n[0]}}else if(t.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=t.reduce((r,s)=>{let o=typeof s._def.value;switch(o){case"string":case"number":case"boolean":return [...r,o];case"bigint":return [...r,"integer"];case"object":if(s._def.value===null)return [...r,"null"];case"symbol":case"undefined":case"function":default:return r}},[]);if(n.length===t.length){let r=n.filter((s,o,a)=>a.indexOf(s)===o);return {type:r.length>1?r:r[0],enum:t.reduce((s,o)=>s.includes(o._def.value)?s:[...s,o._def.value],[])}}}else if(t.every(n=>n._def.typeName==="ZodEnum"))return {type:"string",enum:t.reduce((n,r)=>[...n,...r._def.values.filter(s=>!n.includes(s))],[])};return Hn(i,e)}ue.parseUnionDef=Ao;var Hn=(i,e)=>{let t=(i.options instanceof Map?Array.from(i.options.values()):i.options).map((n,r)=>(0, So.parseDef)(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${r}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return t.length?{anyOf:t}:void 0};});var tn=b(pi=>{Object.defineProperty(pi,"__esModule",{value:!0});pi.parseNullableDef=void 0;var er=D(),tr=ui();function Io(i,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(i.innerType._def.typeName)&&(!i.innerType._def.checks||!i.innerType._def.checks.length))return e.target==="openApi3"?{type:tr.primitiveMappings[i.innerType._def.typeName],nullable:!0}:{type:[tr.primitiveMappings[i.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=(0, er.parseDef)(i.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let t=(0, er.parseDef)(i.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}pi.parseNullableDef=Io;});var nn=b(hi=>{Object.defineProperty(hi,"__esModule",{value:!0});hi.parseNumberDef=void 0;var pe=oe();function Po(i,e){let t={type:"number"};if(!i.checks)return t;for(let n of i.checks)switch(n.kind){case"int":t.type="integer",(0, pe.addErrorMessage)(t,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?(0, pe.setResponseValueAndErrors)(t,"minimum",n.value,n.message,e):(0, pe.setResponseValueAndErrors)(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),(0, pe.setResponseValueAndErrors)(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?(0, pe.setResponseValueAndErrors)(t,"maximum",n.value,n.message,e):(0, pe.setResponseValueAndErrors)(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),(0, pe.setResponseValueAndErrors)(t,"maximum",n.value,n.message,e));break;case"multipleOf":(0, pe.setResponseValueAndErrors)(t,"multipleOf",n.value,n.message,e);break}return t}hi.parseNumberDef=Po;});var sn=b(Be=>{Object.defineProperty(Be,"__esModule",{value:!0});Be.parseObjectDef=Be.parseObjectDefX=void 0;var rt=D();function rn(i,e){return e.removeAdditionalStrategy==="strict"?i.catchall._def.typeName==="ZodNever"?i.unknownKeys!=="strict":(0, rt.parseDef)(i.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:i.catchall._def.typeName==="ZodNever"?i.unknownKeys==="passthrough":(0, rt.parseDef)(i.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function Ro(i,e){Object.keys(i.shape()).reduce((n,r)=>{let s=i.shape()[r],o=s.isOptional();o||(s={...s._def.innerSchema});let a=(0, rt.parseDef)(s._def,{...e,currentPath:[...e.currentPath,"properties",r],propertyPath:[...e.currentPath,"properties",r]});return a!==void 0&&(n.properties[r]=a,o||(n.required||(n.required=[]),n.required.push(r))),n},{type:"object",properties:{},additionalProperties:rn(i,e)});let t={type:"object",...Object.entries(i.shape()).reduce((n,[r,s])=>{if(s===void 0||s._def===void 0)return n;let o=(0, rt.parseDef)(s._def,{...e,currentPath:[...e.currentPath,"properties",r],propertyPath:[...e.currentPath,"properties",r]});return o===void 0?n:{properties:{...n.properties,[r]:o},required:s.isOptional()?n.required:[...n.required,r]}},{properties:{},required:[]}),additionalProperties:rn(i,e)};return t.required.length||delete t.required,t}Be.parseObjectDefX=Ro;function Eo(i,e){let t={type:"object",...Object.entries(i.shape()).reduce((n,[r,s])=>{if(s===void 0||s._def===void 0)return n;let o=(0, rt.parseDef)(s._def,{...e,currentPath:[...e.currentPath,"properties",r],propertyPath:[...e.currentPath,"properties",r]});return o===void 0?n:{properties:{...n.properties,[r]:o},required:s.isOptional()?n.required:[...n.required,r]}},{properties:{},required:[]}),additionalProperties:rn(i,e)};return t.required.length||delete t.required,t}Be.parseObjectDef=Eo;});var on=b(fi=>{Object.defineProperty(fi,"__esModule",{value:!0});fi.parseOptionalDef=void 0;var ir=D(),Do=(i,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return (0, ir.parseDef)(i.innerType._def,e);let t=(0, ir.parseDef)(i.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:{}},t]}:{}};fi.parseOptionalDef=Do;});var an=b(yi=>{Object.defineProperty(yi,"__esModule",{value:!0});yi.parsePipelineDef=void 0;var mi=D(),Co=(i,e)=>{if(e.pipeStrategy==="input")return (0, mi.parseDef)(i.in._def,e);if(e.pipeStrategy==="output")return (0, mi.parseDef)(i.out._def,e);let t=(0, mi.parseDef)(i.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=(0, mi.parseDef)(i.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return {allOf:[t,n].filter(r=>r!==void 0)}};yi.parsePipelineDef=Co;});var cn=b(_i=>{Object.defineProperty(_i,"__esModule",{value:!0});_i.parsePromiseDef=void 0;var jo=D();function No(i,e){return (0, jo.parseDef)(i.type._def,e)}_i.parsePromiseDef=No;});var ln=b(gi=>{Object.defineProperty(gi,"__esModule",{value:!0});gi.parseSetDef=void 0;var nr=oe(),Mo=D();function Zo(i,e){let n={type:"array",uniqueItems:!0,items:(0, Mo.parseDef)(i.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return i.minSize&&(0, nr.setResponseValueAndErrors)(n,"minItems",i.minSize.value,i.minSize.message,e),i.maxSize&&(0, nr.setResponseValueAndErrors)(n,"maxItems",i.maxSize.value,i.maxSize.message,e),n}gi.parseSetDef=Zo;});var un=b(bi=>{Object.defineProperty(bi,"__esModule",{value:!0});bi.parseTupleDef=void 0;var dn=D();function $o(i,e){return i.rest?{type:"array",minItems:i.items.length,items:i.items.map((t,n)=>(0, dn.parseDef)(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[]),additionalItems:(0, dn.parseDef)(i.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:i.items.length,maxItems:i.items.length,items:i.items.map((t,n)=>(0, dn.parseDef)(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[])}}bi.parseTupleDef=$o;});var pn=b(vi=>{Object.defineProperty(vi,"__esModule",{value:!0});vi.parseUndefinedDef=void 0;function Uo(){return {not:{}}}vi.parseUndefinedDef=Uo;});var hn=b(Ti=>{Object.defineProperty(Ti,"__esModule",{value:!0});Ti.parseUnknownDef=void 0;function qo(){return {}}Ti.parseUnknownDef=qo;});var fn=b(xi=>{Object.defineProperty(xi,"__esModule",{value:!0});xi.parseReadonlyDef=void 0;var Vo=D(),Lo=(i,e)=>(0, Vo.parseDef)(i.innerType._def,e);xi.parseReadonlyDef=Lo;});var D=b(wi=>{Object.defineProperty(wi,"__esModule",{value:!0});wi.parseDef=void 0;var w=Ft(),Yo=$i(),Fo=Ui(),Wo=qi(),Bo=Vi(),Ko=Li(),zo=Yi(),Go=Fi(),Jo=Wi(),Xo=Bi(),Qo=Ki(),Ho=zi(),ea=Gi(),ta=Xi(),ia=Qi(),na=Hi(),ra=en(),sa=tn(),oa=nn(),aa=sn(),ca=on(),la=an(),da=cn(),ua=oi(),pa=ln(),ha=ri(),fa=un(),ma=pn(),ya=ui(),_a=hn(),ga=fn(),ba=Nt();function rr(i,e,t=!1){let n=e.seen.get(i);if(e.override){let o=e.override?.(i,e,n,t);if(o!==ba.ignoreOverride)return o}if(n&&!t){let o=va(n,e);if(o!==void 0)return o}let r={def:i,path:e.currentPath,jsonSchema:void 0};e.seen.set(i,r);let s=xa(i,i.typeName,e);return s&&wa(i,e,s),r.jsonSchema=s,s}wi.parseDef=rr;var va=(i,e)=>{switch(e.$refStrategy){case"root":return {$ref:i.path.join("/")};case"relative":return {$ref:Ta(e.currentPath,i.path)};case"none":case"seen":return i.path.length<e.currentPath.length&&i.path.every((t,n)=>e.currentPath[n]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},Ta=(i,e)=>{let t=0;for(;t<i.length&&t<e.length&&i[t]===e[t];t++);return [(i.length-t).toString(),...e.slice(t)].join("/")},xa=(i,e,t)=>{switch(e){case w.ZodFirstPartyTypeKind.ZodString:return (0, ha.parseStringDef)(i,t);case w.ZodFirstPartyTypeKind.ZodNumber:return (0, oa.parseNumberDef)(i,t);case w.ZodFirstPartyTypeKind.ZodObject:return (0, aa.parseObjectDef)(i,t);case w.ZodFirstPartyTypeKind.ZodBigInt:return (0, Wo.parseBigintDef)(i,t);case w.ZodFirstPartyTypeKind.ZodBoolean:return (0, Bo.parseBooleanDef)();case w.ZodFirstPartyTypeKind.ZodDate:return (0, Go.parseDateDef)(i,t);case w.ZodFirstPartyTypeKind.ZodUndefined:return (0, ma.parseUndefinedDef)();case w.ZodFirstPartyTypeKind.ZodNull:return (0, ra.parseNullDef)(t);case w.ZodFirstPartyTypeKind.ZodArray:return (0, Fo.parseArrayDef)(i,t);case w.ZodFirstPartyTypeKind.ZodUnion:case w.ZodFirstPartyTypeKind.ZodDiscriminatedUnion:return (0, ya.parseUnionDef)(i,t);case w.ZodFirstPartyTypeKind.ZodIntersection:return (0, Ho.parseIntersectionDef)(i,t);case w.ZodFirstPartyTypeKind.ZodTuple:return (0, fa.parseTupleDef)(i,t);case w.ZodFirstPartyTypeKind.ZodRecord:return (0, ua.parseRecordDef)(i,t);case w.ZodFirstPartyTypeKind.ZodLiteral:return (0, ea.parseLiteralDef)(i,t);case w.ZodFirstPartyTypeKind.ZodEnum:return (0, Qo.parseEnumDef)(i);case w.ZodFirstPartyTypeKind.ZodNativeEnum:return (0, ia.parseNativeEnumDef)(i);case w.ZodFirstPartyTypeKind.ZodNullable:return (0, sa.parseNullableDef)(i,t);case w.ZodFirstPartyTypeKind.ZodOptional:return (0, ca.parseOptionalDef)(i,t);case w.ZodFirstPartyTypeKind.ZodMap:return (0, ta.parseMapDef)(i,t);case w.ZodFirstPartyTypeKind.ZodSet:return (0, pa.parseSetDef)(i,t);case w.ZodFirstPartyTypeKind.ZodLazy:return rr(i.getter()._def,t);case w.ZodFirstPartyTypeKind.ZodPromise:return (0, da.parsePromiseDef)(i,t);case w.ZodFirstPartyTypeKind.ZodNaN:case w.ZodFirstPartyTypeKind.ZodNever:return (0, na.parseNeverDef)();case w.ZodFirstPartyTypeKind.ZodEffects:return (0, Xo.parseEffectsDef)(i,t);case w.ZodFirstPartyTypeKind.ZodAny:return (0, Yo.parseAnyDef)();case w.ZodFirstPartyTypeKind.ZodUnknown:return (0, _a.parseUnknownDef)();case w.ZodFirstPartyTypeKind.ZodDefault:return (0, Jo.parseDefaultDef)(i,t);case w.ZodFirstPartyTypeKind.ZodBranded:return (0, Ko.parseBrandedDef)(i,t);case w.ZodFirstPartyTypeKind.ZodReadonly:return (0, ga.parseReadonlyDef)(i,t);case w.ZodFirstPartyTypeKind.ZodCatch:return (0, zo.parseCatchDef)(i,t);case w.ZodFirstPartyTypeKind.ZodPipeline:return (0, la.parsePipelineDef)(i,t);case w.ZodFirstPartyTypeKind.ZodFunction:case w.ZodFirstPartyTypeKind.ZodVoid:case w.ZodFirstPartyTypeKind.ZodSymbol:return;default:return (n=>{})()}},wa=(i,e,t)=>(i.description&&(t.description=i.description,e.markdownDescription&&(t.markdownDescription=i.description)),t);});var mn=b(ki=>{Object.defineProperty(ki,"__esModule",{value:!0});ki.zodToJsonSchema=void 0;var sr=D(),ka=Ri(),Oa=(i,e)=>{let t=(0, ka.getRefs)(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((d,[p,y])=>({...d,[p]:(0, sr.parseDef)(y._def,{...t,currentPath:[...t.basePath,t.definitionPath,p]},!0)??{}}),{}):void 0,r=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=(0, sr.parseDef)(i._def,r===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,r]},!1)??{},o=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;o!==void 0&&(s.title=o);let a=r===void 0?n?{...s,[t.definitionPath]:n}:s:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,r].join("/"),[t.definitionPath]:{...n,[r]:s}};return t.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":t.target==="jsonSchema2019-09"&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),a};ki.zodToJsonSchema=Oa;});var or=b(x=>{var Sa=x&&x.__createBinding||(Object.create?function(i,e,t,n){n===void 0&&(n=t);var r=Object.getOwnPropertyDescriptor(e,t);(!r||("get"in r?!e.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(i,n,r);}:function(i,e,t,n){n===void 0&&(n=t),i[n]=e[t];}),k=x&&x.__exportStar||function(i,e){for(var t in i)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Sa(e,i,t);};Object.defineProperty(x,"__esModule",{value:!0});k(Nt(),x);k(Ri(),x);k(oe(),x);k(D(),x);k($i(),x);k(Ui(),x);k(qi(),x);k(Vi(),x);k(Li(),x);k(Yi(),x);k(Fi(),x);k(Wi(),x);k(Bi(),x);k(Ki(),x);k(zi(),x);k(Gi(),x);k(Xi(),x);k(Qi(),x);k(Hi(),x);k(en(),x);k(tn(),x);k(nn(),x);k(sn(),x);k(on(),x);k(an(),x);k(cn(),x);k(fn(),x);k(oi(),x);k(ln(),x);k(ri(),x);k(un(),x);k(pn(),x);k(ui(),x);k(hn(),x);k(mn(),x);var Aa=mn();x.default=Aa.zodToJsonSchema;});var at=(n=>(n.TRIGGER="trigger",n.EXECUTE="execute",n.PREVIEW="preview",n))(at||{}),ct=(n=>(n.DISCOVER="discover",n.HEALTH_CHECK="health-check",n.CODE="code",n))(ct||{});var Sr=(t=>(t.SYNC="/v1/bridge/sync",t.DIFF="/v1/bridge/diff",t))(Sr||{}),vn=5,Tn=1500;var F=(P=>(P.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",P.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",P.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",P.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",P.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",P.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",P.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",P.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",P.STEP_NOT_FOUND_ERROR="StepNotFoundError",P.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",P.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",P.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",P.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",P.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",P.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",P.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",P.INVALID_ACTION_ERROR="InvalidActionError",P.MISSING_API_KEY_ERROR="MissingApiKeyError",P.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",P.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",P.SIGNATURE_INVALID_ERROR="SignatureInvalidError",P.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",P.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",P.PLATFORM_ERROR="PlatformError",P.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",P))(F||{});var Ii=(R=>(R.NOVU_SIGNATURE="novu-signature",R.NOVU_ANONYMOUS="novu-anonymous",R.NOVU_SIGNATURE_DEPRECATED="x-novu-signature",R.NOVU_ANONYMOUS_DEPRECATED="x-novu-anonymous",R.NOVU_FRAMEWORK_SDK="novu-framework-sdk",R.NOVU_FRAMEWORK_API="novu-framework-api",R.NOVU_FRAMEWORK_VERSION="novu-framework-version",R.USER_AGENT="user-agent",R.CONTENT_TYPE="content-type",R.ACCESS_CONTROL_ALLOW_ORIGIN="access-control-allow-origin",R.ACCESS_CONTROL_ALLOW_METHODS="access-control-allow-methods",R.ACCESS_CONTROL_ALLOW_HEADERS="access-control-allow-headers",R.ACCESS_CONTROL_MAX_AGE="access-control-max-age",R))(Ii||{});var lt=(n=>(n.POST="POST",n.GET="GET",n.OPTIONS="OPTIONS",n))(lt||{});var xn=(r=>(r.WORKFLOW_ID="workflowId",r.STEP_ID="stepId",r.ACTION="action",r.SOURCE="source",r))(xn||{});var dt=(u=>(u[u.CONTINUE=100]="CONTINUE",u[u.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",u[u.PROCESSING=102]="PROCESSING",u[u.EARLYHINTS=103]="EARLYHINTS",u[u.OK=200]="OK",u[u.CREATED=201]="CREATED",u[u.ACCEPTED=202]="ACCEPTED",u[u.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",u[u.NO_CONTENT=204]="NO_CONTENT",u[u.RESET_CONTENT=205]="RESET_CONTENT",u[u.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",u[u.AMBIGUOUS=300]="AMBIGUOUS",u[u.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",u[u.FOUND=302]="FOUND",u[u.SEE_OTHER=303]="SEE_OTHER",u[u.NOT_MODIFIED=304]="NOT_MODIFIED",u[u.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",u[u.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",u[u.BAD_REQUEST=400]="BAD_REQUEST",u[u.UNAUTHORIZED=401]="UNAUTHORIZED",u[u.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",u[u.FORBIDDEN=403]="FORBIDDEN",u[u.NOT_FOUND=404]="NOT_FOUND",u[u.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",u[u.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",u[u.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",u[u.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",u[u.CONFLICT=409]="CONFLICT",u[u.GONE=410]="GONE",u[u.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",u[u.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",u[u.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",u[u.URI_TOO_LONG=414]="URI_TOO_LONG",u[u.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",u[u.REQUESTED_RANGE_NOT_SATISFIABLE=416]="REQUESTED_RANGE_NOT_SATISFIABLE",u[u.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",u[u.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",u[u.MISDIRECTED=421]="MISDIRECTED",u[u.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",u[u.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",u[u.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",u[u.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",u[u.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",u[u.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",u[u.BAD_GATEWAY=502]="BAD_GATEWAY",u[u.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",u[u.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",u[u.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",u))(dt||{}),pc=[500];var ut=(n=>(n.WORKFLOW="workflow",n.PROVIDER="provider",n.STEP="step",n))(ut||{});var pt=(s=>(s.EMAIL="email",s.SMS="sms",s.PUSH="push",s.CHAT="chat",s.IN_APP="in_app",s))(pt||{}),Ar=(n=>(n.DIGEST="digest",n.DELAY="delay",n.CUSTOM="custom",n))(Ar||{});var H=class extends Error{data},ht=class extends H{statusCode=404},q=class extends H{statusCode=400},re=class extends H{statusCode=401},je=class extends H{statusCode=500},ft=class extends H{statusCode=409};var mt=class extends q{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};}},ze=class extends q{code="ExecutionEventPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct event payload.`),this.data=t;}},yt=class extends q{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},_t=class extends q{code="ExecutionStateControlInvalidError";constructor(e,t,n){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid \`controls\`. Please provide the correct step controls.`),this.data=n;}},gt=class extends q{code="ExecutionStateOutputInvalidError";constructor(e,t,n){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid output. Please provide the correct step output.`),this.data=n;}},bt=class extends q{code="ExecutionStateResultInvalidError";constructor(e,t,n){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid result. Please provide the correct step result.`),this.data=n;}},vt=class extends q{code="ExecutionProviderOutputInvalidError";constructor(e,t,n,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` and provider with id: \`${n}\` has invalid output. Please provide the correct provider output.`),this.data=r;}};var A={info:i=>Ne__default.default.blue(i),warning:i=>Ne__default.default.yellow(i),error:i=>Ne__default.default.red(i),success:i=>Ne__default.default.green(i),underline:i=>Ne__default.default.underline(i),bold:i=>Ne__default.default.bold(i)},E={SUCCESS:A.success("\u2714"),ERROR:A.error("\u2717"),WARNING:A.warning("\u26A0"),INFO:A.info("\u2139"),ARROW:A.bold("\u2192"),MOCK:A.info("\u25CB"),HYDRATED:A.bold(A.info("\u2192")),STEP:A.info("\u03C3"),ACTION:A.info("\u03B1"),DURATION:A.info("\u0394"),PROVIDER:A.info("\u2699"),OUTPUT:A.info("\u21E2"),INPUT:A.info("\u21E0"),WORKFLOW:A.info("\u03C9"),STATE:A.info("\u03C3"),EXECUTE:A.info("\u03B5"),PREVIEW:A.info("\u03C1")};var Pi=i=>Object.values(i).map(e=>`\`${e}\``).join(", "),Tt=i=>i.replaceAll(/(\w)(\w*)/g,(e,t,n)=>t.toUpperCase()+n.toLowerCase()).replaceAll(/[\s-]+/g,"");var wn=(i,e="https://api.novu.co")=>{let t=process.env.NOVU_API_URL||e;return {post:async(n,r)=>(await fetch(t+"/v1"+n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${i}`},body:JSON.stringify(r)})).json()}};var xt=class extends H{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${Pi(lt)}`},Ge=class extends q{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${Pi(t)}`);}};var wt=class extends je{code="PlatformError";message="Something went wrong. Please try again later."};var Me=class extends ft{constructor(e,t){super(`${Tt(e)} with id: \`${t}\` already exists. Please use a different id.`);}},se=class extends ht{constructor(e,t){super(`${Tt(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},Ze=class extends je{constructor(e,t){super(`Failed to execute ${Tt(e)} with id: \`${t}\`. Please try again later.`);}};var kt=class extends se{code="ProviderNotFoundError";constructor(e){super("provider",e);}},Ot=class extends Ze{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var St=class extends re{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.");}},At=class extends re{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},It=class extends re{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},Pt=class extends re{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},Rt=class extends re{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.apiKey`");}};var Et=class extends se{code="StepNotFoundError";constructor(e){super("step",e);}},Dt=class extends Me{code="StepAlreadyExistsError";constructor(e){super("step",e);}};var Je=class extends se{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},Ct=class extends Me{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var jt=class{ajv;compiledSchemas;constructor(){this.ajv=new Ir__default.default({useDefaults:!0,removeAdditional:"all"}),Pr__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 n=this.compiledSchemas.get(t);return n||(n=this.ajv.compile(t),this.compiledSchemas.set(t,n)),n(e)?{success:!0,data:e}:{success:!1,errors:n.errors.map(s=>({path:s.instancePath,message:s.message}))}}transformToJsonSchema(e){return e}};var Oi=class{isSchema(e){return e.safeParseAsync!==void 0}async validate(e,t){let n=t.safeParse(e);return n.success?{success:!0,data:n.data}:{success:!1,errors:n.error.errors.map(r=>({path:`/${r.path.join("/")}`,message:r.message}))}}transformToJsonSchema(e){try{return or().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 ar=[new Oi,new jt],cr=async(i,e)=>{for(let t of ar)if(t.isSchema(i))return t.validate(e,i);throw new Error("Invalid schema")},C=i=>{for(let e of ar)if(e.isSchema(i))return e.transformToJsonSchema(i);throw new Error("Invalid schema")};var lr={name:"@novu/framework",version:"0.24.3-alpha.11",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",zod:"^3.23.0","zod-to-json-schema":"^3.23.0"},dependencies:{"@novu/shared":"0.24.2",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 st=lr.version,Si="2024-06-26";jsonSchemaFaker.JSONSchemaFaker.random.shuffle=function(){return ["[placeholder]"]};jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});var ot=class{discoveredWorkflows=[];templateEngine=new liquidjs.Liquid;apiKey;version=st;strictAuthentication;constructor(e){let t=this.buildOptions(e);this.apiKey=t.apiKey,this.strictAuthentication=t.strictAuthentication;}buildOptions(e){let t={apiKey:void 0,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?.strictAuthentication!==void 0?t.strictAuthentication=e.strictAuthentication:process.env.NODE_ENV==="development"&&(t.strictAuthentication=!1),t}addWorkflows(e){for(let t of e){if(this.discoveredWorkflows.some(n=>n.workflowId===t.workflowId))throw new Ct(t.workflowId);this.discoveredWorkflows.push(t);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((n,r)=>n+r.steps.length,0);return {status:"ok",sdkVersion:st,frameworkVersion:Si,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(n=>n.workflowId===e);if(t)return t;throw new Je(e)}getStep(e,t){let r=this.getWorkflow(e).steps.find(s=>s.stepId===t);if(r)return r;throw new Et(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(C(e))}async validate(e,t,n,r,s,o,a){let d=await cr(t,e);if(d.success)return d.data;switch(n){case"event":this.throwInvalidEvent(r,s,d.errors);case"step":this.throwInvalidStep(o,r,s,d.errors);case"provider":this.throwInvalidProvider(o,a,r,s,d.errors);default:throw new Error(`Invalid component: '${n}'`)}}throwInvalidProvider(e,t,n,r,s){if(!e)throw new Error("stepId is required");if(!t)throw new Error("providerId is required");switch(n){case"output":throw new vt(r,e,t,s);default:throw new Error(`Invalid payload type: '${n}'`)}}throwInvalidStep(e,t,n,r){if(!e)throw new Error("stepId is required");switch(t){case"output":throw new gt(n,e,r);case"result":throw new bt(n,e,r);case"controls":throw new _t(n,e,r);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(e,t,n){switch(e){case"controls":throw new yt(t,n);case"payload":throw new ze(t,n);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(n,r,s)=>{let o=this.getStep(e.workflowId,n),a=Ra(e),d=await this.createStepControls(o,a),p=e.action==="preview";if(!p&&await this.shouldSkip(s?.skip,d))return t({options:{skip:!0}}),{};let y=this.previewStep.bind(this),I=this.executeStep.bind(this),R=await(p?y:I)(e,{...o,providers:o.providers.map(Ce=>{let Ke=s?.providers?.[Ce.type];if(!Ke)throw new kt(Ce.type);return {...Ce,resolve:Ke}}),resolve:r});return n===e.stepId&&t(R),R.outputs}}async shouldSkip(e,t){return e?e(t):!1}async executeWorkflow(e){let r=`${{execute:"Executing",preview:"Previewing"}[e.action]} workflowId:`;console.log(`
|
|
23
23
|
${A.bold(A.underline(r))} '${e.workflowId}'`);let s=this.getWorkflow(e.workflowId),o=process.hrtime(),a={outputs:{},providers:{},options:{}},d,p=new Promise(he=>{d=he;}),y=he=>{d(),a=he;},I;try{if(e.action==="execute"&&!e.payload&&!e.data)throw new ze(e.workflowId,{message:"Event `payload` is required"});let he=await this.createExecutionPayload(e,s);await Promise.race([p,s.execute({payload:he,environment:{},inputs:{},controls:{},subscriber:e.subscriber,step:{email:this.executeStepFactory(e,y),sms:this.executeStepFactory(e,y),inApp:this.executeStepFactory(e,y),digest:this.executeStepFactory(e,y),delay:this.executeStepFactory(e,y),push:this.executeStepFactory(e,y),chat:this.executeStepFactory(e,y),custom:this.executeStepFactory(e,y)}})]);}catch(he){I=he;}let ne=process.hrtime(o),R=ne[0],Ce=ne[1],Ke=R*1e3+Ce/1e6,kr=I?E.ERROR:E.SUCCESS,Or=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action";if(console.log(`${kr} ${Or} workflowId: \`${e.workflowId}\``),this.prettyPrintExecute(e,Ke,I),I)throw I;return {outputs:a.outputs,providers:a.providers,options:a.options,metadata:{status:"success",error:!1,duration:Ke}}}async createExecutionPayload(e,t){let n=e.payload||e.data;if(e.action==="preview"){let s=this.mock(t.payload.schema);n=Object.assign(s,n);}return await this.validate(n,t.payload.unknownSchema,"event","payload",e.workflowId)}prettyPrintExecute(e,t,n){let r=n?E.ERROR:E.SUCCESS,s=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action",o=n?"Failed to execute":s,a=n?A.error:A.success,d=`${r} ${o} workflowId: '${e.workflowId}`;console.log(`
|
|
24
24
|
${A.bold(a(d))}'`),console.log(` \u251C ${E.STEP} stepId: '${e.stepId}'`),console.log(` \u251C ${E.ACTION} action: '${e.action}'`),console.log(` \u2514 ${E.DURATION} duration: '${t.toFixed(2)}ms'
|
|
25
25
|
`);}async executeProviders(e,t,n){return t.providers.reduce(async(r,s)=>{let o=await r,a=this.previewProvider.bind(this),d=this.executeProvider.bind(this),y=await(e.action==="preview"?a:d)(e,t,s,n);return {...o,[s.type]:y}},Promise.resolve({}))}previewProvider(e,t,n,r){return console.log(` ${E.MOCK} Mocked provider: \`${n.type}\``),this.mock(n.outputs.schema)}async executeProvider(e,t,n,r){let s=Ai__default.default({indent:2}).start(`Executing provider: \`${n.type}\``);try{if(e.stepId===t.stepId){let o=await this.createStepControls(t,e),a=await n.resolve({controls:o,outputs:r}),d=await this.validate(a,n.outputs.unknownSchema,"step","output",e.workflowId,t.stepId,n.type);return s.succeed(`Executed provider: \`${n.type}\``),d}else s.stopAndPersist({symbol:E.HYDRATED,text:`Hydrated provider: \`${n.type}\``});}catch(o){throw s.stopAndPersist({symbol:E.ERROR,text:`Failed to execute provider: \`${n.type}\``}),new Ot(`Failed to execute provider: '${n.type}'.
|