@openfin/cloud-notification-core-api 0.0.1-alpha.ce2c445 → 0.0.1-alpha.ce9c8f0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -2
- package/bundle.d.ts +624 -531
- package/index.cjs +457 -158
- package/index.mjs +456 -159
- package/package.json +7 -9
package/index.cjs
CHANGED
|
@@ -3,9 +3,13 @@
|
|
|
3
3
|
var buffer = require('buffer');
|
|
4
4
|
var mqtt = require('mqtt');
|
|
5
5
|
|
|
6
|
-
var g;(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(o=>typeof n[n[o]]!="number"),i={};for(let o of a)i[o]=n[o];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;})(g||(g={}));var be;(function(r){r.mergeShapes=(e,t)=>({...e,...t});})(be||(be={}));var f$1=g.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),j=r=>{switch(typeof r){case "undefined":return f$1.undefined;case "string":return f$1.string;case "number":return isNaN(r)?f$1.nan:f$1.number;case "boolean":return f$1.boolean;case "function":return f$1.function;case "bigint":return f$1.bigint;case "symbol":return f$1.symbol;case "object":return Array.isArray(r)?f$1.array:r===null?f$1.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?f$1.promise:typeof Map<"u"&&r instanceof Map?f$1.map:typeof Set<"u"&&r instanceof Set?f$1.set:typeof Date<"u"&&r instanceof Date?f$1.date:f$1.object;default:return f$1.unknown}},d=g.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"]),ze=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),T=class r extends Error{get errors(){return this.issues}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;}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 o=s,l=0;for(;l<i.path.length;){let c=i.path[l];l===i.path.length-1?(o[c]=o[c]||{_errors:[]},o[c]._errors.push(t(i))):o[c]=o[c]||{_errors:[]},o=o[c],l++;}}};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,g.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()}};T.create=r=>new T(r);var re=(r,e)=>{let t;switch(r.code){case d.invalid_type:r.received===f$1.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case d.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,g.jsonStringifyReplacer)}`;break;case d.unrecognized_keys:t=`Unrecognized key(s) in object: ${g.joinValues(r.keys,", ")}`;break;case d.invalid_union:t="Invalid input";break;case d.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${g.joinValues(r.options)}`;break;case d.invalid_enum_value:t=`Invalid enum value. Expected ${g.joinValues(r.options)}, received '${r.received}'`;break;case d.invalid_arguments:t="Invalid function arguments";break;case d.invalid_return_type:t="Invalid function return type";break;case d.invalid_date:t="Invalid date";break;case d.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}"`:g.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case d.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 d.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 d.custom:t="Invalid input";break;case d.invalid_intersection_types:t="Intersection results could not be merged";break;case d.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case d.not_finite:t="Number must be finite";break;default:t=e.defaultError,g.assertNever(r);}return {message:t}},Ee=re;function De(r){Ee=r;}function pe(){return Ee}var me=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 o="",l=s.filter(c=>!!c).slice().reverse();for(let c of l)o=c(i,{data:e,defaultError:o}).message;return {...n,path:a,message:o}},Le=[];function u(r,e){let t=pe(),s=me({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===re?void 0:re].filter(n=>!!n)});r.common.issues.push(s);}var x=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 v;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 v;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}}},v=Object.freeze({status:"aborted"}),te=r=>({status:"dirty",value:r}),b=r=>({status:"valid",value:r}),we=r=>r.status==="aborted",Te=r=>r.status==="dirty",P=r=>r.status==="valid",ue=r=>typeof Promise<"u"&&r instanceof Promise;function ve(r,e,t,s){if(typeof e=="function"?r!==e||true:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(r)}function Re(r,e,t,s,n){if(typeof e=="function"?r!==e||true:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(r,t),t}var h;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message;})(h||(h={}));var de,ce,S=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}},Oe=(r,e)=>{if(P(e))return {success:true,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return {success:false,get error(){if(this._error)return this._error;let t=new T(r.common.issues);return this._error=t,this._error}}};function _(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,o)=>{var l,c;let{message:p}=r;return i.code==="invalid_enum_value"?{message:p??o.defaultError}:typeof o.data>"u"?{message:(l=p??s)!==null&&l!==void 0?l:o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:(c=p??t)!==null&&c!==void 0?c:o.defaultError}},description:n}}var y=class{get description(){return this._def.description}_getType(e){return j(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:j(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return {status:new x,ctx:{common:e.parent.common,data:e.data,parsedType:j(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(ue(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:false,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:j(e)},a=this._parseSync({data:e,path:n.path,parent:n});return Oe(n,a)}"~validate"(e){var t,s;let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:j(e)};if(!this["~standard"].async)try{let a=this._parseSync({data:e,path:[],parent:n});return P(a)?{value:a.value}:{issues:n.common.issues}}catch(a){!((s=(t=a?.message)===null||t===void 0?void 0:t.toLowerCase())===null||s===void 0)&&s.includes("encountered")&&(this["~standard"].async=true),n.common={issues:[],async:true};}return this._parseAsync({data:e,path:[],parent:n}).then(a=>P(a)?{value:a.value}:{issues:n.common.issues})}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:true},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:j(e)},n=this._parse({data:e,path:s.path,parent:s}),a=await(ue(n)?n:Promise.resolve(n));return Oe(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),o=()=>a.addIssue({code:d.custom,...s(n)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?true:(o(),false)):i?true:(o(),false)})}refinement(e,t){return this._refinement((s,n)=>e(s)?true:(n.addIssue(typeof t=="function"?t(s,n):t),false))}_refinement(e){return new C({schema:this,typeName:m.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}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),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)};}optional(){return O.create(this,this._def)}nullable(){return R.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return I.create(this)}promise(){return V.create(this,this._def)}or(e){return W.create([this,e],this._def)}and(e){return q.create(this,e,this._def)}transform(e){return new C({..._(this._def),schema:this,typeName:m.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Q({..._(this._def),innerType:this,defaultValue:t,typeName:m.ZodDefault})}brand(){return new le({typeName:m.ZodBranded,type:this,..._(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new X({..._(this._def),innerType:this,catchValue:t,typeName:m.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return fe.create(this,e)}readonly(){return K.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Ue=/^c[^\s-]{8,}$/i,Fe=/^[0-9a-z]+$/,Be=/^[0-9A-HJKMNP-TV-Z]{26}$/i,We=/^[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,qe=/^[a-z0-9_-]{21}$/i,Je=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ye=/^[-+]?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)?)??$/,He=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ge="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ke,Qe=/^(?:(?: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])$/,Xe=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,Ke=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,et=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,tt=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,rt=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ze="((\\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])))",st=new RegExp(`^${Ze}$`);function je(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return `([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function nt(r){return new RegExp(`^${je(r)}$`)}function Ne(r){let e=`${Ze}T${je(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function at(r,e){return !!((e==="v4"||!e)&&Qe.test(r)||(e==="v6"||!e)&&Ke.test(r))}function it(r,e){if(!Je.test(r))return false;try{let[t]=r.split("."),s=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),n=JSON.parse(atob(s));return !(typeof n!="object"||n===null||!n.typ||!n.alg||e&&n.alg!==e)}catch{return false}}function ot(r,e){return !!((e==="v4"||!e)&&Xe.test(r)||(e==="v6"||!e)&&et.test(r))}var $=class r extends y{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==f$1.string){let a=this._getOrReturnCtx(e);return u(a,{code:d.invalid_type,expected:f$1.string,received:a.parsedType}),v}let s=new x,n;for(let a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(n=this._getOrReturnCtx(e,n),u(n,{code:d.too_small,minimum:a.value,type:"string",inclusive:true,exact:false,message:a.message}),s.dirty());else if(a.kind==="max")e.data.length>a.value&&(n=this._getOrReturnCtx(e,n),u(n,{code:d.too_big,maximum:a.value,type:"string",inclusive:true,exact:false,message:a.message}),s.dirty());else if(a.kind==="length"){let i=e.data.length>a.value,o=e.data.length<a.value;(i||o)&&(n=this._getOrReturnCtx(e,n),i?u(n,{code:d.too_big,maximum:a.value,type:"string",inclusive:true,exact:true,message:a.message}):o&&u(n,{code:d.too_small,minimum:a.value,type:"string",inclusive:true,exact:true,message:a.message}),s.dirty());}else if(a.kind==="email")He.test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"email",code:d.invalid_string,message:a.message}),s.dirty());else if(a.kind==="emoji")ke||(ke=new RegExp(Ge,"u")),ke.test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"emoji",code:d.invalid_string,message:a.message}),s.dirty());else if(a.kind==="uuid")We.test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"uuid",code:d.invalid_string,message:a.message}),s.dirty());else if(a.kind==="nanoid")qe.test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"nanoid",code:d.invalid_string,message:a.message}),s.dirty());else if(a.kind==="cuid")Ue.test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"cuid",code:d.invalid_string,message:a.message}),s.dirty());else if(a.kind==="cuid2")Fe.test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"cuid2",code:d.invalid_string,message:a.message}),s.dirty());else if(a.kind==="ulid")Be.test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"ulid",code:d.invalid_string,message:a.message}),s.dirty());else if(a.kind==="url")try{new URL(e.data);}catch{n=this._getOrReturnCtx(e,n),u(n,{validation:"url",code:d.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),u(n,{validation:"regex",code:d.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),u(n,{code:d.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),u(n,{code:d.invalid_string,validation:{startsWith:a.value},message:a.message}),s.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(n=this._getOrReturnCtx(e,n),u(n,{code:d.invalid_string,validation:{endsWith:a.value},message:a.message}),s.dirty()):a.kind==="datetime"?Ne(a).test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{code:d.invalid_string,validation:"datetime",message:a.message}),s.dirty()):a.kind==="date"?st.test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{code:d.invalid_string,validation:"date",message:a.message}),s.dirty()):a.kind==="time"?nt(a).test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{code:d.invalid_string,validation:"time",message:a.message}),s.dirty()):a.kind==="duration"?Ye.test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"duration",code:d.invalid_string,message:a.message}),s.dirty()):a.kind==="ip"?at(e.data,a.version)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"ip",code:d.invalid_string,message:a.message}),s.dirty()):a.kind==="jwt"?it(e.data,a.alg)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"jwt",code:d.invalid_string,message:a.message}),s.dirty()):a.kind==="cidr"?ot(e.data,a.version)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"cidr",code:d.invalid_string,message:a.message}),s.dirty()):a.kind==="base64"?tt.test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"base64",code:d.invalid_string,message:a.message}),s.dirty()):a.kind==="base64url"?rt.test(e.data)||(n=this._getOrReturnCtx(e,n),u(n,{validation:"base64url",code:d.invalid_string,message:a.message}),s.dirty()):g.assertNever(a);return {status:s.value,value:e.data}}_regex(e,t,s){return this.refinement(n=>e.test(n),{validation:t,code:d.invalid_string,...h.errToObj(s)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...h.errToObj(e)})}url(e){return this._addCheck({kind:"url",...h.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...h.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...h.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...h.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...h.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...h.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...h.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...h.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...h.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...h.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...h.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...h.errToObj(e)})}datetime(e){var t,s;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:false,local:false,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:(t=e?.offset)!==null&&t!==void 0?t:false,local:(s=e?.local)!==null&&s!==void 0?s:false,...h.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,...h.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...h.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...h.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...h.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...h.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...h.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...h.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...h.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...h.errToObj(t)})}nonempty(e){return this.min(1,h.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 isCIDR(){return !!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return !!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return !!this._def.checks.find(e=>e.kind==="base64url")}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}};$.create=r=>{var e;return new $({checks:[],typeName:m.ZodString,coerce:(e=r?.coerce)!==null&&e!==void 0?e:false,..._(r)})};function dt(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 z=class r extends y{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$1.number){let a=this._getOrReturnCtx(e);return u(a,{code:d.invalid_type,expected:f$1.number,received:a.parsedType}),v}let s,n=new x;for(let a of this._def.checks)a.kind==="int"?g.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{code:d.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),u(s,{code:d.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:false,message:a.message}),n.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(s=this._getOrReturnCtx(e,s),u(s,{code:d.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:false,message:a.message}),n.dirty()):a.kind==="multipleOf"?dt(e.data,a.value)!==0&&(s=this._getOrReturnCtx(e,s),u(s,{code:d.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{code:d.not_finite,message:a.message}),n.dirty()):g.assertNever(a);return {status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,true,h.toString(t))}gt(e,t){return this.setLimit("min",e,false,h.toString(t))}lte(e,t){return this.setLimit("max",e,true,h.toString(t))}lt(e,t){return this.setLimit("max",e,false,h.toString(t))}setLimit(e,t,s,n){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:h.toString(n)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:h.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:false,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:false,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:true,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:true,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:h.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:true,value:Number.MIN_SAFE_INTEGER,message:h.toString(e)})._addCheck({kind:"max",inclusive:true,value:Number.MAX_SAFE_INTEGER,message:h.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"&&g.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 true;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)}};z.create=r=>new z({checks:[],typeName:m.ZodNumber,coerce:r?.coerce||false,..._(r)});var D=class r extends y{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte;}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data);}catch{return this._getInvalidInput(e)}if(this._getType(e)!==f$1.bigint)return this._getInvalidInput(e);let s,n=new x;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),u(s,{code:d.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),u(s,{code:d.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),u(s,{code:d.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):g.assertNever(a);return {status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return u(t,{code:d.invalid_type,expected:f$1.bigint,received:t.parsedType}),v}gte(e,t){return this.setLimit("min",e,true,h.toString(t))}gt(e,t){return this.setLimit("min",e,false,h.toString(t))}lte(e,t){return this.setLimit("max",e,true,h.toString(t))}lt(e,t){return this.setLimit("max",e,false,h.toString(t))}setLimit(e,t,s,n){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:h.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:false,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:false,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:true,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:true,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.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}};D.create=r=>{var e;return new D({checks:[],typeName:m.ZodBigInt,coerce:(e=r?.coerce)!==null&&e!==void 0?e:false,..._(r)})};var L=class extends y{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==f$1.boolean){let s=this._getOrReturnCtx(e);return u(s,{code:d.invalid_type,expected:f$1.boolean,received:s.parsedType}),v}return b(e.data)}};L.create=r=>new L({typeName:m.ZodBoolean,coerce:r?.coerce||false,..._(r)});var U=class r extends y{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==f$1.date){let a=this._getOrReturnCtx(e);return u(a,{code:d.invalid_type,expected:f$1.date,received:a.parsedType}),v}if(isNaN(e.data.getTime())){let a=this._getOrReturnCtx(e);return u(a,{code:d.invalid_date}),v}let s=new x,n;for(let a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(n=this._getOrReturnCtx(e,n),u(n,{code:d.too_small,message:a.message,inclusive:true,exact:false,minimum:a.value,type:"date"}),s.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(n=this._getOrReturnCtx(e,n),u(n,{code:d.too_big,message:a.message,inclusive:true,exact:false,maximum:a.value,type:"date"}),s.dirty()):g.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:h.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:h.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}};U.create=r=>new U({checks:[],coerce:r?.coerce||false,typeName:m.ZodDate,..._(r)});var se=class extends y{_parse(e){if(this._getType(e)!==f$1.symbol){let s=this._getOrReturnCtx(e);return u(s,{code:d.invalid_type,expected:f$1.symbol,received:s.parsedType}),v}return b(e.data)}};se.create=r=>new se({typeName:m.ZodSymbol,..._(r)});var F=class extends y{_parse(e){if(this._getType(e)!==f$1.undefined){let s=this._getOrReturnCtx(e);return u(s,{code:d.invalid_type,expected:f$1.undefined,received:s.parsedType}),v}return b(e.data)}};F.create=r=>new F({typeName:m.ZodUndefined,..._(r)});var B=class extends y{_parse(e){if(this._getType(e)!==f$1.null){let s=this._getOrReturnCtx(e);return u(s,{code:d.invalid_type,expected:f$1.null,received:s.parsedType}),v}return b(e.data)}};B.create=r=>new B({typeName:m.ZodNull,..._(r)});var M=class extends y{constructor(){super(...arguments),this._any=true;}_parse(e){return b(e.data)}};M.create=r=>new M({typeName:m.ZodAny,..._(r)});var N=class extends y{constructor(){super(...arguments),this._unknown=true;}_parse(e){return b(e.data)}};N.create=r=>new N({typeName:m.ZodUnknown,..._(r)});var A=class extends y{_parse(e){let t=this._getOrReturnCtx(e);return u(t,{code:d.invalid_type,expected:f$1.never,received:t.parsedType}),v}};A.create=r=>new A({typeName:m.ZodNever,..._(r)});var ne=class extends y{_parse(e){if(this._getType(e)!==f$1.undefined){let s=this._getOrReturnCtx(e);return u(s,{code:d.invalid_type,expected:f$1.void,received:s.parsedType}),v}return b(e.data)}};ne.create=r=>new ne({typeName:m.ZodVoid,..._(r)});var I=class r extends y{_parse(e){let{ctx:t,status:s}=this._processInputParams(e),n=this._def;if(t.parsedType!==f$1.array)return u(t,{code:d.invalid_type,expected:f$1.array,received:t.parsedType}),v;if(n.exactLength!==null){let i=t.data.length>n.exactLength.value,o=t.data.length<n.exactLength.value;(i||o)&&(u(t,{code:i?d.too_big:d.too_small,minimum:o?n.exactLength.value:void 0,maximum:i?n.exactLength.value:void 0,type:"array",inclusive:true,exact:true,message:n.exactLength.message}),s.dirty());}if(n.minLength!==null&&t.data.length<n.minLength.value&&(u(t,{code:d.too_small,minimum:n.minLength.value,type:"array",inclusive:true,exact:false,message:n.minLength.message}),s.dirty()),n.maxLength!==null&&t.data.length>n.maxLength.value&&(u(t,{code:d.too_big,maximum:n.maxLength.value,type:"array",inclusive:true,exact:false,message:n.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((i,o)=>n.type._parseAsync(new S(t,i,t.path,o)))).then(i=>x.mergeArray(s,i));let a=[...t.data].map((i,o)=>n.type._parseSync(new S(t,i,t.path,o)));return x.mergeArray(s,a)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:h.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:h.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:h.toString(t)}})}nonempty(e){return this.min(1,e)}};I.create=(r,e)=>new I({type:r,minLength:null,maxLength:null,exactLength:null,typeName:m.ZodArray,..._(e)});function ee(r){if(r instanceof w){let e={};for(let t in r.shape){let s=r.shape[t];e[t]=O.create(ee(s));}return new w({...r._def,shape:()=>e})}else return r instanceof I?new I({...r._def,type:ee(r.element)}):r instanceof O?O.create(ee(r.unwrap())):r instanceof R?R.create(ee(r.unwrap())):r instanceof E?E.create(r.items.map(e=>ee(e))):r}var w=class r extends y{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=g.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==f$1.object){let c=this._getOrReturnCtx(e);return u(c,{code:d.invalid_type,expected:f$1.object,received:c.parsedType}),v}let{status:s,ctx:n}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof A&&this._def.unknownKeys==="strip"))for(let c in n.data)i.includes(c)||o.push(c);let l=[];for(let c of i){let p=a[c],k=n.data[c];l.push({key:{status:"valid",value:c},value:p._parse(new S(n,k,n.path,c)),alwaysSet:c in n.data});}if(this._def.catchall instanceof A){let c=this._def.unknownKeys;if(c==="passthrough")for(let p of o)l.push({key:{status:"valid",value:p},value:{status:"valid",value:n.data[p]}});else if(c==="strict")o.length>0&&(u(n,{code:d.unrecognized_keys,keys:o}),s.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else {let c=this._def.catchall;for(let p of o){let k=n.data[p];l.push({key:{status:"valid",value:p},value:c._parse(new S(n,k,n.path,p)),alwaysSet:p in n.data});}}return n.common.async?Promise.resolve().then(async()=>{let c=[];for(let p of l){let k=await p.key,he=await p.value;c.push({key:k,value:he,alwaysSet:p.alwaysSet});}return c}).then(c=>x.mergeObjectSync(s,c)):x.mergeObjectSync(s,l)}get shape(){return this._def.shape()}strict(e){return h.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,s)=>{var n,a,i,o;let l=(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:(o=h.errToObj(e).message)!==null&&o!==void 0?o:l}:{message:l}}}:{}})}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:m.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};return g.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 g.objectKeys(this.shape).forEach(s=>{e[s]||(t[s]=this.shape[s]);}),new r({...this._def,shape:()=>t})}deepPartial(){return ee(this)}partial(e){let t={};return g.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 g.objectKeys(this.shape).forEach(s=>{if(e&&!e[s])t[s]=this.shape[s];else {let a=this.shape[s];for(;a instanceof O;)a=a._def.innerType;t[s]=a;}}),new r({...this._def,shape:()=>t})}keyof(){return Ie(g.objectKeys(this.shape))}};w.create=(r,e)=>new w({shape:()=>r,unknownKeys:"strip",catchall:A.create(),typeName:m.ZodObject,..._(e)});w.strictCreate=(r,e)=>new w({shape:()=>r,unknownKeys:"strict",catchall:A.create(),typeName:m.ZodObject,..._(e)});w.lazycreate=(r,e)=>new w({shape:r,unknownKeys:"strip",catchall:A.create(),typeName:m.ZodObject,..._(e)});var W=class extends y{_parse(e){let{ctx:t}=this._processInputParams(e),s=this._def.options;function n(a){for(let o of a)if(o.result.status==="valid")return o.result;for(let o of a)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;let i=a.map(o=>new T(o.ctx.common.issues));return u(t,{code:d.invalid_union,unionErrors:i}),v}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 l of s){let c={...t,common:{...t.common,issues:[]},parent:null},p=l._parseSync({data:t.data,path:t.path,parent:c});if(p.status==="valid")return p;p.status==="dirty"&&!a&&(a={result:p,ctx:c}),c.common.issues.length&&i.push(c.common.issues);}if(a)return t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(l=>new T(l));return u(t,{code:d.invalid_union,unionErrors:o}),v}}get options(){return this._def.options}};W.create=(r,e)=>new W({options:r,typeName:m.ZodUnion,..._(e)});var Z=r=>r instanceof J?Z(r.schema):r instanceof C?Z(r.innerType()):r instanceof Y?[r.value]:r instanceof H?r.options:r instanceof G?g.objectValues(r.enum):r instanceof Q?Z(r._def.innerType):r instanceof F?[void 0]:r instanceof B?[null]:r instanceof O?[void 0,...Z(r.unwrap())]:r instanceof R?[null,...Z(r.unwrap())]:r instanceof le||r instanceof K?Z(r.unwrap()):r instanceof X?Z(r._def.innerType):[],_e=class r extends y{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f$1.object)return u(t,{code:d.invalid_type,expected:f$1.object,received:t.parsedType}),v;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}):(u(t,{code:d.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),v)}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=Z(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 o of i){if(n.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);n.set(o,a);}}return new r({typeName:m.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,..._(s)})}};function Ce(r,e){let t=j(r),s=j(e);if(r===e)return {valid:true,data:r};if(t===f$1.object&&s===f$1.object){let n=g.objectKeys(e),a=g.objectKeys(r).filter(o=>n.indexOf(o)!==-1),i={...r,...e};for(let o of a){let l=Ce(r[o],e[o]);if(!l.valid)return {valid:false};i[o]=l.data;}return {valid:true,data:i}}else if(t===f$1.array&&s===f$1.array){if(r.length!==e.length)return {valid:false};let n=[];for(let a=0;a<r.length;a++){let i=r[a],o=e[a],l=Ce(i,o);if(!l.valid)return {valid:false};n.push(l.data);}return {valid:true,data:n}}else return t===f$1.date&&s===f$1.date&&+r==+e?{valid:true,data:r}:{valid:false}}var q=class extends y{_parse(e){let{status:t,ctx:s}=this._processInputParams(e),n=(a,i)=>{if(we(a)||we(i))return v;let o=Ce(a.value,i.value);return o.valid?((Te(a)||Te(i))&&t.dirty(),{status:t.value,value:o.data}):(u(s,{code:d.invalid_intersection_types}),v)};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}))}};q.create=(r,e,t)=>new q({left:r,right:e,typeName:m.ZodIntersection,..._(t)});var E=class r extends y{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==f$1.array)return u(s,{code:d.invalid_type,expected:f$1.array,received:s.parsedType}),v;if(s.data.length<this._def.items.length)return u(s,{code:d.too_small,minimum:this._def.items.length,inclusive:true,exact:false,type:"array"}),v;!this._def.rest&&s.data.length>this._def.items.length&&(u(s,{code:d.too_big,maximum:this._def.items.length,inclusive:true,exact:false,type:"array"}),t.dirty());let a=[...s.data].map((i,o)=>{let l=this._def.items[o]||this._def.rest;return l?l._parse(new S(s,i,s.path,o)):null}).filter(i=>!!i);return s.common.async?Promise.all(a).then(i=>x.mergeArray(t,i)):x.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};E.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new E({items:r,typeName:m.ZodTuple,rest:null,..._(e)})};var ye=class r extends y{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$1.object)return u(s,{code:d.invalid_type,expected:f$1.object,received:s.parsedType}),v;let n=[],a=this._def.keyType,i=this._def.valueType;for(let o in s.data)n.push({key:a._parse(new S(s,o,s.path,o)),value:i._parse(new S(s,s.data[o],s.path,o)),alwaysSet:o in s.data});return s.common.async?x.mergeObjectAsync(t,n):x.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,s){return t instanceof y?new r({keyType:e,valueType:t,typeName:m.ZodRecord,..._(s)}):new r({keyType:$.create(),valueType:e,typeName:m.ZodRecord,..._(t)})}},ae=class extends y{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$1.map)return u(s,{code:d.invalid_type,expected:f$1.map,received:s.parsedType}),v;let n=this._def.keyType,a=this._def.valueType,i=[...s.data.entries()].map(([o,l],c)=>({key:n._parse(new S(s,o,s.path,[c,"key"])),value:a._parse(new S(s,l,s.path,[c,"value"]))}));if(s.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let l of i){let c=await l.key,p=await l.value;if(c.status==="aborted"||p.status==="aborted")return v;(c.status==="dirty"||p.status==="dirty")&&t.dirty(),o.set(c.value,p.value);}return {status:t.value,value:o}})}else {let o=new Map;for(let l of i){let c=l.key,p=l.value;if(c.status==="aborted"||p.status==="aborted")return v;(c.status==="dirty"||p.status==="dirty")&&t.dirty(),o.set(c.value,p.value);}return {status:t.value,value:o}}}};ae.create=(r,e,t)=>new ae({valueType:e,keyType:r,typeName:m.ZodMap,..._(t)});var ie=class r extends y{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==f$1.set)return u(s,{code:d.invalid_type,expected:f$1.set,received:s.parsedType}),v;let n=this._def;n.minSize!==null&&s.data.size<n.minSize.value&&(u(s,{code:d.too_small,minimum:n.minSize.value,type:"set",inclusive:true,exact:false,message:n.minSize.message}),t.dirty()),n.maxSize!==null&&s.data.size>n.maxSize.value&&(u(s,{code:d.too_big,maximum:n.maxSize.value,type:"set",inclusive:true,exact:false,message:n.maxSize.message}),t.dirty());let a=this._def.valueType;function i(l){let c=new Set;for(let p of l){if(p.status==="aborted")return v;p.status==="dirty"&&t.dirty(),c.add(p.value);}return {status:t.value,value:c}}let o=[...s.data.values()].map((l,c)=>a._parse(new S(s,l,s.path,c)));return s.common.async?Promise.all(o).then(l=>i(l)):i(o)}min(e,t){return new r({...this._def,minSize:{value:e,message:h.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:h.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};ie.create=(r,e)=>new ie({valueType:r,minSize:null,maxSize:null,typeName:m.ZodSet,..._(e)});var ge=class r extends y{constructor(){super(...arguments),this.validate=this.implement;}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f$1.function)return u(t,{code:d.invalid_type,expected:f$1.function,received:t.parsedType}),v;function s(o,l){return me({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,pe(),re].filter(c=>!!c),issueData:{code:d.invalid_arguments,argumentsError:l}})}function n(o,l){return me({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,pe(),re].filter(c=>!!c),issueData:{code:d.invalid_return_type,returnTypeError:l}})}let a={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof V){let o=this;return b(async function(...l){let c=new T([]),p=await o._def.args.parseAsync(l,a).catch(xe=>{throw c.addIssue(s(l,xe)),c}),k=await Reflect.apply(i,this,p);return await o._def.returns._def.type.parseAsync(k,a).catch(xe=>{throw c.addIssue(n(k,xe)),c})})}else {let o=this;return b(function(...l){let c=o._def.args.safeParse(l,a);if(!c.success)throw new T([s(l,c.error)]);let p=Reflect.apply(i,this,c.data),k=o._def.returns.safeParse(p,a);if(!k.success)throw new T([n(p,k.error)]);return k.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:E.create(e).rest(N.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||E.create([]).rest(N.create()),returns:t||N.create(),typeName:m.ZodFunction,..._(s)})}},J=class extends y{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})}};J.create=(r,e)=>new J({getter:r,typeName:m.ZodLazy,..._(e)});var Y=class extends y{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return u(t,{received:t.data,code:d.invalid_literal,expected:this._def.value}),v}return {status:"valid",value:e.data}}get value(){return this._def.value}};Y.create=(r,e)=>new Y({value:r,typeName:m.ZodLiteral,..._(e)});function Ie(r,e){return new H({values:r,typeName:m.ZodEnum,..._(e)})}var H=class r extends y{constructor(){super(...arguments),de.set(this,void 0);}_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),s=this._def.values;return u(t,{expected:g.joinValues(s),received:t.parsedType,code:d.invalid_type}),v}if(ve(this,de)||Re(this,de,new Set(this._def.values)),!ve(this,de).has(e.data)){let t=this._getOrReturnCtx(e),s=this._def.values;return u(t,{received:t.data,code:d.invalid_enum_value,options:s}),v}return b(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})}};de=new WeakMap;H.create=Ie;var G=class extends y{constructor(){super(...arguments),ce.set(this,void 0);}_parse(e){let t=g.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==f$1.string&&s.parsedType!==f$1.number){let n=g.objectValues(t);return u(s,{expected:g.joinValues(n),received:s.parsedType,code:d.invalid_type}),v}if(ve(this,ce)||Re(this,ce,new Set(g.getValidEnumValues(this._def.values))),!ve(this,ce).has(e.data)){let n=g.objectValues(t);return u(s,{received:s.data,code:d.invalid_enum_value,options:n}),v}return b(e.data)}get enum(){return this._def.values}};ce=new WeakMap;G.create=(r,e)=>new G({values:r,typeName:m.ZodNativeEnum,..._(e)});var V=class extends y{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f$1.promise&&t.common.async===false)return u(t,{code:d.invalid_type,expected:f$1.promise,received:t.parsedType}),v;let s=t.parsedType===f$1.promise?t.data:Promise.resolve(t.data);return b(s.then(n=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}};V.create=(r,e)=>new V({type:r,typeName:m.ZodPromise,..._(e)});var C=class extends y{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===m.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=>{u(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 o=>{if(t.value==="aborted")return v;let l=await this._def.schema._parseAsync({data:o,path:s.path,parent:s});return l.status==="aborted"?v:l.status==="dirty"||t.value==="dirty"?te(l.value):l});{if(t.value==="aborted")return v;let o=this._def.schema._parseSync({data:i,path:s.path,parent:s});return o.status==="aborted"?v:o.status==="dirty"||t.value==="dirty"?te(o.value):o}}if(n.type==="refinement"){let i=o=>{let l=n.refinement(o,a);if(s.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(s.common.async===false){let o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return o.status==="aborted"?v:(o.status==="dirty"&&t.dirty(),i(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>o.status==="aborted"?v:(o.status==="dirty"&&t.dirty(),i(o.value).then(()=>({status:t.value,value:o.value}))))}if(n.type==="transform")if(s.common.async===false){let i=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!P(i))return i;let o=n.transform(i.value,a);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return {status:t.value,value:o}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(i=>P(i)?Promise.resolve(n.transform(i.value,a)).then(o=>({status:t.value,value:o})):i);g.assertNever(n);}};C.create=(r,e,t)=>new C({schema:r,typeName:m.ZodEffects,effect:e,..._(t)});C.createWithPreprocess=(r,e,t)=>new C({schema:e,effect:{type:"preprocess",transform:r},typeName:m.ZodEffects,..._(t)});var O=class extends y{_parse(e){return this._getType(e)===f$1.undefined?b(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};O.create=(r,e)=>new O({innerType:r,typeName:m.ZodOptional,..._(e)});var R=class extends y{_parse(e){return this._getType(e)===f$1.null?b(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};R.create=(r,e)=>new R({innerType:r,typeName:m.ZodNullable,..._(e)});var Q=class extends y{_parse(e){let{ctx:t}=this._processInputParams(e),s=t.data;return t.parsedType===f$1.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Q.create=(r,e)=>new Q({innerType:r,typeName:m.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,..._(e)});var X=class extends y{_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 ue(n)?n.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new T(s.common.issues)},input:s.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new T(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};X.create=(r,e)=>new X({innerType:r,typeName:m.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,..._(e)});var oe=class extends y{_parse(e){if(this._getType(e)!==f$1.nan){let s=this._getOrReturnCtx(e);return u(s,{code:d.invalid_type,expected:f$1.nan,received:s.parsedType}),v}return {status:"valid",value:e.data}}};oe.create=r=>new oe({typeName:m.ZodNaN,..._(r)});var ct=Symbol("zod_brand"),le=class extends y{_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}},fe=class r extends y{_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"?v:a.status==="dirty"?(t.dirty(),te(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"?v: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:m.ZodPipeline})}},K=class extends y{_parse(e){let t=this._def.innerType._parse(e),s=n=>(P(n)&&(n.value=Object.freeze(n.value)),n);return ue(t)?t.then(n=>s(n)):s(t)}unwrap(){return this._def.innerType}};K.create=(r,e)=>new K({innerType:r,typeName:m.ZodReadonly,..._(e)});function Se(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function $e(r,e={},t){return r?M.create().superRefine((s,n)=>{var a,i;let o=r(s);if(o instanceof Promise)return o.then(l=>{var c,p;if(!l){let k=Se(e,s),he=(p=(c=k.fatal)!==null&&c!==void 0?c:t)!==null&&p!==void 0?p:true;n.addIssue({code:"custom",...k,fatal:he});}});if(!o){let l=Se(e,s),c=(i=(a=l.fatal)!==null&&a!==void 0?a:t)!==null&&i!==void 0?i:true;n.addIssue({code:"custom",...l,fatal:c});}}):M.create()}var ut={object:w.lazycreate},m;(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";})(m||(m={}));var lt=(r,e={message:`Input not instance of ${r.name}`})=>$e(t=>t instanceof r,e),Me=$.create,Ve=z.create,ft=oe.create,ht=D.create,Pe=L.create,pt=U.create,mt=se.create,vt=F.create,_t=B.create,yt=M.create,gt=N.create,xt=A.create,kt=ne.create,bt=I.create,wt=w.create,Tt=w.strictCreate,Ct=W.create,Ot=_e.create,St=q.create,At=E.create,Et=ye.create,Rt=ae.create,Zt=ie.create,jt=ge.create,Nt=J.create,It=Y.create,$t=H.create,Mt=G.create,Vt=V.create,Ae=C.create,Pt=O.create,zt=R.create,Dt=C.createWithPreprocess,Lt=fe.create,Ut=()=>Me().optional(),Ft=()=>Ve().optional(),Bt=()=>Pe().optional(),Wt={string:r=>$.create({...r,coerce:true}),number:r=>z.create({...r,coerce:true}),boolean:r=>L.create({...r,coerce:true}),bigint:r=>D.create({...r,coerce:true}),date:r=>U.create({...r,coerce:true})},qt=v,Jt=Object.freeze({__proto__:null,defaultErrorMap:re,setErrorMap:De,getErrorMap:pe,makeIssue:me,EMPTY_PATH:Le,addIssueToContext:u,ParseStatus:x,INVALID:v,DIRTY:te,OK:b,isAborted:we,isDirty:Te,isValid:P,isAsync:ue,get util(){return g},get objectUtil(){return be},ZodParsedType:f$1,getParsedType:j,ZodType:y,datetimeRegex:Ne,ZodString:$,ZodNumber:z,ZodBigInt:D,ZodBoolean:L,ZodDate:U,ZodSymbol:se,ZodUndefined:F,ZodNull:B,ZodAny:M,ZodUnknown:N,ZodNever:A,ZodVoid:ne,ZodArray:I,ZodObject:w,ZodUnion:W,ZodDiscriminatedUnion:_e,ZodIntersection:q,ZodTuple:E,ZodRecord:ye,ZodMap:ae,ZodSet:ie,ZodFunction:ge,ZodLazy:J,ZodLiteral:Y,ZodEnum:H,ZodNativeEnum:G,ZodPromise:V,ZodEffects:C,ZodTransformer:C,ZodOptional:O,ZodNullable:R,ZodDefault:Q,ZodCatch:X,ZodNaN:oe,BRAND:ct,ZodBranded:le,ZodPipeline:fe,ZodReadonly:K,custom:$e,Schema:y,ZodSchema:y,late:ut,get ZodFirstPartyTypeKind(){return m},coerce:Wt,any:yt,array:bt,bigint:ht,boolean:Pe,date:pt,discriminatedUnion:Ot,effect:Ae,enum:$t,function:jt,instanceof:lt,intersection:St,lazy:Nt,literal:It,map:Rt,nan:ft,nativeEnum:Mt,never:xt,null:_t,nullable:zt,number:Ve,object:wt,oboolean:Bt,onumber:Ft,optional:Pt,ostring:Ut,pipeline:Lt,preprocess:Dt,promise:Vt,record:Et,set:Zt,strictObject:Tt,string:Me,symbol:mt,transformer:Ae,tuple:At,undefined:vt,union:Ct,unknown:gt,void:kt,NEVER:qt,ZodIssueCode:d,quotelessJson:ze,ZodError:T});
|
|
6
|
+
var Y$1;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Y$1="oauth4webapi/v3.8.8");function q$1(e,t){if(e==null)return false;try{return e instanceof t||Object.getPrototypeOf(e)[Symbol.toStringTag]===t.prototype[Symbol.toStringTag]}catch{return false}}var y$1="ERR_INVALID_ARG_VALUE",_$1="ERR_INVALID_ARG_TYPE";function l(e,t,n){let r=new TypeError(e,{cause:n});return Object.assign(r,{code:t}),r}var L$1=Symbol(),W$1=Symbol(),M$1=Symbol(),O$1=Symbol();var qe$1=new TextEncoder,We$1=new TextDecoder;function le$1(e){return typeof e=="string"?qe$1.encode(e):We$1.decode(e)}var Q$1;Uint8Array.prototype.toBase64?Q$1=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:true})):Q$1=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));let n=[];for(let r=0;r<t.byteLength;r+=32768)n.push(String.fromCharCode.apply(null,t.subarray(r,r+32768)));return btoa(n.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};var X$1;Uint8Array.fromBase64?X$1=e=>{try{return Uint8Array.fromBase64(e,{alphabet:"base64url"})}catch(t){throw l("The input to be decoded is not correctly encoded.",y$1,t)}}:X$1=e=>{try{let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}catch(t){throw l("The input to be decoded is not correctly encoded.",y$1,t)}};function fe$1(e){return typeof e=="string"?X$1(e):Q$1(e)}var T=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=K$1,Error.captureStackTrace?.(this,this.constructor);}},D$1=class D extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,n?.code&&(this.code=n?.code),Error.captureStackTrace?.(this,this.constructor);}};function i$1(e,t,n){return new D$1(e,{code:t,cause:n})}function H$1(e){return !(e===null||typeof e!="object"||Array.isArray(e))}function me$1(e){q$1(e,Headers)&&(e=Object.fromEntries(e.entries()));let t=new Headers(e??{});if(Y$1&&!t.has("user-agent")&&t.set("user-agent",Y$1),t.has("authorization"))throw l('"options.headers" must not include the "authorization" header name',y$1);return t}function ye$1(e,t){if(t!==void 0){if(typeof t=="function"&&(t=t(e.href)),!(t instanceof AbortSignal))throw l('"options.signal" must return or be an instance of AbortSignal',_$1);return t}}function _e$1(e){return e.includes("//")?e.replace("//","/"):e}function Me$1(e,t,n=false){return e.pathname==="/"?e.pathname=t:e.pathname=_e$1(`${t}/${n?e.pathname:e.pathname.replace(/(\/)$/,"")}`),e}function ze$1(e,t){return e.pathname=_e$1(`${e.pathname}/${t}`),e}async function Ke$1(e,t,n,r){if(!(e instanceof URL))throw l(`"${t}" must be an instance of URL`,_$1);z$1(e,r?.[L$1]!==true);let o=n(new URL(e.href)),s=me$1(r?.headers);return s.set("accept","application/json"),(r?.[O$1]||fetch)(o.href,{body:void 0,headers:Object.fromEntries(s.entries()),method:"GET",redirect:"manual",signal:ye$1(o,r?.signal)})}async function ge(e,t){return Ke$1(e,"issuerIdentifier",n=>{switch(t?.algorithm){case void 0:case "oidc":ze$1(n,".well-known/openid-configuration");break;case "oauth2":Me$1(n,".well-known/oauth-authorization-server");break;default:throw l('"options.algorithm" must be "oidc" (default), or "oauth2"',y$1)}return n},t)}function Z$1(e,t,n,r,o){try{if(typeof e!="number"||!Number.isFinite(e))throw l(`${n} must be a number`,_$1,o);if(e>0)return;if(t){if(e!==0)throw l(`${n} must be a non-negative number`,y$1,o);return}throw l(`${n} must be a positive number`,y$1,o)}catch(s){throw r?i$1(s.message,r,o):s}}function b$1(e,t,n,r){try{if(typeof e!="string")throw l(`${t} must be a string`,_$1,r);if(e.length===0)throw l(`${t} must not be empty`,y$1,r)}catch(o){throw n?i$1(o.message,n,r):o}}async function Re$1(e,t){let n=e;if(!(n instanceof URL)&&n!==J$1)throw l('"expectedIssuerIdentifier" must be an instance of URL',_$1);if(!q$1(t,Response))throw l('"response" must be an instance of Response',_$1);if(t.status!==200)throw i$1('"response" is not a conform Authorization Server Metadata response (unexpected HTTP status code)',$$1,t);oe$1(t);let r=await Ie$1(t);if(b$1(r.issuer,'"response" body "issuer" property',d$2,{body:r}),n!==J$1&&new URL(r.issuer).href!==n.href)throw i$1('"response" body "issuer" property does not match the expected value',F$1,{expected:n.href,body:r,attribute:"issuer"});return r}function be(e){Fe$1(e,"application/json");}function $e(e,...t){let n='"response" content-type must be ';if(t.length>2){let r=t.pop();n+=`${t.join(", ")}, or ${r}`;}else t.length===2?n+=`${t[0]} or ${t[1]}`:n+=t[0];return i$1(n,te$1,e)}function Fe$1(e,t){if(Ee$1(e)!==t)throw $e(e,t)}function Be$1(e){let t=e?.[W$1];return typeof t=="number"&&Number.isFinite(t)?t:0}function Ge$1(e){let t=e?.[M$1];return typeof t=="number"&&Number.isFinite(t)&&Math.sign(t)!==-1?t:30}function Ve$1(){return Math.floor(Date.now()/1e3)}function Se$1(e){if(typeof e!="object"||e===null)throw l('"as" must be an object',_$1);b$1(e.issuer,'"as.issuer"');}function Pe$1(e){if(typeof e!="object"||e===null)throw l('"client" must be an object',_$1);b$1(e.client_id,'"client.client_id"');}function ee$1(e){return b$1(e,'"clientSecret"'),(t,n,r,o)=>{r.set("client_id",n.client_id),r.set("client_secret",e);}}function Ae$1(){return (e,t,n,r)=>{n.set("client_id",t.client_id);}}var Ye$1=URL.parse?(e,t)=>URL.parse(e,t):(e,t)=>{try{return new URL(e,t)}catch{return null}};function z$1(e,t){if(t&&e.protocol!=="https:")throw i$1("only requests to HTTPS are allowed",ne$1,e);if(e.protocol!=="https:"&&e.protocol!=="http:")throw i$1("only HTTP and HTTPS requests are allowed",re$1,e)}function pe$1(e,t,n,r){let o;if(typeof e!="string"||!(o=Ye$1(e)))throw i$1(`authorization server metadata does not contain a valid ${n?`"as.mtls_endpoint_aliases.${t}"`:`"as.${t}"`}`,e===void 0?Tt$1:kt$1,{attribute:n?`mtls_endpoint_aliases.${t}`:t});return z$1(o,r),o}function Te$1(e,t,n,r){return n&&e.mtls_endpoint_aliases&&t in e.mtls_endpoint_aliases?pe$1(e.mtls_endpoint_aliases[t],t,n,r):pe$1(e[t],t,n,r)}var g$1=class g extends Error{cause;code;error;status;error_description;response;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=Pt$1,this.cause=n.cause,this.error=n.cause.error,this.status=n.response.status,this.error_description=n.cause.error_description,Object.defineProperty(this,"response",{enumerable:false,value:n.response}),Error.captureStackTrace?.(this,this.constructor);}},I$2=class I extends Error{cause;code;error;error_description;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=At$1,this.cause=n.cause,this.error=n.cause.get("error"),this.error_description=n.cause.get("error_description")??void 0,Error.captureStackTrace?.(this,this.constructor);}},k$1=class k extends Error{cause;code;response;status;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=St$1,this.cause=n.cause,this.status=n.response.status,this.response=n.response,Object.defineProperty(this,"response",{enumerable:false}),Error.captureStackTrace?.(this,this.constructor);}},N$2="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",Qe$1="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",Xe$1='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',Ze$1="("+N$2+")\\s*=\\s*"+Xe$1,et$1="("+N$2+")\\s*=\\s*("+N$2+")",tt$1=new RegExp("^[,\\s]*("+N$2+")"),nt$1=new RegExp("^[,\\s]*"+Ze$1+"[,\\s]*(.*)"),rt$1=new RegExp("^[,\\s]*"+et$1+"[,\\s]*(.*)"),ot$1=new RegExp("^("+Qe$1+")(?:$|[,\\s])(.*)");function at$1(e){if(!q$1(e,Response))throw l('"response" must be an instance of Response',_$1);let t=e.headers.get("www-authenticate");if(t===null)return;let n=[],r=t;for(;r;){let o=r.match(tt$1),s=o?.[1].toLowerCase();if(!s)return;let a=r.substring(o[0].length);if(a&&!a.match(/^[\s,]/))return;let u=a.match(/^\s+(.*)$/),h=!!u;r=u?u[1]:void 0;let c={},p;if(h)for(;r;){let P,A;if(o=r.match(nt$1)){[,P,A,r]=o,A.includes("\\")&&(A=A.replace(/\\([\s\S])/g,"$1")),c[P.toLowerCase()]=A;continue}if(o=r.match(rt$1)){[,P,A,r]=o,c[P.toLowerCase()]=A;continue}if(o=r.match(ot$1)){if(Object.keys(c).length)break;[,p,r]=o;break}return}else r=a||void 0;let m={scheme:s,parameters:c};p&&(m.token68=p),n.push(m);}if(n.length)return n}async function st$1(e){if(e.status>399&&e.status<500){oe$1(e),be(e);try{let t=await e.clone().json();if(H$1(t)&&typeof t.error=="string"&&t.error.length)return t}catch{}}}async function it$1(e,t,n){if(e.status!==t){ft$1(e);let r;throw (r=await st$1(e))?(await e.body?.cancel(),new g$1("server responded with an error in the response body",{cause:r,response:e})):i$1(`"response" is not a conform ${n} response (unexpected HTTP status code)`,$$1,e)}}function Ee$1(e){return e.headers.get("content-type")?.split(";")[0]}async function ut$1(e,t,n,r,o,s,a){return await n(e,t,o,s),s.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(a?.[O$1]||fetch)(r.href,{body:o,headers:Object.fromEntries(s.entries()),method:"POST",redirect:"manual",signal:ye$1(r,a?.signal)})}async function dt$1(e,t,n,r,o,s){let a=Te$1(e,"token_endpoint",t.use_mtls_endpoint_aliases,s?.[L$1]!==true);o.set("grant_type",r);let u=me$1(s?.headers);u.set("accept","application/json");let h=await ut$1(e,t,n,a,o,u,s);return h}var xe$1=new WeakMap,ht$1=new WeakMap;function Oe$1(e){if(!e.id_token)return;let t=xe$1.get(e);if(!t)throw l('"ref" was already garbage collected or did not resolve from the proper sources',y$1);return t}async function lt$1(e,t,n,r,o,s){if(Se$1(e),Pe$1(t),!q$1(n,Response))throw l('"response" must be an instance of Response',_$1);await it$1(n,200,"Token Endpoint"),oe$1(n);let a=await Ie$1(n);if(b$1(a.access_token,'"response" body "access_token" property',d$2,{body:a}),b$1(a.token_type,'"response" body "token_type" property',d$2,{body:a}),a.token_type=a.token_type.toLowerCase(),a.expires_in!==void 0){let u=typeof a.expires_in!="number"?parseFloat(a.expires_in):a.expires_in;Z$1(u,true,'"response" body "expires_in" property',d$2,{body:a}),a.expires_in=u;}if(a.refresh_token!==void 0&&b$1(a.refresh_token,'"response" body "refresh_token" property',d$2,{body:a}),a.scope!==void 0&&typeof a.scope!="string")throw i$1('"response" body "scope" property must be a string',d$2,{body:a});if(a.id_token!==void 0){b$1(a.id_token,'"response" body "id_token" property',d$2,{body:a});let u=[];t.require_auth_time===true&&u.push("auth_time"),t.default_max_age!==void 0&&(Z$1(t.default_max_age,true,'"client.default_max_age"'),u.push("auth_time"));let{claims:h,jwt:c}=await gt$1(e,t,a.id_token,u);bt$1(t,h),Rt$1(h),ht$1.set(n,c),xe$1.set(a,h);}if(a.token_type!=="dpop"&&a.token_type!=="bearer")throw new T("unsupported `token_type` value",{cause:{body:a}});return a}function ft$1(e){let t;if(t=at$1(e))throw new k$1("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:t,response:e})}function pt$1(e,t){if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e))throw i$1('unexpected JWT "aud" (audience) claim value',E$1,{expected:e,claims:t.claims,claim:"aud"})}else if(t.claims.aud!==e)throw i$1('unexpected JWT "aud" (audience) claim value',E$1,{expected:e,claims:t.claims,claim:"aud"});return t}function wt$1(e,t){let n=e[ae$1]?.(t)??e.issuer;if(t.claims.iss!==n)throw i$1('unexpected JWT "iss" (issuer) claim value',E$1,{expected:n,claims:t.claims,claim:"iss"});return t}var Ce$1={aud:"audience",c_hash:"code hash",client_id:"client id",exp:"expiration time",iat:"issued at",iss:"issuer",jti:"jwt id",nonce:"nonce",s_hash:"state hash",sub:"subject",ath:"access token hash",htm:"http method",htu:"http uri",cnf:"confirmation",auth_time:"authentication time"};function yt$1(e,t){for(let n of e)if(t.claims[n]===void 0)throw i$1(`JWT "${n}" (${Ce$1[n]}) claim missing`,d$2,{claims:t.claims});return t}function _t$1(e,t){if(typeof t.claims[e]!="string")throw i$1(`unexpected JWT "${e}" (${Ce$1[e]}) claim type`,d$2,{claims:t.claims});return t}function gt$1(e,t,n,r,o){return Et$1(n,xt$1.bind(void 0,t.id_token_signed_response_alg,e.id_token_signing_alg_values_supported,"RS256"),Be$1(t),Ge$1(t)).then(yt$1.bind(void 0,["aud","exp","iat","iss","sub",...r])).then(wt$1.bind(void 0,e)).then(pt$1.bind(void 0,t.client_id)).then(_t$1.bind(void 0,"sub"))}function Rt$1(e){e.auth_time!==void 0&&Z$1(e.auth_time,true,'ID Token "auth_time" (authentication time)',d$2,{claims:e});}function bt$1(e,t){if(Array.isArray(t.aud)&&t.aud.length!==1){if(t.azp===void 0)throw i$1('ID Token "aud" (audience) claim includes additional untrusted audiences',E$1,{claims:t,claim:"aud"});if(t.azp!==e.client_id)throw i$1('unexpected ID Token "azp" (authorized party) claim value',E$1,{expected:e.client_id,claims:t,claim:"azp"})}}var St$1="OAUTH_WWW_AUTHENTICATE_CHALLENGE",Pt$1="OAUTH_RESPONSE_BODY_ERROR",K$1="OAUTH_UNSUPPORTED_OPERATION",At$1="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var U$1="OAUTH_PARSE_ERROR",d$2="OAUTH_INVALID_RESPONSE";var te$1="OAUTH_RESPONSE_IS_NOT_JSON",$$1="OAUTH_RESPONSE_IS_NOT_CONFORM",ne$1="OAUTH_HTTP_REQUEST_FORBIDDEN",re$1="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",j$1="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",E$1="OAUTH_JWT_CLAIM_COMPARISON_FAILED",F$1="OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED";var Tt$1="OAUTH_MISSING_SERVER_METADATA",kt$1="OAUTH_INVALID_SERVER_METADATA";async function ve$1(e,t,n,r,o){return Se$1(e),Pe$1(t),dt$1(e,t,n,"client_credentials",new URLSearchParams(r),o)}async function De$1(e,t,n,r){return lt$1(e,t,n)}function oe$1(e){if(e.bodyUsed)throw l('"response" body has been used already',y$1)}async function Et$1(e,t,n,r,o){let{0:s,1:a,length:u}=e.split(".");if(u===5)throw new T("JWE decryption is not configured",{cause:e});if(u!==3)throw i$1("Invalid JWT",d$2,e);let h;try{h=JSON.parse(le$1(fe$1(s)));}catch(m){throw i$1("failed to parse JWT Header body as base64url encoded JSON",U$1,m)}if(!H$1(h))throw i$1("JWT Header must be a top level object",d$2,e);if(t(h),h.crit!==void 0)throw new T('no JWT "crit" header parameter extensions are supported',{cause:{header:h}});let c;try{c=JSON.parse(le$1(fe$1(a)));}catch(m){throw i$1("failed to parse JWT Payload body as base64url encoded JSON",U$1,m)}if(!H$1(c))throw i$1("JWT Payload must be a top level object",d$2,e);let p=Ve$1()+n;if(c.exp!==void 0){if(typeof c.exp!="number")throw i$1('unexpected JWT "exp" (expiration time) claim type',d$2,{claims:c});if(c.exp<=p-r)throw i$1('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',j$1,{claims:c,now:p,tolerance:r,claim:"exp"})}if(c.iat!==void 0&&typeof c.iat!="number")throw i$1('unexpected JWT "iat" (issued at) claim type',d$2,{claims:c});if(c.iss!==void 0&&typeof c.iss!="string")throw i$1('unexpected JWT "iss" (issuer) claim type',d$2,{claims:c});if(c.nbf!==void 0){if(typeof c.nbf!="number")throw i$1('unexpected JWT "nbf" (not before) claim type',d$2,{claims:c});if(c.nbf>p+r)throw i$1('unexpected JWT "nbf" (not before) claim value',j$1,{claims:c,now:p,tolerance:r,claim:"nbf"})}if(c.aud!==void 0&&typeof c.aud!="string"&&!Array.isArray(c.aud))throw i$1('unexpected JWT "aud" (audience) claim type',d$2,{claims:c});return {header:h,claims:c,jwt:e}}function xt$1(e,t,n,r){if(e!==void 0){if(typeof e=="string"?r.alg!==e:!e.includes(r.alg))throw i$1('unexpected JWT "alg" header parameter',d$2,{header:r,expected:e,reason:"client configuration"});return}if(Array.isArray(t)){if(!t.includes(r.alg))throw i$1('unexpected JWT "alg" header parameter',d$2,{header:r,expected:t,reason:"authorization server metadata"});return}if(n!==void 0){if(typeof n=="string"?r.alg!==n:typeof n=="function"?!n(r.alg):!n.includes(r.alg))throw i$1('unexpected JWT "alg" header parameter',d$2,{header:r,expected:n,reason:"default value"});return}throw i$1('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:e,issuer:t,fallback:n})}async function Ie$1(e,t=be){let n;try{n=await e.json();}catch(r){throw t(e),i$1('failed to parse "response" body as JSON',U$1,r)}if(!H$1(n))throw i$1('"response" body must be a top level object',d$2,{body:n});return n}var J$1=Symbol(),ae$1=Symbol();var B$1,Ue$1;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Ue$1="openid-client/v6.8.8",B$1={"user-agent":Ue$1});var R$1=e=>se$1.get(e),se$1;function ce$1(e){if(e!==void 0)return ee$1(e);let t=new WeakMap;return (n,r,o,s)=>{let a;return (a=t.get(r))||(Ct$1(r.client_secret,'"metadata.client_secret"'),a=ee$1(r.client_secret),t.set(r,a)),a(n,r,o,s)}}function Ct$1(e,t){if(typeof e!="string")throw x$1(`${t} must be a string`,V$1);if(e.length===0)throw x$1(`${t} must not be empty`,ue$1)}function vt$1(){return Ae$1()}var S$1=O$1;var ue$1="ERR_INVALID_ARG_VALUE",V$1="ERR_INVALID_ARG_TYPE";function x$1(e,t,n){let r=new TypeError(e,{cause:n});return Object.assign(r,{code:t}),r}var C$1=class C extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=n?.code,Error.captureStackTrace?.(this,this.constructor);}};new TextDecoder;function f(e,t,n){return new C$1(e,{cause:t,code:n})}function ie$1(e){if(e instanceof TypeError||e instanceof C$1||e instanceof g$1||e instanceof I$2||e instanceof k$1)throw e;if(e instanceof D$1)switch(e.code){case ne$1:throw f("only requests to HTTPS are allowed",e,e.code);case re$1:throw f("only requests to HTTP or HTTPS are allowed",e,e.code);case $$1:throw f("unexpected HTTP response status code",e.cause,e.code);case te$1:throw f("unexpected response content-type",e.cause,e.code);case U$1:throw f("parsing error occured",e,e.code);case d$2:throw f("invalid response encountered",e,e.code);case E$1:throw f("unexpected JWT claim value encountered",e,e.code);case F$1:throw f("unexpected JSON attribute value encountered",e,e.code);case j$1:throw f("JWT timestamp claim value failed validation",e,e.code);default:throw f(e.message,e,e.code)}if(e instanceof T)throw f("unsupported operation",e,e.code);if(e instanceof DOMException)switch(e.name){case "OperationError":throw f("runtime operation error",e,K$1);case "NotSupportedError":throw f("runtime unsupported operation",e,K$1);case "TimeoutError":throw f("operation timed out",e,"OAUTH_TIMEOUT");case "AbortError":throw f("operation aborted",e,"OAUTH_ABORT")}throw new C$1("something went wrong",{cause:e})}function Dt$1(e,t,n){return e.origin==="https://login.microsoftonline.com"&&(!n?.algorithm||n.algorithm==="oidc")?(t[He$1]=true,true):false}function It$1(e,t){return !!(e.hostname.endsWith(".b2clogin.com")&&(!t?.algorithm||t.algorithm==="oidc"))}async function Le$1(e,t,n,r,o){let s=await Ut$1(e,o),a=new v(s,t,n,r),u=R$1(a);if(o?.[S$1]&&(u.fetch=o[S$1]),o?.timeout!==void 0&&(u.timeout=o.timeout),o?.execute)for(let h of o.execute)h(a);return a}async function Ut$1(e,t){if(!(e instanceof URL))throw x$1('"server" must be an instance of URL',V$1);let n=!e.href.includes("/.well-known/"),r=t?.timeout??30,o=AbortSignal.timeout(r*1e3),s=await(n?ge(e,{algorithm:t?.algorithm,[O$1]:t?.[S$1],[L$1]:t?.execute?.includes(G$1),signal:o,headers:new Headers(B$1)}):(t?.[S$1]||fetch)((z$1(e,!t?.execute?.includes(G$1)),e.href),{headers:Object.fromEntries(new Headers({accept:"application/json",...B$1}).entries()),body:void 0,method:"GET",redirect:"manual",signal:o})).then(a=>Re$1(J$1,a)).catch(ie$1);return n&&new URL(s.issuer).href!==e.href&&(Dt$1(e,s,t)||It$1(e,t)||(()=>{throw new C$1("discovered metadata issuer does not match the expected issuer",{code:F$1,cause:{expected:e.href,body:s,attribute:"issuer"}})})()),s}function Lt$1(e){return {supportsPKCE:{__proto__:null,value(t="S256"){return e.code_challenge_methods_supported?.includes(t)===true}}}}function Ht(e){Object.defineProperties(e,Lt$1(e));}var He$1=Symbol(),v=class{constructor(t,n,r,o){if(typeof n!="string"||!n.length)throw x$1('"clientId" must be a non-empty string',V$1);if(typeof r=="string"&&(r={client_secret:r}),r?.client_id!==void 0&&n!==r.client_id)throw x$1('"clientId" and "metadata.client_id" must be the same',ue$1);let s={...structuredClone(r),client_id:n};s[W$1]=r?.[W$1]??0,s[M$1]=r?.[M$1]??30;let a;o?a=o:typeof s.client_secret=="string"&&s.client_secret.length?a=ce$1(s.client_secret):a=vt$1();let u=Object.freeze(s),h=structuredClone(t);He$1 in t&&(h[ae$1]=({claims:{tid:p}})=>t.issuer.replace("{tenantid}",p));let c=Object.freeze(h);se$1||=new WeakMap,se$1.set(this,{__proto__:null,as:c,c:u,auth:a,tlsOnly:true,timeout:30,jwksCache:{}});}serverMetadata(){let t=structuredClone(R$1(this).as);return Ht(t),t}clientMetadata(){return structuredClone(R$1(this).c)}get timeout(){return R$1(this).timeout}set timeout(t){R$1(this).timeout=t;}get[S$1](){return R$1(this).fetch}set[S$1](t){R$1(this).fetch=t;}};Object.freeze(v.prototype);function Nt$1(e){let t;return e.expires_in!==void 0&&(t=Date.now()+e.expires_in*1e3),{expiresIn:{__proto__:null,value(){if(t){let n=Date.now();return t>n?Math.floor((t-n)/1e3):0}}},claims:{__proto__:null,value(){return Oe$1(e)}}}}function jt$1(e){Object.defineProperties(e,Nt$1(e));}function G$1(e){R$1(e).tlsOnly=false;}async function de$1(e,t,n){Jt(e),t=new URLSearchParams(t);let{as:r,c:o,auth:s,fetch:a,tlsOnly:u,timeout:h}=R$1(e),c=await ve$1(r,o,s,t,{[O$1]:a,[L$1]:!u,DPoP:n?.DPoP,headers:new Headers(B$1),signal:qt(h)}).catch(ie$1),p=De$1(r,o,c),m;try{m=await p;}catch(P){ie$1(P);}return jt$1(m),m}function Jt(e){if(!(e instanceof v))throw x$1('"config" must be an instance of Configuration',V$1);if(Object.getPrototypeOf(e)!==v.prototype)throw x$1("subclassing Configuration is not allowed",ue$1)}function qt(e){return e?AbortSignal.timeout(e*1e3):void 0}var w$1=class w extends Error{code;constructor(t,n){super(t,{cause:n}),this.name="OAuthClientCredentialsError",this.code="ERR_OAUTH";}};var zt$1=6e4,Kt=new Set(["localhost","127.0.0.1"]),je$1=e=>e.protocol==="http:"&&Kt.has(e.hostname),$t$1=e=>typeof e=="number"&&Number.isFinite(e)&&e>0,Ft$1=e=>{try{return new URL(e)}catch{return}},he$1=e=>e?`OAuth token request failed: ${e}`:"OAuth token request failed",Je$1=class e{#e;constructor(t,n,r,o){if(t.protocol!=="https:"&&!je$1(t))throw new w$1("OAuth client credentials require an https service URL; http is only allowed for localhost and 127.0.0.1");this.#e={issuer:t,clientId:n,clientSecret:r,fetchImpl:o?.fetch,clock:o?.clock??(()=>Date.now()),cachedToken:void 0,configuration:void 0,flight:void 0,generation:0};}static fromServiceUrl(t,n,r){let o=Ft$1(t);if(!o||o.protocol!=="http:"&&o.protocol!=="https:")throw new w$1("OAuth client credentials require an absolute service URL");return new e(new URL(o.origin),n,r)}async getAccessToken(){let{cachedToken:t,clock:n}=this.#e;if(t!==void 0&&t.expiresAt-n()>zt$1)return t.accessToken;if(this.#e.flight)return this.#e.flight;let r=this.#e.generation,o=this.#t(r).finally(()=>{this.#e.flight===o&&(this.#e.flight=void 0);});return this.#e.flight=o,o}invalidate(){this.#e.cachedToken=void 0,this.#e.generation+=1,this.#e.flight=void 0;}async#t(t){let n=await this.#n(),r;try{r=await de$1(n);}catch(s){throw s instanceof TypeError||s instanceof w$1?s:s instanceof g$1?new w$1(he$1(s.error),s):new w$1(he$1(),s)}let o=r.access_token;if(typeof o!="string"||o.length===0)throw new w$1(he$1());if(this.#e.generation===t){let s=r.expires_in;this.#e.cachedToken=$t$1(s)?{accessToken:o,expiresAt:this.#e.clock()+s*1e3}:void 0;}return o}async#n(){if(this.#e.configuration)return this.#e.configuration;let t=this.#e.fetchImpl??globalThis.fetch;try{let n=await Le$1(this.#e.issuer,this.#e.clientId,this.#e.clientSecret,ce$1(this.#e.clientSecret),{algorithm:"oauth2",[S$1]:t,...je$1(this.#e.issuer)?{execute:[G$1]}:{}});return this.#e.configuration=n,n}catch(n){throw n instanceof TypeError?n:new w$1("OAuth authorization server discovery failed",n)}}},$n=({grantType:e,clientSecret:t})=>{if(e!=="client_credentials")throw new w$1("Only the client_credentials grant is supported");if(globalThis.window!==void 0&&t.length>0)throw new w$1("Client credentials authentication is not supported in the browser")},Fn=async(e,t)=>{let n=await t();return n.status!==401?n:(await n.body?.cancel().catch(()=>{}),e.invalidate(),t())};
|
|
7
7
|
|
|
8
|
-
|
|
8
|
+
var d$1=Object.defineProperty;var e$1=(c,a)=>{for(var b in a)d$1(c,b,{get:a[b],enumerable:true});};
|
|
9
|
+
|
|
10
|
+
var g;(function(r){r.assertEqual=a=>{};function e(a){}r.assertIs=e;function t(a){throw new Error}r.assertNever=t,r.arrayToEnum=a=>{let n={};for(let i of a)n[i]=i;return n},r.getValidEnumValues=a=>{let n=r.objectKeys(a).filter(o=>typeof a[a[o]]!="number"),i={};for(let o of n)i[o]=a[o];return r.objectValues(i)},r.objectValues=a=>r.objectKeys(a).map(function(n){return a[n]}),r.objectKeys=typeof Object.keys=="function"?a=>Object.keys(a):a=>{let n=[];for(let i in a)Object.prototype.hasOwnProperty.call(a,i)&&n.push(i);return n},r.find=(a,n)=>{for(let i of a)if(n(i))return i},r.isInteger=typeof Number.isInteger=="function"?a=>Number.isInteger(a):a=>typeof a=="number"&&Number.isFinite(a)&&Math.floor(a)===a;function s(a,n=" | "){return a.map(i=>typeof i=="string"?`'${i}'`:i).join(n)}r.joinValues=s,r.jsonStringifyReplacer=(a,n)=>typeof n=="bigint"?n.toString():n;})(g||(g={}));var ve;(function(r){r.mergeShapes=(e,t)=>({...e,...t});})(ve||(ve={}));var u=g.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),R=r=>{switch(typeof r){case "undefined":return u.undefined;case "string":return u.string;case "number":return Number.isNaN(r)?u.nan:u.number;case "boolean":return u.boolean;case "function":return u.function;case "bigint":return u.bigint;case "symbol":return u.symbol;case "object":return Array.isArray(r)?u.array:r===null?u.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?u.promise:typeof Map<"u"&&r instanceof Map?u.map:typeof Set<"u"&&r instanceof Set?u.set:typeof Date<"u"&&r instanceof Date?u.date:u.object;default:return u.unknown}};var c$1=g.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"]),Me=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),b=class r extends Error{get errors(){return this.issues}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;}format(e){let t=e||function(n){return n.message},s={_errors:[]},a=n=>{for(let i of n.issues)if(i.code==="invalid_union")i.unionErrors.map(a);else if(i.code==="invalid_return_type")a(i.returnTypeError);else if(i.code==="invalid_arguments")a(i.argumentsError);else if(i.path.length===0)s._errors.push(t(i));else {let o=s,f=0;for(;f<i.path.length;){let l=i.path[f];f===i.path.length-1?(o[l]=o[l]||{_errors:[]},o[l]._errors.push(t(i))):o[l]=o[l]||{_errors:[]},o=o[l],f++;}}};return a(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,g.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},s=[];for(let a of this.issues)if(a.path.length>0){let n=a.path[0];t[n]=t[n]||[],t[n].push(e(a));}else s.push(e(a));return {formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}};b.create=r=>new b(r);var Ve=(r,e)=>{let t;switch(r.code){case c$1.invalid_type:r.received===u.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case c$1.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,g.jsonStringifyReplacer)}`;break;case c$1.unrecognized_keys:t=`Unrecognized key(s) in object: ${g.joinValues(r.keys,", ")}`;break;case c$1.invalid_union:t="Invalid input";break;case c$1.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${g.joinValues(r.options)}`;break;case c$1.invalid_enum_value:t=`Invalid enum value. Expected ${g.joinValues(r.options)}, received '${r.received}'`;break;case c$1.invalid_arguments:t="Invalid function arguments";break;case c$1.invalid_return_type:t="Invalid function return type";break;case c$1.invalid_date:t="Invalid date";break;case c$1.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}"`:g.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case c$1.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==="bigint"?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$1.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$1.custom:t="Invalid input";break;case c$1.invalid_intersection_types:t="Intersection results could not be merged";break;case c$1.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case c$1.not_finite:t="Number must be finite";break;default:t=e.defaultError,g.assertNever(r);}return {message:t}},I$1=Ve;var we=I$1;function Pe(r){we=r;}function re(){return we}var h;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message;})(h||(h={}));var ue=r=>{let{data:e,path:t,errorMaps:s,issueData:a}=r,n=[...t,...a.path||[]],i={...a,path:n};if(a.message!==void 0)return {...a,path:n,message:a.message};let o="",f=s.filter(l=>!!l).slice().reverse();for(let l of f)o=l(i,{data:e,defaultError:o}).message;return {...a,path:n,message:o}},ze=[];function d(r,e){let t=re(),s=ue({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===I$1?void 0:I$1].filter(a=>!!a)});r.common.issues.push(s);}var x=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 a of t){if(a.status==="aborted")return p$1;a.status==="dirty"&&e.dirty(),s.push(a.value);}return {status:e.value,value:s}}static async mergeObjectAsync(e,t){let s=[];for(let a of t){let n=await a.key,i=await a.value;s.push({key:n,value:i});}return r.mergeObjectSync(e,s)}static mergeObjectSync(e,t){let s={};for(let a of t){let{key:n,value:i}=a;if(n.status==="aborted"||i.status==="aborted")return p$1;n.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),n.value!=="__proto__"&&(typeof i.value<"u"||a.alwaysSet)&&(s[n.value]=i.value);}return {status:e.value,value:s}}},p$1=Object.freeze({status:"aborted"}),D=r=>({status:"dirty",value:r}),k=r=>({status:"valid",value:r}),he=r=>r.status==="aborted",pe=r=>r.status==="dirty",M=r=>r.status==="valid",se=r=>typeof Promise<"u"&&r instanceof Promise;var O=class{constructor(e,t,s,a){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=a;}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Te=(r,e)=>{if(M(e))return {success:true,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return {success:false,get error(){if(this._error)return this._error;let t=new b(r.common.issues);return this._error=t,this._error}}};function y(r){if(!r)return {};let{errorMap:e,invalid_type_error:t,required_error:s,description:a}=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:a}:{errorMap:(i,o)=>{let{message:f}=r;return i.code==="invalid_enum_value"?{message:f??o.defaultError}:typeof o.data>"u"?{message:f??s??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:f??t??o.defaultError}},description:a}}var _=class{get description(){return this._def.description}_getType(e){return R(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:R(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return {status:new x,ctx:{common:e.parent.common,data:e.data,parsedType:R(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(se(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){let s={common:{issues:[],async:t?.async??false,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:R(e)},a=this._parseSync({data:e,path:s.path,parent:s});return Te(s,a)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:R(e)};if(!this["~standard"].async)try{let s=this._parseSync({data:e,path:[],parent:t});return M(s)?{value:s.value}:{issues:t.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=true),t.common={issues:[],async:true};}return this._parseAsync({data:e,path:[],parent:t}).then(s=>M(s)?{value:s.value}:{issues:t.common.issues})}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:true},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:R(e)},a=this._parse({data:e,path:s.path,parent:s}),n=await(se(a)?a:Promise.resolve(a));return Te(s,n)}refine(e,t){let s=a=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(a):t;return this._refinement((a,n)=>{let i=e(a),o=()=>n.addIssue({code:c$1.custom,...s(a)});return typeof Promise<"u"&&i instanceof Promise?i.then(f=>f?true:(o(),false)):i?true:(o(),false)})}refinement(e,t){return this._refinement((s,a)=>e(s)?true:(a.addIssue(typeof t=="function"?t(s,a):t),false))}_refinement(e){return new S({schema:this,typeName:m.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}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),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)};}optional(){return C.create(this,this._def)}nullable(){return j.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return $.create(this)}promise(){return z.create(this,this._def)}or(e){return J.create([this,e],this._def)}and(e){return Y.create(this,e,this._def)}transform(e){return new S({...y(this._def),schema:this,typeName:m.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new K({...y(this._def),innerType:this,defaultValue:t,typeName:m.ZodDefault})}brand(){return new le({typeName:m.ZodBranded,type:this,...y(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new ee({...y(this._def),innerType:this,catchValue:t,typeName:m.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return fe.create(this,e)}readonly(){return te.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},De=/^c[^\s-]{8,}$/i,Le=/^[0-9a-z]+$/,Ue=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Fe=/^[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,Be=/^[a-z0-9_-]{21}$/i,We=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,qe=/^[-+]?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)?)??$/,Je=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ye="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",xe,He=/^(?:(?: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])$/,Ge=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,Qe=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Xe=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ke=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,et=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Oe="((\\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])))",tt=new RegExp(`^${Oe}$`);function Se(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return `([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function rt(r){return new RegExp(`^${Se(r)}$`)}function Ae(r){let e=`${Oe}T${Se(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function st(r,e){return !!((e==="v4"||!e)&&He.test(r)||(e==="v6"||!e)&&Qe.test(r))}function at(r,e){if(!We.test(r))return false;try{let[t]=r.split(".");if(!t)return !1;let s=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),a=JSON.parse(atob(s));return !(typeof a!="object"||a===null||"typ"in a&&a?.typ!=="JWT"||!a.alg||e&&a.alg!==e)}catch{return false}}function nt(r,e){return !!((e==="v4"||!e)&&Ge.test(r)||(e==="v6"||!e)&&Xe.test(r))}var V=class r extends _{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==u.string){let n=this._getOrReturnCtx(e);return d(n,{code:c$1.invalid_type,expected:u.string,received:n.parsedType}),p$1}let s=new x,a;for(let n of this._def.checks)if(n.kind==="min")e.data.length<n.value&&(a=this._getOrReturnCtx(e,a),d(a,{code:c$1.too_small,minimum:n.value,type:"string",inclusive:true,exact:false,message:n.message}),s.dirty());else if(n.kind==="max")e.data.length>n.value&&(a=this._getOrReturnCtx(e,a),d(a,{code:c$1.too_big,maximum:n.value,type:"string",inclusive:true,exact:false,message:n.message}),s.dirty());else if(n.kind==="length"){let i=e.data.length>n.value,o=e.data.length<n.value;(i||o)&&(a=this._getOrReturnCtx(e,a),i?d(a,{code:c$1.too_big,maximum:n.value,type:"string",inclusive:true,exact:true,message:n.message}):o&&d(a,{code:c$1.too_small,minimum:n.value,type:"string",inclusive:true,exact:true,message:n.message}),s.dirty());}else if(n.kind==="email")Je.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"email",code:c$1.invalid_string,message:n.message}),s.dirty());else if(n.kind==="emoji")xe||(xe=new RegExp(Ye,"u")),xe.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"emoji",code:c$1.invalid_string,message:n.message}),s.dirty());else if(n.kind==="uuid")Fe.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"uuid",code:c$1.invalid_string,message:n.message}),s.dirty());else if(n.kind==="nanoid")Be.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"nanoid",code:c$1.invalid_string,message:n.message}),s.dirty());else if(n.kind==="cuid")De.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"cuid",code:c$1.invalid_string,message:n.message}),s.dirty());else if(n.kind==="cuid2")Le.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"cuid2",code:c$1.invalid_string,message:n.message}),s.dirty());else if(n.kind==="ulid")Ue.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"ulid",code:c$1.invalid_string,message:n.message}),s.dirty());else if(n.kind==="url")try{new URL(e.data);}catch{a=this._getOrReturnCtx(e,a),d(a,{validation:"url",code:c$1.invalid_string,message:n.message}),s.dirty();}else n.kind==="regex"?(n.regex.lastIndex=0,n.regex.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"regex",code:c$1.invalid_string,message:n.message}),s.dirty())):n.kind==="trim"?e.data=e.data.trim():n.kind==="includes"?e.data.includes(n.value,n.position)||(a=this._getOrReturnCtx(e,a),d(a,{code:c$1.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),s.dirty()):n.kind==="toLowerCase"?e.data=e.data.toLowerCase():n.kind==="toUpperCase"?e.data=e.data.toUpperCase():n.kind==="startsWith"?e.data.startsWith(n.value)||(a=this._getOrReturnCtx(e,a),d(a,{code:c$1.invalid_string,validation:{startsWith:n.value},message:n.message}),s.dirty()):n.kind==="endsWith"?e.data.endsWith(n.value)||(a=this._getOrReturnCtx(e,a),d(a,{code:c$1.invalid_string,validation:{endsWith:n.value},message:n.message}),s.dirty()):n.kind==="datetime"?Ae(n).test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{code:c$1.invalid_string,validation:"datetime",message:n.message}),s.dirty()):n.kind==="date"?tt.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{code:c$1.invalid_string,validation:"date",message:n.message}),s.dirty()):n.kind==="time"?rt(n).test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{code:c$1.invalid_string,validation:"time",message:n.message}),s.dirty()):n.kind==="duration"?qe.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"duration",code:c$1.invalid_string,message:n.message}),s.dirty()):n.kind==="ip"?st(e.data,n.version)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"ip",code:c$1.invalid_string,message:n.message}),s.dirty()):n.kind==="jwt"?at(e.data,n.alg)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"jwt",code:c$1.invalid_string,message:n.message}),s.dirty()):n.kind==="cidr"?nt(e.data,n.version)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"cidr",code:c$1.invalid_string,message:n.message}),s.dirty()):n.kind==="base64"?Ke.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"base64",code:c$1.invalid_string,message:n.message}),s.dirty()):n.kind==="base64url"?et.test(e.data)||(a=this._getOrReturnCtx(e,a),d(a,{validation:"base64url",code:c$1.invalid_string,message:n.message}),s.dirty()):g.assertNever(n);return {status:s.value,value:e.data}}_regex(e,t,s){return this.refinement(a=>e.test(a),{validation:t,code:c$1.invalid_string,...h.errToObj(s)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...h.errToObj(e)})}url(e){return this._addCheck({kind:"url",...h.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...h.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...h.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...h.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...h.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...h.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...h.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...h.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...h.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...h.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...h.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...h.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:false,local:false,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??false,local:e?.local??false,...h.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,...h.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...h.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...h.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...h.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...h.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...h.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...h.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...h.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...h.errToObj(t)})}nonempty(e){return this.min(1,h.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 isCIDR(){return !!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return !!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return !!this._def.checks.find(e=>e.kind==="base64url")}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}};V.create=r=>new V({checks:[],typeName:m.ZodString,coerce:r?.coerce??false,...y(r)});function it(r,e){let t=(r.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,a=t>s?t:s,n=Number.parseInt(r.toFixed(a).replace(".","")),i=Number.parseInt(e.toFixed(a).replace(".",""));return n%i/10**a}var L=class r extends _{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)!==u.number){let n=this._getOrReturnCtx(e);return d(n,{code:c$1.invalid_type,expected:u.number,received:n.parsedType}),p$1}let s,a=new x;for(let n of this._def.checks)n.kind==="int"?g.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),d(s,{code:c$1.invalid_type,expected:"integer",received:"float",message:n.message}),a.dirty()):n.kind==="min"?(n.inclusive?e.data<n.value:e.data<=n.value)&&(s=this._getOrReturnCtx(e,s),d(s,{code:c$1.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:false,message:n.message}),a.dirty()):n.kind==="max"?(n.inclusive?e.data>n.value:e.data>=n.value)&&(s=this._getOrReturnCtx(e,s),d(s,{code:c$1.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:false,message:n.message}),a.dirty()):n.kind==="multipleOf"?it(e.data,n.value)!==0&&(s=this._getOrReturnCtx(e,s),d(s,{code:c$1.not_multiple_of,multipleOf:n.value,message:n.message}),a.dirty()):n.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),d(s,{code:c$1.not_finite,message:n.message}),a.dirty()):g.assertNever(n);return {status:a.value,value:e.data}}gte(e,t){return this.setLimit("min",e,true,h.toString(t))}gt(e,t){return this.setLimit("min",e,false,h.toString(t))}lte(e,t){return this.setLimit("max",e,true,h.toString(t))}lt(e,t){return this.setLimit("max",e,false,h.toString(t))}setLimit(e,t,s,a){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:h.toString(a)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:h.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:false,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:false,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:true,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:true,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:h.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:true,value:Number.MIN_SAFE_INTEGER,message:h.toString(e)})._addCheck({kind:"max",inclusive:true,value:Number.MAX_SAFE_INTEGER,message:h.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"&&g.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 true;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)}};L.create=r=>new L({checks:[],typeName:m.ZodNumber,coerce:r?.coerce||false,...y(r)});var U=class r extends _{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte;}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data);}catch{return this._getInvalidInput(e)}if(this._getType(e)!==u.bigint)return this._getInvalidInput(e);let s,a=new x;for(let n of this._def.checks)n.kind==="min"?(n.inclusive?e.data<n.value:e.data<=n.value)&&(s=this._getOrReturnCtx(e,s),d(s,{code:c$1.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),a.dirty()):n.kind==="max"?(n.inclusive?e.data>n.value:e.data>=n.value)&&(s=this._getOrReturnCtx(e,s),d(s,{code:c$1.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),a.dirty()):n.kind==="multipleOf"?e.data%n.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),d(s,{code:c$1.not_multiple_of,multipleOf:n.value,message:n.message}),a.dirty()):g.assertNever(n);return {status:a.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return d(t,{code:c$1.invalid_type,expected:u.bigint,received:t.parsedType}),p$1}gte(e,t){return this.setLimit("min",e,true,h.toString(t))}gt(e,t){return this.setLimit("min",e,false,h.toString(t))}lte(e,t){return this.setLimit("max",e,true,h.toString(t))}lt(e,t){return this.setLimit("max",e,false,h.toString(t))}setLimit(e,t,s,a){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:h.toString(a)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:false,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:false,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:true,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:true,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.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}};U.create=r=>new U({checks:[],typeName:m.ZodBigInt,coerce:r?.coerce??false,...y(r)});var F=class extends _{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==u.boolean){let s=this._getOrReturnCtx(e);return d(s,{code:c$1.invalid_type,expected:u.boolean,received:s.parsedType}),p$1}return k(e.data)}};F.create=r=>new F({typeName:m.ZodBoolean,coerce:r?.coerce||false,...y(r)});var B=class r extends _{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==u.date){let n=this._getOrReturnCtx(e);return d(n,{code:c$1.invalid_type,expected:u.date,received:n.parsedType}),p$1}if(Number.isNaN(e.data.getTime())){let n=this._getOrReturnCtx(e);return d(n,{code:c$1.invalid_date}),p$1}let s=new x,a;for(let n of this._def.checks)n.kind==="min"?e.data.getTime()<n.value&&(a=this._getOrReturnCtx(e,a),d(a,{code:c$1.too_small,message:n.message,inclusive:true,exact:false,minimum:n.value,type:"date"}),s.dirty()):n.kind==="max"?e.data.getTime()>n.value&&(a=this._getOrReturnCtx(e,a),d(a,{code:c$1.too_big,message:n.message,inclusive:true,exact:false,maximum:n.value,type:"date"}),s.dirty()):g.assertNever(n);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:h.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:h.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}};B.create=r=>new B({checks:[],coerce:r?.coerce||false,typeName:m.ZodDate,...y(r)});var ne=class extends _{_parse(e){if(this._getType(e)!==u.symbol){let s=this._getOrReturnCtx(e);return d(s,{code:c$1.invalid_type,expected:u.symbol,received:s.parsedType}),p$1}return k(e.data)}};ne.create=r=>new ne({typeName:m.ZodSymbol,...y(r)});var W=class extends _{_parse(e){if(this._getType(e)!==u.undefined){let s=this._getOrReturnCtx(e);return d(s,{code:c$1.invalid_type,expected:u.undefined,received:s.parsedType}),p$1}return k(e.data)}};W.create=r=>new W({typeName:m.ZodUndefined,...y(r)});var q=class extends _{_parse(e){if(this._getType(e)!==u.null){let s=this._getOrReturnCtx(e);return d(s,{code:c$1.invalid_type,expected:u.null,received:s.parsedType}),p$1}return k(e.data)}};q.create=r=>new q({typeName:m.ZodNull,...y(r)});var P=class extends _{constructor(){super(...arguments),this._any=true;}_parse(e){return k(e.data)}};P.create=r=>new P({typeName:m.ZodAny,...y(r)});var Z=class extends _{constructor(){super(...arguments),this._unknown=true;}_parse(e){return k(e.data)}};Z.create=r=>new Z({typeName:m.ZodUnknown,...y(r)});var A=class extends _{_parse(e){let t=this._getOrReturnCtx(e);return d(t,{code:c$1.invalid_type,expected:u.never,received:t.parsedType}),p$1}};A.create=r=>new A({typeName:m.ZodNever,...y(r)});var ie=class extends _{_parse(e){if(this._getType(e)!==u.undefined){let s=this._getOrReturnCtx(e);return d(s,{code:c$1.invalid_type,expected:u.void,received:s.parsedType}),p$1}return k(e.data)}};ie.create=r=>new ie({typeName:m.ZodVoid,...y(r)});var $=class r extends _{_parse(e){let{ctx:t,status:s}=this._processInputParams(e),a=this._def;if(t.parsedType!==u.array)return d(t,{code:c$1.invalid_type,expected:u.array,received:t.parsedType}),p$1;if(a.exactLength!==null){let i=t.data.length>a.exactLength.value,o=t.data.length<a.exactLength.value;(i||o)&&(d(t,{code:i?c$1.too_big:c$1.too_small,minimum:o?a.exactLength.value:void 0,maximum:i?a.exactLength.value:void 0,type:"array",inclusive:true,exact:true,message:a.exactLength.message}),s.dirty());}if(a.minLength!==null&&t.data.length<a.minLength.value&&(d(t,{code:c$1.too_small,minimum:a.minLength.value,type:"array",inclusive:true,exact:false,message:a.minLength.message}),s.dirty()),a.maxLength!==null&&t.data.length>a.maxLength.value&&(d(t,{code:c$1.too_big,maximum:a.maxLength.value,type:"array",inclusive:true,exact:false,message:a.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((i,o)=>a.type._parseAsync(new O(t,i,t.path,o)))).then(i=>x.mergeArray(s,i));let n=[...t.data].map((i,o)=>a.type._parseSync(new O(t,i,t.path,o)));return x.mergeArray(s,n)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:h.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:h.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:h.toString(t)}})}nonempty(e){return this.min(1,e)}};$.create=(r,e)=>new $({type:r,minLength:null,maxLength:null,exactLength:null,typeName:m.ZodArray,...y(e)});function ae(r){if(r instanceof w){let e={};for(let t in r.shape){let s=r.shape[t];e[t]=C.create(ae(s));}return new w({...r._def,shape:()=>e})}else return r instanceof $?new $({...r._def,type:ae(r.element)}):r instanceof C?C.create(ae(r.unwrap())):r instanceof j?j.create(ae(r.unwrap())):r instanceof N$1?N$1.create(r.items.map(e=>ae(e))):r}var w=class r extends _{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=g.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==u.object){let l=this._getOrReturnCtx(e);return d(l,{code:c$1.invalid_type,expected:u.object,received:l.parsedType}),p$1}let{status:s,ctx:a}=this._processInputParams(e),{shape:n,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof A&&this._def.unknownKeys==="strip"))for(let l in a.data)i.includes(l)||o.push(l);let f=[];for(let l of i){let v=n[l],T=a.data[l];f.push({key:{status:"valid",value:l},value:v._parse(new O(a,T,a.path,l)),alwaysSet:l in a.data});}if(this._def.catchall instanceof A){let l=this._def.unknownKeys;if(l==="passthrough")for(let v of o)f.push({key:{status:"valid",value:v},value:{status:"valid",value:a.data[v]}});else if(l==="strict")o.length>0&&(d(a,{code:c$1.unrecognized_keys,keys:o}),s.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else {let l=this._def.catchall;for(let v of o){let T=a.data[v];f.push({key:{status:"valid",value:v},value:l._parse(new O(a,T,a.path,v)),alwaysSet:v in a.data});}}return a.common.async?Promise.resolve().then(async()=>{let l=[];for(let v of f){let T=await v.key,be=await v.value;l.push({key:T,value:be,alwaysSet:v.alwaysSet});}return l}).then(l=>x.mergeObjectSync(s,l)):x.mergeObjectSync(s,f)}get shape(){return this._def.shape()}strict(e){return h.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,s)=>{let a=this._def.errorMap?.(t,s).message??s.defaultError;return t.code==="unrecognized_keys"?{message:h.errToObj(e).message??a}:{message:a}}}:{}})}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:m.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let s of g.objectKeys(e))e[s]&&this.shape[s]&&(t[s]=this.shape[s]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let s of g.objectKeys(this.shape))e[s]||(t[s]=this.shape[s]);return new r({...this._def,shape:()=>t})}deepPartial(){return ae(this)}partial(e){let t={};for(let s of g.objectKeys(this.shape)){let a=this.shape[s];e&&!e[s]?t[s]=a:t[s]=a.optional();}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let s of g.objectKeys(this.shape))if(e&&!e[s])t[s]=this.shape[s];else {let n=this.shape[s];for(;n instanceof C;)n=n._def.innerType;t[s]=n;}return new r({...this._def,shape:()=>t})}keyof(){return Re(g.objectKeys(this.shape))}};w.create=(r,e)=>new w({shape:()=>r,unknownKeys:"strip",catchall:A.create(),typeName:m.ZodObject,...y(e)});w.strictCreate=(r,e)=>new w({shape:()=>r,unknownKeys:"strict",catchall:A.create(),typeName:m.ZodObject,...y(e)});w.lazycreate=(r,e)=>new w({shape:r,unknownKeys:"strip",catchall:A.create(),typeName:m.ZodObject,...y(e)});var J=class extends _{_parse(e){let{ctx:t}=this._processInputParams(e),s=this._def.options;function a(n){for(let o of n)if(o.result.status==="valid")return o.result;for(let o of n)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;let i=n.map(o=>new b(o.ctx.common.issues));return d(t,{code:c$1.invalid_union,unionErrors:i}),p$1}if(t.common.async)return Promise.all(s.map(async n=>{let i={...t,common:{...t.common,issues:[]},parent:null};return {result:await n._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(a);{let n,i=[];for(let f of s){let l={...t,common:{...t.common,issues:[]},parent:null},v=f._parseSync({data:t.data,path:t.path,parent:l});if(v.status==="valid")return v;v.status==="dirty"&&!n&&(n={result:v,ctx:l}),l.common.issues.length&&i.push(l.common.issues);}if(n)return t.common.issues.push(...n.ctx.common.issues),n.result;let o=i.map(f=>new b(f));return d(t,{code:c$1.invalid_union,unionErrors:o}),p$1}}get options(){return this._def.options}};J.create=(r,e)=>new J({options:r,typeName:m.ZodUnion,...y(e)});var E=r=>r instanceof H?E(r.schema):r instanceof S?E(r.innerType()):r instanceof G?[r.value]:r instanceof Q?r.options:r instanceof X?g.objectValues(r.enum):r instanceof K?E(r._def.innerType):r instanceof W?[void 0]:r instanceof q?[null]:r instanceof C?[void 0,...E(r.unwrap())]:r instanceof j?[null,...E(r.unwrap())]:r instanceof le||r instanceof te?E(r.unwrap()):r instanceof ee?E(r._def.innerType):[],me=class r extends _{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==u.object)return d(t,{code:c$1.invalid_type,expected:u.object,received:t.parsedType}),p$1;let s=this.discriminator,a=t.data[s],n=this.optionsMap.get(a);return n?t.common.async?n._parseAsync({data:t.data,path:t.path,parent:t}):n._parseSync({data:t.data,path:t.path,parent:t}):(d(t,{code:c$1.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),p$1)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,s){let a=new Map;for(let n of t){let i=E(n.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let o of i){if(a.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);a.set(o,n);}}return new r({typeName:m.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:a,...y(s)})}};function ke(r,e){let t=R(r),s=R(e);if(r===e)return {valid:true,data:r};if(t===u.object&&s===u.object){let a=g.objectKeys(e),n=g.objectKeys(r).filter(o=>a.indexOf(o)!==-1),i={...r,...e};for(let o of n){let f=ke(r[o],e[o]);if(!f.valid)return {valid:false};i[o]=f.data;}return {valid:true,data:i}}else if(t===u.array&&s===u.array){if(r.length!==e.length)return {valid:false};let a=[];for(let n=0;n<r.length;n++){let i=r[n],o=e[n],f=ke(i,o);if(!f.valid)return {valid:false};a.push(f.data);}return {valid:true,data:a}}else return t===u.date&&s===u.date&&+r==+e?{valid:true,data:r}:{valid:false}}var Y=class extends _{_parse(e){let{status:t,ctx:s}=this._processInputParams(e),a=(n,i)=>{if(he(n)||he(i))return p$1;let o=ke(n.value,i.value);return o.valid?((pe(n)||pe(i))&&t.dirty(),{status:t.value,value:o.data}):(d(s,{code:c$1.invalid_intersection_types}),p$1)};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(([n,i])=>a(n,i)):a(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}};Y.create=(r,e,t)=>new Y({left:r,right:e,typeName:m.ZodIntersection,...y(t)});var N$1=class r extends _{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==u.array)return d(s,{code:c$1.invalid_type,expected:u.array,received:s.parsedType}),p$1;if(s.data.length<this._def.items.length)return d(s,{code:c$1.too_small,minimum:this._def.items.length,inclusive:true,exact:false,type:"array"}),p$1;!this._def.rest&&s.data.length>this._def.items.length&&(d(s,{code:c$1.too_big,maximum:this._def.items.length,inclusive:true,exact:false,type:"array"}),t.dirty());let n=[...s.data].map((i,o)=>{let f=this._def.items[o]||this._def.rest;return f?f._parse(new O(s,i,s.path,o)):null}).filter(i=>!!i);return s.common.async?Promise.all(n).then(i=>x.mergeArray(t,i)):x.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};N$1.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new N$1({items:r,typeName:m.ZodTuple,rest:null,...y(e)})};var ye=class r extends _{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!==u.object)return d(s,{code:c$1.invalid_type,expected:u.object,received:s.parsedType}),p$1;let a=[],n=this._def.keyType,i=this._def.valueType;for(let o in s.data)a.push({key:n._parse(new O(s,o,s.path,o)),value:i._parse(new O(s,s.data[o],s.path,o)),alwaysSet:o in s.data});return s.common.async?x.mergeObjectAsync(t,a):x.mergeObjectSync(t,a)}get element(){return this._def.valueType}static create(e,t,s){return t instanceof _?new r({keyType:e,valueType:t,typeName:m.ZodRecord,...y(s)}):new r({keyType:V.create(),valueType:e,typeName:m.ZodRecord,...y(t)})}},oe=class extends _{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!==u.map)return d(s,{code:c$1.invalid_type,expected:u.map,received:s.parsedType}),p$1;let a=this._def.keyType,n=this._def.valueType,i=[...s.data.entries()].map(([o,f],l)=>({key:a._parse(new O(s,o,s.path,[l,"key"])),value:n._parse(new O(s,f,s.path,[l,"value"]))}));if(s.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let f of i){let l=await f.key,v=await f.value;if(l.status==="aborted"||v.status==="aborted")return p$1;(l.status==="dirty"||v.status==="dirty")&&t.dirty(),o.set(l.value,v.value);}return {status:t.value,value:o}})}else {let o=new Map;for(let f of i){let l=f.key,v=f.value;if(l.status==="aborted"||v.status==="aborted")return p$1;(l.status==="dirty"||v.status==="dirty")&&t.dirty(),o.set(l.value,v.value);}return {status:t.value,value:o}}}};oe.create=(r,e,t)=>new oe({valueType:e,keyType:r,typeName:m.ZodMap,...y(t)});var ce=class r extends _{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==u.set)return d(s,{code:c$1.invalid_type,expected:u.set,received:s.parsedType}),p$1;let a=this._def;a.minSize!==null&&s.data.size<a.minSize.value&&(d(s,{code:c$1.too_small,minimum:a.minSize.value,type:"set",inclusive:true,exact:false,message:a.minSize.message}),t.dirty()),a.maxSize!==null&&s.data.size>a.maxSize.value&&(d(s,{code:c$1.too_big,maximum:a.maxSize.value,type:"set",inclusive:true,exact:false,message:a.maxSize.message}),t.dirty());let n=this._def.valueType;function i(f){let l=new Set;for(let v of f){if(v.status==="aborted")return p$1;v.status==="dirty"&&t.dirty(),l.add(v.value);}return {status:t.value,value:l}}let o=[...s.data.values()].map((f,l)=>n._parse(new O(s,f,s.path,l)));return s.common.async?Promise.all(o).then(f=>i(f)):i(o)}min(e,t){return new r({...this._def,minSize:{value:e,message:h.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:h.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};ce.create=(r,e)=>new ce({valueType:r,minSize:null,maxSize:null,typeName:m.ZodSet,...y(e)});var _e=class r extends _{constructor(){super(...arguments),this.validate=this.implement;}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==u.function)return d(t,{code:c$1.invalid_type,expected:u.function,received:t.parsedType}),p$1;function s(o,f){return ue({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,re(),I$1].filter(l=>!!l),issueData:{code:c$1.invalid_arguments,argumentsError:f}})}function a(o,f){return ue({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,re(),I$1].filter(l=>!!l),issueData:{code:c$1.invalid_return_type,returnTypeError:f}})}let n={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof z){let o=this;return k(async function(...f){let l=new b([]),v=await o._def.args.parseAsync(f,n).catch(ge=>{throw l.addIssue(s(f,ge)),l}),T=await Reflect.apply(i,this,v);return await o._def.returns._def.type.parseAsync(T,n).catch(ge=>{throw l.addIssue(a(T,ge)),l})})}else {let o=this;return k(function(...f){let l=o._def.args.safeParse(f,n);if(!l.success)throw new b([s(f,l.error)]);let v=Reflect.apply(i,this,l.data),T=o._def.returns.safeParse(v,n);if(!T.success)throw new b([a(v,T.error)]);return T.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:N$1.create(e).rest(Z.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||N$1.create([]).rest(Z.create()),returns:t||Z.create(),typeName:m.ZodFunction,...y(s)})}},H=class extends _{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})}};H.create=(r,e)=>new H({getter:r,typeName:m.ZodLazy,...y(e)});var G=class extends _{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return d(t,{received:t.data,code:c$1.invalid_literal,expected:this._def.value}),p$1}return {status:"valid",value:e.data}}get value(){return this._def.value}};G.create=(r,e)=>new G({value:r,typeName:m.ZodLiteral,...y(e)});function Re(r,e){return new Q({values:r,typeName:m.ZodEnum,...y(e)})}var Q=class r extends _{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),s=this._def.values;return d(t,{expected:g.joinValues(s),received:t.parsedType,code:c$1.invalid_type}),p$1}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),s=this._def.values;return d(t,{received:t.data,code:c$1.invalid_enum_value,options:s}),p$1}return k(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})}};Q.create=Re;var X=class extends _{_parse(e){let t=g.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==u.string&&s.parsedType!==u.number){let a=g.objectValues(t);return d(s,{expected:g.joinValues(a),received:s.parsedType,code:c$1.invalid_type}),p$1}if(this._cache||(this._cache=new Set(g.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let a=g.objectValues(t);return d(s,{received:s.data,code:c$1.invalid_enum_value,options:a}),p$1}return k(e.data)}get enum(){return this._def.values}};X.create=(r,e)=>new X({values:r,typeName:m.ZodNativeEnum,...y(e)});var z=class extends _{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==u.promise&&t.common.async===false)return d(t,{code:c$1.invalid_type,expected:u.promise,received:t.parsedType}),p$1;let s=t.parsedType===u.promise?t.data:Promise.resolve(t.data);return k(s.then(a=>this._def.type.parseAsync(a,{path:t.path,errorMap:t.common.contextualErrorMap})))}};z.create=(r,e)=>new z({type:r,typeName:m.ZodPromise,...y(e)});var S=class extends _{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===m.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:s}=this._processInputParams(e),a=this._def.effect||null,n={addIssue:i=>{d(s,i),i.fatal?t.abort():t.dirty();},get path(){return s.path}};if(n.addIssue=n.addIssue.bind(n),a.type==="preprocess"){let i=a.transform(s.data,n);if(s.common.async)return Promise.resolve(i).then(async o=>{if(t.value==="aborted")return p$1;let f=await this._def.schema._parseAsync({data:o,path:s.path,parent:s});return f.status==="aborted"?p$1:f.status==="dirty"?D(f.value):t.value==="dirty"?D(f.value):f});{if(t.value==="aborted")return p$1;let o=this._def.schema._parseSync({data:i,path:s.path,parent:s});return o.status==="aborted"?p$1:o.status==="dirty"?D(o.value):t.value==="dirty"?D(o.value):o}}if(a.type==="refinement"){let i=o=>{let f=a.refinement(o,n);if(s.common.async)return Promise.resolve(f);if(f instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(s.common.async===false){let o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return o.status==="aborted"?p$1:(o.status==="dirty"&&t.dirty(),i(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>o.status==="aborted"?p$1:(o.status==="dirty"&&t.dirty(),i(o.value).then(()=>({status:t.value,value:o.value}))))}if(a.type==="transform")if(s.common.async===false){let i=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!M(i))return p$1;let o=a.transform(i.value,n);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return {status:t.value,value:o}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(i=>M(i)?Promise.resolve(a.transform(i.value,n)).then(o=>({status:t.value,value:o})):p$1);g.assertNever(a);}};S.create=(r,e,t)=>new S({schema:r,typeName:m.ZodEffects,effect:e,...y(t)});S.createWithPreprocess=(r,e,t)=>new S({schema:e,effect:{type:"preprocess",transform:r},typeName:m.ZodEffects,...y(t)});var C=class extends _{_parse(e){return this._getType(e)===u.undefined?k(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};C.create=(r,e)=>new C({innerType:r,typeName:m.ZodOptional,...y(e)});var j=class extends _{_parse(e){return this._getType(e)===u.null?k(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};j.create=(r,e)=>new j({innerType:r,typeName:m.ZodNullable,...y(e)});var K=class extends _{_parse(e){let{ctx:t}=this._processInputParams(e),s=t.data;return t.parsedType===u.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};K.create=(r,e)=>new K({innerType:r,typeName:m.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...y(e)});var ee=class extends _{_parse(e){let{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},a=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return se(a)?a.then(n=>({status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new b(s.common.issues)},input:s.data})})):{status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new b(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};ee.create=(r,e)=>new ee({innerType:r,typeName:m.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...y(e)});var de=class extends _{_parse(e){if(this._getType(e)!==u.nan){let s=this._getOrReturnCtx(e);return d(s,{code:c$1.invalid_type,expected:u.nan,received:s.parsedType}),p$1}return {status:"valid",value:e.data}}};de.create=r=>new de({typeName:m.ZodNaN,...y(r)});var ot=Symbol("zod_brand"),le=class extends _{_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}},fe=class r extends _{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.common.async)return (async()=>{let n=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return n.status==="aborted"?p$1:n.status==="dirty"?(t.dirty(),D(n.value)):this._def.out._parseAsync({data:n.value,path:s.path,parent:s})})();{let a=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?p$1:a.status==="dirty"?(t.dirty(),{status:"dirty",value:a.value}):this._def.out._parseSync({data:a.value,path:s.path,parent:s})}}static create(e,t){return new r({in:e,out:t,typeName:m.ZodPipeline})}},te=class extends _{_parse(e){let t=this._def.innerType._parse(e),s=a=>(M(a)&&(a.value=Object.freeze(a.value)),a);return se(t)?t.then(a=>s(a)):s(t)}unwrap(){return this._def.innerType}};te.create=(r,e)=>new te({innerType:r,typeName:m.ZodReadonly,...y(e)});function Ce(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function Ne(r,e={},t){return r?P.create().superRefine((s,a)=>{let n=r(s);if(n instanceof Promise)return n.then(i=>{if(!i){let o=Ce(e,s),f=o.fatal??t??true;a.addIssue({code:"custom",...o,fatal:f});}});if(!n){let i=Ce(e,s),o=i.fatal??t??true;a.addIssue({code:"custom",...i,fatal:o});}}):P.create()}var ct={object:w.lazycreate},m;(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";})(m||(m={}));var dt=(r,e={message:`Input not instance of ${r.name}`})=>Ne(t=>t instanceof r,e),je=V.create,Ie=L.create,ut=de.create,lt=U.create,Ee=F.create,ft=B.create,ht=ne.create,pt=W.create,mt=q.create,yt=P.create,_t=Z.create,gt=A.create,vt=ie.create,xt=$.create,kt=w.create,bt=w.strictCreate,wt=J.create,Tt=me.create,Ct=Y.create,Ot=N$1.create,St=ye.create,At=oe.create,Rt=ce.create,Nt=_e.create,jt=H.create,It=G.create,Et=Q.create,Zt=X.create,$t=z.create,Mt=S.create,Vt=C.create,Pt=j.create,zt=S.createWithPreprocess,Dt=fe.create,Lt=()=>je().optional(),Ut=()=>Ie().optional(),Ft=()=>Ee().optional(),Bt={string:(r=>V.create({...r,coerce:true})),number:(r=>L.create({...r,coerce:true})),boolean:(r=>F.create({...r,coerce:true})),bigint:(r=>U.create({...r,coerce:true})),date:(r=>B.create({...r,coerce:true}))};var Wt=p$1;var Ze={};e$1(Ze,{BRAND:()=>ot,DIRTY:()=>D,EMPTY_PATH:()=>ze,INVALID:()=>p$1,NEVER:()=>Wt,OK:()=>k,ParseStatus:()=>x,Schema:()=>_,ZodAny:()=>P,ZodArray:()=>$,ZodBigInt:()=>U,ZodBoolean:()=>F,ZodBranded:()=>le,ZodCatch:()=>ee,ZodDate:()=>B,ZodDefault:()=>K,ZodDiscriminatedUnion:()=>me,ZodEffects:()=>S,ZodEnum:()=>Q,ZodError:()=>b,ZodFirstPartyTypeKind:()=>m,ZodFunction:()=>_e,ZodIntersection:()=>Y,ZodIssueCode:()=>c$1,ZodLazy:()=>H,ZodLiteral:()=>G,ZodMap:()=>oe,ZodNaN:()=>de,ZodNativeEnum:()=>X,ZodNever:()=>A,ZodNull:()=>q,ZodNullable:()=>j,ZodNumber:()=>L,ZodObject:()=>w,ZodOptional:()=>C,ZodParsedType:()=>u,ZodPipeline:()=>fe,ZodPromise:()=>z,ZodReadonly:()=>te,ZodRecord:()=>ye,ZodSchema:()=>_,ZodSet:()=>ce,ZodString:()=>V,ZodSymbol:()=>ne,ZodTransformer:()=>S,ZodTuple:()=>N$1,ZodType:()=>_,ZodUndefined:()=>W,ZodUnion:()=>J,ZodUnknown:()=>Z,ZodVoid:()=>ie,addIssueToContext:()=>d,any:()=>yt,array:()=>xt,bigint:()=>lt,boolean:()=>Ee,coerce:()=>Bt,custom:()=>Ne,date:()=>ft,datetimeRegex:()=>Ae,defaultErrorMap:()=>I$1,discriminatedUnion:()=>Tt,effect:()=>Mt,enum:()=>Et,function:()=>Nt,getErrorMap:()=>re,getParsedType:()=>R,instanceof:()=>dt,intersection:()=>Ct,isAborted:()=>he,isAsync:()=>se,isDirty:()=>pe,isValid:()=>M,late:()=>ct,lazy:()=>jt,literal:()=>It,makeIssue:()=>ue,map:()=>At,nan:()=>ut,nativeEnum:()=>Zt,never:()=>gt,null:()=>mt,nullable:()=>Pt,number:()=>Ie,object:()=>kt,objectUtil:()=>ve,oboolean:()=>Ft,onumber:()=>Ut,optional:()=>Vt,ostring:()=>Lt,pipeline:()=>Dt,preprocess:()=>zt,promise:()=>$t,quotelessJson:()=>Me,record:()=>St,set:()=>Rt,setErrorMap:()=>Pe,strictObject:()=>bt,string:()=>je,symbol:()=>ht,transformer:()=>Mt,tuple:()=>Ot,undefined:()=>pt,union:()=>wt,unknown:()=>_t,util:()=>g,void:()=>vt});
|
|
11
|
+
|
|
12
|
+
Ze.object({sessionId:Ze.string().uuid()});var o=Ze.string().min(1).max(255).regex(/^[^/+#]+$/,'Must not contain "/", "+" or "#"');Ze.object({platformId:o,sourceId:Ze.string(),isFullApi:Ze.boolean().optional().default(false),timeOffset:Ze.number().default(0)});var n=Ze.object({uuid:Ze.string(),name:Ze.string(),notificationTopic:Ze.string().optional(),eventTopic:Ze.string().optional()});Ze.object({sessionId:Ze.string(),orgId:Ze.string(),userId:Ze.string(),platformId:Ze.string(),sourceId:Ze.string(),groups:Ze.array(n),mqtt:Ze.object({sessionRootTopic:Ze.string(),userNotificationEventsTopic:Ze.string(),allNotificationEventsTopic:Ze.string().optional(),notificationsRootTopic:Ze.string(),lastWillTopic:Ze.string(),url:Ze.string(),token:Ze.string(),userNotificationTopic:Ze.string(),localSessionExpiryHandling:Ze.boolean()}).optional()}).strict();Ze.object({title:Ze.string().optional(),date:Ze.number().optional(),appId:Ze.string().optional(),stream:Ze.object({appId:Ze.string().optional()}).optional()}).passthrough();var e=Ze.object({groups:Ze.array(Ze.string()).default([]),users:Ze.array(Ze.string().min(1).max(255).regex(/^[\w+.@-]+$/)).default([])});Ze.object({action:Ze.literal("forward"),actionData:Ze.object({id:Ze.string().min(1),forwardTargets:e})});var a=Ze.enum(["reuse","new"]);Ze.object({action:Ze.literal("raise-intent"),actionData:Ze.object({intentName:Ze.string().min(1),context:Ze.object({type:Ze.string().min(1)}).passthrough(),targetApp:Ze.string().min(1).optional(),instanceBehaviour:a.optional()})});Ze.object({action:Ze.literal("open"),actionData:Ze.object({id:Ze.string().min(1),context:Ze.object({type:Ze.string().min(1)}).passthrough().optional()})});Ze.object({forwardActionId:Ze.string().min(1)});var r=Ze.enum(["new","update","delete"]),i=Ze.object({correlationId:Ze.string().optional(),targets:e,ttlSeconds:Ze.number().optional(),notificationClass:o.default("interactive").optional(),payload:Ze.unknown()}),s=Ze.object({sessionId:Ze.string().uuid(),timeOffset:Ze.number(),notification:i});s.extend({notification:i.omit({targets:true}).strict()});Ze.object({sessionId:Ze.string().uuid(),timeOffset:Ze.number().optional().default(0),ttlSeconds:Ze.number().optional(),payload:Ze.unknown()});var p=Ze.enum(["users","groups"]),I=Ze.object({notificationId:Ze.string().uuid(),category:Ze.string(),type:Ze.string(),sourceId:Ze.string(),originatingSessionId:Ze.string().uuid(),platformId:Ze.string(),userId:Ze.string().uuid(),userName:Ze.string().optional(),payload:Ze.unknown().optional(),correlationId:Ze.string().optional()}),N=Ze.object({action:r,notificationId:Ze.string().uuid(),originatingSessionId:Ze.string().uuid(),correlationId:Ze.string().optional(),target:Ze.string(),targetType:p,payload:Ze.unknown(),txInstanceId:Ze.string().uuid()}),c=Ze.object({category:Ze.string(),type:Ze.string(),payload:Ze.unknown().optional()});Ze.object({sessionId:Ze.string().uuid(),timeOffset:Ze.number().optional().default(0),event:c,targets:e.nullable().optional()});Ze.object({userId:Ze.string().uuid(),platformId:Ze.string(),sourceId:Ze.string(),notificationId:Ze.string().uuid(),category:Ze.string(),type:Ze.string(),sessionId:Ze.string().uuid(),payload:Ze.unknown().optional(),timestamp:Ze.date(),cursor:Ze.string().base64(),correlationId:Ze.string().nullish(),targets:e.optional()});
|
|
9
13
|
|
|
10
14
|
class CloudNotificationAPIError extends Error {
|
|
11
15
|
code;
|
|
@@ -20,6 +24,11 @@ class AuthorizationError extends CloudNotificationAPIError {
|
|
|
20
24
|
super(message, code, undefined);
|
|
21
25
|
}
|
|
22
26
|
}
|
|
27
|
+
class OAuthAuthenticationError extends CloudNotificationAPIError {
|
|
28
|
+
constructor(message, code = 'ERR_OAUTH', cause) {
|
|
29
|
+
super(message, code, cause);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
23
32
|
class SessionNotConnectedError extends CloudNotificationAPIError {
|
|
24
33
|
constructor(message = 'Session not connected', code = 'ERR_SESSION_NOT_CONNECTED') {
|
|
25
34
|
super(message, code, undefined);
|
|
@@ -54,6 +63,16 @@ class InvalidMessageFormatError extends CloudNotificationAPIError {
|
|
|
54
63
|
// Error codes as defined in https://docs.emqx.com/en/cloud/latest/connect_to_deployments/mqtt_client_error_codes.html
|
|
55
64
|
const BadUserNamePasswordError = 134;
|
|
56
65
|
|
|
66
|
+
const rethrowAsOAuthAuthenticationError = (error) => {
|
|
67
|
+
if (error instanceof w$1) {
|
|
68
|
+
throw new OAuthAuthenticationError(error.message, 'ERR_OAUTH', error);
|
|
69
|
+
}
|
|
70
|
+
if (error instanceof TypeError) {
|
|
71
|
+
throw new OAuthAuthenticationError('OAuth access token could not be obtained', 'ERR_OAUTH', error);
|
|
72
|
+
}
|
|
73
|
+
throw error;
|
|
74
|
+
};
|
|
75
|
+
|
|
57
76
|
class EventController {
|
|
58
77
|
#eventListeners = new Map();
|
|
59
78
|
addEventListener(type, callback) {
|
|
@@ -83,6 +102,108 @@ class EventController {
|
|
|
83
102
|
}
|
|
84
103
|
}
|
|
85
104
|
|
|
105
|
+
class TimeDifferenceTracker {
|
|
106
|
+
#timeServerUrl;
|
|
107
|
+
#intervalMs;
|
|
108
|
+
#samples;
|
|
109
|
+
#authenticatedFetch;
|
|
110
|
+
#currentOffset = 0;
|
|
111
|
+
#timerId;
|
|
112
|
+
#stopped = false;
|
|
113
|
+
#logger;
|
|
114
|
+
constructor(timeServerUrl, authenticatedFetch, logger, intervalMs = 60 * 60 * 1000, samples = 10) {
|
|
115
|
+
this.#timeServerUrl = timeServerUrl;
|
|
116
|
+
this.#logger = logger;
|
|
117
|
+
this.#authenticatedFetch = authenticatedFetch;
|
|
118
|
+
this.#intervalMs = intervalMs;
|
|
119
|
+
this.#samples = samples;
|
|
120
|
+
}
|
|
121
|
+
async start() {
|
|
122
|
+
await this.updateTimeOffset();
|
|
123
|
+
}
|
|
124
|
+
stop() {
|
|
125
|
+
this.#stopped = true;
|
|
126
|
+
if (this.#timerId) {
|
|
127
|
+
clearInterval(this.#timerId);
|
|
128
|
+
this.#timerId = undefined;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
async updateTimeOffset() {
|
|
132
|
+
if (this.#timerId) {
|
|
133
|
+
clearInterval(this.#timerId);
|
|
134
|
+
this.#timerId = undefined;
|
|
135
|
+
}
|
|
136
|
+
try {
|
|
137
|
+
this.#currentOffset = await this.#getAverageOffset();
|
|
138
|
+
this.#logger('debug', `Time offset: ${this.#currentOffset} ms`);
|
|
139
|
+
if (this.#stopped) {
|
|
140
|
+
return this.#currentOffset;
|
|
141
|
+
}
|
|
142
|
+
this.#timerId = setInterval(async () => {
|
|
143
|
+
try {
|
|
144
|
+
this.#currentOffset = await this.#getAverageOffset();
|
|
145
|
+
this.#logger('debug', `Time offset: ${this.#currentOffset} ms`);
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
this.#logger('error', `Failed to update time offset`);
|
|
149
|
+
}
|
|
150
|
+
}, this.#intervalMs);
|
|
151
|
+
return this.#currentOffset;
|
|
152
|
+
}
|
|
153
|
+
catch (error) {
|
|
154
|
+
if (error instanceof OAuthAuthenticationError) {
|
|
155
|
+
throw error;
|
|
156
|
+
}
|
|
157
|
+
this.#logger('error', `Failed to update time offset`);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
get currentOffset() {
|
|
161
|
+
return this.#currentOffset;
|
|
162
|
+
}
|
|
163
|
+
async #measureOffset() {
|
|
164
|
+
const start = Date.now();
|
|
165
|
+
const response = await this.#authenticatedFetch(`${this.#timeServerUrl}/api/time`, {
|
|
166
|
+
method: 'GET',
|
|
167
|
+
});
|
|
168
|
+
if (response.status === 401) {
|
|
169
|
+
return 'unauthorized';
|
|
170
|
+
}
|
|
171
|
+
const end = Date.now();
|
|
172
|
+
const data = await response.json();
|
|
173
|
+
const rtt = end - start;
|
|
174
|
+
const clientMidpoint = (start + end) / 2;
|
|
175
|
+
return {
|
|
176
|
+
offset: data.serverTime - clientMidpoint,
|
|
177
|
+
rtt,
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
async #getAverageOffset() {
|
|
181
|
+
const results = [];
|
|
182
|
+
for (let index = 0; index < this.#samples && !this.#stopped; index++) {
|
|
183
|
+
try {
|
|
184
|
+
const result = await this.#measureOffset();
|
|
185
|
+
if (result === 'unauthorized') {
|
|
186
|
+
break;
|
|
187
|
+
}
|
|
188
|
+
results.push(result);
|
|
189
|
+
}
|
|
190
|
+
catch (error) {
|
|
191
|
+
if (error instanceof OAuthAuthenticationError) {
|
|
192
|
+
throw error;
|
|
193
|
+
}
|
|
194
|
+
// Just ignore any time get failures
|
|
195
|
+
}
|
|
196
|
+
await new Promise((res) => setTimeout(res, 50));
|
|
197
|
+
}
|
|
198
|
+
if (results.length === 0) {
|
|
199
|
+
return this.#currentOffset;
|
|
200
|
+
}
|
|
201
|
+
// Filter out top 20% RTTs as outliers
|
|
202
|
+
const filtered = results.sort((a, b) => a.rtt - b.rtt).slice(0, Math.max(1, Math.floor(results.length * 0.8)));
|
|
203
|
+
return filtered.reduce((sum, r) => sum + r.offset, 0) / filtered.length;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
86
207
|
function validateConnectParameters(parameters) {
|
|
87
208
|
if (!parameters) {
|
|
88
209
|
throw new Error('Connect parameters must be provided');
|
|
@@ -98,6 +219,17 @@ function validateConnectParameters(parameters) {
|
|
|
98
219
|
(!parameters.basicAuthenticationParameters?.username || !parameters.basicAuthenticationParameters?.password)) {
|
|
99
220
|
throw new Error('basicAuthenticationParameters must be provided when using basic authentication');
|
|
100
221
|
}
|
|
222
|
+
if (parameters.authenticationType === 'oauth') {
|
|
223
|
+
if (!parameters.oauthAuthenticationParameters?.clientId?.trim() || !parameters.oauthAuthenticationParameters?.clientSecret?.trim()) {
|
|
224
|
+
throw new OAuthAuthenticationError('oauthAuthenticationParameters must be provided when using oauth authentication');
|
|
225
|
+
}
|
|
226
|
+
try {
|
|
227
|
+
$n(parameters.oauthAuthenticationParameters);
|
|
228
|
+
}
|
|
229
|
+
catch (error) {
|
|
230
|
+
rethrowAsOAuthAuthenticationError(error);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
101
233
|
}
|
|
102
234
|
function handleAPIException(logger, error, message, exceptionConstructor) {
|
|
103
235
|
if (error instanceof Error) {
|
|
@@ -118,9 +250,18 @@ async function checkResponse(logger, response, failMessage, failCode) {
|
|
|
118
250
|
throw new CloudNotificationAPIError(`${failMessage} (HTTP ${response.status}: ${response.statusText})`, failCode, responseBody);
|
|
119
251
|
}
|
|
120
252
|
}
|
|
121
|
-
function getRequestHeaders(connectionParameters) {
|
|
253
|
+
async function getRequestHeaders(connectionParameters, tokenClient) {
|
|
122
254
|
const headers = {};
|
|
123
255
|
headers['Content-Type'] = 'application/json';
|
|
256
|
+
if (connectionParameters.authenticationType === 'oauth' && tokenClient) {
|
|
257
|
+
try {
|
|
258
|
+
const accessToken = await tokenClient.getAccessToken();
|
|
259
|
+
headers['Authorization'] = `Bearer ${accessToken}`;
|
|
260
|
+
}
|
|
261
|
+
catch (error) {
|
|
262
|
+
rethrowAsOAuthAuthenticationError(error);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
124
265
|
if (connectionParameters.authenticationType === 'jwt' && connectionParameters.jwtAuthenticationParameters) {
|
|
125
266
|
const tokenResult = connectionParameters.jwtAuthenticationParameters.jwtRequestCallback();
|
|
126
267
|
if (!tokenResult) {
|
|
@@ -192,87 +333,6 @@ class SetWithTTL {
|
|
|
192
333
|
}
|
|
193
334
|
}
|
|
194
335
|
|
|
195
|
-
class TimeDifferenceTracker {
|
|
196
|
-
#timeServerUrl;
|
|
197
|
-
#intervalMs;
|
|
198
|
-
#samples;
|
|
199
|
-
#connectionParams;
|
|
200
|
-
#currentOffset = 0;
|
|
201
|
-
#timerId;
|
|
202
|
-
#logger;
|
|
203
|
-
constructor(timeServerUrl, connectionParameters, logger, intervalMs = 60 * 60 * 1000, samples = 10) {
|
|
204
|
-
this.#timeServerUrl = timeServerUrl;
|
|
205
|
-
this.#logger = logger;
|
|
206
|
-
this.#connectionParams = connectionParameters;
|
|
207
|
-
this.#intervalMs = intervalMs;
|
|
208
|
-
this.#samples = samples;
|
|
209
|
-
}
|
|
210
|
-
async start() {
|
|
211
|
-
await this.updateTimeOffset();
|
|
212
|
-
}
|
|
213
|
-
stop() {
|
|
214
|
-
if (this.#timerId) {
|
|
215
|
-
clearInterval(this.#timerId);
|
|
216
|
-
this.#timerId = undefined;
|
|
217
|
-
}
|
|
218
|
-
}
|
|
219
|
-
async updateTimeOffset() {
|
|
220
|
-
if (this.#timerId) {
|
|
221
|
-
clearInterval(this.#timerId);
|
|
222
|
-
this.#timerId = undefined;
|
|
223
|
-
}
|
|
224
|
-
try {
|
|
225
|
-
this.#currentOffset = await this.#getAverageOffset();
|
|
226
|
-
this.#logger('debug', `Time offset: ${this.#currentOffset} ms`);
|
|
227
|
-
this.#timerId = setInterval(async () => {
|
|
228
|
-
this.#currentOffset = await this.#getAverageOffset();
|
|
229
|
-
this.#logger('debug', `Time offset: ${this.#currentOffset} ms`);
|
|
230
|
-
}, this.#intervalMs);
|
|
231
|
-
return this.#currentOffset;
|
|
232
|
-
}
|
|
233
|
-
catch {
|
|
234
|
-
this.#logger('error', `Failed to update time offset`);
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
get currentOffset() {
|
|
238
|
-
return this.#currentOffset;
|
|
239
|
-
}
|
|
240
|
-
async #measureOffset() {
|
|
241
|
-
if (!this.#connectionParams) {
|
|
242
|
-
throw new Error('Connection details not set');
|
|
243
|
-
}
|
|
244
|
-
const start = Date.now();
|
|
245
|
-
const response = await fetch(`${this.#timeServerUrl}/api/time`, {
|
|
246
|
-
method: 'GET',
|
|
247
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
248
|
-
});
|
|
249
|
-
const end = Date.now();
|
|
250
|
-
const data = await response.json();
|
|
251
|
-
const rtt = end - start;
|
|
252
|
-
const clientMidpoint = (start + end) / 2;
|
|
253
|
-
return {
|
|
254
|
-
offset: data.serverTime - clientMidpoint,
|
|
255
|
-
rtt,
|
|
256
|
-
};
|
|
257
|
-
}
|
|
258
|
-
async #getAverageOffset() {
|
|
259
|
-
const results = [];
|
|
260
|
-
for (let index = 0; index < this.#samples; index++) {
|
|
261
|
-
try {
|
|
262
|
-
const result = await this.#measureOffset();
|
|
263
|
-
results.push(result);
|
|
264
|
-
}
|
|
265
|
-
catch {
|
|
266
|
-
// Just ignore any time get failures
|
|
267
|
-
}
|
|
268
|
-
await new Promise((res) => setTimeout(res, 50));
|
|
269
|
-
}
|
|
270
|
-
// Filter out top 20% RTTs as outliers
|
|
271
|
-
const filtered = results.sort((a, b) => a.rtt - b.rtt).slice(0, Math.floor(results.length * 0.8));
|
|
272
|
-
return filtered.reduce((sum, r) => sum + r.offset, 0) / filtered.length;
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
|
|
276
336
|
/**
|
|
277
337
|
* Represents a single connection to the Cloud Notification service
|
|
278
338
|
*
|
|
@@ -288,11 +348,14 @@ class CloudNotificationAPI {
|
|
|
288
348
|
#deDuplicator;
|
|
289
349
|
#reconnectRetries = 0;
|
|
290
350
|
#connectionParams;
|
|
351
|
+
#tokenClient;
|
|
291
352
|
#attemptingToReconnect = false;
|
|
353
|
+
#disconnecting = false;
|
|
292
354
|
#events = new EventController();
|
|
293
355
|
#defaultSubscriptionOptions = { qos: 2, nl: true };
|
|
294
356
|
#logger = (level, message) => console[level](message);
|
|
295
357
|
#getCurrentTimeOffset = () => this.#timeDifferenceTracker?.currentOffset || 0;
|
|
358
|
+
#sessionTimer;
|
|
296
359
|
/**
|
|
297
360
|
* Constructs a new instance of the CloudNotificationAPI
|
|
298
361
|
*
|
|
@@ -328,22 +391,49 @@ class CloudNotificationAPI {
|
|
|
328
391
|
* @returns A promise that resolves when the connection is established.
|
|
329
392
|
* @throws {@link CloudNotificationAPIError} If an error occurs during connection.
|
|
330
393
|
* @throws {@link AuthorizationError} If the connection is unauthorized.
|
|
394
|
+
* @throws {@link OAuthAuthenticationError} If OAuth parameters are invalid, the client credentials are rejected, or an access token cannot be obtained.
|
|
331
395
|
*/
|
|
332
396
|
async connect(parameters) {
|
|
333
397
|
validateConnectParameters(parameters);
|
|
398
|
+
const oauthParameters = parameters.oauthAuthenticationParameters;
|
|
399
|
+
if (parameters.authenticationType === 'oauth' && oauthParameters) {
|
|
400
|
+
try {
|
|
401
|
+
this.#tokenClient = Je$1.fromServiceUrl(this.#cloudNotificationSettings.url, oauthParameters.clientId, oauthParameters.clientSecret);
|
|
402
|
+
}
|
|
403
|
+
catch (error) {
|
|
404
|
+
rethrowAsOAuthAuthenticationError(error);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
else {
|
|
408
|
+
this.#tokenClient = undefined;
|
|
409
|
+
}
|
|
334
410
|
this.#connectionParams = parameters;
|
|
335
|
-
if (this.#
|
|
336
|
-
|
|
337
|
-
|
|
411
|
+
if (parameters.authenticationType === 'oauth' && this.#tokenClient) {
|
|
412
|
+
try {
|
|
413
|
+
await this.#tokenClient.getAccessToken();
|
|
414
|
+
}
|
|
415
|
+
catch (error) {
|
|
416
|
+
rethrowAsOAuthAuthenticationError(error);
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
this.#logger('info', 'Creating Notification service session');
|
|
420
|
+
this.#stopTimeSync();
|
|
421
|
+
this.#timeDifferenceTracker = new TimeDifferenceTracker(this.#cloudNotificationSettings.url, this.#authenticatedFetch, this.#logger);
|
|
422
|
+
try {
|
|
423
|
+
return await this.#createSession(this.#timeDifferenceTracker, parameters);
|
|
424
|
+
}
|
|
425
|
+
catch (error) {
|
|
426
|
+
this.#timeDifferenceTracker?.stop();
|
|
427
|
+
throw error;
|
|
338
428
|
}
|
|
339
|
-
|
|
429
|
+
}
|
|
430
|
+
async #createSession(timeDifferenceTracker, parameters) {
|
|
340
431
|
if (this.#syncTime !== false) {
|
|
341
|
-
await
|
|
432
|
+
await timeDifferenceTracker.start();
|
|
342
433
|
}
|
|
343
|
-
const { platformId, sourceId } =
|
|
344
|
-
const createSessionResponse = await
|
|
434
|
+
const { platformId, sourceId } = parameters;
|
|
435
|
+
const createSessionResponse = await this.#authenticatedFetch(`${this.#cloudNotificationSettings.url}/api/sessions`, {
|
|
345
436
|
method: 'POST',
|
|
346
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
347
437
|
body: JSON.stringify({
|
|
348
438
|
platformId,
|
|
349
439
|
sourceId,
|
|
@@ -356,9 +446,15 @@ class CloudNotificationAPI {
|
|
|
356
446
|
throw new CloudNotificationAPIError(`Failed to connect to the Cloud Notification service: ${this.#cloudNotificationSettings.url}`, 'ERR_CONNECT', new Error(createSessionResponse.statusText));
|
|
357
447
|
}
|
|
358
448
|
this.#sessionDetails = (await createSessionResponse.json());
|
|
449
|
+
const { mqtt: _, ...sessionDetailsWithoutMQTT } = this.#sessionDetails;
|
|
450
|
+
this.#logger('info', `Notification service session created: ${JSON.stringify(sessionDetailsWithoutMQTT, null, 2)}`);
|
|
359
451
|
// Now have the details from the server about where to connect to and a token to connect with
|
|
360
452
|
// we can go ahead and connect to the MQTT server
|
|
361
453
|
await this.#connectToMQTT();
|
|
454
|
+
// If local session expiry handling is enabled, start the session timer
|
|
455
|
+
if (this.#sessionDetails.mqtt?.localSessionExpiryHandling) {
|
|
456
|
+
this.#startSessionTimer();
|
|
457
|
+
}
|
|
362
458
|
return { sessionId: this.#sessionDetails.sessionId, platformId, sourceId, userId: this.#sessionDetails.userId, groups: this.#sessionDetails.groups };
|
|
363
459
|
}
|
|
364
460
|
/**
|
|
@@ -373,7 +469,7 @@ class CloudNotificationAPI {
|
|
|
373
469
|
/**
|
|
374
470
|
* Posts a notification event to the Cloud Notification service.
|
|
375
471
|
*
|
|
376
|
-
* @param notificationId - The ID of the notification.
|
|
472
|
+
* @param notificationId - The ID of the notification or an array of notification IDs.
|
|
377
473
|
* @param event - The event details, including category, type, and optional payload.
|
|
378
474
|
* @returns A promise that resolves when the event is posted.
|
|
379
475
|
* @throws {@link SessionNotConnectedError} If the session is not connected.
|
|
@@ -391,9 +487,10 @@ class CloudNotificationAPI {
|
|
|
391
487
|
event,
|
|
392
488
|
targets: options?.targets,
|
|
393
489
|
};
|
|
394
|
-
const
|
|
490
|
+
const notificationIds = Array.isArray(notificationId) ? notificationId : [notificationId];
|
|
491
|
+
const notificationIdsString = notificationIds.join('&id=');
|
|
492
|
+
const publishResponse = await this.#authenticatedFetch(`${this.#cloudNotificationSettings.url}/api/publications/events?id=${notificationIdsString}`, {
|
|
395
493
|
method: 'POST',
|
|
396
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
397
494
|
body: JSON.stringify(publishPayload),
|
|
398
495
|
});
|
|
399
496
|
await checkResponse(this.#logger, publishResponse, 'Error posting notification event', 'ERR_POST_NOTIFICATION_EVENT');
|
|
@@ -410,13 +507,28 @@ class CloudNotificationAPI {
|
|
|
410
507
|
* @returns A promise that resolves when the notification is removed.
|
|
411
508
|
*/
|
|
412
509
|
async removeFromNotificationCenter(notificationId, targets) {
|
|
413
|
-
return this.postNotificationEvent(notificationId, {
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
510
|
+
return this.postNotificationEvent(notificationId, { category: 'notification-center-event', type: 'notification-closed', payload: {} }, { targets });
|
|
511
|
+
}
|
|
512
|
+
/**
|
|
513
|
+
* Post a notification-reminder-created event to the Cloud Notification service.
|
|
514
|
+
*
|
|
515
|
+
* @param notificationId - The ID of the notification or an array of notification IDs to mark as a reminder.
|
|
516
|
+
* @param payload - The payload of the reminder.
|
|
517
|
+
* @returns A promise that resolves when the notification-reminder-created event is posted.
|
|
518
|
+
* @throws {@link SessionNotConnectedError} If the session is not connected.
|
|
519
|
+
*/
|
|
520
|
+
async setReminder(notificationId, payload, targets) {
|
|
521
|
+
return this.postNotificationEvent(notificationId, { category: 'notification-center-event', type: 'notification-reminder-created', payload }, { targets });
|
|
522
|
+
}
|
|
523
|
+
/**
|
|
524
|
+
* Post a notification-reminder-removed event to the Cloud Notification service.
|
|
525
|
+
*
|
|
526
|
+
* @param notificationId - The ID of the notification or an array of notification IDs to cancel the reminder for.
|
|
527
|
+
* @returns A promise that resolves when the notification-reminder-removed event is posted.
|
|
528
|
+
* @throws {@link SessionNotConnectedError} If the session is not connected.
|
|
529
|
+
*/
|
|
530
|
+
async cancelReminder(notificationId, targets) {
|
|
531
|
+
return this.postNotificationEvent(notificationId, { category: 'notification-center-event', type: 'notification-reminder-removed' }, { targets });
|
|
420
532
|
}
|
|
421
533
|
/**
|
|
422
534
|
* Raises a notification to the Cloud Notification service.
|
|
@@ -428,33 +540,22 @@ class CloudNotificationAPI {
|
|
|
428
540
|
* @throws {@link PublishError} If an error occurs during publishing.
|
|
429
541
|
*/
|
|
430
542
|
async raiseNotification(options, payload) {
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
method: 'POST',
|
|
448
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
449
|
-
body: JSON.stringify(publishPayload),
|
|
450
|
-
});
|
|
451
|
-
await checkResponse(this.#logger, publishResponse, 'Error publishing notification', 'ERR_PUBLISH_NOTIFICATION');
|
|
452
|
-
const publishResponseBody = (await publishResponse.json());
|
|
453
|
-
return publishResponseBody;
|
|
454
|
-
}
|
|
455
|
-
catch (error) {
|
|
456
|
-
handleAPIException(this.#logger, error, 'Error publishing notification', PublishError);
|
|
457
|
-
}
|
|
543
|
+
return this.#publishNewNotification('/api/publications', { ...options, payload });
|
|
544
|
+
}
|
|
545
|
+
/**
|
|
546
|
+
* Raises a notification to the connected user via the Cloud Notification service.
|
|
547
|
+
*
|
|
548
|
+
* Unlike {@link raiseNotification}, no notification raise permissions are required and the notification
|
|
549
|
+
* is always targeted at the connected user only.
|
|
550
|
+
*
|
|
551
|
+
* @param options - The options for the notification.
|
|
552
|
+
* @param payload - The payload of the notification which should generally conform to the notification center schema
|
|
553
|
+
* @returns A promise that resolves with the notification raise result.
|
|
554
|
+
* @throws {@link SessionNotConnectedError} If the session is not connected.
|
|
555
|
+
* @throws {@link PublishError} If an error occurs during publishing.
|
|
556
|
+
*/
|
|
557
|
+
async raiseNotificationToMe(options, payload) {
|
|
558
|
+
return this.#publishNewNotification('/api/publications/me', { ...options, payload });
|
|
458
559
|
}
|
|
459
560
|
/**
|
|
460
561
|
* Raises a notification update to the Cloud Notification service.
|
|
@@ -477,9 +578,8 @@ class CloudNotificationAPI {
|
|
|
477
578
|
ttlSeconds: options.ttlSeconds,
|
|
478
579
|
payload,
|
|
479
580
|
};
|
|
480
|
-
const updateResponse = await
|
|
581
|
+
const updateResponse = await this.#authenticatedFetch(`${this.#cloudNotificationSettings.url}/api/publications/${notificationId}`, {
|
|
481
582
|
method: 'PATCH',
|
|
482
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
483
583
|
body: JSON.stringify(updatePayload),
|
|
484
584
|
});
|
|
485
585
|
await checkResponse(this.#logger, updateResponse, 'Error updating notification', 'ERR_UPDATING_NOTIFICATION');
|
|
@@ -503,9 +603,10 @@ class CloudNotificationAPI {
|
|
|
503
603
|
throw new SessionNotConnectedError();
|
|
504
604
|
}
|
|
505
605
|
try {
|
|
506
|
-
const
|
|
606
|
+
const notificationIds = Array.isArray(notificationId) ? notificationId : [notificationId];
|
|
607
|
+
const notificationIdsString = notificationIds.join('&id=');
|
|
608
|
+
const deleteResponse = await this.#authenticatedFetch(`${this.#cloudNotificationSettings.url}/api/publications?id=${notificationIdsString}&sessionId=${this.#sessionDetails.sessionId}`, {
|
|
507
609
|
method: 'DELETE',
|
|
508
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
509
610
|
});
|
|
510
611
|
await checkResponse(this.#logger, deleteResponse, 'Error deleting notification', 'ERR_DELETE_NOTIFICATION');
|
|
511
612
|
}
|
|
@@ -541,9 +642,8 @@ class CloudNotificationAPI {
|
|
|
541
642
|
if ([...parameters].length > 0) {
|
|
542
643
|
replayUrl += `?${parameters.toString()}`;
|
|
543
644
|
}
|
|
544
|
-
const replayResponse = await
|
|
645
|
+
const replayResponse = await this.#authenticatedFetch(replayUrl, {
|
|
545
646
|
method: 'POST',
|
|
546
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
547
647
|
body: JSON.stringify({
|
|
548
648
|
sessionId: this.#sessionDetails.sessionId,
|
|
549
649
|
}),
|
|
@@ -583,11 +683,35 @@ class CloudNotificationAPI {
|
|
|
583
683
|
once(type, callback) {
|
|
584
684
|
this.#events.once(type, callback);
|
|
585
685
|
}
|
|
686
|
+
async #publishNewNotification(path, notification) {
|
|
687
|
+
if (!this.#sessionDetails || !this.#connectionParams) {
|
|
688
|
+
this.#logger('error', 'Invalid Session');
|
|
689
|
+
throw new SessionNotConnectedError();
|
|
690
|
+
}
|
|
691
|
+
try {
|
|
692
|
+
const publishResponse = await this.#authenticatedFetch(`${this.#cloudNotificationSettings.url}${path}`, {
|
|
693
|
+
method: 'POST',
|
|
694
|
+
body: JSON.stringify({
|
|
695
|
+
sessionId: this.#sessionDetails.sessionId,
|
|
696
|
+
timeOffset: this.#getCurrentTimeOffset(),
|
|
697
|
+
notification,
|
|
698
|
+
}),
|
|
699
|
+
});
|
|
700
|
+
await checkResponse(this.#logger, publishResponse, 'Error publishing notification', 'ERR_PUBLISH_NOTIFICATION');
|
|
701
|
+
const publishResponseBody = (await publishResponse.json());
|
|
702
|
+
return publishResponseBody;
|
|
703
|
+
}
|
|
704
|
+
catch (error) {
|
|
705
|
+
handleAPIException(this.#logger, error, 'Error publishing notification', PublishError);
|
|
706
|
+
}
|
|
707
|
+
}
|
|
586
708
|
async #connectToMQTT() {
|
|
587
709
|
if (!this.#sessionDetails || !this.#sessionDetails.mqtt) {
|
|
588
710
|
this.#logger('error', 'Invalid Session');
|
|
589
711
|
throw new SessionNotConnectedError();
|
|
590
712
|
}
|
|
713
|
+
const { token: _, ...mqttDetailsWithoutToken } = this.#sessionDetails.mqtt;
|
|
714
|
+
this.#logger('info', `Connecting to MQTT server: ${JSON.stringify(mqttDetailsWithoutToken, null, 2)}`);
|
|
591
715
|
const clientOptions = {
|
|
592
716
|
keepalive: this.#keepAliveIntervalSeconds,
|
|
593
717
|
clientId: this.#sessionDetails.sessionId,
|
|
@@ -603,14 +727,16 @@ class CloudNotificationAPI {
|
|
|
603
727
|
username: this.#sessionDetails.mqtt.token,
|
|
604
728
|
};
|
|
605
729
|
this.#mqttClient = await mqtt.connectAsync(this.#sessionDetails.mqtt.url, clientOptions);
|
|
606
|
-
this.#logger('debug', `Cloud Notifications successfully connected to notification backbone`);
|
|
607
730
|
this.#mqttClient.on('error', async (error) => this.#mqttErrorHandler(error));
|
|
608
|
-
this.#mqttClient.on('reconnect', () =>
|
|
731
|
+
this.#mqttClient.on('reconnect', async () => {
|
|
732
|
+
await this.#mqttReconnectionHandler();
|
|
733
|
+
});
|
|
609
734
|
// Does not fire on initial connection, only successful reconnection attempts
|
|
610
735
|
this.#mqttClient.on('connect', () => this.#mqttConnectionHandler());
|
|
611
736
|
this.#mqttClient.on('message', (topic, message) => this.#mqttMessageHandler(topic, message));
|
|
612
737
|
// Subscribe any session specific topics
|
|
613
738
|
this.#mqttClient.subscribe(`${this.#sessionDetails.mqtt.sessionRootTopic}/#`);
|
|
739
|
+
this.#logger('info', 'Successfully connected to MQTT server');
|
|
614
740
|
// Subscribe to the user notification delivery topics for groups and users
|
|
615
741
|
await this.#subscribeToNotificationTopics();
|
|
616
742
|
}
|
|
@@ -624,11 +750,11 @@ class CloudNotificationAPI {
|
|
|
624
750
|
this.#attemptingToReconnect = true;
|
|
625
751
|
this.#reconnectRetries += 1;
|
|
626
752
|
this.#logger('debug', `Cloud Notifications attempting reconnection - ${this.#reconnectRetries}...`);
|
|
753
|
+
this.#events.emitEvent('reconnecting', this.#reconnectRetries);
|
|
627
754
|
if (this.#reconnectRetries === this.#reconnectRetryLimit) {
|
|
628
755
|
this.#logger('warn', `Cloud Notifications reached max reconnection attempts - ${this.#reconnectRetryLimit}...`);
|
|
629
|
-
this.#
|
|
756
|
+
await this.#disconnectAndLogFailure(true);
|
|
630
757
|
}
|
|
631
|
-
this.#events.emitEvent('reconnecting', this.#reconnectRetries);
|
|
632
758
|
}
|
|
633
759
|
async #mqttMessageHandler(topic, message) {
|
|
634
760
|
if (!this.#sessionDetails) {
|
|
@@ -644,7 +770,14 @@ class CloudNotificationAPI {
|
|
|
644
770
|
this.#logger('debug', `Session expired`);
|
|
645
771
|
this.#events.emitEvent('session-expired');
|
|
646
772
|
// TODO: Request new JWT if using JWT authentication
|
|
647
|
-
|
|
773
|
+
const sessionId = this.#sessionDetails?.sessionId;
|
|
774
|
+
try {
|
|
775
|
+
await this.#extendSession();
|
|
776
|
+
}
|
|
777
|
+
catch (extendError) {
|
|
778
|
+
await this.#handleSessionExtendFailure(extendError, sessionId);
|
|
779
|
+
return;
|
|
780
|
+
}
|
|
648
781
|
this.#logger('debug', `Session extended`);
|
|
649
782
|
this.#events.emitEvent('session-extended');
|
|
650
783
|
return;
|
|
@@ -706,6 +839,20 @@ class CloudNotificationAPI {
|
|
|
706
839
|
}
|
|
707
840
|
await Promise.all(subscribePromises);
|
|
708
841
|
}
|
|
842
|
+
#authenticatedFetch = async (url, { method, body }) => {
|
|
843
|
+
const connectionParameters = this.#connectionParams;
|
|
844
|
+
if (!connectionParameters) {
|
|
845
|
+
throw new Error('Connect parameters must be provided');
|
|
846
|
+
}
|
|
847
|
+
const attempt = async () => {
|
|
848
|
+
const headers = await getRequestHeaders(connectionParameters, this.#tokenClient);
|
|
849
|
+
return fetch(url, { method, headers, body });
|
|
850
|
+
};
|
|
851
|
+
if (connectionParameters.authenticationType === 'oauth' && this.#tokenClient) {
|
|
852
|
+
return Fn(this.#tokenClient, attempt);
|
|
853
|
+
}
|
|
854
|
+
return attempt();
|
|
855
|
+
};
|
|
709
856
|
async #extendSession() {
|
|
710
857
|
if (!this.#sessionDetails) {
|
|
711
858
|
return;
|
|
@@ -719,9 +866,8 @@ class CloudNotificationAPI {
|
|
|
719
866
|
this.#mqttClient = undefined;
|
|
720
867
|
this.#reconnectRetries = 0;
|
|
721
868
|
this.#attemptingToReconnect = false;
|
|
722
|
-
const extendResponse = await
|
|
869
|
+
const extendResponse = await this.#authenticatedFetch(`${this.#cloudNotificationSettings.url}/api/sessions`, {
|
|
723
870
|
method: 'PUT',
|
|
724
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
725
871
|
body: JSON.stringify({
|
|
726
872
|
sessionId: this.#sessionDetails.sessionId,
|
|
727
873
|
}),
|
|
@@ -732,23 +878,33 @@ class CloudNotificationAPI {
|
|
|
732
878
|
this.#sessionDetails = (await extendResponse.json());
|
|
733
879
|
this.#attemptingToReconnect = true;
|
|
734
880
|
await this.#connectToMQTT();
|
|
881
|
+
// If local session expiry handling is enabled, start the session timer
|
|
882
|
+
if (this.#sessionDetails.mqtt?.localSessionExpiryHandling) {
|
|
883
|
+
this.#startSessionTimer();
|
|
884
|
+
}
|
|
735
885
|
}
|
|
736
886
|
catch (error) {
|
|
737
887
|
throw new CloudNotificationAPIError('Error during session refresh', 'ERR_SESSION_EXTEND', error);
|
|
738
888
|
}
|
|
739
889
|
}
|
|
740
890
|
async #disconnect(fireDisconnectedEvent) {
|
|
891
|
+
this.#stopTimeSync();
|
|
741
892
|
if (!this.#sessionDetails) {
|
|
742
893
|
return;
|
|
743
894
|
}
|
|
895
|
+
this.#disconnecting = true;
|
|
744
896
|
try {
|
|
745
897
|
if (!this.#connectionParams) {
|
|
746
898
|
throw new Error('Connect parameters must be provided');
|
|
747
899
|
}
|
|
900
|
+
// Cancel session timer if it's running
|
|
901
|
+
if (this.#sessionTimer) {
|
|
902
|
+
clearTimeout(this.#sessionTimer);
|
|
903
|
+
this.#sessionTimer = undefined;
|
|
904
|
+
}
|
|
748
905
|
// Clean up our session on the server
|
|
749
|
-
const disconnectResponse = await
|
|
906
|
+
const disconnectResponse = await this.#authenticatedFetch(`${this.#cloudNotificationSettings.url}/api/sessions/${this.#sessionDetails.sessionId}`, {
|
|
750
907
|
method: 'DELETE',
|
|
751
|
-
headers: getRequestHeaders(this.#connectionParams),
|
|
752
908
|
});
|
|
753
909
|
if (disconnectResponse.status !== 204) {
|
|
754
910
|
throw new CloudNotificationAPIError(`Error during session tear down - unexpected status ${disconnectResponse.status}`, 'ERR_DISCONNECT', new Error(disconnectResponse.statusText));
|
|
@@ -769,11 +925,131 @@ class CloudNotificationAPI {
|
|
|
769
925
|
this.#mqttClient = undefined;
|
|
770
926
|
this.#reconnectRetries = 0;
|
|
771
927
|
this.#attemptingToReconnect = false;
|
|
928
|
+
this.#disconnecting = false;
|
|
772
929
|
if (fireDisconnectedEvent) {
|
|
773
930
|
this.#events.emitEvent('disconnected');
|
|
774
931
|
}
|
|
775
932
|
}
|
|
776
933
|
}
|
|
934
|
+
async #disconnectAndLogFailure(fireDisconnectedEvent = false) {
|
|
935
|
+
try {
|
|
936
|
+
await this.#disconnect(fireDisconnectedEvent);
|
|
937
|
+
}
|
|
938
|
+
catch (error) {
|
|
939
|
+
this.#logger('error', `Session teardown failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
#stopTimeSync() {
|
|
943
|
+
this.#timeDifferenceTracker?.stop();
|
|
944
|
+
this.#timeDifferenceTracker = undefined;
|
|
945
|
+
}
|
|
946
|
+
/**
|
|
947
|
+
* @param sessionId - The session that was being extended. The teardown is skipped when that session is already being disconnected or has been replaced.
|
|
948
|
+
*/
|
|
949
|
+
async #handleSessionExtendFailure(error, sessionId) {
|
|
950
|
+
if (this.#disconnecting || !sessionId || this.#sessionDetails?.sessionId !== sessionId) {
|
|
951
|
+
this.#logger('debug', 'Ignoring a failed extend for a session that was disconnected or replaced');
|
|
952
|
+
return;
|
|
953
|
+
}
|
|
954
|
+
this.#logger('error', `Session extend failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
955
|
+
this.#events.emitEvent('error', error instanceof Error ? error : new Error(String(error)));
|
|
956
|
+
await this.#disconnectAndLogFailure(true);
|
|
957
|
+
}
|
|
958
|
+
/**
|
|
959
|
+
* Extracts the expiration timestamp from a JWT token.
|
|
960
|
+
*
|
|
961
|
+
* @param token - The JWT token string
|
|
962
|
+
* @returns The expiration timestamp in seconds, or null if extraction fails
|
|
963
|
+
*/
|
|
964
|
+
#extractExpirationFromJwt(token) {
|
|
965
|
+
if (!token) {
|
|
966
|
+
return null;
|
|
967
|
+
}
|
|
968
|
+
try {
|
|
969
|
+
// JWT tokens have three parts separated by dots: header.payload.signature
|
|
970
|
+
// The exp claim is in the payload
|
|
971
|
+
const parts = token.split('.');
|
|
972
|
+
if (parts.length < 2) {
|
|
973
|
+
this.#logger('warn', 'Invalid JWT token format: expected at least 2 parts');
|
|
974
|
+
return null;
|
|
975
|
+
}
|
|
976
|
+
const payload = parts[1];
|
|
977
|
+
// 'base64' also decodes unpadded base64url. The browser `buffer` polyfill has no 'base64url' encoding.
|
|
978
|
+
const decodedBytes = buffer.Buffer.from(payload, 'base64');
|
|
979
|
+
const payloadJson = decodedBytes.toString('utf8');
|
|
980
|
+
// Parse JSON to get the exp claim
|
|
981
|
+
const claims = JSON.parse(payloadJson);
|
|
982
|
+
const exp = claims.exp;
|
|
983
|
+
if (exp === undefined || exp === null) {
|
|
984
|
+
this.#logger('warn', "JWT token does not contain 'exp' claim");
|
|
985
|
+
return null;
|
|
986
|
+
}
|
|
987
|
+
if (typeof exp !== 'number') {
|
|
988
|
+
this.#logger('warn', `JWT token 'exp' claim is not a number: ${exp}`);
|
|
989
|
+
return null;
|
|
990
|
+
}
|
|
991
|
+
return exp;
|
|
992
|
+
}
|
|
993
|
+
catch (error) {
|
|
994
|
+
this.#logger('error', `Failed to extract expiration from JWT token: ${error instanceof Error ? error.message : error}`);
|
|
995
|
+
return null;
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
/**
|
|
999
|
+
* Start a session timer that will expire at the time specified in the JWT token's exp claim.
|
|
1000
|
+
* On expiry, it will fire session expired event, extend the session, fire session extended event, and restart the timer.
|
|
1001
|
+
*/
|
|
1002
|
+
#startSessionTimer() {
|
|
1003
|
+
if (!this.#sessionDetails?.mqtt?.token) {
|
|
1004
|
+
this.#logger('warn', 'Cannot start session timer: session details or token not available');
|
|
1005
|
+
return;
|
|
1006
|
+
}
|
|
1007
|
+
// Extract expiration time from JWT token
|
|
1008
|
+
const expTimestamp = this.#extractExpirationFromJwt(this.#sessionDetails.mqtt.token);
|
|
1009
|
+
if (expTimestamp === null) {
|
|
1010
|
+
this.#logger('warn', 'Cannot start session timer: could not extract expiration from JWT token');
|
|
1011
|
+
return;
|
|
1012
|
+
}
|
|
1013
|
+
const currentTimeSeconds = Math.floor(Date.now() / 1000);
|
|
1014
|
+
const delaySeconds = expTimestamp - currentTimeSeconds;
|
|
1015
|
+
if (delaySeconds <= 0) {
|
|
1016
|
+
this.#logger('warn', 'JWT token has already expired or expires immediately');
|
|
1017
|
+
this.#events.emitEvent('session-expired');
|
|
1018
|
+
const sessionId = this.#sessionDetails.sessionId;
|
|
1019
|
+
this.#extendSession()
|
|
1020
|
+
.then(() => {
|
|
1021
|
+
this.#logger('debug', 'Session extended');
|
|
1022
|
+
this.#events.emitEvent('session-extended');
|
|
1023
|
+
})
|
|
1024
|
+
.catch((error) => this.#handleSessionExtendFailure(error, sessionId));
|
|
1025
|
+
return;
|
|
1026
|
+
}
|
|
1027
|
+
// Clear any existing timer
|
|
1028
|
+
if (this.#sessionTimer) {
|
|
1029
|
+
clearTimeout(this.#sessionTimer);
|
|
1030
|
+
}
|
|
1031
|
+
const expirationTimeString = new Date(expTimestamp * 1000).toISOString();
|
|
1032
|
+
this.#logger('debug', `Starting session timer to expire in ${delaySeconds} seconds (at ${expirationTimeString})`);
|
|
1033
|
+
this.#sessionTimer = setTimeout(async () => {
|
|
1034
|
+
const sessionId = this.#sessionDetails?.sessionId;
|
|
1035
|
+
try {
|
|
1036
|
+
this.#logger('debug', 'Session timer expired');
|
|
1037
|
+
this.#events.emitEvent('session-expired');
|
|
1038
|
+
await this.#extendSession();
|
|
1039
|
+
this.#logger('debug', 'Session extended');
|
|
1040
|
+
this.#events.emitEvent('session-extended');
|
|
1041
|
+
}
|
|
1042
|
+
catch (error) {
|
|
1043
|
+
await this.#handleSessionExtendFailure(error, sessionId);
|
|
1044
|
+
}
|
|
1045
|
+
}, delaySeconds * 1000);
|
|
1046
|
+
}
|
|
1047
|
+
#isGroupEventTopic(topic) {
|
|
1048
|
+
if (!this.#sessionDetails) {
|
|
1049
|
+
return false;
|
|
1050
|
+
}
|
|
1051
|
+
return this.#sessionDetails.groups.some((group) => group.eventTopic?.startsWith(topic));
|
|
1052
|
+
}
|
|
777
1053
|
#handleMessage(topic, message, sessionDetails) {
|
|
778
1054
|
if (message.length === 0 || !sessionDetails || !sessionDetails.mqtt) {
|
|
779
1055
|
// Ignore clean up messages
|
|
@@ -781,16 +1057,20 @@ class CloudNotificationAPI {
|
|
|
781
1057
|
}
|
|
782
1058
|
try {
|
|
783
1059
|
const messagePayload = JSON.parse(message.toString());
|
|
1060
|
+
// NOTE: uncomment this to debug message payloads
|
|
1061
|
+
// this.#logger('info', `Received message on topic ${topic} with payload ${JSON.stringify(messagePayload)}`);
|
|
784
1062
|
if (topic.startsWith(sessionDetails.mqtt.notificationsRootTopic)) {
|
|
785
1063
|
this.#handleNotificationMessage(messagePayload);
|
|
786
|
-
// The following line allows for both group and user targeted events as well as event for self published notifications. The payload is the same for both scenarios.
|
|
787
1064
|
}
|
|
788
|
-
else if (topic === sessionDetails.mqtt.userNotificationEventsTopic
|
|
1065
|
+
else if (topic === sessionDetails.mqtt.userNotificationEventsTopic) {
|
|
789
1066
|
this.#handleUserNotificationEventMessage(messagePayload);
|
|
790
1067
|
}
|
|
791
1068
|
else if (topic === sessionDetails.mqtt.allNotificationEventsTopic) {
|
|
792
1069
|
this.#handleAllNotificationEventMessage(messagePayload);
|
|
793
1070
|
}
|
|
1071
|
+
else if (this.#isGroupEventTopic(topic)) {
|
|
1072
|
+
this.#handleGroupNotificationEventMessage(messagePayload);
|
|
1073
|
+
}
|
|
794
1074
|
else {
|
|
795
1075
|
this.#logger('warn', `Received message on unknown topic ${topic}`);
|
|
796
1076
|
this.#events.emitEvent('error', new CloudNotificationAPIError(`Received message on unknown topic ${topic}`, 'ERR_UNKNOWN_TOPIC'));
|
|
@@ -802,7 +1082,7 @@ class CloudNotificationAPI {
|
|
|
802
1082
|
}
|
|
803
1083
|
}
|
|
804
1084
|
#handleNotificationMessage(messagePayload) {
|
|
805
|
-
const parseResult =
|
|
1085
|
+
const parseResult = N.safeParse(messagePayload);
|
|
806
1086
|
if (!parseResult.success) {
|
|
807
1087
|
this.#logger('warn', `Received invalid notification message payload format ${parseResult.error?.toString()}`);
|
|
808
1088
|
throw new InvalidMessageFormatError(parseResult);
|
|
@@ -819,40 +1099,57 @@ class CloudNotificationAPI {
|
|
|
819
1099
|
this.#deDuplicator.add(txInstanceId);
|
|
820
1100
|
this.#sendNotificationDeliveredStatus(notificationId);
|
|
821
1101
|
let targetName = target;
|
|
822
|
-
if (targetType === '
|
|
1102
|
+
if (targetType === 'groups') {
|
|
823
1103
|
targetName = this.#lookupGroupNameByUuid(target);
|
|
824
1104
|
}
|
|
1105
|
+
const makePayload = (action) => ({ action, notificationId, correlationId, target, targetName, targetType, payload });
|
|
825
1106
|
switch (action) {
|
|
826
1107
|
case 'new': {
|
|
827
|
-
this.#events.emitEvent('new-notification',
|
|
1108
|
+
this.#events.emitEvent('new-notification', makePayload('new'));
|
|
828
1109
|
break;
|
|
829
1110
|
}
|
|
830
1111
|
case 'update': {
|
|
831
|
-
this.#events.emitEvent('update-notification',
|
|
1112
|
+
this.#events.emitEvent('update-notification', makePayload('update'));
|
|
832
1113
|
break;
|
|
833
1114
|
}
|
|
834
1115
|
case 'delete': {
|
|
835
|
-
this.#events.emitEvent('delete-notification',
|
|
1116
|
+
this.#events.emitEvent('delete-notification', makePayload('delete'));
|
|
836
1117
|
break;
|
|
837
1118
|
}
|
|
838
1119
|
// No default - Schema validation will prevent this
|
|
839
1120
|
}
|
|
840
1121
|
}
|
|
841
1122
|
#handleUserNotificationEventMessage(messagePayload) {
|
|
842
|
-
const
|
|
843
|
-
if (
|
|
844
|
-
this.#logger('
|
|
845
|
-
|
|
1123
|
+
const event = this.#parseNotificationEventMessage(messagePayload);
|
|
1124
|
+
if (event.originatingSessionId === this.#sessionDetails?.sessionId) {
|
|
1125
|
+
this.#logger('debug', `Received notification event from our own session, ignoring. (session id: ${event.originatingSessionId})`);
|
|
1126
|
+
return;
|
|
846
1127
|
}
|
|
847
|
-
this.#events.emitEvent('notification-event',
|
|
1128
|
+
this.#events.emitEvent('notification-event', event);
|
|
1129
|
+
}
|
|
1130
|
+
#handleGroupNotificationEventMessage(messagePayload) {
|
|
1131
|
+
const event = this.#parseNotificationEventMessage(messagePayload);
|
|
1132
|
+
if (event.originatingSessionId === this.#sessionDetails?.sessionId) {
|
|
1133
|
+
this.#logger('debug', `Received notification event from our own session, ignoring. (session id: ${event.originatingSessionId})`);
|
|
1134
|
+
return;
|
|
1135
|
+
}
|
|
1136
|
+
this.#events.emitEvent('notification-event', event);
|
|
848
1137
|
}
|
|
849
1138
|
#handleAllNotificationEventMessage(messagePayload) {
|
|
850
|
-
const
|
|
1139
|
+
const event = this.#parseNotificationEventMessage(messagePayload);
|
|
1140
|
+
if (event.originatingSessionId === this.#sessionDetails?.sessionId) {
|
|
1141
|
+
this.#logger('debug', `Received notification event from our own session, ignoring. (session id: ${event.originatingSessionId})`);
|
|
1142
|
+
return;
|
|
1143
|
+
}
|
|
1144
|
+
this.#events.emitEvent('global-notification-event', event);
|
|
1145
|
+
}
|
|
1146
|
+
#parseNotificationEventMessage(messagePayload) {
|
|
1147
|
+
const parseResult = I.safeParse(messagePayload);
|
|
851
1148
|
if (!parseResult.success) {
|
|
852
1149
|
this.#logger('warn', `Received invalid notification event message payload format ${parseResult.error?.toString()}`);
|
|
853
1150
|
throw new InvalidMessageFormatError(parseResult);
|
|
854
1151
|
}
|
|
855
|
-
|
|
1152
|
+
return parseResult.data;
|
|
856
1153
|
}
|
|
857
1154
|
#lookupGroupNameByUuid(uuid) {
|
|
858
1155
|
if (!this.#sessionDetails) {
|
|
@@ -869,5 +1166,7 @@ exports.EventPublishError = EventPublishError;
|
|
|
869
1166
|
exports.EventRetrievalError = EventRetrievalError;
|
|
870
1167
|
exports.InvalidMessageFormatError = InvalidMessageFormatError;
|
|
871
1168
|
exports.NotificationRetrievalError = NotificationRetrievalError;
|
|
1169
|
+
exports.OAuthAuthenticationError = OAuthAuthenticationError;
|
|
872
1170
|
exports.PublishError = PublishError;
|
|
873
1171
|
exports.SessionNotConnectedError = SessionNotConnectedError;
|
|
1172
|
+
exports.targetTypeSchema = p;
|