@novu/framework 0.24.3-alpha.13 → 0.24.3-alpha.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/express.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { l as SupportedFrameworkName, a as ServeHandlerOptions } from './handler-PIXNhv7t.js';
1
+ import { q as SupportedFrameworkName, b as ServeHandlerOptions } from './handler-Mor_4K8F.js';
2
2
  import 'json-schema-to-ts';
3
3
  import 'zod';
4
4
  import '@novu/shared';
package/dist/express.js CHANGED
@@ -3,27 +3,25 @@
3
3
  var crypto = require('crypto');
4
4
  var jsonSchemaFaker = require('json-schema-faker');
5
5
  var liquidjs = require('liquidjs');
6
- var yr = require('ora');
7
- var Ae = require('chalk');
8
- var tn = require('ajv');
9
- var rn = require('ajv-formats');
6
+ var ie = require('ora');
7
+ require('cross-fetch');
8
+ var A = require('chalk');
9
+ var me = require('ajv');
10
+ var Ae = require('ajv-formats');
11
+ var zodToJsonSchema = require('zod-to-json-schema');
10
12
 
11
13
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
12
14
 
13
- var yr__default = /*#__PURE__*/_interopDefault(yr);
15
+ var ie__default = /*#__PURE__*/_interopDefault(ie);
16
+ var A__default = /*#__PURE__*/_interopDefault(A);
17
+ var me__default = /*#__PURE__*/_interopDefault(me);
14
18
  var Ae__default = /*#__PURE__*/_interopDefault(Ae);
15
- var tn__default = /*#__PURE__*/_interopDefault(tn);
16
- var rn__default = /*#__PURE__*/_interopDefault(rn);
17
19
 
18
- var _=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var Rt=_(F=>{Object.defineProperty(F,"__esModule",{value:!0});F.getDefaultOptions=F.defaultOptions=F.ignoreOverride=void 0;F.ignoreOverride=Symbol("Let zodToJsonSchema decide on which parser to use");F.defaultOptions={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"};var sn=r=>typeof r=="string"?{...F.defaultOptions,name:r}:{...F.defaultOptions,...r};F.getDefaultOptions=sn;});var Tr=_(Et=>{Object.defineProperty(Et,"__esModule",{value:!0});Et.getRefs=void 0;var nn=Rt(),an=r=>{let e=(0, nn.getDefaultOptions)(r),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return {...e,currentPath:t,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([s,n])=>[n._def,{def:n._def,path:[...e.basePath,e.definitionPath,s],jsonSchema:void 0}]))}};Et.getRefs=an;});var te=_(ke=>{Object.defineProperty(ke,"__esModule",{value:!0});ke.setResponseValueAndErrors=ke.addErrorMessage=void 0;function us(r,e,t,s){s?.errorMessages&&t&&(r.errorMessage={...r.errorMessage,[e]:t});}ke.addErrorMessage=us;function on(r,e,t,s,n){r[e]=t,us(r,e,s,n);}ke.setResponseValueAndErrors=on;});var Ke=_(R=>{Object.defineProperty(R,"__esModule",{value:!0});R.getParsedType=R.ZodParsedType=R.objectUtil=R.util=void 0;var cs;(function(r){r.assertEqual=n=>n;function e(n){}r.assertIs=e;function t(n){throw new Error}r.assertNever=t,r.arrayToEnum=n=>{let a={};for(let i of n)a[i]=i;return a},r.getValidEnumValues=n=>{let a=r.objectKeys(n).filter(d=>typeof n[n[d]]!="number"),i={};for(let d of a)i[d]=n[d];return r.objectValues(i)},r.objectValues=n=>r.objectKeys(n).map(function(a){return n[a]}),r.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{let a=[];for(let i in n)Object.prototype.hasOwnProperty.call(n,i)&&a.push(i);return a},r.find=(n,a)=>{for(let i of n)if(a(i))return i},r.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&isFinite(n)&&Math.floor(n)===n;function s(n,a=" | "){return n.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}r.joinValues=s,r.jsonStringifyReplacer=(n,a)=>typeof a=="bigint"?a.toString():a;})(cs=R.util||(R.util={}));(function(r){r.mergeShapes=(e,t)=>({...e,...t});})(R.objectUtil||(R.objectUtil={}));R.ZodParsedType=cs.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var un=r=>{switch(typeof r){case"undefined":return R.ZodParsedType.undefined;case"string":return R.ZodParsedType.string;case"number":return isNaN(r)?R.ZodParsedType.nan:R.ZodParsedType.number;case"boolean":return R.ZodParsedType.boolean;case"function":return R.ZodParsedType.function;case"bigint":return R.ZodParsedType.bigint;case"symbol":return R.ZodParsedType.symbol;case"object":return Array.isArray(r)?R.ZodParsedType.array:r===null?R.ZodParsedType.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?R.ZodParsedType.promise:typeof Map<"u"&&r instanceof Map?R.ZodParsedType.map:typeof Set<"u"&&r instanceof Set?R.ZodParsedType.set:typeof Date<"u"&&r instanceof Date?R.ZodParsedType.date:R.ZodParsedType.object;default:return R.ZodParsedType.unknown}};R.getParsedType=un;});var wt=_(re=>{Object.defineProperty(re,"__esModule",{value:!0});re.ZodError=re.quotelessJson=re.ZodIssueCode=void 0;var ls=Ke();re.ZodIssueCode=ls.util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);var cn=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:");re.quotelessJson=cn;var ze=class r extends Error{constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s];},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s];};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e;}get errors(){return this.issues}format(e){let t=e||function(a){return a.message},s={_errors:[]},n=a=>{for(let i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(n);else if(i.code==="invalid_return_type")n(i.returnTypeError);else if(i.code==="invalid_arguments")n(i.argumentsError);else if(i.path.length===0)s._errors.push(t(i));else {let d=s,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(d[l]=d[l]||{_errors:[]},d[l]._errors.push(t(i))):d[l]=d[l]||{_errors:[]},d=d[l],c++;}}};return n(this),s}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ls.util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},s=[];for(let n of this.issues)n.path.length>0?(t[n.path[0]]=t[n.path[0]]||[],t[n.path[0]].push(e(n))):s.push(e(n));return {formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}};re.ZodError=ze;ze.create=r=>new ze(r);});var Ir=_(Or=>{Object.defineProperty(Or,"__esModule",{value:!0});var ue=Ke(),C=wt(),ln=(r,e)=>{let t;switch(r.code){case C.ZodIssueCode.invalid_type:r.received===ue.ZodParsedType.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case C.ZodIssueCode.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,ue.util.jsonStringifyReplacer)}`;break;case C.ZodIssueCode.unrecognized_keys:t=`Unrecognized key(s) in object: ${ue.util.joinValues(r.keys,", ")}`;break;case C.ZodIssueCode.invalid_union:t="Invalid input";break;case C.ZodIssueCode.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${ue.util.joinValues(r.options)}`;break;case C.ZodIssueCode.invalid_enum_value:t=`Invalid enum value. Expected ${ue.util.joinValues(r.options)}, received '${r.received}'`;break;case C.ZodIssueCode.invalid_arguments:t="Invalid function arguments";break;case C.ZodIssueCode.invalid_return_type:t="Invalid function return type";break;case C.ZodIssueCode.invalid_date:t="Invalid date";break;case C.ZodIssueCode.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:ue.util.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case C.ZodIssueCode.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case C.ZodIssueCode.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case C.ZodIssueCode.custom:t="Invalid input";break;case C.ZodIssueCode.invalid_intersection_types:t="Intersection results could not be merged";break;case C.ZodIssueCode.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case C.ZodIssueCode.not_finite:t="Number must be finite";break;default:t=e.defaultError,ue.util.assertNever(r);}return {message:t}};Or.default=ln;});var bt=_(W=>{var pn=W&&W.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(W,"__esModule",{value:!0});W.getErrorMap=W.setErrorMap=W.defaultErrorMap=void 0;var ps=pn(Ir());W.defaultErrorMap=ps.default;var fs=ps.default;function fn(r){fs=r;}W.setErrorMap=fn;function hn(){return fs}W.getErrorMap=hn;});var Rr=_(x=>{var mn=x&&x.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(x,"__esModule",{value:!0});x.isAsync=x.isValid=x.isDirty=x.isAborted=x.OK=x.DIRTY=x.INVALID=x.ParseStatus=x.addIssueToContext=x.EMPTY_PATH=x.makeIssue=void 0;var yn=bt(),hs=mn(Ir()),_n=r=>{let{data:e,path:t,errorMaps:s,issueData:n}=r,a=[...t,...n.path||[]],i={...n,path:a};if(n.message!==void 0)return {...n,path:a,message:n.message};let d="",c=s.filter(l=>!!l).slice().reverse();for(let l of c)d=l(i,{data:e,defaultError:d}).message;return {...n,path:a,message:d}};x.makeIssue=_n;x.EMPTY_PATH=[];function gn(r,e){let t=(0, yn.getErrorMap)(),s=(0, x.makeIssue)({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===hs.default?void 0:hs.default].filter(n=>!!n)});r.common.issues.push(s);}x.addIssueToContext=gn;var xr=class r{constructor(){this.value="valid";}dirty(){this.value==="valid"&&(this.value="dirty");}abort(){this.value!=="aborted"&&(this.value="aborted");}static mergeArray(e,t){let s=[];for(let n of t){if(n.status==="aborted")return x.INVALID;n.status==="dirty"&&e.dirty(),s.push(n.value);}return {status:e.value,value:s}}static async mergeObjectAsync(e,t){let s=[];for(let n of t){let a=await n.key,i=await n.value;s.push({key:a,value:i});}return r.mergeObjectSync(e,s)}static mergeObjectSync(e,t){let s={};for(let n of t){let{key:a,value:i}=n;if(a.status==="aborted"||i.status==="aborted")return x.INVALID;a.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||n.alwaysSet)&&(s[a.value]=i.value);}return {status:e.value,value:s}}};x.ParseStatus=xr;x.INVALID=Object.freeze({status:"aborted"});var vn=r=>({status:"dirty",value:r});x.DIRTY=vn;var Tn=r=>({status:"valid",value:r});x.OK=Tn;var On=r=>r.status==="aborted";x.isAborted=On;var In=r=>r.status==="dirty";x.isDirty=In;var xn=r=>r.status==="valid";x.isValid=xn;var Rn=r=>typeof Promise<"u"&&r instanceof Promise;x.isAsync=Rn;});var ys=_(ms=>{Object.defineProperty(ms,"__esModule",{value:!0});});var _s=_(Be=>{Object.defineProperty(Be,"__esModule",{value:!0});Be.errorUtil=void 0;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message;})(Be.errorUtil||(Be.errorUtil={}));});var As=_(o=>{var At=o&&o.__classPrivateFieldGet||function(r,e,t,s){if(t==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?s:t==="a"?s.call(r):s?s.value:e.get(r)},vs=o&&o.__classPrivateFieldSet||function(r,e,t,s,n){if(s==="m")throw new TypeError("Private method is not writable");if(s==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?n.call(r,t):n?n.value=t:e.set(r,t),t},Ge,Ye;Object.defineProperty(o,"__esModule",{value:!0});o.boolean=o.bigint=o.array=o.any=o.coerce=o.ZodFirstPartyTypeKind=o.late=o.ZodSchema=o.Schema=o.custom=o.ZodReadonly=o.ZodPipeline=o.ZodBranded=o.BRAND=o.ZodNaN=o.ZodCatch=o.ZodDefault=o.ZodNullable=o.ZodOptional=o.ZodTransformer=o.ZodEffects=o.ZodPromise=o.ZodNativeEnum=o.ZodEnum=o.ZodLiteral=o.ZodLazy=o.ZodFunction=o.ZodSet=o.ZodMap=o.ZodRecord=o.ZodTuple=o.ZodIntersection=o.ZodDiscriminatedUnion=o.ZodUnion=o.ZodObject=o.ZodArray=o.ZodVoid=o.ZodNever=o.ZodUnknown=o.ZodAny=o.ZodNull=o.ZodUndefined=o.ZodSymbol=o.ZodDate=o.ZodBoolean=o.ZodBigInt=o.ZodNumber=o.ZodString=o.datetimeRegex=o.ZodType=void 0;o.NEVER=o.void=o.unknown=o.union=o.undefined=o.tuple=o.transformer=o.symbol=o.string=o.strictObject=o.set=o.record=o.promise=o.preprocess=o.pipeline=o.ostring=o.optional=o.onumber=o.oboolean=o.object=o.number=o.nullable=o.null=o.never=o.nativeEnum=o.nan=o.map=o.literal=o.lazy=o.intersection=o.instanceof=o.function=o.enum=o.effect=o.discriminatedUnion=o.date=void 0;var Pt=bt(),m=_s(),u=Rr(),f=Ke(),p=wt(),M=class{constructor(e,t,s,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=n;}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},gs=(r,e)=>{if((0, u.isValid)(e))return {success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return {success:!1,get error(){if(this._error)return this._error;let t=new p.ZodError(r.common.issues);return this._error=t,this._error}}};function g(r){if(!r)return {};let{errorMap:e,invalid_type_error:t,required_error:s,description:n}=r;if(e&&(t||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(i,d)=>{var c,l;let{message:h}=r;return i.code==="invalid_enum_value"?{message:h??d.defaultError}:typeof d.data>"u"?{message:(c=h??s)!==null&&c!==void 0?c:d.defaultError}:i.code!=="invalid_type"?{message:d.defaultError}:{message:(l=h??t)!==null&&l!==void 0?l:d.defaultError}},description:n}}var v=class{constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this);}get description(){return this._def.description}_getType(e){return (0, f.getParsedType)(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:(0, f.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return {status:new u.ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:(0, f.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if((0, u.isAsync)(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){var s;let n={common:{issues:[],async:(s=t?.async)!==null&&s!==void 0?s:!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0, f.getParsedType)(e)},a=this._parseSync({data:e,path:n.path,parent:n});return gs(n,a)}async parseAsync(e,t){let s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){let s={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0, f.getParsedType)(e)},n=this._parse({data:e,path:s.path,parent:s}),a=await((0, u.isAsync)(n)?n:Promise.resolve(n));return gs(s,a)}refine(e,t){let s=n=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(n):t;return this._refinement((n,a)=>{let i=e(n),d=()=>a.addIssue({code:p.ZodIssueCode.custom,...s(n)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(d(),!1)):i?!0:(d(),!1)})}refinement(e,t){return this._refinement((s,n)=>e(s)?!0:(n.addIssue(typeof t=="function"?t(s,n):t),!1))}_refinement(e){return new D({schema:this,typeName:y.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return j.create(this,this._def)}nullable(){return z.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return J.create(this,this._def)}promise(){return ae.create(this,this._def)}or(e){return ye.create([this,e],this._def)}and(e){return _e.create(this,e,this._def)}transform(e){return new D({...g(this._def),schema:this,typeName:y.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Ie({...g(this._def),innerType:this,defaultValue:t,typeName:y.ZodDefault})}brand(){return new Je({typeName:y.ZodBranded,type:this,...g(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new xe({...g(this._def),innerType:this,catchValue:t,typeName:y.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Xe.create(this,e)}readonly(){return Re.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};o.ZodType=v;o.Schema=v;o.ZodSchema=v;var wn=/^c[^\s-]{8,}$/i,bn=/^[0-9a-z]+$/,Pn=/^[0-9A-HJKMNP-TV-Z]{26}$/,An=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Cn=/^[a-z0-9_-]{21}$/i,kn=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Nn=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Dn="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Er,Sn=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Zn=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,jn=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ts="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Mn=new RegExp(`^${Ts}$`);function Os(r){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`),e}function Un(r){return new RegExp(`^${Os(r)}$`)}function Is(r){let e=`${Ts}T${Os(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}o.datetimeRegex=Is;function Vn(r,e){return !!((e==="v4"||!e)&&Sn.test(r)||(e==="v6"||!e)&&Zn.test(r))}var se=class r extends v{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==f.ZodParsedType.string){let a=this._getOrReturnCtx(e);return (0, u.addIssueToContext)(a,{code:p.ZodIssueCode.invalid_type,expected:f.ZodParsedType.string,received:a.parsedType}),u.INVALID}let s=new u.ParseStatus,n;for(let a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(n=this._getOrReturnCtx(e,n),(0, u.addIssueToContext)(n,{code:p.ZodIssueCode.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),s.dirty());else if(a.kind==="max")e.data.length>a.value&&(n=this._getOrReturnCtx(e,n),(0, u.addIssueToContext)(n,{code:p.ZodIssueCode.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),s.dirty());else if(a.kind==="length"){let i=e.data.length>a.value,d=e.data.length<a.value;(i||d)&&(n=this._getOrReturnCtx(e,n),i?(0, u.addIssueToContext)(n,{code:p.ZodIssueCode.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):d&&(0, u.addIssueToContext)(n,{code:p.ZodIssueCode.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),s.dirty());}else if(a.kind==="email")Nn.test(e.data)||(n=this._getOrReturnCtx(e,n),(0, u.addIssueToContext)(n,{validation:"email",code:p.ZodIssueCode.invalid_string,message:a.message}),s.dirty());else if(a.kind==="emoji")Er||(Er=new RegExp(Dn,"u")),Er.test(e.data)||(n=this._getOrReturnCtx(e,n),(0, u.addIssueToContext)(n,{validation:"emoji",code:p.ZodIssueCode.invalid_string,message:a.message}),s.dirty());else if(a.kind==="uuid")An.test(e.data)||(n=this._getOrReturnCtx(e,n),(0, u.addIssueToContext)(n,{validation:"uuid",code:p.ZodIssueCode.invalid_string,message:a.message}),s.dirty());else if(a.kind==="nanoid")Cn.test(e.data)||(n=this._getOrReturnCtx(e,n),(0, u.addIssueToContext)(n,{validation:"nanoid",code:p.ZodIssueCode.invalid_string,message:a.message}),s.dirty());else if(a.kind==="cuid")wn.test(e.data)||(n=this._getOrReturnCtx(e,n),(0, u.addIssueToContext)(n,{validation:"cuid",code:p.ZodIssueCode.invalid_string,message:a.message}),s.dirty());else if(a.kind==="cuid2")bn.test(e.data)||(n=this._getOrReturnCtx(e,n),(0, u.addIssueToContext)(n,{validation:"cuid2",code:p.ZodIssueCode.invalid_string,message:a.message}),s.dirty());else if(a.kind==="ulid")Pn.test(e.data)||(n=this._getOrReturnCtx(e,n),(0, u.addIssueToContext)(n,{validation:"ulid",code:p.ZodIssueCode.invalid_string,message:a.message}),s.dirty());else if(a.kind==="url")try{new URL(e.data);}catch{n=this._getOrReturnCtx(e,n),(0, u.addIssueToContext)(n,{validation:"url",code:p.ZodIssueCode.invalid_string,message:a.message}),s.dirty();}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),(0, u.addIssueToContext)(n,{validation:"regex",code:p.ZodIssueCode.invalid_string,message:a.message}),s.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(n=this._getOrReturnCtx(e,n),(0, u.addIssueToContext)(n,{code:p.ZodIssueCode.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),s.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(n=this._getOrReturnCtx(e,n),(0, u.addIssueToContext)(n,{code:p.ZodIssueCode.invalid_string,validation:{startsWith:a.value},message:a.message}),s.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(n=this._getOrReturnCtx(e,n),(0, u.addIssueToContext)(n,{code:p.ZodIssueCode.invalid_string,validation:{endsWith:a.value},message:a.message}),s.dirty()):a.kind==="datetime"?Is(a).test(e.data)||(n=this._getOrReturnCtx(e,n),(0, u.addIssueToContext)(n,{code:p.ZodIssueCode.invalid_string,validation:"datetime",message:a.message}),s.dirty()):a.kind==="date"?Mn.test(e.data)||(n=this._getOrReturnCtx(e,n),(0, u.addIssueToContext)(n,{code:p.ZodIssueCode.invalid_string,validation:"date",message:a.message}),s.dirty()):a.kind==="time"?Un(a).test(e.data)||(n=this._getOrReturnCtx(e,n),(0, u.addIssueToContext)(n,{code:p.ZodIssueCode.invalid_string,validation:"time",message:a.message}),s.dirty()):a.kind==="duration"?kn.test(e.data)||(n=this._getOrReturnCtx(e,n),(0, u.addIssueToContext)(n,{validation:"duration",code:p.ZodIssueCode.invalid_string,message:a.message}),s.dirty()):a.kind==="ip"?Vn(e.data,a.version)||(n=this._getOrReturnCtx(e,n),(0, u.addIssueToContext)(n,{validation:"ip",code:p.ZodIssueCode.invalid_string,message:a.message}),s.dirty()):a.kind==="base64"?jn.test(e.data)||(n=this._getOrReturnCtx(e,n),(0, u.addIssueToContext)(n,{validation:"base64",code:p.ZodIssueCode.invalid_string,message:a.message}),s.dirty()):f.util.assertNever(a);return {status:s.value,value:e.data}}_regex(e,t,s){return this.refinement(n=>e.test(n),{validation:t,code:p.ZodIssueCode.invalid_string,...m.errorUtil.errToObj(s)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...m.errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...m.errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...m.errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...m.errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...m.errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...m.errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...m.errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...m.errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...m.errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...m.errorUtil.errToObj(e)})}datetime(e){var t,s;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:(t=e?.offset)!==null&&t!==void 0?t:!1,local:(s=e?.local)!==null&&s!==void 0?s:!1,...m.errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...m.errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...m.errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...m.errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...m.errorUtil.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...m.errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...m.errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...m.errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...m.errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...m.errorUtil.errToObj(t)})}nonempty(e){return this.min(1,m.errorUtil.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return !!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return !!this._def.checks.find(e=>e.kind==="date")}get isTime(){return !!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return !!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return !!this._def.checks.find(e=>e.kind==="email")}get isURL(){return !!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return !!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return !!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return !!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return !!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return !!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return !!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return !!this._def.checks.find(e=>e.kind==="ip")}get isBase64(){return !!this._def.checks.find(e=>e.kind==="base64")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};o.ZodString=se;se.create=r=>{var e;return new se({checks:[],typeName:y.ZodString,coerce:(e=r?.coerce)!==null&&e!==void 0?e:!1,...g(r)})};function Ln(r,e){let t=(r.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,n=t>s?t:s,a=parseInt(r.toFixed(n).replace(".","")),i=parseInt(e.toFixed(n).replace(".",""));return a%i/Math.pow(10,n)}var ce=class r extends v{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf;}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==f.ZodParsedType.number){let a=this._getOrReturnCtx(e);return (0, u.addIssueToContext)(a,{code:p.ZodIssueCode.invalid_type,expected:f.ZodParsedType.number,received:a.parsedType}),u.INVALID}let s,n=new u.ParseStatus;for(let a of this._def.checks)a.kind==="int"?f.util.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),(0, u.addIssueToContext)(s,{code:p.ZodIssueCode.invalid_type,expected:"integer",received:"float",message:a.message}),n.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(s=this._getOrReturnCtx(e,s),(0, u.addIssueToContext)(s,{code:p.ZodIssueCode.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),n.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(s=this._getOrReturnCtx(e,s),(0, u.addIssueToContext)(s,{code:p.ZodIssueCode.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),n.dirty()):a.kind==="multipleOf"?Ln(e.data,a.value)!==0&&(s=this._getOrReturnCtx(e,s),(0, u.addIssueToContext)(s,{code:p.ZodIssueCode.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),(0, u.addIssueToContext)(s,{code:p.ZodIssueCode.not_finite,message:a.message}),n.dirty()):f.util.assertNever(a);return {status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,m.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,m.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,m.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,m.errorUtil.toString(t))}setLimit(e,t,s,n){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:m.errorUtil.toString(n)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:m.errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:m.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:m.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:m.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:m.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:m.errorUtil.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:m.errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:m.errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:m.errorUtil.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return !!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&f.util.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return !0;s.kind==="min"?(t===null||s.value>t)&&(t=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value);}return Number.isFinite(t)&&Number.isFinite(e)}};o.ZodNumber=ce;ce.create=r=>new ce({checks:[],typeName:y.ZodNumber,coerce:r?.coerce||!1,...g(r)});var le=class r extends v{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte;}_parse(e){if(this._def.coerce&&(e.data=BigInt(e.data)),this._getType(e)!==f.ZodParsedType.bigint){let a=this._getOrReturnCtx(e);return (0, u.addIssueToContext)(a,{code:p.ZodIssueCode.invalid_type,expected:f.ZodParsedType.bigint,received:a.parsedType}),u.INVALID}let s,n=new u.ParseStatus;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(s=this._getOrReturnCtx(e,s),(0, u.addIssueToContext)(s,{code:p.ZodIssueCode.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),n.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(s=this._getOrReturnCtx(e,s),(0, u.addIssueToContext)(s,{code:p.ZodIssueCode.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),n.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),(0, u.addIssueToContext)(s,{code:p.ZodIssueCode.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):f.util.assertNever(a);return {status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,m.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,m.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,m.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,m.errorUtil.toString(t))}setLimit(e,t,s,n){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:m.errorUtil.toString(n)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:m.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:m.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:m.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:m.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:m.errorUtil.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};o.ZodBigInt=le;le.create=r=>{var e;return new le({checks:[],typeName:y.ZodBigInt,coerce:(e=r?.coerce)!==null&&e!==void 0?e:!1,...g(r)})};var pe=class extends v{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==f.ZodParsedType.boolean){let s=this._getOrReturnCtx(e);return (0, u.addIssueToContext)(s,{code:p.ZodIssueCode.invalid_type,expected:f.ZodParsedType.boolean,received:s.parsedType}),u.INVALID}return (0, u.OK)(e.data)}};o.ZodBoolean=pe;pe.create=r=>new pe({typeName:y.ZodBoolean,coerce:r?.coerce||!1,...g(r)});var fe=class r extends v{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==f.ZodParsedType.date){let a=this._getOrReturnCtx(e);return (0, u.addIssueToContext)(a,{code:p.ZodIssueCode.invalid_type,expected:f.ZodParsedType.date,received:a.parsedType}),u.INVALID}if(isNaN(e.data.getTime())){let a=this._getOrReturnCtx(e);return (0, u.addIssueToContext)(a,{code:p.ZodIssueCode.invalid_date}),u.INVALID}let s=new u.ParseStatus,n;for(let a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(n=this._getOrReturnCtx(e,n),(0, u.addIssueToContext)(n,{code:p.ZodIssueCode.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),s.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(n=this._getOrReturnCtx(e,n),(0, u.addIssueToContext)(n,{code:p.ZodIssueCode.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),s.dirty()):f.util.assertNever(a);return {status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:m.errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:m.errorUtil.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};o.ZodDate=fe;fe.create=r=>new fe({checks:[],coerce:r?.coerce||!1,typeName:y.ZodDate,...g(r)});var De=class extends v{_parse(e){if(this._getType(e)!==f.ZodParsedType.symbol){let s=this._getOrReturnCtx(e);return (0, u.addIssueToContext)(s,{code:p.ZodIssueCode.invalid_type,expected:f.ZodParsedType.symbol,received:s.parsedType}),u.INVALID}return (0, u.OK)(e.data)}};o.ZodSymbol=De;De.create=r=>new De({typeName:y.ZodSymbol,...g(r)});var he=class extends v{_parse(e){if(this._getType(e)!==f.ZodParsedType.undefined){let s=this._getOrReturnCtx(e);return (0, u.addIssueToContext)(s,{code:p.ZodIssueCode.invalid_type,expected:f.ZodParsedType.undefined,received:s.parsedType}),u.INVALID}return (0, u.OK)(e.data)}};o.ZodUndefined=he;he.create=r=>new he({typeName:y.ZodUndefined,...g(r)});var me=class extends v{_parse(e){if(this._getType(e)!==f.ZodParsedType.null){let s=this._getOrReturnCtx(e);return (0, u.addIssueToContext)(s,{code:p.ZodIssueCode.invalid_type,expected:f.ZodParsedType.null,received:s.parsedType}),u.INVALID}return (0, u.OK)(e.data)}};o.ZodNull=me;me.create=r=>new me({typeName:y.ZodNull,...g(r)});var ne=class extends v{constructor(){super(...arguments),this._any=!0;}_parse(e){return (0, u.OK)(e.data)}};o.ZodAny=ne;ne.create=r=>new ne({typeName:y.ZodAny,...g(r)});var Y=class extends v{constructor(){super(...arguments),this._unknown=!0;}_parse(e){return (0, u.OK)(e.data)}};o.ZodUnknown=Y;Y.create=r=>new Y({typeName:y.ZodUnknown,...g(r)});var L=class extends v{_parse(e){let t=this._getOrReturnCtx(e);return (0, u.addIssueToContext)(t,{code:p.ZodIssueCode.invalid_type,expected:f.ZodParsedType.never,received:t.parsedType}),u.INVALID}};o.ZodNever=L;L.create=r=>new L({typeName:y.ZodNever,...g(r)});var Se=class extends v{_parse(e){if(this._getType(e)!==f.ZodParsedType.undefined){let s=this._getOrReturnCtx(e);return (0, u.addIssueToContext)(s,{code:p.ZodIssueCode.invalid_type,expected:f.ZodParsedType.void,received:s.parsedType}),u.INVALID}return (0, u.OK)(e.data)}};o.ZodVoid=Se;Se.create=r=>new Se({typeName:y.ZodVoid,...g(r)});var J=class r extends v{_parse(e){let{ctx:t,status:s}=this._processInputParams(e),n=this._def;if(t.parsedType!==f.ZodParsedType.array)return (0, u.addIssueToContext)(t,{code:p.ZodIssueCode.invalid_type,expected:f.ZodParsedType.array,received:t.parsedType}),u.INVALID;if(n.exactLength!==null){let i=t.data.length>n.exactLength.value,d=t.data.length<n.exactLength.value;(i||d)&&((0, u.addIssueToContext)(t,{code:i?p.ZodIssueCode.too_big:p.ZodIssueCode.too_small,minimum:d?n.exactLength.value:void 0,maximum:i?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),s.dirty());}if(n.minLength!==null&&t.data.length<n.minLength.value&&((0, u.addIssueToContext)(t,{code:p.ZodIssueCode.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),s.dirty()),n.maxLength!==null&&t.data.length>n.maxLength.value&&((0, u.addIssueToContext)(t,{code:p.ZodIssueCode.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((i,d)=>n.type._parseAsync(new M(t,i,t.path,d)))).then(i=>u.ParseStatus.mergeArray(s,i));let a=[...t.data].map((i,d)=>n.type._parseSync(new M(t,i,t.path,d)));return u.ParseStatus.mergeArray(s,a)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:m.errorUtil.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:m.errorUtil.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:m.errorUtil.toString(t)}})}nonempty(e){return this.min(1,e)}};o.ZodArray=J;J.create=(r,e)=>new J({type:r,minLength:null,maxLength:null,exactLength:null,typeName:y.ZodArray,...g(e)});function Ne(r){if(r instanceof k){let e={};for(let t in r.shape){let s=r.shape[t];e[t]=j.create(Ne(s));}return new k({...r._def,shape:()=>e})}else return r instanceof J?new J({...r._def,type:Ne(r.element)}):r instanceof j?j.create(Ne(r.unwrap())):r instanceof z?z.create(Ne(r.unwrap())):r instanceof K?K.create(r.items.map(e=>Ne(e))):r}var k=class r extends v{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend;}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=f.util.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==f.ZodParsedType.object){let l=this._getOrReturnCtx(e);return (0, u.addIssueToContext)(l,{code:p.ZodIssueCode.invalid_type,expected:f.ZodParsedType.object,received:l.parsedType}),u.INVALID}let{status:s,ctx:n}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),d=[];if(!(this._def.catchall instanceof L&&this._def.unknownKeys==="strip"))for(let l in n.data)i.includes(l)||d.push(l);let c=[];for(let l of i){let h=a[l],E=n.data[l];c.push({key:{status:"valid",value:l},value:h._parse(new M(n,E,n.path,l)),alwaysSet:l in n.data});}if(this._def.catchall instanceof L){let l=this._def.unknownKeys;if(l==="passthrough")for(let h of d)c.push({key:{status:"valid",value:h},value:{status:"valid",value:n.data[h]}});else if(l==="strict")d.length>0&&((0, u.addIssueToContext)(n,{code:p.ZodIssueCode.unrecognized_keys,keys:d}),s.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else {let l=this._def.catchall;for(let h of d){let E=n.data[h];c.push({key:{status:"valid",value:h},value:l._parse(new M(n,E,n.path,h)),alwaysSet:h in n.data});}}return n.common.async?Promise.resolve().then(async()=>{let l=[];for(let h of c){let E=await h.key,X=await h.value;l.push({key:E,value:X,alwaysSet:h.alwaysSet});}return l}).then(l=>u.ParseStatus.mergeObjectSync(s,l)):u.ParseStatus.mergeObjectSync(s,c)}get shape(){return this._def.shape()}strict(e){return m.errorUtil.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,s)=>{var n,a,i,d;let c=(i=(a=(n=this._def).errorMap)===null||a===void 0?void 0:a.call(n,t,s).message)!==null&&i!==void 0?i:s.defaultError;return t.code==="unrecognized_keys"?{message:(d=m.errorUtil.errToObj(e).message)!==null&&d!==void 0?d:c}:{message:c}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:y.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};return f.util.objectKeys(e).forEach(s=>{e[s]&&this.shape[s]&&(t[s]=this.shape[s]);}),new r({...this._def,shape:()=>t})}omit(e){let t={};return f.util.objectKeys(this.shape).forEach(s=>{e[s]||(t[s]=this.shape[s]);}),new r({...this._def,shape:()=>t})}deepPartial(){return Ne(this)}partial(e){let t={};return f.util.objectKeys(this.shape).forEach(s=>{let n=this.shape[s];e&&!e[s]?t[s]=n:t[s]=n.optional();}),new r({...this._def,shape:()=>t})}required(e){let t={};return f.util.objectKeys(this.shape).forEach(s=>{if(e&&!e[s])t[s]=this.shape[s];else {let a=this.shape[s];for(;a instanceof j;)a=a._def.innerType;t[s]=a;}}),new r({...this._def,shape:()=>t})}keyof(){return xs(f.util.objectKeys(this.shape))}};o.ZodObject=k;k.create=(r,e)=>new k({shape:()=>r,unknownKeys:"strip",catchall:L.create(),typeName:y.ZodObject,...g(e)});k.strictCreate=(r,e)=>new k({shape:()=>r,unknownKeys:"strict",catchall:L.create(),typeName:y.ZodObject,...g(e)});k.lazycreate=(r,e)=>new k({shape:r,unknownKeys:"strip",catchall:L.create(),typeName:y.ZodObject,...g(e)});var ye=class extends v{_parse(e){let{ctx:t}=this._processInputParams(e),s=this._def.options;function n(a){for(let d of a)if(d.result.status==="valid")return d.result;for(let d of a)if(d.result.status==="dirty")return t.common.issues.push(...d.ctx.common.issues),d.result;let i=a.map(d=>new p.ZodError(d.ctx.common.issues));return (0, u.addIssueToContext)(t,{code:p.ZodIssueCode.invalid_union,unionErrors:i}),u.INVALID}if(t.common.async)return Promise.all(s.map(async a=>{let i={...t,common:{...t.common,issues:[]},parent:null};return {result:await a._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(n);{let a,i=[];for(let c of s){let l={...t,common:{...t.common,issues:[]},parent:null},h=c._parseSync({data:t.data,path:t.path,parent:l});if(h.status==="valid")return h;h.status==="dirty"&&!a&&(a={result:h,ctx:l}),l.common.issues.length&&i.push(l.common.issues);}if(a)return t.common.issues.push(...a.ctx.common.issues),a.result;let d=i.map(c=>new p.ZodError(c));return (0, u.addIssueToContext)(t,{code:p.ZodIssueCode.invalid_union,unionErrors:d}),u.INVALID}}get options(){return this._def.options}};o.ZodUnion=ye;ye.create=(r,e)=>new ye({options:r,typeName:y.ZodUnion,...g(e)});var G=r=>r instanceof ge?G(r.schema):r instanceof D?G(r.innerType()):r instanceof ve?[r.value]:r instanceof Te?r.options:r instanceof Oe?f.util.objectValues(r.enum):r instanceof Ie?G(r._def.innerType):r instanceof he?[void 0]:r instanceof me?[null]:r instanceof j?[void 0,...G(r.unwrap())]:r instanceof z?[null,...G(r.unwrap())]:r instanceof Je||r instanceof Re?G(r.unwrap()):r instanceof xe?G(r._def.innerType):[],Ct=class r extends v{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.ZodParsedType.object)return (0, u.addIssueToContext)(t,{code:p.ZodIssueCode.invalid_type,expected:f.ZodParsedType.object,received:t.parsedType}),u.INVALID;let s=this.discriminator,n=t.data[s],a=this.optionsMap.get(n);return a?t.common.async?a._parseAsync({data:t.data,path:t.path,parent:t}):a._parseSync({data:t.data,path:t.path,parent:t}):((0, u.addIssueToContext)(t,{code:p.ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),u.INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,s){let n=new Map;for(let a of t){let i=G(a.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let d of i){if(n.has(d))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(d)}`);n.set(d,a);}}return new r({typeName:y.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...g(s)})}};o.ZodDiscriminatedUnion=Ct;function wr(r,e){let t=(0, f.getParsedType)(r),s=(0, f.getParsedType)(e);if(r===e)return {valid:!0,data:r};if(t===f.ZodParsedType.object&&s===f.ZodParsedType.object){let n=f.util.objectKeys(e),a=f.util.objectKeys(r).filter(d=>n.indexOf(d)!==-1),i={...r,...e};for(let d of a){let c=wr(r[d],e[d]);if(!c.valid)return {valid:!1};i[d]=c.data;}return {valid:!0,data:i}}else if(t===f.ZodParsedType.array&&s===f.ZodParsedType.array){if(r.length!==e.length)return {valid:!1};let n=[];for(let a=0;a<r.length;a++){let i=r[a],d=e[a],c=wr(i,d);if(!c.valid)return {valid:!1};n.push(c.data);}return {valid:!0,data:n}}else return t===f.ZodParsedType.date&&s===f.ZodParsedType.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var _e=class extends v{_parse(e){let{status:t,ctx:s}=this._processInputParams(e),n=(a,i)=>{if((0, u.isAborted)(a)||(0, u.isAborted)(i))return u.INVALID;let d=wr(a.value,i.value);return d.valid?(((0, u.isDirty)(a)||(0, u.isDirty)(i))&&t.dirty(),{status:t.value,value:d.data}):((0, u.addIssueToContext)(s,{code:p.ZodIssueCode.invalid_intersection_types}),u.INVALID)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([a,i])=>n(a,i)):n(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}};o.ZodIntersection=_e;_e.create=(r,e,t)=>new _e({left:r,right:e,typeName:y.ZodIntersection,...g(t)});var K=class r extends v{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.ZodParsedType.array)return (0, u.addIssueToContext)(s,{code:p.ZodIssueCode.invalid_type,expected:f.ZodParsedType.array,received:s.parsedType}),u.INVALID;if(s.data.length<this._def.items.length)return (0, u.addIssueToContext)(s,{code:p.ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),u.INVALID;!this._def.rest&&s.data.length>this._def.items.length&&((0, u.addIssueToContext)(s,{code:p.ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let a=[...s.data].map((i,d)=>{let c=this._def.items[d]||this._def.rest;return c?c._parse(new M(s,i,s.path,d)):null}).filter(i=>!!i);return s.common.async?Promise.all(a).then(i=>u.ParseStatus.mergeArray(t,i)):u.ParseStatus.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};o.ZodTuple=K;K.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new K({items:r,typeName:y.ZodTuple,rest:null,...g(e)})};var kt=class r extends v{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.ZodParsedType.object)return (0, u.addIssueToContext)(s,{code:p.ZodIssueCode.invalid_type,expected:f.ZodParsedType.object,received:s.parsedType}),u.INVALID;let n=[],a=this._def.keyType,i=this._def.valueType;for(let d in s.data)n.push({key:a._parse(new M(s,d,s.path,d)),value:i._parse(new M(s,s.data[d],s.path,d)),alwaysSet:d in s.data});return s.common.async?u.ParseStatus.mergeObjectAsync(t,n):u.ParseStatus.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,s){return t instanceof v?new r({keyType:e,valueType:t,typeName:y.ZodRecord,...g(s)}):new r({keyType:se.create(),valueType:e,typeName:y.ZodRecord,...g(t)})}};o.ZodRecord=kt;var Ze=class extends v{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.ZodParsedType.map)return (0, u.addIssueToContext)(s,{code:p.ZodIssueCode.invalid_type,expected:f.ZodParsedType.map,received:s.parsedType}),u.INVALID;let n=this._def.keyType,a=this._def.valueType,i=[...s.data.entries()].map(([d,c],l)=>({key:n._parse(new M(s,d,s.path,[l,"key"])),value:a._parse(new M(s,c,s.path,[l,"value"]))}));if(s.common.async){let d=new Map;return Promise.resolve().then(async()=>{for(let c of i){let l=await c.key,h=await c.value;if(l.status==="aborted"||h.status==="aborted")return u.INVALID;(l.status==="dirty"||h.status==="dirty")&&t.dirty(),d.set(l.value,h.value);}return {status:t.value,value:d}})}else {let d=new Map;for(let c of i){let l=c.key,h=c.value;if(l.status==="aborted"||h.status==="aborted")return u.INVALID;(l.status==="dirty"||h.status==="dirty")&&t.dirty(),d.set(l.value,h.value);}return {status:t.value,value:d}}}};o.ZodMap=Ze;Ze.create=(r,e,t)=>new Ze({valueType:e,keyType:r,typeName:y.ZodMap,...g(t)});var je=class r extends v{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.ZodParsedType.set)return (0, u.addIssueToContext)(s,{code:p.ZodIssueCode.invalid_type,expected:f.ZodParsedType.set,received:s.parsedType}),u.INVALID;let n=this._def;n.minSize!==null&&s.data.size<n.minSize.value&&((0, u.addIssueToContext)(s,{code:p.ZodIssueCode.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),n.maxSize!==null&&s.data.size>n.maxSize.value&&((0, u.addIssueToContext)(s,{code:p.ZodIssueCode.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());let a=this._def.valueType;function i(c){let l=new Set;for(let h of c){if(h.status==="aborted")return u.INVALID;h.status==="dirty"&&t.dirty(),l.add(h.value);}return {status:t.value,value:l}}let d=[...s.data.values()].map((c,l)=>a._parse(new M(s,c,s.path,l)));return s.common.async?Promise.all(d).then(c=>i(c)):i(d)}min(e,t){return new r({...this._def,minSize:{value:e,message:m.errorUtil.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:m.errorUtil.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};o.ZodSet=je;je.create=(r,e)=>new je({valueType:r,minSize:null,maxSize:null,typeName:y.ZodSet,...g(e)});var Nt=class r extends v{constructor(){super(...arguments),this.validate=this.implement;}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.ZodParsedType.function)return (0, u.addIssueToContext)(t,{code:p.ZodIssueCode.invalid_type,expected:f.ZodParsedType.function,received:t.parsedType}),u.INVALID;function s(d,c){return (0, u.makeIssue)({data:d,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,(0, Pt.getErrorMap)(),Pt.defaultErrorMap].filter(l=>!!l),issueData:{code:p.ZodIssueCode.invalid_arguments,argumentsError:c}})}function n(d,c){return (0, u.makeIssue)({data:d,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,(0, Pt.getErrorMap)(),Pt.defaultErrorMap].filter(l=>!!l),issueData:{code:p.ZodIssueCode.invalid_return_type,returnTypeError:c}})}let a={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof ae){let d=this;return (0, u.OK)(async function(...c){let l=new p.ZodError([]),h=await d._def.args.parseAsync(c,a).catch(Q=>{throw l.addIssue(s(c,Q)),l}),E=await Reflect.apply(i,this,h);return await d._def.returns._def.type.parseAsync(E,a).catch(Q=>{throw l.addIssue(n(E,Q)),l})})}else {let d=this;return (0, u.OK)(function(...c){let l=d._def.args.safeParse(c,a);if(!l.success)throw new p.ZodError([s(c,l.error)]);let h=Reflect.apply(i,this,l.data),E=d._def.returns.safeParse(h,a);if(!E.success)throw new p.ZodError([n(h,E.error)]);return E.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:K.create(e).rest(Y.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,s){return new r({args:e||K.create([]).rest(Y.create()),returns:t||Y.create(),typeName:y.ZodFunction,...g(s)})}};o.ZodFunction=Nt;var ge=class extends v{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};o.ZodLazy=ge;ge.create=(r,e)=>new ge({getter:r,typeName:y.ZodLazy,...g(e)});var ve=class extends v{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return (0, u.addIssueToContext)(t,{received:t.data,code:p.ZodIssueCode.invalid_literal,expected:this._def.value}),u.INVALID}return {status:"valid",value:e.data}}get value(){return this._def.value}};o.ZodLiteral=ve;ve.create=(r,e)=>new ve({value:r,typeName:y.ZodLiteral,...g(e)});function xs(r,e){return new Te({values:r,typeName:y.ZodEnum,...g(e)})}var Te=class r extends v{constructor(){super(...arguments),Ge.set(this,void 0);}_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),s=this._def.values;return (0, u.addIssueToContext)(t,{expected:f.util.joinValues(s),received:t.parsedType,code:p.ZodIssueCode.invalid_type}),u.INVALID}if(At(this,Ge,"f")||vs(this,Ge,new Set(this._def.values),"f"),!At(this,Ge,"f").has(e.data)){let t=this._getOrReturnCtx(e),s=this._def.values;return (0, u.addIssueToContext)(t,{received:t.data,code:p.ZodIssueCode.invalid_enum_value,options:s}),u.INVALID}return (0, u.OK)(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(s=>!e.includes(s)),{...this._def,...t})}};o.ZodEnum=Te;Ge=new WeakMap;Te.create=xs;var Oe=class extends v{constructor(){super(...arguments),Ye.set(this,void 0);}_parse(e){let t=f.util.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==f.ZodParsedType.string&&s.parsedType!==f.ZodParsedType.number){let n=f.util.objectValues(t);return (0, u.addIssueToContext)(s,{expected:f.util.joinValues(n),received:s.parsedType,code:p.ZodIssueCode.invalid_type}),u.INVALID}if(At(this,Ye,"f")||vs(this,Ye,new Set(f.util.getValidEnumValues(this._def.values)),"f"),!At(this,Ye,"f").has(e.data)){let n=f.util.objectValues(t);return (0, u.addIssueToContext)(s,{received:s.data,code:p.ZodIssueCode.invalid_enum_value,options:n}),u.INVALID}return (0, u.OK)(e.data)}get enum(){return this._def.values}};o.ZodNativeEnum=Oe;Ye=new WeakMap;Oe.create=(r,e)=>new Oe({values:r,typeName:y.ZodNativeEnum,...g(e)});var ae=class extends v{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.ZodParsedType.promise&&t.common.async===!1)return (0, u.addIssueToContext)(t,{code:p.ZodIssueCode.invalid_type,expected:f.ZodParsedType.promise,received:t.parsedType}),u.INVALID;let s=t.parsedType===f.ZodParsedType.promise?t.data:Promise.resolve(t.data);return (0, u.OK)(s.then(n=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}};o.ZodPromise=ae;ae.create=(r,e)=>new ae({type:r,typeName:y.ZodPromise,...g(e)});var D=class extends v{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===y.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:s}=this._processInputParams(e),n=this._def.effect||null,a={addIssue:i=>{(0, u.addIssueToContext)(s,i),i.fatal?t.abort():t.dirty();},get path(){return s.path}};if(a.addIssue=a.addIssue.bind(a),n.type==="preprocess"){let i=n.transform(s.data,a);if(s.common.async)return Promise.resolve(i).then(async d=>{if(t.value==="aborted")return u.INVALID;let c=await this._def.schema._parseAsync({data:d,path:s.path,parent:s});return c.status==="aborted"?u.INVALID:c.status==="dirty"||t.value==="dirty"?(0, u.DIRTY)(c.value):c});{if(t.value==="aborted")return u.INVALID;let d=this._def.schema._parseSync({data:i,path:s.path,parent:s});return d.status==="aborted"?u.INVALID:d.status==="dirty"||t.value==="dirty"?(0, u.DIRTY)(d.value):d}}if(n.type==="refinement"){let i=d=>{let c=n.refinement(d,a);if(s.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return d};if(s.common.async===!1){let d=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return d.status==="aborted"?u.INVALID:(d.status==="dirty"&&t.dirty(),i(d.value),{status:t.value,value:d.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(d=>d.status==="aborted"?u.INVALID:(d.status==="dirty"&&t.dirty(),i(d.value).then(()=>({status:t.value,value:d.value}))))}if(n.type==="transform")if(s.common.async===!1){let i=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!(0, u.isValid)(i))return i;let d=n.transform(i.value,a);if(d instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return {status:t.value,value:d}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(i=>(0, u.isValid)(i)?Promise.resolve(n.transform(i.value,a)).then(d=>({status:t.value,value:d})):i);f.util.assertNever(n);}};o.ZodEffects=D;o.ZodTransformer=D;D.create=(r,e,t)=>new D({schema:r,typeName:y.ZodEffects,effect:e,...g(t)});D.createWithPreprocess=(r,e,t)=>new D({schema:e,effect:{type:"preprocess",transform:r},typeName:y.ZodEffects,...g(t)});var j=class extends v{_parse(e){return this._getType(e)===f.ZodParsedType.undefined?(0, u.OK)(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};o.ZodOptional=j;j.create=(r,e)=>new j({innerType:r,typeName:y.ZodOptional,...g(e)});var z=class extends v{_parse(e){return this._getType(e)===f.ZodParsedType.null?(0, u.OK)(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};o.ZodNullable=z;z.create=(r,e)=>new z({innerType:r,typeName:y.ZodNullable,...g(e)});var Ie=class extends v{_parse(e){let{ctx:t}=this._processInputParams(e),s=t.data;return t.parsedType===f.ZodParsedType.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};o.ZodDefault=Ie;Ie.create=(r,e)=>new Ie({innerType:r,typeName:y.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...g(e)});var xe=class extends v{_parse(e){let{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return (0, u.isAsync)(n)?n.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new p.ZodError(s.common.issues)},input:s.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new p.ZodError(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};o.ZodCatch=xe;xe.create=(r,e)=>new xe({innerType:r,typeName:y.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...g(e)});var Me=class extends v{_parse(e){if(this._getType(e)!==f.ZodParsedType.nan){let s=this._getOrReturnCtx(e);return (0, u.addIssueToContext)(s,{code:p.ZodIssueCode.invalid_type,expected:f.ZodParsedType.nan,received:s.parsedType}),u.INVALID}return {status:"valid",value:e.data}}};o.ZodNaN=Me;Me.create=r=>new Me({typeName:y.ZodNaN,...g(r)});o.BRAND=Symbol("zod_brand");var Je=class extends v{_parse(e){let{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}};o.ZodBranded=Je;var Xe=class r extends v{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.common.async)return (async()=>{let a=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?u.INVALID:a.status==="dirty"?(t.dirty(),(0, u.DIRTY)(a.value)):this._def.out._parseAsync({data:a.value,path:s.path,parent:s})})();{let n=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return n.status==="aborted"?u.INVALID:n.status==="dirty"?(t.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:s.path,parent:s})}}static create(e,t){return new r({in:e,out:t,typeName:y.ZodPipeline})}};o.ZodPipeline=Xe;var Re=class extends v{_parse(e){let t=this._def.innerType._parse(e),s=n=>((0, u.isValid)(n)&&(n.value=Object.freeze(n.value)),n);return (0, u.isAsync)(t)?t.then(n=>s(n)):s(t)}unwrap(){return this._def.innerType}};o.ZodReadonly=Re;Re.create=(r,e)=>new Re({innerType:r,typeName:y.ZodReadonly,...g(e)});function Rs(r,e={},t){return r?ne.create().superRefine((s,n)=>{var a,i;if(!r(s)){let d=typeof e=="function"?e(s):typeof e=="string"?{message:e}:e,c=(i=(a=d.fatal)!==null&&a!==void 0?a:t)!==null&&i!==void 0?i:!0,l=typeof d=="string"?{message:d}:d;n.addIssue({code:"custom",...l,fatal:c});}}):ne.create()}o.custom=Rs;o.late={object:k.lazycreate};var y;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly";})(y=o.ZodFirstPartyTypeKind||(o.ZodFirstPartyTypeKind={}));var $n=(r,e={message:`Input not instance of ${r.name}`})=>Rs(t=>t instanceof r,e);o.instanceof=$n;var Es=se.create;o.string=Es;var ws=ce.create;o.number=ws;var qn=Me.create;o.nan=qn;var Fn=le.create;o.bigint=Fn;var bs=pe.create;o.boolean=bs;var Wn=fe.create;o.date=Wn;var Kn=De.create;o.symbol=Kn;var zn=he.create;o.undefined=zn;var Bn=me.create;o.null=Bn;var Gn=ne.create;o.any=Gn;var Yn=Y.create;o.unknown=Yn;var Jn=L.create;o.never=Jn;var Xn=Se.create;o.void=Xn;var Qn=J.create;o.array=Qn;var Hn=k.create;o.object=Hn;var ea=k.strictCreate;o.strictObject=ea;var ta=ye.create;o.union=ta;var ra=Ct.create;o.discriminatedUnion=ra;var sa=_e.create;o.intersection=sa;var na=K.create;o.tuple=na;var aa=kt.create;o.record=aa;var ia=Ze.create;o.map=ia;var oa=je.create;o.set=oa;var da=Nt.create;o.function=da;var ua=ge.create;o.lazy=ua;var ca=ve.create;o.literal=ca;var la=Te.create;o.enum=la;var pa=Oe.create;o.nativeEnum=pa;var fa=ae.create;o.promise=fa;var Ps=D.create;o.effect=Ps;o.transformer=Ps;var ha=j.create;o.optional=ha;var ma=z.create;o.nullable=ma;var ya=D.createWithPreprocess;o.preprocess=ya;var _a=Xe.create;o.pipeline=_a;var ga=()=>Es().optional();o.ostring=ga;var va=()=>ws().optional();o.onumber=va;var Ta=()=>bs().optional();o.oboolean=Ta;o.coerce={string:r=>se.create({...r,coerce:!0}),number:r=>ce.create({...r,coerce:!0}),boolean:r=>pe.create({...r,coerce:!0}),bigint:r=>le.create({...r,coerce:!0}),date:r=>fe.create({...r,coerce:!0})};o.NEVER=u.INVALID;});var br=_(U=>{var Oa=U&&U.__createBinding||(Object.create?function(r,e,t,s){s===void 0&&(s=t),Object.defineProperty(r,s,{enumerable:!0,get:function(){return e[t]}});}:function(r,e,t,s){s===void 0&&(s=t),r[s]=e[t];}),Ue=U&&U.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Oa(e,r,t);};Object.defineProperty(U,"__esModule",{value:!0});Ue(bt(),U);Ue(Rr(),U);Ue(ys(),U);Ue(Ke(),U);Ue(As(),U);Ue(wt(),U);});var Dt=_(N=>{var Cs=N&&N.__createBinding||(Object.create?function(r,e,t,s){s===void 0&&(s=t),Object.defineProperty(r,s,{enumerable:!0,get:function(){return e[t]}});}:function(r,e,t,s){s===void 0&&(s=t),r[s]=e[t];}),Ia=N&&N.__setModuleDefault||(Object.create?function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e});}:function(r,e){r.default=e;}),xa=N&&N.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&Cs(e,r,t);return Ia(e,r),e},Ra=N&&N.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Cs(e,r,t);};Object.defineProperty(N,"__esModule",{value:!0});N.z=void 0;var ks=xa(br());N.z=ks;Ra(br(),N);N.default=ks;});var Pr=_(St=>{Object.defineProperty(St,"__esModule",{value:!0});St.parseAnyDef=void 0;function Ea(){return {}}St.parseAnyDef=Ea;});var Ar=_(jt=>{Object.defineProperty(jt,"__esModule",{value:!0});jt.parseArrayDef=void 0;var wa=Dt(),Zt=te(),ba=P();function Pa(r,e){let t={type:"array"};return r.type?._def?.typeName!==wa.ZodFirstPartyTypeKind.ZodAny&&(t.items=(0, ba.parseDef)(r.type._def,{...e,currentPath:[...e.currentPath,"items"]})),r.minLength&&(0, Zt.setResponseValueAndErrors)(t,"minItems",r.minLength.value,r.minLength.message,e),r.maxLength&&(0, Zt.setResponseValueAndErrors)(t,"maxItems",r.maxLength.value,r.maxLength.message,e),r.exactLength&&((0, Zt.setResponseValueAndErrors)(t,"minItems",r.exactLength.value,r.exactLength.message,e),(0, Zt.setResponseValueAndErrors)(t,"maxItems",r.exactLength.value,r.exactLength.message,e)),t}jt.parseArrayDef=Pa;});var Cr=_(Mt=>{Object.defineProperty(Mt,"__esModule",{value:!0});Mt.parseBigintDef=void 0;var Ee=te();function Aa(r,e){let t={type:"integer",format:"int64"};if(!r.checks)return t;for(let s of r.checks)switch(s.kind){case"min":e.target==="jsonSchema7"?s.inclusive?(0, Ee.setResponseValueAndErrors)(t,"minimum",s.value,s.message,e):(0, Ee.setResponseValueAndErrors)(t,"exclusiveMinimum",s.value,s.message,e):(s.inclusive||(t.exclusiveMinimum=!0),(0, Ee.setResponseValueAndErrors)(t,"minimum",s.value,s.message,e));break;case"max":e.target==="jsonSchema7"?s.inclusive?(0, Ee.setResponseValueAndErrors)(t,"maximum",s.value,s.message,e):(0, Ee.setResponseValueAndErrors)(t,"exclusiveMaximum",s.value,s.message,e):(s.inclusive||(t.exclusiveMaximum=!0),(0, Ee.setResponseValueAndErrors)(t,"maximum",s.value,s.message,e));break;case"multipleOf":(0, Ee.setResponseValueAndErrors)(t,"multipleOf",s.value,s.message,e);break}return t}Mt.parseBigintDef=Aa;});var kr=_(Ut=>{Object.defineProperty(Ut,"__esModule",{value:!0});Ut.parseBooleanDef=void 0;function Ca(){return {type:"boolean"}}Ut.parseBooleanDef=Ca;});var Nr=_(Vt=>{Object.defineProperty(Vt,"__esModule",{value:!0});Vt.parseBrandedDef=void 0;var ka=P();function Na(r,e){return (0, ka.parseDef)(r.type._def,e)}Vt.parseBrandedDef=Na;});var Dr=_(Lt=>{Object.defineProperty(Lt,"__esModule",{value:!0});Lt.parseCatchDef=void 0;var Da=P(),Sa=(r,e)=>(0, Da.parseDef)(r.innerType._def,e);Lt.parseCatchDef=Sa;});var Sr=_($t=>{Object.defineProperty($t,"__esModule",{value:!0});$t.parseDateDef=void 0;var Ns=te();function Ds(r,e,t){let s=t??e.dateStrategy;if(Array.isArray(s))return {anyOf:s.map((n,a)=>Ds(r,e,n))};switch(s){case"string":case"format:date-time":return {type:"string",format:"date-time"};case"format:date":return {type:"string",format:"date"};case"integer":return Za(r,e)}}$t.parseDateDef=Ds;var Za=(r,e)=>{let t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(let s of r.checks)switch(s.kind){case"min":(0, Ns.setResponseValueAndErrors)(t,"minimum",s.value,s.message,e);break;case"max":(0, Ns.setResponseValueAndErrors)(t,"maximum",s.value,s.message,e);break}return t};});var Zr=_(qt=>{Object.defineProperty(qt,"__esModule",{value:!0});qt.parseDefaultDef=void 0;var ja=P();function Ma(r,e){return {...(0, ja.parseDef)(r.innerType._def,e),default:r.defaultValue()}}qt.parseDefaultDef=Ma;});var jr=_(Ft=>{Object.defineProperty(Ft,"__esModule",{value:!0});Ft.parseEffectsDef=void 0;var Ua=P();function Va(r,e){return e.effectStrategy==="input"?(0, Ua.parseDef)(r.schema._def,e):{}}Ft.parseEffectsDef=Va;});var Mr=_(Wt=>{Object.defineProperty(Wt,"__esModule",{value:!0});Wt.parseEnumDef=void 0;function La(r){return {type:"string",enum:r.values}}Wt.parseEnumDef=La;});var Ur=_(Kt=>{Object.defineProperty(Kt,"__esModule",{value:!0});Kt.parseIntersectionDef=void 0;var Ss=P(),$a=r=>"type"in r&&r.type==="string"?!1:"allOf"in r;function qa(r,e){let t=[(0, Ss.parseDef)(r.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),(0, Ss.parseDef)(r.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(a=>!!a),s=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,n=[];return t.forEach(a=>{if($a(a))n.push(...a.allOf),a.unevaluatedProperties===void 0&&(s=void 0);else {let i=a;if("additionalProperties"in a&&a.additionalProperties===!1){let{additionalProperties:d,...c}=a;i=c;}else s=void 0;n.push(i);}}),n.length?{allOf:n,...s}:void 0}Kt.parseIntersectionDef=qa;});var Vr=_(zt=>{Object.defineProperty(zt,"__esModule",{value:!0});zt.parseLiteralDef=void 0;function Fa(r,e){let t=typeof r.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(r.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[r.value]}:{type:t==="bigint"?"integer":t,const:r.value}}zt.parseLiteralDef=Fa;});var Bt=_(S=>{Object.defineProperty(S,"__esModule",{value:!0});S.parseStringDef=S.zodPatterns=void 0;var we=te();S.zodPatterns={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u"),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};function Wa(r,e){let t={type:"string"};function s(n){return e.patternStrategy==="escape"?Ka(n):n}if(r.checks)for(let n of r.checks)switch(n.kind){case"min":(0, we.setResponseValueAndErrors)(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e);break;case"max":(0, we.setResponseValueAndErrors)(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":$(t,"email",n.message,e);break;case"format:idn-email":$(t,"idn-email",n.message,e);break;case"pattern:zod":q(t,S.zodPatterns.email,n.message,e);break}break;case"url":$(t,"uri",n.message,e);break;case"uuid":$(t,"uuid",n.message,e);break;case"regex":q(t,n.regex,n.message,e);break;case"cuid":q(t,S.zodPatterns.cuid,n.message,e);break;case"cuid2":q(t,S.zodPatterns.cuid2,n.message,e);break;case"startsWith":q(t,RegExp(`^${s(n.value)}`),n.message,e);break;case"endsWith":q(t,RegExp(`${s(n.value)}$`),n.message,e);break;case"datetime":$(t,"date-time",n.message,e);break;case"date":$(t,"date",n.message,e);break;case"time":$(t,"time",n.message,e);break;case"duration":$(t,"duration",n.message,e);break;case"length":(0, we.setResponseValueAndErrors)(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e),(0, we.setResponseValueAndErrors)(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"includes":{q(t,RegExp(s(n.value)),n.message,e);break}case"ip":{n.version!=="v6"&&$(t,"ipv4",n.message,e),n.version!=="v4"&&$(t,"ipv6",n.message,e);break}case"emoji":q(t,S.zodPatterns.emoji,n.message,e);break;case"ulid":{q(t,S.zodPatterns.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{$(t,"binary",n.message,e);break}case"contentEncoding:base64":{(0, we.setResponseValueAndErrors)(t,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{q(t,S.zodPatterns.base64,n.message,e);break}}break}case"nanoid":q(t,S.zodPatterns.nanoid,n.message,e);}return t}S.parseStringDef=Wa;var Ka=r=>Array.from(r).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),$=(r,e,t,s)=>{r.format||r.anyOf?.some(n=>n.format)?(r.anyOf||(r.anyOf=[]),r.format&&(r.anyOf.push({format:r.format,...r.errorMessage&&s.errorMessages&&{errorMessage:{format:r.errorMessage.format}}}),delete r.format,r.errorMessage&&(delete r.errorMessage.format,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.anyOf.push({format:e,...t&&s.errorMessages&&{errorMessage:{format:t}}})):(0, we.setResponseValueAndErrors)(r,"format",e,t,s);},q=(r,e,t,s)=>{r.pattern||r.allOf?.some(n=>n.pattern)?(r.allOf||(r.allOf=[]),r.pattern&&(r.allOf.push({pattern:r.pattern,...r.errorMessage&&s.errorMessages&&{errorMessage:{pattern:r.errorMessage.pattern}}}),delete r.pattern,r.errorMessage&&(delete r.errorMessage.pattern,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.allOf.push({pattern:Zs(e,s),...t&&s.errorMessages&&{errorMessage:{pattern:t}}})):(0, we.setResponseValueAndErrors)(r,"pattern",Zs(e,s),t,s);},Zs=(r,e)=>{if(!e.applyRegexFlags||!r.flags)return r.source;let t={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},s=t.i?r.source.toLowerCase():r.source,n="",a=!1,i=!1,d=!1;for(let c=0;c<s.length;c++){if(a){n+=s[c],a=!1;continue}if(t.i){if(i){if(s[c].match(/[a-z]/)){d?(n+=s[c],n+=`${s[c-2]}-${s[c]}`.toUpperCase(),d=!1):s[c+1]==="-"&&s[c+2]?.match(/[a-z]/)?(n+=s[c],d=!0):n+=`${s[c]}${s[c].toUpperCase()}`;continue}}else if(s[c].match(/[a-z]/)){n+=`[${s[c]}${s[c].toUpperCase()}]`;continue}}if(t.m){if(s[c]==="^"){n+=`(^|(?<=[\r
19
- ]))`;continue}else if(s[c]==="$"){n+=`($|(?=[\r
20
- ]))`;continue}}if(t.s&&s[c]==="."){n+=i?`${s[c]}\r
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(),za=Bt();function Ba(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, za.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=Ba;});var $r=_(Jt=>{Object.defineProperty(Jt,"__esModule",{value:!0});Jt.parseMapDef=void 0;var Ms=P(),Ga=Yt();function Ya(r,e){if(e.mapStrategy==="record")return (0, Ga.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=Ya;});var qr=_(Xt=>{Object.defineProperty(Xt,"__esModule",{value:!0});Xt.parseNativeEnumDef=void 0;function Ja(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=Ja;});var Fr=_(Qt=>{Object.defineProperty(Qt,"__esModule",{value:!0});Qt.parseNeverDef=void 0;function Xa(){return {not:{}}}Qt.parseNeverDef=Xa;});var Wr=_(Ht=>{Object.defineProperty(Ht,"__esModule",{value:!0});Ht.parseNullDef=void 0;function Qa(r){return r.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}Ht.parseNullDef=Qa;});var er=_(ie=>{Object.defineProperty(ie,"__esModule",{value:!0});ie.parseUnionDef=ie.primitiveMappings=void 0;var Ha=P();ie.primitiveMappings={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function ei(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=ei;var Us=(r,e)=>{let t=(r.options instanceof Map?Array.from(r.options.values()):r.options).map((s,n)=>(0, Ha.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 ti(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=ti;});var zr=_(rr=>{Object.defineProperty(rr,"__esModule",{value:!0});rr.parseNumberDef=void 0;var oe=te();function ri(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=ri;});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 si(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=si;function ni(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=ni;});var Yr=_(sr=>{Object.defineProperty(sr,"__esModule",{value:!0});sr.parseOptionalDef=void 0;var $s=P(),ai=(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=ai;});var Jr=_(ar=>{Object.defineProperty(ar,"__esModule",{value:!0});ar.parsePipelineDef=void 0;var nr=P(),ii=(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=ii;});var Xr=_(ir=>{Object.defineProperty(ir,"__esModule",{value:!0});ir.parsePromiseDef=void 0;var oi=P();function di(r,e){return (0, oi.parseDef)(r.type._def,e)}ir.parsePromiseDef=di;});var Qr=_(or=>{Object.defineProperty(or,"__esModule",{value:!0});or.parseSetDef=void 0;var qs=te(),ui=P();function ci(r,e){let s={type:"array",uniqueItems:!0,items:(0, ui.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=ci;});var es=_(dr=>{Object.defineProperty(dr,"__esModule",{value:!0});dr.parseTupleDef=void 0;var Hr=P();function li(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=li;});var ts=_(ur=>{Object.defineProperty(ur,"__esModule",{value:!0});ur.parseUndefinedDef=void 0;function pi(){return {not:{}}}ur.parseUndefinedDef=pi;});var rs=_(cr=>{Object.defineProperty(cr,"__esModule",{value:!0});cr.parseUnknownDef=void 0;function fi(){return {}}cr.parseUnknownDef=fi;});var ss=_(lr=>{Object.defineProperty(lr,"__esModule",{value:!0});lr.parseReadonlyDef=void 0;var hi=P(),mi=(r,e)=>(0, hi.parseDef)(r.innerType._def,e);lr.parseReadonlyDef=mi;});var P=_(pr=>{Object.defineProperty(pr,"__esModule",{value:!0});pr.parseDef=void 0;var O=Dt(),yi=Pr(),_i=Ar(),gi=Cr(),vi=kr(),Ti=Nr(),Oi=Dr(),Ii=Sr(),xi=Zr(),Ri=jr(),Ei=Mr(),wi=Ur(),bi=Vr(),Pi=$r(),Ai=qr(),Ci=Fr(),ki=Wr(),Ni=Kr(),Di=zr(),Si=Gr(),Zi=Yr(),ji=Jr(),Mi=Xr(),Ui=Yt(),Vi=Qr(),Li=Bt(),$i=es(),qi=ts(),Fi=er(),Wi=rs(),Ki=ss(),zi=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!==zi.ignoreOverride)return i}if(s&&!t){let i=Bi(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=Yi(r,r.typeName,e);return a&&Ji(r,e,a),n.jsonSchema=a,a}pr.parseDef=Fs;var Bi=(r,e)=>{switch(e.$refStrategy){case"root":return {$ref:r.path.join("/")};case"relative":return {$ref:Gi(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}},Gi=(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("/")},Yi=(r,e,t)=>{switch(e){case O.ZodFirstPartyTypeKind.ZodString:return (0, Li.parseStringDef)(r,t);case O.ZodFirstPartyTypeKind.ZodNumber:return (0, Di.parseNumberDef)(r,t);case O.ZodFirstPartyTypeKind.ZodObject:return (0, Si.parseObjectDef)(r,t);case O.ZodFirstPartyTypeKind.ZodBigInt:return (0, gi.parseBigintDef)(r,t);case O.ZodFirstPartyTypeKind.ZodBoolean:return (0, vi.parseBooleanDef)();case O.ZodFirstPartyTypeKind.ZodDate:return (0, Ii.parseDateDef)(r,t);case O.ZodFirstPartyTypeKind.ZodUndefined:return (0, qi.parseUndefinedDef)();case O.ZodFirstPartyTypeKind.ZodNull:return (0, ki.parseNullDef)(t);case O.ZodFirstPartyTypeKind.ZodArray:return (0, _i.parseArrayDef)(r,t);case O.ZodFirstPartyTypeKind.ZodUnion:case O.ZodFirstPartyTypeKind.ZodDiscriminatedUnion:return (0, Fi.parseUnionDef)(r,t);case O.ZodFirstPartyTypeKind.ZodIntersection:return (0, wi.parseIntersectionDef)(r,t);case O.ZodFirstPartyTypeKind.ZodTuple:return (0, $i.parseTupleDef)(r,t);case O.ZodFirstPartyTypeKind.ZodRecord:return (0, Ui.parseRecordDef)(r,t);case O.ZodFirstPartyTypeKind.ZodLiteral:return (0, bi.parseLiteralDef)(r,t);case O.ZodFirstPartyTypeKind.ZodEnum:return (0, Ei.parseEnumDef)(r);case O.ZodFirstPartyTypeKind.ZodNativeEnum:return (0, Ai.parseNativeEnumDef)(r);case O.ZodFirstPartyTypeKind.ZodNullable:return (0, Ni.parseNullableDef)(r,t);case O.ZodFirstPartyTypeKind.ZodOptional:return (0, Zi.parseOptionalDef)(r,t);case O.ZodFirstPartyTypeKind.ZodMap:return (0, Pi.parseMapDef)(r,t);case O.ZodFirstPartyTypeKind.ZodSet:return (0, Vi.parseSetDef)(r,t);case O.ZodFirstPartyTypeKind.ZodLazy:return Fs(r.getter()._def,t);case O.ZodFirstPartyTypeKind.ZodPromise:return (0, Mi.parsePromiseDef)(r,t);case O.ZodFirstPartyTypeKind.ZodNaN:case O.ZodFirstPartyTypeKind.ZodNever:return (0, Ci.parseNeverDef)();case O.ZodFirstPartyTypeKind.ZodEffects:return (0, Ri.parseEffectsDef)(r,t);case O.ZodFirstPartyTypeKind.ZodAny:return (0, yi.parseAnyDef)();case O.ZodFirstPartyTypeKind.ZodUnknown:return (0, Wi.parseUnknownDef)();case O.ZodFirstPartyTypeKind.ZodDefault:return (0, xi.parseDefaultDef)(r,t);case O.ZodFirstPartyTypeKind.ZodBranded:return (0, Ti.parseBrandedDef)(r,t);case O.ZodFirstPartyTypeKind.ZodReadonly:return (0, Ki.parseReadonlyDef)(r,t);case O.ZodFirstPartyTypeKind.ZodCatch:return (0, Oi.parseCatchDef)(r,t);case O.ZodFirstPartyTypeKind.ZodPipeline:return (0, ji.parsePipelineDef)(r,t);case O.ZodFirstPartyTypeKind.ZodFunction:case O.ZodFirstPartyTypeKind.ZodVoid:case O.ZodFirstPartyTypeKind.ZodSymbol:return;default:return (s=>{})()}},Ji=(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(),Xi=Tr(),Qi=(r,e)=>{let t=(0, Xi.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=Qi;});var Ks=_(T=>{var Hi=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];}),I=T&&T.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Hi(e,r,t);};Object.defineProperty(T,"__esModule",{value:!0});I(Rt(),T);I(Tr(),T);I(te(),T);I(P(),T);I(Pr(),T);I(Ar(),T);I(Cr(),T);I(kr(),T);I(Nr(),T);I(Dr(),T);I(Sr(),T);I(Zr(),T);I(jr(),T);I(Mr(),T);I(Ur(),T);I(Vr(),T);I($r(),T);I(qr(),T);I(Fr(),T);I(Wr(),T);I(Kr(),T);I(zr(),T);I(Gr(),T);I(Yr(),T);I(Jr(),T);I(Xr(),T);I(ss(),T);I(Yt(),T);I(Qr(),T);I(Bt(),T);I(es(),T);I(ts(),T);I(er(),T);I(rs(),T);I(ns(),T);var eo=ns();T.default=eo.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_SECRET_KEY_ERROR="MissingSecretKeyError",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.`);}},Ce=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 Ce{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.secretKey`");}};var Ot=class extends ee{code="StepNotFoundError";constructor(e){super("step",e);}};var We=class extends ee{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},It=class extends Fe{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var xt=class{ajv;compiledSchemas;constructor(){this.ajv=new tn__default.default({useDefaults:!0,removeAdditional:"all"}),rn__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.12",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 Team <engineering@novu.co>",license:"ISC",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});function Js(){return process.env.NODE_ENV==="development"}var _r=class{discoveredWorkflows=[];templateEngine=new liquidjs.Liquid;secretKey;version=He;strictAuthentication;constructor(e){let t=this.buildOptions(e);this.secretKey=t.secretKey,this.strictAuthentication=t.strictAuthentication;}buildOptions(e){let t={secretKey:void 0,strictAuthentication:!Js()};if(t.secretKey=e?.secretKey||process.env.NOVU_SECRET_KEY||process.env.NOVU_API_KEY,!Js()&&!t.secretKey)throw new Error("Missing secret key. Set the NOVU_SECRET_KEY environment variable or pass `secretKey` to the client options.");return e?.strictAuthentication!==void 0?t.strictAuthentication=e.strictAuthentication:process.env.NOVU_STRICT_AUTHENTICATION_ENABLED!==void 0&&(t.strictAuthentication=process.env.NOVU_STRICT_AUTHENTICATION_ENABLED==="true"),t}addWorkflows(e){for(let t of e){if(this.discoveredWorkflows.some(s=>s.workflowId===t.workflowId))throw new It(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 Ot(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=so(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
- ${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,Xs=E?A.ERROR:A.SUCCESS,Qs=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action";if(console.log(`${Xs} ${Qs} 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
- ${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
- `);}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}'.
26
- ${i.message}`)}}async executeStep(e,t){if(e.stepId===t.stepId){let s=yr__default.default({indent:1}).start(`Executing stepId: \`${t.stepId}\``);try{let n=await this.createStepControls(t,e),a=await this.compileControls(n,e),i=await t.resolve(a),d=await this.validate(i,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId),c=await this.executeProviders(e,t,d);return s.succeed(`Executed stepId: \`${t.stepId}\``),{outputs:d,providers:c}}catch(n){throw s.stopAndPersist({prefixText:"",symbol:A.ERROR,text:`Failed to execute stepId: \`${t.stepId}\``}),n}}else {let s=yr__default.default({indent:1}).start(`Hydrating stepId: \`${t.stepId}\``);try{let n=e.state.find(a=>a.stepId===t.stepId);if(n){let a=await this.validate(n.outputs,t.results.unknownSchema,"step","result",e.workflowId,t.stepId);return s.stopAndPersist({symbol:A.HYDRATED,text:`Hydrated stepId: \`${t.stepId}\``}),{outputs:a,providers:await this.executeProviders(e,t,a)}}else throw new at(e.workflowId,t.stepId)}catch(n){throw s.stopAndPersist({symbol:A.ERROR,text:`Failed to hydrate stepId: \`${t.stepId}\``}),n}}}async compileControls(e,t){let s=this.templateEngine.parse(JSON.stringify(e)),n=await this.templateEngine.render(s,{...t.payload||t.data,subscriber:t.subscriber});return JSON.parse(n)}async createStepControls(e,t){let s=t.controls||t.inputs;return await this.validate(s,e.controls.unknownSchema,"step","controls",t.workflowId,e.stepId)}async previewStep(e,t){let s=yr__default.default({indent:1}).start(`Previewing stepId: \`${t.stepId}\``);try{if(e.stepId===t.stepId){let n=await this.createStepControls(t,e),a=await this.compileControls(n,e),i=await t.resolve(a),d=await this.validate(i,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId);return s.stopAndPersist({symbol:A.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:d,providers:await this.executeProviders(e,t,d)}}else {let n=this.mock(t.results.schema);return s.stopAndPersist({symbol:A.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:n,providers:await this.executeProviders(e,t,n)}}}catch(n){throw s.stopAndPersist({symbol:A.ERROR,text:`Failed to preview stepId: \`${t.stepId}\``}),n}}getStepCode(e,t){return {code:this.getStep(e,t).resolve.toString()}}getWorkflowCode(e){return {code:this.getWorkflow(e).execute.toString()}}getCode(e,t){let s;if(e)t?s=this.getStepCode(e,t):s=this.getWorkflowCode(e);else throw new We(e);return s}};function so(r){return JSON.parse(JSON.stringify(r))}var gr=class{frameworkName;handler;client;hmacEnabled;http;constructor(e){this.handler=e.handler,this.client=e.client?e.client:new _r,this.client.addWorkflows(e.workflows),this.http=os(this.client.secretKey),this.frameworkName=e.frameworkName,this.hmacEnabled=this.client.strictAuthentication;}createHandler(){return async(...e)=>{let t=await this.handler(...e),s=await this.handleAction({actions:t});return t.transformResponse(s)}}getStaticHeaders(){let e=`novu-framework:v${this.client.version}`;return {"content-type":"application/json","access-control-allow-origin":"*","access-control-allow-methods":"GET, POST","access-control-allow-headers":"*","access-control-max-age":"604800","novu-framework-version":mr,"novu-framework-sdk":He,"novu-framework-api":this.frameworkName,"user-agent":e}}createResponse(e,t){return {status:e,body:JSON.stringify(t),headers:{...this.getStaticHeaders()}}}createError(e){return {status:e.statusCode,body:JSON.stringify({message:e.message,data:e.data,code:e.code}),headers:this.getStaticHeaders()}}async handleAction({actions:e}){let t=await e.url(),s=await e.method(),n=t.searchParams.get("action")||"",a=t.searchParams.get("workflowId")||"",i=t.searchParams.get("stepId")||"",d=await e.headers("novu-signature")||await e.headers("x-novu-signature")||"",c=await e.headers("novu-anonymous")||await e.headers("x-novu-anonymous")||"",l=t.searchParams.get("source")||"",h={};try{s==="POST"&&(h=await e.body());}catch{}try{n!=="health-check"&&this.validateHmac(h,d);let E=this.getPostActionMap(h,a,i,n,c,l),X=this.getGetActionMap(a,i);if(s==="POST")return await this.handlePostAction(n,E);if(s==="GET")return await this.handleGetAction(n,X);if(s==="OPTIONS")return this.createResponse(200,{})}catch(E){return this.handleError(E)}return this.createError(new pt(s))}getPostActionMap(e,t,s,n,a,i){return {trigger:this.triggerAction({workflowId:t,...e}),execute:async()=>{let d=await this.client.executeWorkflow({...e,workflowId:t,stepId:s,action:n});return this.createResponse(200,d)},preview:async()=>{let d=await this.client.executeWorkflow({...e,workflowId:t,stepId:s,action:n});return this.createResponse(200,d)}}}triggerAction(e){return async()=>{let t={name:e.workflowId,to:e.to,payload:e?.payload||{},transactionId:e.transactionId,overrides:e.overrides||{},...e.actor&&{actor:e.actor},...e.tenant&&{tenant:e.tenant},...e.bridgeUrl&&{bridgeUrl:e.bridgeUrl}},s=await this.http.post("/events/trigger",t);return this.createResponse(200,s)}}getGetActionMap(e,t){return {discover:async()=>{let s=await this.client.discover();return this.createResponse(200,s)},"health-check":async()=>{let s=await this.client.healthCheck();return this.createResponse(200,s)},code:async()=>{let s=await this.client.getCode(e,t);return this.createResponse(200,s)}}}async handlePostAction(e,t){if(Object.values(et).includes(e)){let s=t[e];return s()}else throw new qe(e,et)}async handleGetAction(e,t){if(Object.values(tt).includes(e)){let s=t[e];return s()}else throw new qe(e,tt)}isClientError(e){return Object.values(V).includes(e.code)}handleError(e){return this.isClientError(e)?(e.statusCode===500&&console.error(e),this.createError(e)):e.response.status===400?this.createError(e.response):(console.error(e),this.createError(new ft))}validateHmac(e,t){if(!this.hmacEnabled)return;if(!t)throw new _t;if(!this.client.secretKey)throw new Tt;let[s,n]=t.split(",");if(!s||!n)throw new gt;let[a,i]=s.split("="),[d,c]=n.split("=");if(Number(a)<Date.now()-1500)throw new vt;if(!(this.hashHmac(this.client.secretKey,`${i}.${JSON.stringify(e)}`)===c))throw new yt}hashHmac(e,t){return crypto.createHmac("sha256",e).update(t).digest("hex")}};var io="express",Yu=r=>new gr({frameworkName:io,...r,handler:(t,s)=>({body:()=>t.body,headers:n=>{let a=t.headers[n];return Array.isArray(a)?a[0]:a},method:()=>t.method||"GET",url:()=>{let n=t.headers.host||"",a=n?.includes("://")?"":`${t.protocol||"https"}://`;return new URL(t.originalUrl||t.url||"",`${a}${n||""}`)},queryString:n=>{let a=t.query[n];return Array.isArray(a)?a[0]:a},transformResponse:({body:n,headers:a,status:i})=>(Object.entries(a).forEach(([d,c])=>{s.setHeader(d,c);}),s.status(i).send(n))})}).createHandler();
20
+ var D=(r=>(r.TRIGGER="trigger",r.EXECUTE="execute",r.PREVIEW="preview",r))(D||{}),k=(r=>(r.DISCOVER="discover",r.HEALTH_CHECK="health-check",r.CODE="code",r))(k||{});var h=(c=>(c.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",c.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",c.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",c.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",c.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",c.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",c.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",c.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",c.STEP_NOT_FOUND_ERROR="StepNotFoundError",c.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",c.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",c.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",c.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",c.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",c.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",c.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",c.INVALID_ACTION_ERROR="InvalidActionError",c.MISSING_SECRET_KEY_ERROR="MissingSecretKeyError",c.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",c.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",c.SIGNATURE_INVALID_ERROR="SignatureInvalidError",c.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",c.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",c.PLATFORM_ERROR="PlatformError",c.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",c.WORKFLOW_PAYLOAD_INVALID_ERROR="WorkflowPayloadInvalidError",c))(h||{});var U=(r=>(r.POST="POST",r.GET="GET",r.OPTIONS="OPTIONS",r))(U||{});var O=class extends Error{data},L=class extends O{statusCode=404},R=class extends O{statusCode=400},T=class extends O{statusCode=401},m=class extends O{statusCode=500},b=class extends O{statusCode=409};var V=class extends R{code="ExecutionStateCorruptError";constructor(e,t){super(`Workflow with id: \`${e}\` has a corrupt state. Step with id: \`${t}\` does not exist. Please provide the missing state.`),this.data={workflowId:e,stepId:t};}},x=class extends R{code="ExecutionEventPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct event payload.`),this.data=t;}},F=class extends R{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},W=class extends R{code="ExecutionStateControlInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid \`controls\`. Please provide the correct step controls.`),this.data=r;}},$=class extends R{code="ExecutionStateOutputInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid output. Please provide the correct step output.`),this.data=r;}},M=class extends R{code="ExecutionStateResultInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid result. Please provide the correct step result.`),this.data=r;}},G=class extends R{code="ExecutionProviderOutputInvalidError";constructor(e,t,r,o){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` and provider with id: \`${r}\` has invalid output. Please provide the correct provider output.`),this.data=o;}};var j=class extends Error{statusCode;message;code;constructor(e,t,r){super(r),this.statusCode=e,this.code=t;}};var l={info:s=>A__default.default.blue(s),warning:s=>A__default.default.yellow(s),error:s=>A__default.default.red(s),success:s=>A__default.default.green(s),underline:s=>A__default.default.underline(s),bold:s=>A__default.default.bold(s)},p={SUCCESS:l.success("\u2714"),ERROR:l.error("\u2717"),WARNING:l.warning("\u26A0"),INFO:l.info("\u2139"),ARROW:l.bold("\u2192"),MOCK:l.info("\u25CB"),HYDRATED:l.bold(l.info("\u2192")),STEP:l.info("\u03C3"),ACTION:l.info("\u03B1"),DURATION:l.info("\u0394"),PROVIDER:l.info("\u2699"),OUTPUT:l.info("\u21E2"),INPUT:l.info("\u21E0"),WORKFLOW:l.info("\u03C9"),STATE:l.info("\u03C3"),EXECUTE:l.info("\u03B5"),PREVIEW:l.info("\u03C1")};var de=s=>Object.values(s).map(e=>`\`${e}\``).join(", "),K=s=>s.replaceAll(/(\w)(\w*)/g,(e,t,r)=>t.toUpperCase()+r.toLowerCase()).replaceAll(/[\s-]+/g,"");var ue=(s,e="https://api.novu.co")=>{let t=process.env.NOVU_API_URL||e;return {post:async(r,o)=>{let i=await fetch(t+"/v1"+r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${s}`},body:JSON.stringify(o)}),n=await i.json();if(i.ok)return n;throw new j(n.statusCode,n.error,n.message)},delete:async r=>(await fetch(t+"/v1"+r,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${s}`}})).json()}};var Y=class extends O{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${de(U)}`},y=class extends R{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${de(t)}`);}};var X=class extends m{code="PlatformError";message="Something went wrong. Please try again later."};var g=class extends b{constructor(e,t){super(`${K(e)} with id: \`${t}\` already exists. Please use a different id.`);}},w=class extends L{constructor(e,t){super(`${K(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},N=class extends m{constructor(e,t){super(`Failed to execute ${K(e)} with id: \`${t}\`. Please try again later.`);}};var J=class extends w{code="ProviderNotFoundError";constructor(e){super("provider",e);}},B=class extends N{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var q=class extends T{code="SignatureMismatchError";constructor(){super("Signature does not match the expected signature. Please ensure the signature provided in the `novu-signature` header is correct and try again.");}},z=class extends T{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},Z=class extends T{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},Q=class extends T{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},H=class extends T{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.secretKey`");}};var ee=class extends w{code="StepNotFoundError";constructor(e){super("step",e);}};var S=class extends w{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},te=class extends g{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var re=class{ajv;compiledSchemas;constructor(){this.ajv=new me__default.default({useDefaults:!0,removeAdditional:"all"}),Ae__default.default(this.ajv),this.compiledSchemas=new Map;}isSchema(e){return typeof e=="boolean"?!1:e.type==="object"||!!e.anyOf||!!e.oneOf}async validate(e,t){let r=this.compiledSchemas.get(t);return r||(r=this.ajv.compile(t),this.compiledSchemas.set(t,r)),r(e)?{success:!0,data:e}:{success:!1,errors:r.errors.map(i=>({path:i.instancePath,message:i.message}))}}transformToJsonSchema(e){return e}};var oe=class{isSchema(e){return e.safeParseAsync!==void 0}async validate(e,t){let r=t.safeParse(e);return r.success?{success:!0,data:r.data}:{success:!1,errors:r.error.errors.map(o=>({path:`/${o.path.join("/")}`,message:o.message}))}}transformToJsonSchema(e){try{return zodToJsonSchema.zodToJsonSchema(e)}catch(t){throw t?.message?.includes("Cannot find module")&&console.error("Tried to use a zod schema in @novu/framework without `zod-to-json-schema` installed. Please install it by running `npm install zod-to-json-schema`."),t}}};var Ee=[new oe,new re],he=async(s,e)=>{for(let t of Ee)if(t.isSchema(s))return t.validate(e,s);throw new Error("Invalid schema")},Oe=s=>{for(let e of Ee)if(e.isSchema(s))return e.transformToJsonSchema(s);throw new Error("Invalid schema")};var Te={name:"@novu/framework",version:"0.24.3-alpha.15",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 Team <engineering@novu.co>",license:"ISC",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"}},peerDependencies:{"@sveltejs/kit":">=1.27.3","@vercel/node":">=2.15.9",express:">=4.19.2",h3:">=1.8.1",next:">=12.0.0",zod:">=3.0.0","zod-to-json-schema":">=3.0.0"},peerDependenciesMeta:{"@sveltejs/kit":{optional:!0},"@vercel/node":{optional:!0},express:{optional:!0},fastify:{optional:!0},h3:{optional:!0},next:{optional:!0},zod:{optional:!0},"zod-to-json-schema":{optional:!0}},devDependencies:{"@sveltejs/kit":"^1.27.3","@types/express":"^4.17.13","@types/json-schema":"^7.0.15","@types/node":"^20.11.20","@vercel/node":"^2.15.9",express:"^4.19.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":"workspace:*",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 P=Te.version,se="2024-06-26";jsonSchemaFaker.JSONSchemaFaker.random.shuffle=function(){return ["[placeholder]"]};jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});function ye(){return process.env.NODE_ENV==="development"}var ne=class{discoveredWorkflows=[];templateEngine=new liquidjs.Liquid;secretKey;version=P;strictAuthentication;constructor(e){let t=this.buildOptions(e);this.secretKey=t.secretKey,this.strictAuthentication=t.strictAuthentication;}buildOptions(e){let t={secretKey:void 0,strictAuthentication:!ye()};return t.secretKey=e?.secretKey||process.env.NOVU_SECRET_KEY||process.env.NOVU_API_KEY,e?.strictAuthentication!==void 0?t.strictAuthentication=e.strictAuthentication:process.env.NOVU_STRICT_AUTHENTICATION_ENABLED!==void 0&&(t.strictAuthentication=process.env.NOVU_STRICT_AUTHENTICATION_ENABLED==="true"),t}addWorkflows(e){for(let t of e){if(this.discoveredWorkflows.some(r=>r.workflowId===t.definition.workflowId))throw new te(t.definition.workflowId);this.discoveredWorkflows.push(t.definition);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((r,o)=>r+o.steps.length,0);return {status:"ok",sdkVersion:P,frameworkVersion:se,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(r=>r.workflowId===e);if(t)return t;throw new S(e)}getStep(e,t){let o=this.getWorkflow(e).steps.find(i=>i.stepId===t);if(o)return o;throw new ee(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(Oe(e))}async validate(e,t,r,o,i,n,d){let a=await he(t,e);if(a.success)return a.data;switch(r){case"event":this.throwInvalidEvent(o,i,a.errors);case"step":this.throwInvalidStep(n,o,i,a.errors);case"provider":this.throwInvalidProvider(n,d,o,i,a.errors);default:throw new Error(`Invalid component: '${r}'`)}}throwInvalidProvider(e,t,r,o,i){if(!e)throw new Error("stepId is required");if(!t)throw new Error("providerId is required");switch(r){case"output":throw new G(o,e,t,i);default:throw new Error(`Invalid payload type: '${r}'`)}}throwInvalidStep(e,t,r,o){if(!e)throw new Error("stepId is required");switch(t){case"output":throw new $(r,e,o);case"result":throw new M(r,e,o);case"controls":throw new W(r,e,o);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(e,t,r){switch(e){case"controls":throw new F(t,r);case"payload":throw new x(t,r);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(r,o,i)=>{let n=this.getStep(e.workflowId,r),d=ge(e),a=await this.createStepControls(n,d),E=e.action==="preview";if(!E&&await this.shouldSkip(i?.skip,a))return t({options:{skip:!0}}),{};let u=this.previewStep.bind(this),I=this.executeStep.bind(this),C=await(E?u:I)(e,{...n,providers:n.providers.map(f=>{let v=i?.providers?.[f.type];if(!v)throw new J(f.type);return {...f,resolve:v}}),resolve:o});return r===e.stepId&&t(C),C.outputs}}async shouldSkip(e,t){return e?e(t):!1}async executeWorkflow(e){let o=`${{execute:"Executing",preview:"Previewing"}[e.action]} workflowId:`;console.log(`
21
+ ${l.bold(l.underline(o))} '${e.workflowId}'`);let i=this.getWorkflow(e.workflowId),n=process.hrtime(),d={outputs:{},providers:{},options:{}},a,E=new Promise(_=>{a=_;}),u=_=>{a(),d=_;},I;try{if(e.action==="execute"&&!e.payload&&!e.data)throw new x(e.workflowId,{message:"Event `payload` is required"});let _=await this.createExecutionPayload(e,i);await Promise.race([E,i.execute({payload:_,environment:{},inputs:{},controls:{},subscriber:e.subscriber,step:{email:this.executeStepFactory(e,u),sms:this.executeStepFactory(e,u),inApp:this.executeStepFactory(e,u),digest:this.executeStepFactory(e,u),delay:this.executeStepFactory(e,u),push:this.executeStepFactory(e,u),chat:this.executeStepFactory(e,u),custom:this.executeStepFactory(e,u)}})]);}catch(_){I=_;}let ce=process.hrtime(n),C=ce[0],f=ce[1],v=C*1e3+f/1e6,we=I?p.ERROR:p.SUCCESS,Ie=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action";if(console.log(`${we} ${Ie} workflowId: \`${e.workflowId}\``),this.prettyPrintExecute(e,v,I),I)throw I;return {outputs:d.outputs,providers:d.providers,options:d.options,metadata:{status:"success",error:!1,duration:v}}}async createExecutionPayload(e,t){let r=e.payload||e.data;if(e.action==="preview"){let i=this.mock(t.payload.schema);r=Object.assign(i,r);}return await this.validate(r,t.payload.unknownSchema,"event","payload",e.workflowId)}prettyPrintExecute(e,t,r){let o=r?p.ERROR:p.SUCCESS,i=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action",n=r?"Failed to execute":i,d=r?l.error:l.success,a=`${o} ${n} workflowId: '${e.workflowId}`;console.log(`
22
+ ${l.bold(d(a))}'`),console.log(` \u251C ${p.STEP} stepId: '${e.stepId}'`),console.log(` \u251C ${p.ACTION} action: '${e.action}'`),console.log(` \u2514 ${p.DURATION} duration: '${t.toFixed(2)}ms'
23
+ `);}async executeProviders(e,t,r){return t.providers.reduce(async(o,i)=>{let n=await o,d=this.previewProvider.bind(this),a=this.executeProvider.bind(this),u=await(e.action==="preview"?d:a)(e,t,i,r);return {...n,[i.type]:u}},Promise.resolve({}))}previewProvider(e,t,r,o){return console.log(` ${p.MOCK} Mocked provider: \`${r.type}\``),this.mock(r.outputs.schema)}async executeProvider(e,t,r,o){let i=ie__default.default({indent:2}).start(`Executing provider: \`${r.type}\``);try{if(e.stepId===t.stepId){let n=await this.createStepControls(t,e),d=await r.resolve({controls:n,outputs:o}),a=await this.validate(d,r.outputs.unknownSchema,"step","output",e.workflowId,t.stepId,r.type);return i.succeed(`Executed provider: \`${r.type}\``),a}else i.stopAndPersist({symbol:p.HYDRATED,text:`Hydrated provider: \`${r.type}\``});}catch(n){throw i.stopAndPersist({symbol:p.ERROR,text:`Failed to execute provider: \`${r.type}\``}),new B(`Failed to execute provider: '${r.type}'.
24
+ ${n.message}`)}}async executeStep(e,t){if(e.stepId===t.stepId){let r=ie__default.default({indent:1}).start(`Executing stepId: \`${t.stepId}\``);try{let o=await this.createStepControls(t,e),i=await this.compileControls(o,e),n=await t.resolve(i),d=await this.validate(n,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId),a=await this.executeProviders(e,t,d);return r.succeed(`Executed stepId: \`${t.stepId}\``),{outputs:d,providers:a}}catch(o){throw r.stopAndPersist({prefixText:"",symbol:p.ERROR,text:`Failed to execute stepId: \`${t.stepId}\``}),o}}else {let r=ie__default.default({indent:1}).start(`Hydrating stepId: \`${t.stepId}\``);try{let o=e.state.find(i=>i.stepId===t.stepId);if(o){let i=await this.validate(o.outputs,t.results.unknownSchema,"step","result",e.workflowId,t.stepId);return r.stopAndPersist({symbol:p.HYDRATED,text:`Hydrated stepId: \`${t.stepId}\``}),{outputs:i,providers:await this.executeProviders(e,t,i)}}else throw new V(e.workflowId,t.stepId)}catch(o){throw r.stopAndPersist({symbol:p.ERROR,text:`Failed to hydrate stepId: \`${t.stepId}\``}),o}}}async compileControls(e,t){let r=this.templateEngine.parse(JSON.stringify(e)),o=await this.templateEngine.render(r,{...t.payload||t.data,subscriber:t.subscriber});return JSON.parse(o)}async createStepControls(e,t){let r=t.controls||t.inputs;return await this.validate(r,e.controls.unknownSchema,"step","controls",t.workflowId,e.stepId)}async previewStep(e,t){let r=ie__default.default({indent:1}).start(`Previewing stepId: \`${t.stepId}\``);try{if(e.stepId===t.stepId){let o=await this.createStepControls(t,e),i=await this.compileControls(o,e),n=await t.resolve(i),d=await this.validate(n,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId);return r.stopAndPersist({symbol:p.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:d,providers:await this.executeProviders(e,t,d)}}else {let o=this.mock(t.results.schema);return r.stopAndPersist({symbol:p.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:o,providers:await this.executeProviders(e,t,o)}}}catch(o){throw r.stopAndPersist({symbol:p.ERROR,text:`Failed to preview stepId: \`${t.stepId}\``}),o}}getStepCode(e,t){return {code:this.getStep(e,t).resolve.toString()}}getWorkflowCode(e){return {code:this.getWorkflow(e).execute.toString()}}getCode(e,t){let r;if(e)t?r=this.getStepCode(e,t):r=this.getWorkflowCode(e);else throw new S(e);return r}};function ge(s){return JSON.parse(JSON.stringify(s))}var ae=class{frameworkName;handler;client;hmacEnabled;http;constructor(e){this.handler=e.handler,this.client=e.client?e.client:new ne,this.client.addWorkflows(e.workflows),this.http=ue(this.client.secretKey),this.frameworkName=e.frameworkName,this.hmacEnabled=this.client.strictAuthentication;}createHandler(){return async(...e)=>{let t=await this.handler(...e),r=await this.handleAction({actions:t});return t.transformResponse(r)}}getStaticHeaders(){let e=`novu-framework:v${this.client.version}`;return {"content-type":"application/json","access-control-allow-origin":"*","access-control-allow-methods":"GET, POST","access-control-allow-headers":"*","access-control-max-age":"604800","novu-framework-version":se,"novu-framework-sdk":P,"novu-framework-api":this.frameworkName,"user-agent":e}}createResponse(e,t){return {status:e,body:JSON.stringify(t),headers:{...this.getStaticHeaders()}}}createError(e){return {status:e.statusCode,body:JSON.stringify({message:e.message,data:e.data,code:e.code}),headers:this.getStaticHeaders()}}async handleAction({actions:e}){let t=await e.url(),r=await e.method(),o=t.searchParams.get("action")||"",i=t.searchParams.get("workflowId")||"",n=t.searchParams.get("stepId")||"",d=await e.headers("novu-signature")||await e.headers("x-novu-signature")||"",a={};try{r==="POST"&&(a=await e.body());}catch{}try{o!=="health-check"&&this.validateHmac(a,d);let E=this.getPostActionMap(a,i,n,o),u=this.getGetActionMap(i,n);if(r==="POST")return await this.handlePostAction(o,E);if(r==="GET")return await this.handleGetAction(o,u);if(r==="OPTIONS")return this.createResponse(200,{})}catch(E){return this.handleError(E)}return this.createError(new Y(r))}getPostActionMap(e,t,r,o){return {trigger:this.triggerAction({workflowId:t,...e}),execute:async()=>{let i=await this.client.executeWorkflow({...e,workflowId:t,stepId:r,action:o});return this.createResponse(200,i)},preview:async()=>{let i=await this.client.executeWorkflow({...e,workflowId:t,stepId:r,action:o});return this.createResponse(200,i)}}}triggerAction(e){return async()=>{let t={name:e.workflowId,to:e.to,payload:e?.payload||{},transactionId:e.transactionId,overrides:e.overrides||{},...e.actor&&{actor:e.actor},...e.tenant&&{tenant:e.tenant},...e.bridgeUrl&&{bridgeUrl:e.bridgeUrl},...e.controls&&{controls:e.controls}},r=await this.http.post("/events/trigger",t);return this.createResponse(200,r)}}getGetActionMap(e,t){return {discover:async()=>{let r=await this.client.discover();return this.createResponse(200,r)},"health-check":async()=>{let r=await this.client.healthCheck();return this.createResponse(200,r)},code:async()=>{let r=await this.client.getCode(e,t);return this.createResponse(200,r)}}}async handlePostAction(e,t){if(Object.values(D).includes(e)){let r=t[e];return r()}else throw new y(e,D)}async handleGetAction(e,t){if(Object.values(k).includes(e)){let r=t[e];return r()}else throw new y(e,k)}isClientError(e){let t=Object.values(h).includes(e.code),r=Ce(e);return t||r}handleError(e){return this.isClientError(e)?(e.statusCode===500&&console.error(e),this.createError(e)):(console.error(e),this.createError(new X))}validateHmac(e,t){if(!this.hmacEnabled)return;if(!t)throw new z;if(!this.client.secretKey)throw new H;let[r,o]=t.split(",");if(!r||!o)throw new Z;let[i,n]=r.split("="),[d,a]=o.split("=");if(Number(i)<Date.now()-1500)throw new Q;if(!(this.hashHmac(this.client.secretKey,`${n}.${JSON.stringify(e)}`)===a))throw new q}hashHmac(e,t){return crypto.createHmac("sha256",e).update(t).digest("hex")}};function Ce(s){return s?.statusCode>=400&&s?.statusCode<500}var De="express",Pr=s=>new ae({frameworkName:De,...s,handler:(t,r)=>({body:()=>t.body,headers:o=>{let i=t.headers[o];return Array.isArray(i)?i[0]:i},method:()=>t.method||"GET",url:()=>{let o=t.headers.host||"",i=o?.includes("://")?"":`${t.protocol||"https"}://`;return new URL(t.originalUrl||t.url||"",`${i}${o||""}`)},queryString:o=>{let i=t.query[o];return Array.isArray(i)?i[0]:i},transformResponse:({body:o,headers:i,status:n})=>(Object.entries(i).forEach(([d,a])=>{r.setHeader(d,a);}),r.status(n).send(o))})}).createHandler();
27
25
 
28
- exports.frameworkName = io;
29
- exports.serve = Yu;
26
+ exports.frameworkName = De;
27
+ exports.serve = Pr;
package/dist/h3.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as h3 from 'h3';
2
2
  import { H3Event } from 'h3';
3
- import { l as SupportedFrameworkName, a as ServeHandlerOptions } from './handler-PIXNhv7t.js';
3
+ import { q as SupportedFrameworkName, b as ServeHandlerOptions } from './handler-Mor_4K8F.js';
4
4
  import 'json-schema-to-ts';
5
5
  import 'zod';
6
6
  import '@novu/shared';