authhero 0.22.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/authhero.cjs CHANGED
@@ -122,4 +122,4 @@ PERFORMANCE OF THIS SOFTWARE.
122
122
  `,s=0;for(;s<t.length;)s+64<=t.length?n+=t.substr(s,64)+`\r
123
123
  `:n+=t.substr(s)+`\r
124
124
  `,s+=64;return n+=`-----END ${r} KEY-----\r
125
- `,n}async function sk(r){const e=await r.publicKey.export(),t=await crypto.subtle.exportKey("jwk",e),n=JSON.stringify(t,Object.keys(t).sort()),i=new TextEncoder().encode(n);return Qd(await B0(i))}const ik=1e3*60*60*24,ak=new ut().openapi(ge({tags:["keys"],method:"get",path:"/signing",request:{headers:m.object({"tenant-id":m.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:m.array(Pl)}},description:"List of keys"}}}),async r=>{const t=(await r.env.data.keys.list()).filter(n=>"cert"in n).map(n=>n);return r.json(t)}).openapi(ge({tags:["keys"],method:"get",path:"/signing/{kid}",request:{headers:m.object({"tenant-id":m.string()}),params:m.object({kid:m.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Pl}},description:"The requested key"}}}),async r=>{const{kid:e}=r.req.valid("param"),n=(await r.env.data.keys.list()).find(s=>s.kid===e);if(!n)throw new de(404,{message:"Key not found"});return r.json(n)}).openapi(ge({tags:["keys"],method:"post",path:"/signing/rotate",request:{headers:m.object({"tenant-id":m.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{description:"Status"}}}),async r=>{const e=await r.env.data.keys.list();for await(const n of e)await r.env.data.keys.update(n.kid,{revoked_at:new Date(Date.now()+ik).toISOString()});const t=await ef({name:`CN=${r.env.ORGANIZATION_NAME}`});return await r.env.data.keys.create(t),r.text("OK",{status:201})}).openapi(ge({tags:["keys"],method:"put",path:"/signing/{kid}/revoke",request:{headers:m.object({"tenant-id":m.string()}),params:m.object({kid:m.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{description:"Status"}}}),async r=>{const{kid:e}=r.req.valid("param");if(!await r.env.data.keys.update(e,{revoked_at:new Date().toISOString()}))throw new de(404,{message:"Key not found"});const n=await ef({name:`CN=${r.env.ORGANIZATION_NAME}`});return await r.env.data.keys.create(n),r.text("OK")}),ok=new ut().openapi(ge({tags:["users"],method:"get",path:"/",request:{query:m.object({email:m.string()}),headers:m.object({"tenant-id":m.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"tenant/json":{schema:m.array(df)}},description:"List of users"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),{email:t}=r.req.valid("query"),s=(await Uy(r.env.data.users,e,t)).filter(i=>!i.linked_to);return r.json(s)}),ck=jn.extend({clients:m.array(Mn)}),uk=new ut().openapi(ge({tags:["clients"],method:"get",path:"/",request:{query:rs,headers:m.object({"tenant-id":m.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:m.union([ck,m.array(Mn)])}},description:"List of clients"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),{page:t,per_page:n,include_totals:s,sort:i,q:a}=r.req.valid("query"),c=(await r.env.data.applications.list(e,{page:t,per_page:n,include_totals:s,sort:ci(i),q:a})).applications;return s?r.json({clients:c,start:0,limit:10,length:c.length}):r.json(c)}).openapi(ge({tags:["clients"],method:"get",path:"/{id}",request:{params:m.object({id:m.string()}),headers:m.object({"tenant-id":m.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Mn}},description:"An application"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),{id:t}=r.req.valid("param"),s=(await r.env.data.applications.list(e,{page:1,per_page:0,include_totals:!1})).applications.find(i=>i.id===t);if(!s)throw new de(404);return r.json(s)}).openapi(ge({tags:["clients"],method:"delete",path:"/{id}",request:{params:m.object({id:m.string()}),headers:m.object({"tenant-id":m.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),{id:t}=r.req.valid("param");if(!await r.env.data.applications.remove(e,t))throw new de(404,{message:"Application not found"});return r.text("OK")}).openapi(ge({tags:["clients"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:m.object(ic.shape).partial()}}},params:m.object({id:m.string()}),headers:m.object({"tenant-id":m.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:Mn}},description:"The update application"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),{id:t}=r.req.valid("param"),s=r.req.valid("json");await r.env.data.applications.update(e,t,s);const i=await r.env.data.applications.get(e,t);if(!i)throw new de(404,{message:"Application not found"});return r.json(i)}).openapi(ge({tags:["clients"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:m.object(ic.shape)}}},headers:m.object({"tenant-id":m.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:m.object(Mn.shape)}},description:"An application"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),t=r.req.valid("json"),n={...t,id:t.id||fc(),client_secret:t.client_secret||fc()},s=await r.env.data.applications.create(e,n);return r.json(s,{status:201})});var $e;(function(r){r.assertEqual=s=>s;function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{const i={};for(const a of s)i[a]=a;return i},r.getValidEnumValues=s=>{const i=r.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),a={};for(const o of i)a[o]=s[o];return r.objectValues(a)},r.objectValues=s=>r.objectKeys(s).map(function(i){return s[i]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const i=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&i.push(a);return i},r.find=(s,i)=>{for(const a of s)if(i(a))return a},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function n(s,i=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}r.joinValues=n,r.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})($e||($e={}));var tf;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(tf||(tf={}));const J=$e.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),on=r=>{switch(typeof r){case"undefined":return J.undefined;case"string":return J.string;case"number":return isNaN(r)?J.nan:J.number;case"boolean":return J.boolean;case"function":return J.function;case"bigint":return J.bigint;case"symbol":return J.symbol;case"object":return Array.isArray(r)?J.array:r===null?J.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?J.promise:typeof Map<"u"&&r instanceof Map?J.map:typeof Set<"u"&&r instanceof Set?J.set:typeof Date<"u"&&r instanceof Date?J.date:J.object;default:return J.unknown}},M=$e.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"]),lk=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:");class Zt extends Error{constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){const t=e||function(i){return i.message},n={_errors:[]},s=i=>{for(const a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)n._errors.push(t(a));else{let o=n,c=0;for(;c<a.path.length;){const u=a.path[c];c===a.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(t(a))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return s(this),n}static assert(e){if(!(e instanceof Zt))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,$e.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},n=[];for(const s of this.issues)s.path.length>0?(t[s.path[0]]=t[s.path[0]]||[],t[s.path[0]].push(e(s))):n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}Zt.create=r=>new Zt(r);const si=(r,e)=>{let t;switch(r.code){case M.invalid_type:r.received===J.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case M.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,$e.jsonStringifyReplacer)}`;break;case M.unrecognized_keys:t=`Unrecognized key(s) in object: ${$e.joinValues(r.keys,", ")}`;break;case M.invalid_union:t="Invalid input";break;case M.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${$e.joinValues(r.options)}`;break;case M.invalid_enum_value:t=`Invalid enum value. Expected ${$e.joinValues(r.options)}, received '${r.received}'`;break;case M.invalid_arguments:t="Invalid function arguments";break;case M.invalid_return_type:t="Invalid function return type";break;case M.invalid_date:t="Invalid date";break;case M.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}"`:$e.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case M.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 M.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 M.custom:t="Invalid input";break;case M.invalid_intersection_types:t="Intersection results could not be merged";break;case M.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case M.not_finite:t="Number must be finite";break;default:t=e.defaultError,$e.assertNever(r)}return{message:t}};let R0=si;function dk(r){R0=r}function Wc(){return R0}const zc=r=>{const{data:e,path:t,errorMaps:n,issueData:s}=r,i=[...t,...s.path||[]],a={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let o="";const c=n.filter(u=>!!u).slice().reverse();for(const u of c)o=u(a,{data:e,defaultError:o}).message;return{...s,path:i,message:o}},fk=[];function K(r,e){const t=Wc(),n=zc({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===si?void 0:si].filter(s=>!!s)});r.common.issues.push(n)}class vt{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const n=[];for(const s of t){if(s.status==="aborted")return ye;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const s of t){const i=await s.key,a=await s.value;n.push({key:i,value:a})}return vt.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const s of t){const{key:i,value:a}=s;if(i.status==="aborted"||a.status==="aborted")return ye;i.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(n[i.value]=a.value)}return{status:e.value,value:n}}}const ye=Object.freeze({status:"aborted"}),Cs=r=>({status:"dirty",value:r}),kt=r=>({status:"valid",value:r}),rf=r=>r.status==="aborted",nf=r=>r.status==="dirty",ja=r=>r.status==="valid",Ta=r=>typeof Promise<"u"&&r instanceof Promise;function Gc(r,e,t,n){if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(r)}function P0(r,e,t,n,s){if(typeof e=="function"?r!==e||!s:!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 ce;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(ce||(ce={}));var Ni,Bi;class Ir{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=s}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}}const lm=(r,e)=>{if(ja(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new Zt(r.common.issues);return this._error=t,this._error}}};function ke(r){if(!r)return{};const{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(a,o)=>{var c,u;const{message:f}=r;return a.code==="invalid_enum_value"?{message:f??o.defaultError}:typeof o.data>"u"?{message:(c=f??n)!==null&&c!==void 0?c:o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:(u=f??t)!==null&&u!==void 0?u:o.defaultError}},description:s}}class Ie{constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(e){return on(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:on(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new vt,ctx:{common:e.parent.common,data:e.data,parsedType:on(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(Ta(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){var n;const s={common:{issues:[],async:(n=t==null?void 0:t.async)!==null&&n!==void 0?n:!1,contextualErrorMap:t==null?void 0:t.errorMap},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:on(e)},i=this._parseSync({data:e,path:s.path,parent:s});return lm(s,i)}async parseAsync(e,t){const n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){const n={common:{issues:[],contextualErrorMap:t==null?void 0:t.errorMap,async:!0},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:on(e)},s=this._parse({data:e,path:n.path,parent:n}),i=await(Ta(s)?s:Promise.resolve(s));return lm(n,i)}refine(e,t){const n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,i)=>{const a=e(s),o=()=>i.addIssue({code:M.custom,...n(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new hr({schema:this,typeName:pe.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return kr.create(this,this._def)}nullable(){return Cn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return lr.create(this,this._def)}promise(){return ai.create(this,this._def)}or(e){return Pa.create([this,e],this._def)}and(e){return $a.create(this,e,this._def)}transform(e){return new hr({...ke(this._def),schema:this,typeName:pe.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new Va({...ke(this._def),innerType:this,defaultValue:t,typeName:pe.ZodDefault})}brand(){return new oh({typeName:pe.ZodBranded,type:this,...ke(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new La({...ke(this._def),innerType:this,catchValue:t,typeName:pe.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return vo.create(this,e)}readonly(){return qa.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const hk=/^c[^\s-]{8,}$/i,pk=/^[0-9a-z]+$/,mk=/^[0-9A-HJKMNP-TV-Z]{26}$/,yk=/^[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,gk=/^[a-z0-9_-]{21}$/i,vk=/^[-+]?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)?)??$/,bk=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,xk="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let ml;const _k=/^(?:(?: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])$/,wk=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,kk=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,$0="((\\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])))",Sk=new RegExp(`^${$0}$`);function D0(r){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`),e}function Ak(r){return new RegExp(`^${D0(r)}$`)}function Z0(r){let e=`${$0}T${D0(r)}`;const t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Ok(r,e){return!!((e==="v4"||!e)&&_k.test(r)||(e==="v6"||!e)&&wk.test(r))}class ar extends Ie{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==J.string){const i=this._getOrReturnCtx(e);return K(i,{code:M.invalid_type,expected:J.string,received:i.parsedType}),ye}const n=new vt;let s;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),K(s,{code:M.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),K(s,{code:M.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){const a=e.data.length>i.value,o=e.data.length<i.value;(a||o)&&(s=this._getOrReturnCtx(e,s),a?K(s,{code:M.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):o&&K(s,{code:M.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")bk.test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{validation:"email",code:M.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")ml||(ml=new RegExp(xk,"u")),ml.test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{validation:"emoji",code:M.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")yk.test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{validation:"uuid",code:M.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")gk.test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{validation:"nanoid",code:M.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")hk.test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{validation:"cuid",code:M.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")pk.test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{validation:"cuid2",code:M.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")mk.test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{validation:"ulid",code:M.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),K(s,{validation:"url",code:M.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{validation:"regex",code:M.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),K(s,{code:M.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),K(s,{code:M.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),K(s,{code:M.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?Z0(i).test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{code:M.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?Sk.test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{code:M.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?Ak(i).test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{code:M.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?vk.test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{validation:"duration",code:M.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?Ok(e.data,i.version)||(s=this._getOrReturnCtx(e,s),K(s,{validation:"ip",code:M.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?kk.test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{validation:"base64",code:M.invalid_string,message:i.message}),n.dirty()):$e.assertNever(i);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:M.invalid_string,...ce.errToObj(n)})}_addCheck(e){return new ar({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...ce.errToObj(e)})}url(e){return this._addCheck({kind:"url",...ce.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...ce.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...ce.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...ce.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...ce.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...ce.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...ce.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...ce.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...ce.errToObj(e)})}datetime(e){var t,n;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(t=e==null?void 0:e.offset)!==null&&t!==void 0?t:!1,local:(n=e==null?void 0:e.local)!==null&&n!==void 0?n:!1,...ce.errToObj(e==null?void 0: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==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...ce.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...ce.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...ce.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...ce.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...ce.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...ce.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...ce.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...ce.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...ce.errToObj(t)})}nonempty(e){return this.min(1,ce.errToObj(e))}trim(){return new ar({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ar({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ar({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}ar.create=r=>{var e;return new ar({checks:[],typeName:pe.ZodString,coerce:(e=r==null?void 0:r.coerce)!==null&&e!==void 0?e:!1,...ke(r)})};function Ek(r,e){const t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,i=parseInt(r.toFixed(s).replace(".","")),a=parseInt(e.toFixed(s).replace(".",""));return i%a/Math.pow(10,s)}class On extends Ie{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)!==J.number){const i=this._getOrReturnCtx(e);return K(i,{code:M.invalid_type,expected:J.number,received:i.parsedType}),ye}let n;const s=new vt;for(const i of this._def.checks)i.kind==="int"?$e.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{code:M.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),K(n,{code:M.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),K(n,{code:M.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Ek(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),K(n,{code:M.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{code:M.not_finite,message:i.message}),s.dirty()):$e.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,ce.toString(t))}gt(e,t){return this.setLimit("min",e,!1,ce.toString(t))}lte(e,t){return this.setLimit("max",e,!0,ce.toString(t))}lt(e,t){return this.setLimit("max",e,!1,ce.toString(t))}setLimit(e,t,n,s){return new On({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:ce.toString(s)}]})}_addCheck(e){return new On({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:ce.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ce.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ce.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ce.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ce.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:ce.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:ce.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ce.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ce.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const 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"&&$e.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}}On.create=r=>new On({checks:[],typeName:pe.ZodNumber,coerce:(r==null?void 0:r.coerce)||!1,...ke(r)});class En extends Ie{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce&&(e.data=BigInt(e.data)),this._getType(e)!==J.bigint){const i=this._getOrReturnCtx(e);return K(i,{code:M.invalid_type,expected:J.bigint,received:i.parsedType}),ye}let n;const s=new vt;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),K(n,{code:M.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),K(n,{code:M.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),K(n,{code:M.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):$e.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,ce.toString(t))}gt(e,t){return this.setLimit("min",e,!1,ce.toString(t))}lte(e,t){return this.setLimit("max",e,!0,ce.toString(t))}lt(e,t){return this.setLimit("max",e,!1,ce.toString(t))}setLimit(e,t,n,s){return new En({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:ce.toString(s)}]})}_addCheck(e){return new En({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ce.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ce.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ce.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ce.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:ce.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}En.create=r=>{var e;return new En({checks:[],typeName:pe.ZodBigInt,coerce:(e=r==null?void 0:r.coerce)!==null&&e!==void 0?e:!1,...ke(r)})};class Na extends Ie{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==J.boolean){const n=this._getOrReturnCtx(e);return K(n,{code:M.invalid_type,expected:J.boolean,received:n.parsedType}),ye}return kt(e.data)}}Na.create=r=>new Na({typeName:pe.ZodBoolean,coerce:(r==null?void 0:r.coerce)||!1,...ke(r)});class ms extends Ie{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==J.date){const i=this._getOrReturnCtx(e);return K(i,{code:M.invalid_type,expected:J.date,received:i.parsedType}),ye}if(isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return K(i,{code:M.invalid_date}),ye}const n=new vt;let s;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),K(s,{code:M.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),K(s,{code:M.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):$e.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ms({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:ce.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:ce.toString(t)})}get minDate(){let e=null;for(const 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(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}ms.create=r=>new ms({checks:[],coerce:(r==null?void 0:r.coerce)||!1,typeName:pe.ZodDate,...ke(r)});class Jc extends Ie{_parse(e){if(this._getType(e)!==J.symbol){const n=this._getOrReturnCtx(e);return K(n,{code:M.invalid_type,expected:J.symbol,received:n.parsedType}),ye}return kt(e.data)}}Jc.create=r=>new Jc({typeName:pe.ZodSymbol,...ke(r)});class Ba extends Ie{_parse(e){if(this._getType(e)!==J.undefined){const n=this._getOrReturnCtx(e);return K(n,{code:M.invalid_type,expected:J.undefined,received:n.parsedType}),ye}return kt(e.data)}}Ba.create=r=>new Ba({typeName:pe.ZodUndefined,...ke(r)});class Ra extends Ie{_parse(e){if(this._getType(e)!==J.null){const n=this._getOrReturnCtx(e);return K(n,{code:M.invalid_type,expected:J.null,received:n.parsedType}),ye}return kt(e.data)}}Ra.create=r=>new Ra({typeName:pe.ZodNull,...ke(r)});class ii extends Ie{constructor(){super(...arguments),this._any=!0}_parse(e){return kt(e.data)}}ii.create=r=>new ii({typeName:pe.ZodAny,...ke(r)});class Xn extends Ie{constructor(){super(...arguments),this._unknown=!0}_parse(e){return kt(e.data)}}Xn.create=r=>new Xn({typeName:pe.ZodUnknown,...ke(r)});class Yr extends Ie{_parse(e){const t=this._getOrReturnCtx(e);return K(t,{code:M.invalid_type,expected:J.never,received:t.parsedType}),ye}}Yr.create=r=>new Yr({typeName:pe.ZodNever,...ke(r)});class Yc extends Ie{_parse(e){if(this._getType(e)!==J.undefined){const n=this._getOrReturnCtx(e);return K(n,{code:M.invalid_type,expected:J.void,received:n.parsedType}),ye}return kt(e.data)}}Yc.create=r=>new Yc({typeName:pe.ZodVoid,...ke(r)});class lr extends Ie{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==J.array)return K(t,{code:M.invalid_type,expected:J.array,received:t.parsedType}),ye;if(s.exactLength!==null){const a=t.data.length>s.exactLength.value,o=t.data.length<s.exactLength.value;(a||o)&&(K(t,{code:a?M.too_big:M.too_small,minimum:o?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(K(t,{code:M.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(K(t,{code:M.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((a,o)=>s.type._parseAsync(new Ir(t,a,t.path,o)))).then(a=>vt.mergeArray(n,a));const i=[...t.data].map((a,o)=>s.type._parseSync(new Ir(t,a,t.path,o)));return vt.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new lr({...this._def,minLength:{value:e,message:ce.toString(t)}})}max(e,t){return new lr({...this._def,maxLength:{value:e,message:ce.toString(t)}})}length(e,t){return new lr({...this._def,exactLength:{value:e,message:ce.toString(t)}})}nonempty(e){return this.min(1,e)}}lr.create=(r,e)=>new lr({type:r,minLength:null,maxLength:null,exactLength:null,typeName:pe.ZodArray,...ke(e)});function As(r){if(r instanceof Ye){const e={};for(const t in r.shape){const n=r.shape[t];e[t]=kr.create(As(n))}return new Ye({...r._def,shape:()=>e})}else return r instanceof lr?new lr({...r._def,type:As(r.element)}):r instanceof kr?kr.create(As(r.unwrap())):r instanceof Cn?Cn.create(As(r.unwrap())):r instanceof Cr?Cr.create(r.items.map(e=>As(e))):r}class Ye extends Ie{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=$e.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==J.object){const u=this._getOrReturnCtx(e);return K(u,{code:M.invalid_type,expected:J.object,received:u.parsedType}),ye}const{status:n,ctx:s}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof Yr&&this._def.unknownKeys==="strip"))for(const u in s.data)a.includes(u)||o.push(u);const c=[];for(const u of a){const f=i[u],y=s.data[u];c.push({key:{status:"valid",value:u},value:f._parse(new Ir(s,y,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof Yr){const u=this._def.unknownKeys;if(u==="passthrough")for(const f of o)c.push({key:{status:"valid",value:f},value:{status:"valid",value:s.data[f]}});else if(u==="strict")o.length>0&&(K(s,{code:M.unrecognized_keys,keys:o}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const f of o){const y=s.data[f];c.push({key:{status:"valid",value:f},value:u._parse(new Ir(s,y,s.path,f)),alwaysSet:f in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const u=[];for(const f of c){const y=await f.key,B=await f.value;u.push({key:y,value:B,alwaysSet:f.alwaysSet})}return u}).then(u=>vt.mergeObjectSync(n,u)):vt.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return ce.errToObj,new Ye({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{var s,i,a,o;const c=(a=(i=(s=this._def).errorMap)===null||i===void 0?void 0:i.call(s,t,n).message)!==null&&a!==void 0?a:n.defaultError;return t.code==="unrecognized_keys"?{message:(o=ce.errToObj(e).message)!==null&&o!==void 0?o:c}:{message:c}}}:{}})}strip(){return new Ye({...this._def,unknownKeys:"strip"})}passthrough(){return new Ye({...this._def,unknownKeys:"passthrough"})}extend(e){return new Ye({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Ye({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:pe.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new Ye({...this._def,catchall:e})}pick(e){const t={};return $e.objectKeys(e).forEach(n=>{e[n]&&this.shape[n]&&(t[n]=this.shape[n])}),new Ye({...this._def,shape:()=>t})}omit(e){const t={};return $e.objectKeys(this.shape).forEach(n=>{e[n]||(t[n]=this.shape[n])}),new Ye({...this._def,shape:()=>t})}deepPartial(){return As(this)}partial(e){const t={};return $e.objectKeys(this.shape).forEach(n=>{const s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}),new Ye({...this._def,shape:()=>t})}required(e){const t={};return $e.objectKeys(this.shape).forEach(n=>{if(e&&!e[n])t[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof kr;)i=i._def.innerType;t[n]=i}}),new Ye({...this._def,shape:()=>t})}keyof(){return M0($e.objectKeys(this.shape))}}Ye.create=(r,e)=>new Ye({shape:()=>r,unknownKeys:"strip",catchall:Yr.create(),typeName:pe.ZodObject,...ke(e)});Ye.strictCreate=(r,e)=>new Ye({shape:()=>r,unknownKeys:"strict",catchall:Yr.create(),typeName:pe.ZodObject,...ke(e)});Ye.lazycreate=(r,e)=>new Ye({shape:r,unknownKeys:"strip",catchall:Yr.create(),typeName:pe.ZodObject,...ke(e)});class Pa extends Ie{_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;function s(i){for(const o of i)if(o.result.status==="valid")return o.result;for(const o of i)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;const a=i.map(o=>new Zt(o.ctx.common.issues));return K(t,{code:M.invalid_union,unionErrors:a}),ye}if(t.common.async)return Promise.all(n.map(async i=>{const a={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(s);{let i;const a=[];for(const c of n){const u={...t,common:{...t.common,issues:[]},parent:null},f=c._parseSync({data:t.data,path:t.path,parent:u});if(f.status==="valid")return f;f.status==="dirty"&&!i&&(i={result:f,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;const o=a.map(c=>new Zt(c));return K(t,{code:M.invalid_union,unionErrors:o}),ye}}get options(){return this._def.options}}Pa.create=(r,e)=>new Pa({options:r,typeName:pe.ZodUnion,...ke(e)});const Rr=r=>r instanceof Za?Rr(r.schema):r instanceof hr?Rr(r.innerType()):r instanceof Ma?[r.value]:r instanceof In?r.options:r instanceof Ua?$e.objectValues(r.enum):r instanceof Va?Rr(r._def.innerType):r instanceof Ba?[void 0]:r instanceof Ra?[null]:r instanceof kr?[void 0,...Rr(r.unwrap())]:r instanceof Cn?[null,...Rr(r.unwrap())]:r instanceof oh||r instanceof qa?Rr(r.unwrap()):r instanceof La?Rr(r._def.innerType):[];class zu extends Ie{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==J.object)return K(t,{code:M.invalid_type,expected:J.object,received:t.parsedType}),ye;const n=this.discriminator,s=t.data[n],i=this.optionsMap.get(s);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(K(t,{code:M.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),ye)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){const s=new Map;for(const i of t){const a=Rr(i.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const o of a){if(s.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);s.set(o,i)}}return new zu({typeName:pe.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...ke(n)})}}function sf(r,e){const t=on(r),n=on(e);if(r===e)return{valid:!0,data:r};if(t===J.object&&n===J.object){const s=$e.objectKeys(e),i=$e.objectKeys(r).filter(o=>s.indexOf(o)!==-1),a={...r,...e};for(const o of i){const c=sf(r[o],e[o]);if(!c.valid)return{valid:!1};a[o]=c.data}return{valid:!0,data:a}}else if(t===J.array&&n===J.array){if(r.length!==e.length)return{valid:!1};const s=[];for(let i=0;i<r.length;i++){const a=r[i],o=e[i],c=sf(a,o);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return t===J.date&&n===J.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}class $a extends Ie{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),s=(i,a)=>{if(rf(i)||rf(a))return ye;const o=sf(i.value,a.value);return o.valid?((nf(i)||nf(a))&&t.dirty(),{status:t.value,value:o.data}):(K(n,{code:M.invalid_intersection_types}),ye)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,a])=>s(i,a)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}$a.create=(r,e,t)=>new $a({left:r,right:e,typeName:pe.ZodIntersection,...ke(t)});class Cr extends Ie{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==J.array)return K(n,{code:M.invalid_type,expected:J.array,received:n.parsedType}),ye;if(n.data.length<this._def.items.length)return K(n,{code:M.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ye;!this._def.rest&&n.data.length>this._def.items.length&&(K(n,{code:M.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const i=[...n.data].map((a,o)=>{const c=this._def.items[o]||this._def.rest;return c?c._parse(new Ir(n,a,n.path,o)):null}).filter(a=>!!a);return n.common.async?Promise.all(i).then(a=>vt.mergeArray(t,a)):vt.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new Cr({...this._def,rest:e})}}Cr.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Cr({items:r,typeName:pe.ZodTuple,rest:null,...ke(e)})};class Da extends Ie{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==J.object)return K(n,{code:M.invalid_type,expected:J.object,received:n.parsedType}),ye;const s=[],i=this._def.keyType,a=this._def.valueType;for(const o in n.data)s.push({key:i._parse(new Ir(n,o,n.path,o)),value:a._parse(new Ir(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?vt.mergeObjectAsync(t,s):vt.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof Ie?new Da({keyType:e,valueType:t,typeName:pe.ZodRecord,...ke(n)}):new Da({keyType:ar.create(),valueType:e,typeName:pe.ZodRecord,...ke(t)})}}class Xc extends Ie{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==J.map)return K(n,{code:M.invalid_type,expected:J.map,received:n.parsedType}),ye;const s=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([o,c],u)=>({key:s._parse(new Ir(n,o,n.path,[u,"key"])),value:i._parse(new Ir(n,c,n.path,[u,"value"]))}));if(n.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const c of a){const u=await c.key,f=await c.value;if(u.status==="aborted"||f.status==="aborted")return ye;(u.status==="dirty"||f.status==="dirty")&&t.dirty(),o.set(u.value,f.value)}return{status:t.value,value:o}})}else{const o=new Map;for(const c of a){const u=c.key,f=c.value;if(u.status==="aborted"||f.status==="aborted")return ye;(u.status==="dirty"||f.status==="dirty")&&t.dirty(),o.set(u.value,f.value)}return{status:t.value,value:o}}}}Xc.create=(r,e,t)=>new Xc({valueType:e,keyType:r,typeName:pe.ZodMap,...ke(t)});class ys extends Ie{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==J.set)return K(n,{code:M.invalid_type,expected:J.set,received:n.parsedType}),ye;const s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(K(n,{code:M.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(K(n,{code:M.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const i=this._def.valueType;function a(c){const u=new Set;for(const f of c){if(f.status==="aborted")return ye;f.status==="dirty"&&t.dirty(),u.add(f.value)}return{status:t.value,value:u}}const o=[...n.data.values()].map((c,u)=>i._parse(new Ir(n,c,n.path,u)));return n.common.async?Promise.all(o).then(c=>a(c)):a(o)}min(e,t){return new ys({...this._def,minSize:{value:e,message:ce.toString(t)}})}max(e,t){return new ys({...this._def,maxSize:{value:e,message:ce.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ys.create=(r,e)=>new ys({valueType:r,minSize:null,maxSize:null,typeName:pe.ZodSet,...ke(e)});class Ps extends Ie{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==J.function)return K(t,{code:M.invalid_type,expected:J.function,received:t.parsedType}),ye;function n(o,c){return zc({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Wc(),si].filter(u=>!!u),issueData:{code:M.invalid_arguments,argumentsError:c}})}function s(o,c){return zc({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Wc(),si].filter(u=>!!u),issueData:{code:M.invalid_return_type,returnTypeError:c}})}const i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof ai){const o=this;return kt(async function(...c){const u=new Zt([]),f=await o._def.args.parseAsync(c,i).catch(C=>{throw u.addIssue(n(c,C)),u}),y=await Reflect.apply(a,this,f);return await o._def.returns._def.type.parseAsync(y,i).catch(C=>{throw u.addIssue(s(y,C)),u})})}else{const o=this;return kt(function(...c){const u=o._def.args.safeParse(c,i);if(!u.success)throw new Zt([n(c,u.error)]);const f=Reflect.apply(a,this,u.data),y=o._def.returns.safeParse(f,i);if(!y.success)throw new Zt([s(f,y.error)]);return y.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new Ps({...this._def,args:Cr.create(e).rest(Xn.create())})}returns(e){return new Ps({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new Ps({args:e||Cr.create([]).rest(Xn.create()),returns:t||Xn.create(),typeName:pe.ZodFunction,...ke(n)})}}class Za extends Ie{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Za.create=(r,e)=>new Za({getter:r,typeName:pe.ZodLazy,...ke(e)});class Ma extends Ie{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return K(t,{received:t.data,code:M.invalid_literal,expected:this._def.value}),ye}return{status:"valid",value:e.data}}get value(){return this._def.value}}Ma.create=(r,e)=>new Ma({value:r,typeName:pe.ZodLiteral,...ke(e)});function M0(r,e){return new In({values:r,typeName:pe.ZodEnum,...ke(e)})}class In extends Ie{constructor(){super(...arguments),Ni.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),n=this._def.values;return K(t,{expected:$e.joinValues(n),received:t.parsedType,code:M.invalid_type}),ye}if(Gc(this,Ni)||P0(this,Ni,new Set(this._def.values)),!Gc(this,Ni).has(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return K(t,{received:t.data,code:M.invalid_enum_value,options:n}),ye}return kt(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return In.create(e,{...this._def,...t})}exclude(e,t=this._def){return In.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}}Ni=new WeakMap;In.create=M0;class Ua extends Ie{constructor(){super(...arguments),Bi.set(this,void 0)}_parse(e){const t=$e.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==J.string&&n.parsedType!==J.number){const s=$e.objectValues(t);return K(n,{expected:$e.joinValues(s),received:n.parsedType,code:M.invalid_type}),ye}if(Gc(this,Bi)||P0(this,Bi,new Set($e.getValidEnumValues(this._def.values))),!Gc(this,Bi).has(e.data)){const s=$e.objectValues(t);return K(n,{received:n.data,code:M.invalid_enum_value,options:s}),ye}return kt(e.data)}get enum(){return this._def.values}}Bi=new WeakMap;Ua.create=(r,e)=>new Ua({values:r,typeName:pe.ZodNativeEnum,...ke(e)});class ai extends Ie{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==J.promise&&t.common.async===!1)return K(t,{code:M.invalid_type,expected:J.promise,received:t.parsedType}),ye;const n=t.parsedType===J.promise?t.data:Promise.resolve(t.data);return kt(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}}ai.create=(r,e)=>new ai({type:r,typeName:pe.ZodPromise,...ke(e)});class hr extends Ie{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===pe.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:a=>{K(n,a),a.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){const a=s.transform(n.data,i);if(n.common.async)return Promise.resolve(a).then(async o=>{if(t.value==="aborted")return ye;const c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?ye:c.status==="dirty"||t.value==="dirty"?Cs(c.value):c});{if(t.value==="aborted")return ye;const o=this._def.schema._parseSync({data:a,path:n.path,parent:n});return o.status==="aborted"?ye:o.status==="dirty"||t.value==="dirty"?Cs(o.value):o}}if(s.type==="refinement"){const a=o=>{const c=s.refinement(o,i);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){const o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?ye:(o.status==="dirty"&&t.dirty(),a(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?ye:(o.status==="dirty"&&t.dirty(),a(o.value).then(()=>({status:t.value,value:o.value}))))}if(s.type==="transform")if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!ja(a))return a;const o=s.transform(a.value,i);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:n.data,path:n.path,parent:n}).then(a=>ja(a)?Promise.resolve(s.transform(a.value,i)).then(o=>({status:t.value,value:o})):a);$e.assertNever(s)}}hr.create=(r,e,t)=>new hr({schema:r,typeName:pe.ZodEffects,effect:e,...ke(t)});hr.createWithPreprocess=(r,e,t)=>new hr({schema:e,effect:{type:"preprocess",transform:r},typeName:pe.ZodEffects,...ke(t)});class kr extends Ie{_parse(e){return this._getType(e)===J.undefined?kt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}kr.create=(r,e)=>new kr({innerType:r,typeName:pe.ZodOptional,...ke(e)});class Cn extends Ie{_parse(e){return this._getType(e)===J.null?kt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Cn.create=(r,e)=>new Cn({innerType:r,typeName:pe.ZodNullable,...ke(e)});class Va extends Ie{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===J.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Va.create=(r,e)=>new Va({innerType:r,typeName:pe.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ke(e)});class La extends Ie{_parse(e){const{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Ta(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Zt(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Zt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}La.create=(r,e)=>new La({innerType:r,typeName:pe.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ke(e)});class Qc extends Ie{_parse(e){if(this._getType(e)!==J.nan){const n=this._getOrReturnCtx(e);return K(n,{code:M.invalid_type,expected:J.nan,received:n.parsedType}),ye}return{status:"valid",value:e.data}}}Qc.create=r=>new Qc({typeName:pe.ZodNaN,...ke(r)});const Ik=Symbol("zod_brand");class oh extends Ie{_parse(e){const{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class vo extends Ie{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?ye:i.status==="dirty"?(t.dirty(),Cs(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{const s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?ye:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new vo({in:e,out:t,typeName:pe.ZodPipeline})}}class qa extends Ie{_parse(e){const t=this._def.innerType._parse(e),n=s=>(ja(s)&&(s.value=Object.freeze(s.value)),s);return Ta(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}}qa.create=(r,e)=>new qa({innerType:r,typeName:pe.ZodReadonly,...ke(e)});function U0(r,e={},t){return r?ii.create().superRefine((n,s)=>{var i,a;if(!r(n)){const o=typeof e=="function"?e(n):typeof e=="string"?{message:e}:e,c=(a=(i=o.fatal)!==null&&i!==void 0?i:t)!==null&&a!==void 0?a:!0,u=typeof o=="string"?{message:o}:o;s.addIssue({code:"custom",...u,fatal:c})}}):ii.create()}const Ck={object:Ye.lazycreate};var pe;(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"})(pe||(pe={}));const jk=(r,e={message:`Input not instance of ${r.name}`})=>U0(t=>t instanceof r,e),V0=ar.create,L0=On.create,Tk=Qc.create,Nk=En.create,q0=Na.create,Bk=ms.create,Rk=Jc.create,Pk=Ba.create,$k=Ra.create,Dk=ii.create,Zk=Xn.create,Mk=Yr.create,Uk=Yc.create,Vk=lr.create,Lk=Ye.create,qk=Ye.strictCreate,Hk=Pa.create,Fk=zu.create,Kk=$a.create,Wk=Cr.create,zk=Da.create,Gk=Xc.create,Jk=ys.create,Yk=Ps.create,Xk=Za.create,Qk=Ma.create,eS=In.create,tS=Ua.create,rS=ai.create,dm=hr.create,nS=kr.create,sS=Cn.create,iS=hr.createWithPreprocess,aS=vo.create,oS=()=>V0().optional(),cS=()=>L0().optional(),uS=()=>q0().optional(),lS={string:r=>ar.create({...r,coerce:!0}),number:r=>On.create({...r,coerce:!0}),boolean:r=>Na.create({...r,coerce:!0}),bigint:r=>En.create({...r,coerce:!0}),date:r=>ms.create({...r,coerce:!0})},dS=ye;var Lt=Object.freeze({__proto__:null,defaultErrorMap:si,setErrorMap:dk,getErrorMap:Wc,makeIssue:zc,EMPTY_PATH:fk,addIssueToContext:K,ParseStatus:vt,INVALID:ye,DIRTY:Cs,OK:kt,isAborted:rf,isDirty:nf,isValid:ja,isAsync:Ta,get util(){return $e},get objectUtil(){return tf},ZodParsedType:J,getParsedType:on,ZodType:Ie,datetimeRegex:Z0,ZodString:ar,ZodNumber:On,ZodBigInt:En,ZodBoolean:Na,ZodDate:ms,ZodSymbol:Jc,ZodUndefined:Ba,ZodNull:Ra,ZodAny:ii,ZodUnknown:Xn,ZodNever:Yr,ZodVoid:Yc,ZodArray:lr,ZodObject:Ye,ZodUnion:Pa,ZodDiscriminatedUnion:zu,ZodIntersection:$a,ZodTuple:Cr,ZodRecord:Da,ZodMap:Xc,ZodSet:ys,ZodFunction:Ps,ZodLazy:Za,ZodLiteral:Ma,ZodEnum:In,ZodNativeEnum:Ua,ZodPromise:ai,ZodEffects:hr,ZodTransformer:hr,ZodOptional:kr,ZodNullable:Cn,ZodDefault:Va,ZodCatch:La,ZodNaN:Qc,BRAND:Ik,ZodBranded:oh,ZodPipeline:vo,ZodReadonly:qa,custom:U0,Schema:Ie,ZodSchema:Ie,late:Ck,get ZodFirstPartyTypeKind(){return pe},coerce:lS,any:Dk,array:Vk,bigint:Nk,boolean:q0,date:Bk,discriminatedUnion:Fk,effect:dm,enum:eS,function:Yk,instanceof:jk,intersection:Kk,lazy:Xk,literal:Qk,map:Gk,nan:Tk,nativeEnum:tS,never:Mk,null:$k,nullable:sS,number:L0,object:Lk,oboolean:uS,onumber:cS,optional:nS,ostring:oS,pipeline:aS,preprocess:iS,promise:rS,record:zk,set:Jk,strictObject:qk,string:V0,symbol:Rk,transformer:dm,tuple:Wk,undefined:Pk,union:Hk,unknown:Zk,void:Uk,NEVER:dS,ZodIssueCode:M,quotelessJson:lk,ZodError:Zt});Lt.object({start:Lt.number(),limit:Lt.number(),length:Lt.number()});su.extend({email:Lt.string(),login_count:Lt.number(),multifactor:Lt.array(Lt.string()).optional(),last_ip:Lt.string().optional(),last_login:Lt.string().optional(),user_id:Lt.string()}).catchall(Lt.any());const fS=jn.extend({tenants:m.array(Ns)}),hS=new ut().openapi(ge({tags:["tenants"],method:"get",path:"/",request:{query:rs},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"tenant/json":{schema:m.union([m.array(Ns),fS])}},description:"List of tenants"}}}),async r=>{const{page:e,per_page:t,include_totals:n,sort:s,q:i}=r.req.valid("query"),a=await r.env.data.tenants.list({page:e,per_page:t,include_totals:n,sort:ci(s),q:i});return n?r.json(a):r.json(a.tenants)}).openapi(ge({tags:["tenants"],method:"get",path:"/{id}",request:{params:m.object({id:m.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"tenant/json":{schema:Ns}},description:"A tenant"}}}),async r=>{const{id:e}=r.req.valid("param"),t=await r.env.data.tenants.get(e);if(!t)throw new de(404);return r.json(t)}).openapi(ge({tags:["tenants"],method:"delete",path:"/{id}",request:{params:m.object({id:m.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async r=>{const{id:e}=r.req.valid("param");return await r.env.data.tenants.remove(e),r.text("OK")}).openapi(ge({tags:["tenants"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:m.object(oc.shape).partial()}}},params:m.object({id:m.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async r=>{const{id:e}=r.req.valid("param"),t=r.req.valid("json");return await r.env.data.tenants.update(e,t),r.text("OK")}).openapi(ge({tags:["tenants"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:m.object(oc.shape)}}}},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"tenant/json":{schema:Ns}},description:"An tenant"}}}),async r=>{const e=r.req.valid("json"),t=await r.env.data.tenants.create(e);return r.json(t,{status:201})}),pS=jn.extend({logs:m.array(uc)}),mS=new ut().openapi(ge({tags:["logs"],method:"get",path:"/",request:{query:rs,headers:m.object({"tenant-id":m.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:m.union([m.array(uc),pS])}},description:"List of log rows"}}}),async r=>{const{page:e,per_page:t,include_totals:n,sort:s,q:i}=r.req.valid("query"),{"tenant-id":a}=r.req.valid("header"),o=await r.env.data.logs.list(a,{page:e,per_page:t,include_totals:n,sort:ci(s),q:i});return n?r.json(o):r.json(o.logs)}).openapi(ge({tags:["logs"],method:"get",path:"/{id}",request:{headers:m.object({"tenant-id":m.string()}),params:m.object({id:m.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:uc}},description:"A log entry"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),{id:t}=r.req.valid("param"),n=await r.env.data.logs.get(e,t);if(!n)throw new de(404);return r.json(n)}),yS=jn.extend({hooks:m.array(Es)}),gS=new ut().openapi(ge({tags:["hooks"],method:"get",path:"/",request:{query:rs,headers:m.object({"tenant-id":m.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:m.union([m.array(Es),yS])}},description:"List of hooks"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),{page:t,per_page:n,include_totals:s,sort:i,q:a}=r.req.valid("query"),o=await r.env.data.hooks.list(e,{page:t,per_page:n,include_totals:s,sort:ci(i),q:a});return s?r.json(o):r.json(o.hooks)}).openapi(ge({tags:["hooks"],method:"post",path:"/",request:{headers:m.object({"tenant-id":m.string()}),body:{content:{"application/json":{schema:m.object(cc.shape)}}}},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:Es}},description:"The created hook"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),t=r.req.valid("json"),n=await r.env.data.hooks.create(e,t);return r.json(n,{status:201})}).openapi(ge({tags:["hooks"],method:"patch",path:"/{hook_id}",request:{headers:m.object({"tenant-id":m.string()}),params:m.object({hook_id:m.string()}),body:{content:{"application/json":{schema:m.object(cc.shape).omit({hook_id:!0}).partial()}}}},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:Es.shape}},description:"The updated hook"},404:{description:"Hook not found"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),{hook_id:t}=r.req.valid("param"),n=r.req.valid("json");await r.env.data.hooks.update(e,t,n);const s=await r.env.data.hooks.get(e,t);if(!s)throw new de(404,{message:"Hook not found"});return r.json(s)}).openapi(ge({tags:["hooks"],method:"get",path:"/{hook_id}",request:{headers:m.object({"tenant-id":m.string()}),params:m.object({hook_id:m.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Es}},description:"A hook"},404:{description:"Hook not found"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),{hook_id:t}=r.req.valid("param"),n=await r.env.data.hooks.get(e,t);if(!n)throw new de(404,{message:"Hook not found"});return r.json(n)}).openapi(ge({tags:["hooks"],method:"delete",path:"/{hook_id}",request:{headers:m.object({"tenant-id":m.string()}),params:m.object({hook_id:m.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{description:"A hook"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),{hook_id:t}=r.req.valid("param");if(!await r.env.data.hooks.remove(e,t))throw new de(404,{message:"Hook not found"});return r.text("OK")}),vS=jn.extend({connections:m.array(Un)}),bS=new ut().openapi(ge({tags:["connections"],method:"get",path:"/",request:{query:rs,headers:m.object({"tenant-id":m.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:m.union([m.array(Un),vS])}},description:"List of connectionss"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),{page:t,per_page:n,include_totals:s=!1,sort:i,q:a}=r.req.valid("query"),o=await r.env.data.connections.list(e,{page:t,per_page:n,include_totals:s,sort:ci(i),q:a});return s?r.json(o):r.json(o.connections)}).openapi(ge({tags:["connections"],method:"get",path:"/{id}",request:{params:m.object({id:m.string()}),headers:m.object({"tenant-id":m.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Un}},description:"A connection"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),{id:t}=r.req.valid("param"),n=await r.env.data.connections.get(e,t);if(!n)throw new de(404);return r.json(n)}).openapi(ge({tags:["connections"],method:"delete",path:"/{id}",request:{params:m.object({id:m.string()}),headers:m.object({"tenant-id":m.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),{id:t}=r.req.valid("param");if(!await r.env.data.connections.remove(e,t))throw new de(404,{message:"Connection not found"});return r.text("OK")}).openapi(ge({tags:["connections"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:m.object(ac.shape).partial()}}},params:m.object({id:m.string()}),headers:m.object({"tenant-id":m.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:Un}},description:"The updated connection"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),{id:t}=r.req.valid("param"),n=r.req.valid("json");if(!await r.env.data.connections.update(e,t,n))throw new de(404,{message:"Connection not found"});const i=await r.env.data.connections.get(e,t);if(!i)throw new de(404,{message:"Connection not found"});return r.json(i)}).openapi(ge({tags:["connections"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:m.object(ac.shape)}}},headers:m.object({"tenant-id":m.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:Un}},description:"A connection"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),t=r.req.valid("json"),n=await r.env.data.connections.create(e,t);return r.json(n,{status:201})}),xS=new ut().openapi(ge({tags:["prompts"],method:"get",path:"/",request:{headers:m.object({"tenant-id":m.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:To}},description:"Branding settings"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),t=await r.env.data.promptSettings.get(e);return t?r.json(t):r.json(To.parse({}))}).openapi(ge({tags:["prompts"],method:"patch",path:"/",request:{headers:m.object({"tenant-id":m.string()}),body:{content:{"application/json":{schema:m.object(To.shape).partial()}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Prompts settings"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),t=r.req.valid("json"),n=await r.env.data.promptSettings.get(e);return Object.assign(n,t),await r.env.data.promptSettings.set(e,n),r.json(n)});let fm=!1;function H0(r){r.use(async(e,t)=>(fm||(r.openAPIRegistry.registerComponent("securitySchemes","Bearer",{type:"oauth2",scheme:"bearer",flows:{implicit:{authorizationUrl:`${e.env.AUTH_URL}/authorize`,scopes:{openid:"Basic user information",email:"User email",profile:"User profile information"}}}}),fm=!0),await t()))}m.object({alg:m.literal("RS256"),kty:m.literal("RSA"),use:m.literal("sig"),n:m.string(),e:m.string(),kid:m.string(),x5t:m.string(),x5c:m.array(m.string())});async function _S(r){try{const e=await r.JWKS_SERVICE.fetch(r.JWKS_URL);if(!e.ok)throw new Error("Failed to fetch jwks");return(await e.json()).keys}catch(e){throw new de(500,{message:`Failed to fetch jwks: ${e.message}`})}}async function wS(r,e){const n=new TextEncoder().encode([e.raw.header,e.raw.payload].join(".")),s=new Uint8Array(Array.from(e.signature).map(c=>c.charCodeAt(0))),a=(await _S(r.env)).find(c=>c.kid===e.header.kid);if(!a)return console.log("No matching kid found"),!1;const o=await crypto.subtle.importKey("jwk",a,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);return crypto.subtle.verify("RSASSA-PKCS1-v1_5",o,s,n)}function kS(r){const[e,t,n]=r.split(".");if(!e||!t||!n)return null;const s=JSON.parse(atob(e)),i=JSON.parse(atob(t)),a=atob(n.replace(/-/g,"+").replace(/_/g,"/"));return{header:s,payload:i,signature:a,raw:{header:e,payload:t,signature:n}}}function F0(r){return async(e,t)=>{var s,i,a;const n=r.openAPIRegistry.definitions.find(o=>"route"in o&&o.route.path===e.req.path&&o.route.method.toUpperCase()===e.req.method);if(n&&"route"in n){const o=(i=(s=n.route.security)==null?void 0:s[0])==null?void 0:i.Bearer;if(!(o!=null&&o.length))return await t();const c=e.req.header("authorization")||"",[u,f]=c.split(" ");if((u==null?void 0:u.toLowerCase())!=="bearer"||!f)throw new de(401,{message:"Missing bearer token"});const y=kS(f);if(!y||!await wS(e,y))throw new de(403,{message:"Invalid JWT signature"});e.set("user_id",y.payload.sub),e.set("user",y.payload);const B=y.payload.permissions||[],C=((a=y.payload.scope)==null?void 0:a.split(" "))||[];if(o.length&&!(o.some(p=>B.includes(p))||o.some(p=>C.includes(p))))throw new de(403,{message:"Unauthorized"})}return await t()}}const SS=new ut().openapi(ge({tags:["emails"],method:"get",path:"/",request:{headers:m.object({"tenant-id":m.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:No}},description:"Email provider"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),t=await r.env.data.emailProviders.get(e);if(!t)throw new de(404,{message:"Email provider not found"});return r.json(t)}).openapi(ge({tags:["emails"],method:"post",path:"/",request:{headers:m.object({"tenant-id":m.string()}),body:{content:{"application/json":{schema:m.object(No.shape)}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Branding settings"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),t=r.req.valid("json");return await r.env.data.emailProviders.create(e,t),r.text("OK",{status:201})}).openapi(ge({tags:["emails"],method:"patch",path:"/",request:{headers:m.object({"tenant-id":m.string()}),body:{content:{"application/json":{schema:m.object(No.shape).partial()}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Branding settings"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),t=r.req.valid("json");return await r.env.data.emailProviders.update(e,t),r.text("OK")});function AS(){const r=new ut;r.use(F0(r));const e=r.route("/branding",M_).route("/email/providers",SS).route("/users",aw).route("/keys",ak).route("/users-by-email",ok).route("/clients",uk).route("/tenants",hS).route("/logs",mS).route("/hooks",gS).route("/connections",bS).route("/prompts",xS);return H0(e),e.doc("/spec",{openapi:"3.0.0",info:{version:"1.0.0",title:"Management api"}}),e}const Ao=60*5,K0=30*24*60*60,OS="auth-token",ES=new ut().openapi(ge({tags:["jwks"],method:"get",path:"/jwks.json",request:{},responses:{200:{content:{"application/json":{schema:Iy}},description:"List of tenants"}}}),async r=>{const e=await r.env.data.keys.list(),t=await Promise.all(e.map(async n=>{const i=await new ah(n.cert).publicKey.export(),a=await crypto.subtle.exportKey("jwk",i);return mf.parse({...a,kid:n.kid})}));return r.json({keys:t},{headers:{"access-control-allow-origin":"*","access-control-allow-method":"GET","cache-control":`public, max-age=${Ao}, stale-while-revalidate=${Ao*2}, stale-if-error=86400`}})}).openapi(ge({tags:["well known"],method:"get",path:"/openid-configuration",request:{},responses:{200:{content:{"application/json":{schema:Rl}},description:"List of tenants"}}}),async r=>{const e=r.env.ISSUER,t=Rl.parse({issuer:e,authorization_endpoint:`${e}authorize`,token_endpoint:`${e}oauth/token`,device_authorization_endpoint:`${e}oauth/device/code`,userinfo_endpoint:`${e}userinfo`,mfa_challenge_endpoint:`${e}mfa/challenge`,jwks_uri:`${e}.well-known/jwks.json`,registration_endpoint:`${e}oidc/register`,revocation_endpoint:`${e}oauth/revoke`,scopes_supported:["openid","profile","offline_access","name","given_name","family_name","nickname","email","email_verified","picture","created_at","identities","phone","address"],response_types_supported:["code","token","id_token","code token","code id_token","token id_token","code token id_token"],code_challenge_methods_supported:["S256","plain"],response_modes_supported:["query","fragment","form_post"],subject_types_supported:["public"],id_token_signing_alg_values_supported:["RS256"],token_endpoint_auth_methods_supported:["client_secret_basic","client_secret_post"],claims_supported:["aud","auth_time","created_at","email","email_verified","exp","family_name","given_name","iat","identities","iss","name","nickname","phone_number","picture","sub"],request_uri_parameter_supported:!1,request_parameter_supported:!1,token_endpoint_auth_signing_alg_values_supported:["RS256","RS384","PS256"]});return r.json(t,{headers:{"access-control-allow-origin":"*","access-control-allow-method":"GET","cache-control":`public, max-age=${Ao}, stale-while-revalidate=${Ao*2}, stale-if-error=86400`}})});class eu{constructor(e,t){ne(this,"value");ne(this,"unit");this.value=e,this.unit=t}milliseconds(){return this.unit==="ms"?this.value:this.unit==="s"?this.value*1e3:this.unit==="m"?this.value*1e3*60:this.unit==="h"?this.value*1e3*60*60:this.unit==="d"?this.value*1e3*60*60*24:this.value*1e3*60*60*24*7}seconds(){return this.milliseconds()/1e3}transform(e){return new eu(Math.round(this.milliseconds()*e),"ms")}}async function hm(r,e,t,n){const s={alg:r,typ:"JWT",...n==null?void 0:n.headers},i={...t};(n==null?void 0:n.audiences)!==void 0&&(i.aud=n.audiences),(n==null?void 0:n.subject)!==void 0&&(i.sub=n.subject),(n==null?void 0:n.issuer)!==void 0&&(i.iss=n.issuer),(n==null?void 0:n.jwtId)!==void 0&&(i.jti=n.jwtId),(n==null?void 0:n.expiresIn)!==void 0&&(i.exp=Math.floor(Date.now()/1e3)+n.expiresIn.seconds()),(n==null?void 0:n.notBefore)!==void 0&&(i.nbf=Math.floor(n.notBefore.getTime()/1e3)),(n==null?void 0:n.includeIssuedTimestamp)===!0&&(i.iat=Math.floor(Date.now()/1e3));const a=new TextEncoder,o=Do.encode(a.encode(JSON.stringify(s)),{includePadding:!1}),c=Do.encode(a.encode(JSON.stringify(i)),{includePadding:!1}),u=a.encode([o,c].join(".")),f=await IS(r).sign(e,u),y=Do.encode(new Uint8Array(f),{includePadding:!1});return[o,c,y].join(".")}function IS(r){return new rk(CS[r])}const CS={RS256:"SHA-256",RS384:"SHA-384",RS512:"SHA-512"};function jS(r){try{const t=/-----BEGIN (?:RSA )?(?:PRIVATE|PUBLIC) KEY-----([^-]*)-----END (?:RSA )?(?:PRIVATE|PUBLIC) KEY-----/.exec(r);if(!t||!t[1])throw new Error("Invalid PEM format");return Uint8Array.from(atob(t[1].replace(/\s/g,"")),n=>n.charCodeAt(0)).buffer}finally{r=r.replace(/./g,"\0")}}async function TS(r,e){if(e==="plain")return r;const t=new TextEncoder().encode(r),n=await B0(t);return Do.encode(new Uint8Array(n))}async function W0(r,e){var y;const{authParams:t,user:n,sid:s}=e,a=(await r.env.data.keys.list()).filter(B=>!B.revoked_at||new Date(B.revoked_at)>new Date),o=a[a.length-1];if(!(o!=null&&o.pkcs7))throw new de(500,{message:"No signing key available"});const c=jS(o.pkcs7),u=await hm("RS256",c,{aud:t.audience||"default",scope:t.scope||"",sub:(n==null?void 0:n.user_id)||t.client_id,iss:r.env.ISSUER,tenant_id:r.var.tenant_id,sid:s},{includeIssuedTimestamp:!0,expiresIn:new eu(1,"d"),headers:{kid:o.kid}}),f=n&&((y=t.scope)!=null&&y.split(" ").includes("openid"))?await hm("RS256",c,{aud:t.client_id,sub:n.user_id,iss:r.env.ISSUER,sid:s,nonce:t.nonce,given_name:n.given_name,family_name:n.family_name,nickname:n.nickname,picture:n.picture,locale:n.locale,name:n.name,email:n.email,email_verified:n.email_verified},{includeIssuedTimestamp:!0,expiresIn:new eu(1,"d"),headers:{kid:o.kid}}):void 0;return{access_token:u,id_token:f,token_type:"Bearer",expires_in:86400}}function Zo(r,e){if(!r||!e||r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r.charCodeAt(n)^e.charCodeAt(n);return t===0}const z0=m.object({grant_type:m.literal("client_credentials"),scope:m.string().optional(),client_secret:m.string(),client_id:m.string(),audience:m.string().optional()});async function NS(r,e){const t=await r.env.data.clients.get(e.client_id);if(!t)throw new de(403,{message:"Invalid client credentials"});if(t.client_secret&&!Zo(t.client_secret,e.client_secret))throw new de(403,{message:"Invalid client credentials"});const n={client_id:t.id,scope:e.scope,audience:e.audience},s=await W0(r,{authParams:n});return r.json(s)}function G0(r,e,t){const n=[];return n.push([encodeURIComponent(r),encodeURIComponent(e)]),(t==null?void 0:t.domain)!==void 0&&n.push(["Domain",t.domain]),(t==null?void 0:t.expires)!==void 0&&n.push(["Expires",t.expires.toUTCString()]),t!=null&&t.httpOnly&&n.push(["HttpOnly"]),(t==null?void 0:t.maxAge)!==void 0&&n.push(["Max-Age",t.maxAge.toString()]),(t==null?void 0:t.path)!==void 0&&n.push(["Path",t.path]),(t==null?void 0:t.sameSite)==="lax"&&n.push(["SameSite","Lax"]),(t==null?void 0:t.sameSite)==="none"&&n.push(["SameSite","None"]),(t==null?void 0:t.sameSite)==="strict"&&n.push(["SameSite","Strict"]),t!=null&&t.secure&&n.push(["Secure"]),n.map(s=>s.join("=")).join("; ")}function BS(r){const e=new Map,t=r.split("; ");for(const n of t){const s=n.split("="),i=s[0],a=s[1]??"";i&&e.set(decodeURIComponent(i),decodeURIComponent(a))}return e}function ch(r){return`${r}-${OS}`}function RS(r,e){return e?BS(e).get(ch(r)):void 0}function PS(r){const e={path:"/",httpOnly:!0,secure:!0,maxAge:0};return G0(ch(r),"",{...e,sameSite:"none"})}function $S(r,e){const t={path:"/",httpOnly:!0,secure:!0,maxAge:K0};return G0(ch(r),e,{...t,sameSite:"none"})}const DS=m.object({grant_type:m.literal("authorization_code"),client_id:m.string(),code:m.string(),redirect_uri:m.string().optional(),client_secret:m.string().optional(),code_verifier:m.string().optional()}).refine(r=>"client_secret"in r&&!("code_verifier"in r)||!("client_secret"in r)&&"code_verifier"in r,{message:"Must provide either client_secret (standard flow) or code_verifier/code_verifier_mode (PKCE flow), but not both"});async function ZS(r,e){const t=await r.env.data.clients.get(e.client_id);if(!t)throw new de(403,{message:"Client not found"});const n=await r.env.data.codes.get(t.tenant.id,e.code,"authorization_code");if(!n||!n.user_id)throw new de(403,{message:"Invalid client credentials"});if(new Date(n.expires_at)<new Date)throw new de(403,{message:"Code expired"});const s=await r.env.data.logins.get(t.tenant.id,n.login_id);if(!s)throw new de(403,{message:"Invalid login"});if("client_secret"in e){const c=await r.env.data.clients.get("DEFAULT_CLIENT");if(!Zo(t.client_secret,e.client_secret)&&!Zo(c==null?void 0:c.client_secret,e.client_secret))throw new de(403,{message:"Invalid client credentials"})}else if("code_verifier"in e&&typeof e.code_verifier=="string"&&"code_challenge_method"in s.authParams&&typeof s.authParams.code_challenge_method=="string"){const c=await TS(e.code_verifier,s.authParams.code_challenge_method);if(!Zo(c,s.authParams.code_challenge||""))throw new de(403,{message:"Invalid client credentials"})}if(s.authParams.redirect_uri&&s.authParams.redirect_uri!==e.redirect_uri)throw new de(403,{message:"Invalid redirect uri"});const i=await r.env.data.users.get(t.tenant.id,n.user_id);if(!i)throw new de(403,{message:"User not found"});await r.env.data.codes.remove(t.tenant.id,e.code);const a=await r.env.data.sessions.create(t.tenant.id,{session_id:fc(),user_id:i.user_id,client_id:t.id,expires_at:new Date(Date.now()+K0*1e3).toISOString(),used_at:new Date().toISOString()}),o=await W0(r,{authParams:s.authParams,user:i,sid:a.session_id});return r.json(o,{headers:{"set-cookie":$S(t.tenant.id,a.session_id)}})}const pm=m.object({client_id:m.string().optional(),client_secret:m.string().optional()}),MS=m.union([z0.extend(pm.shape),m.object({grant_type:m.literal("authorization_code"),client_id:m.string(),code:m.string(),redirect_uri:m.string(),code_verifier:m.string().min(43).max(128)}),m.object({grant_type:m.literal("authorization_code"),code:m.string(),redirect_uri:m.string().optional(),...pm.shape})]);function US(r){if(!r)return{};const[e,t]=r.split(" ");if((e==null?void 0:e.toLowerCase())==="basic"&&t){const[n,s]=atob(t).split(":");return{client_id:n,client_secret:s}}return{}}const VS=new ut().openapi(ge({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:MS}}}},responses:{200:{content:{"application/json":{schema:m.object({access_token:m.string(),id_token:m.string().optional(),refresh_token:m.string().optional(),token_type:m.string(),expires_in:m.number()})}},description:"Tokens"}}}),async r=>{const e=r.req.valid("form"),t=US(r.req.header("Authorization")),n={...e,...t};if(!n.client_id)throw new de(400,{message:"client_id is required"});switch(e.grant_type){case lc.AuthorizationCode:return ZS(r,DS.parse(n));case lc.ClientCredential:return NS(r,z0.parse(n));default:throw new de(400,{message:"Not implemented"})}});function LS(r,e){try{const t=new URL(r);return e.some(n=>{try{return qS(t,new URL(n))}catch{return!1}})}catch{return!1}}function qS(r,e){if(r.protocol!==e.protocol||r.pathname!==e.pathname)return!1;if(e.hostname.startsWith("*.")&&e.hostname.split(".").length>2&&["http:","https:"].includes(e.protocol)){const t=e.hostname.split(".").slice(1).join(".");return r.hostname.endsWith(t)}return r.hostname===e.hostname}const HS=new ut().openapi(ge({tags:["oauth2"],method:"get",path:"/",request:{query:m.object({client_id:m.string(),returnTo:m.string().optional()}),header:m.object({cookie:m.string().optional()})},responses:{302:{description:"Log the user out"}}}),async r=>{const{client_id:e,returnTo:t}=r.req.valid("query"),n=await r.env.data.clients.get(e);if(!n)return r.text("OK");const s=await r.env.data.clients.get("DEFAULT_CLIENT");r.set("client_id",e),r.set("tenant_id",n.tenant.id);const i=t||r.req.header("referer");if(!i)return r.text("OK");if(!LS(i,[...n.allowed_logout_urls||[],...(s==null?void 0:s.allowed_logout_urls)||[]]))throw new de(400,{message:"Invalid redirect uri"});const a=r.req.header("cookie");if(a){const c=RS(n.tenant.id,a);if(c){const u=await r.env.data.sessions.get(n.tenant.id,c);if(u){const f=await r.env.data.users.get(n.tenant.id,u.user_id);f&&(r.set("user_id",f.user_id),r.set("connection",f.connection))}await r.env.data.sessions.remove(n.tenant.id,c)}}const o=gf(r,{type:Xa.SUCCESS_LOGOUT,description:"User successfully logged out"});return await r.env.data.logs.create(n.tenant.id,o),new Response("Redirecting",{status:302,headers:{"set-cookie":PS(n.tenant.id),location:i}})}),mm=m.object({sub:m.string(),email:m.string().optional(),family_name:m.string().optional(),given_name:m.string().optional(),email_verified:m.boolean()}),FS=new ut().openapi(ge({tags:["oauth2"],method:"get",path:"/",request:{},security:[{Bearer:["openid"]}],responses:{200:{content:{"application/json":{schema:mm}},description:"Userinfo"}}}),async r=>{if(!r.var.user)throw new de(404,{message:"User not found"});const e=await r.env.data.users.get(r.var.user.tenant_id,r.var.user.sub);if(!e)throw new de(404,{message:"User not found"});return r.json(mm.parse({...e,sub:e.user_id}))});function KS(){const r=new ut;r.use(F0(r));const e=r.route("/.well-known",ES).route("/oauth/token",VS).route("/v2/logout",HS).route("/userinfo",FS);return e.doc("/spec",{openapi:"3.0.0",info:{version:"1.0.0",title:"Oauth API"}}),H0(e),e}function WS(r){return async(e,t)=>{if(!t.email||!t.email_verified)return r.users.create(e,t);const n=await ew({userAdapter:r.users,tenant_id:e,email:t.email});return n?(await r.users.create(e,{...t,linked_to:n.user_id}),n):r.users.create(e,t)}}async function zS(r,e,t){for await(const n of e)if(!(await fetch(n.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).ok){const i=gf(r,{type:Xa.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid password"});await t.logs.create(r.var.tenant_id,i)}}function GS(r,e){return async(t,n)=>{const{hooks:s}=await e.hooks.list(t,{q:"trigger_id:post-user-registration",page:0,per_page:100,include_totals:!1});return await zS(r,s,{tenant_id:t,user:n,trigger_id:"post-user-registration"}),n}}function JS(r,e){return async(t,n)=>{let s=await WS(e)(t,n);return await GS(r,e)(t,s),s}}function YS(r,e){return{...e,users:{...e.users,create:JS(r,e)}}}function XS(r){const e=new ut;e.use(async(s,i)=>(s.env.data=YS(s,r.dataAdapter),i())),e.get("/",s=>s.json({name:"authhero"}));const t=AS();e.route("/api/v2",t);const n=KS();return e.route("/",n),{app:e,managementApp:t,oauthApp:n,createX509Certificate:ef}}exports.Auth0Client=jy;exports.AuthorizationResponseMode=hf;exports.AuthorizationResponseType=ff;exports.CodeChallengeMethod=pf;exports.GrantType=lc;exports.LogTypes=Xa;exports.applicationInsertSchema=ic;exports.applicationSchema=Mn;exports.auth0UserResponseSchema=vr;exports.authParamsSchema=Sy;exports.baseUserSchema=su;exports.bordersSchema=By;exports.brandingSchema=Bl;exports.codeInsertSchema=Oy;exports.codeSchema=N_;exports.codeTypeSchema=Ay;exports.colorsSchema=Ry;exports.connectionInsertSchema=ac;exports.connectionSchema=Un;exports.domainInsertSchema=Ey;exports.domainSchema=B_;exports.emailProviderSchema=No;exports.fontDetailsSchema=Dn;exports.fontsSchema=Py;exports.hookInsertSchema=cc;exports.hookSchema=Es;exports.identitySchema=wy;exports.init=XS;exports.jwksKeySchema=Iy;exports.jwksSchema=mf;exports.logSchema=uc;exports.loginInsertSchema=Cy;exports.loginSchema=R_;exports.openIDConfigurationSchema=Rl;exports.pageBackgroundSchema=$y;exports.parseUserId=Z_;exports.passwordInsertSchema=Ty;exports.passwordSchema=$_;exports.profileDataSchema=_y;exports.promptSettingSchema=To;exports.samlpAddon=ky;exports.sessionInsertSchema=Ny;exports.sessionSchema=yf;exports.signingKeySchema=Pl;exports.tenantInsertSchema=oc;exports.tenantSchema=Ns;exports.themeInsertSchema=Zy;exports.themeSchema=D_;exports.totalsSchema=jn;exports.userInsertSchema=sc;exports.userResponseSchema=E_;exports.userSchema=df;exports.vendorSettingsSchema=j_;exports.widgetSchema=Dy;
125
+ `,n}async function sk(r){const e=await r.publicKey.export(),t=await crypto.subtle.exportKey("jwk",e),n=JSON.stringify(t,Object.keys(t).sort()),i=new TextEncoder().encode(n);return Qd(await B0(i))}const ik=1e3*60*60*24,ak=new ut().openapi(ge({tags:["keys"],method:"get",path:"/signing",request:{headers:m.object({"tenant-id":m.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:m.array(Pl)}},description:"List of keys"}}}),async r=>{const t=(await r.env.data.keys.list()).filter(n=>"cert"in n).map(n=>n);return r.json(t)}).openapi(ge({tags:["keys"],method:"get",path:"/signing/{kid}",request:{headers:m.object({"tenant-id":m.string()}),params:m.object({kid:m.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Pl}},description:"The requested key"}}}),async r=>{const{kid:e}=r.req.valid("param"),n=(await r.env.data.keys.list()).find(s=>s.kid===e);if(!n)throw new de(404,{message:"Key not found"});return r.json(n)}).openapi(ge({tags:["keys"],method:"post",path:"/signing/rotate",request:{headers:m.object({"tenant-id":m.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{description:"Status"}}}),async r=>{const e=await r.env.data.keys.list();for await(const n of e)await r.env.data.keys.update(n.kid,{revoked_at:new Date(Date.now()+ik).toISOString()});const t=await ef({name:`CN=${r.env.ORGANIZATION_NAME}`});return await r.env.data.keys.create(t),r.text("OK",{status:201})}).openapi(ge({tags:["keys"],method:"put",path:"/signing/{kid}/revoke",request:{headers:m.object({"tenant-id":m.string()}),params:m.object({kid:m.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{description:"Status"}}}),async r=>{const{kid:e}=r.req.valid("param");if(!await r.env.data.keys.update(e,{revoked_at:new Date().toISOString()}))throw new de(404,{message:"Key not found"});const n=await ef({name:`CN=${r.env.ORGANIZATION_NAME}`});return await r.env.data.keys.create(n),r.text("OK")}),ok=new ut().openapi(ge({tags:["users"],method:"get",path:"/",request:{query:m.object({email:m.string()}),headers:m.object({"tenant-id":m.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"tenant/json":{schema:m.array(df)}},description:"List of users"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),{email:t}=r.req.valid("query"),s=(await Uy(r.env.data.users,e,t)).filter(i=>!i.linked_to);return r.json(s)}),ck=jn.extend({clients:m.array(Mn)}),uk=new ut().openapi(ge({tags:["clients"],method:"get",path:"/",request:{query:rs,headers:m.object({"tenant-id":m.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:m.union([ck,m.array(Mn)])}},description:"List of clients"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),{page:t,per_page:n,include_totals:s,sort:i,q:a}=r.req.valid("query"),c=(await r.env.data.applications.list(e,{page:t,per_page:n,include_totals:s,sort:ci(i),q:a})).applications;return s?r.json({clients:c,start:0,limit:10,length:c.length}):r.json(c)}).openapi(ge({tags:["clients"],method:"get",path:"/{id}",request:{params:m.object({id:m.string()}),headers:m.object({"tenant-id":m.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Mn}},description:"An application"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),{id:t}=r.req.valid("param"),s=(await r.env.data.applications.list(e,{page:1,per_page:0,include_totals:!1})).applications.find(i=>i.id===t);if(!s)throw new de(404);return r.json(s)}).openapi(ge({tags:["clients"],method:"delete",path:"/{id}",request:{params:m.object({id:m.string()}),headers:m.object({"tenant-id":m.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),{id:t}=r.req.valid("param");if(!await r.env.data.applications.remove(e,t))throw new de(404,{message:"Application not found"});return r.text("OK")}).openapi(ge({tags:["clients"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:m.object(ic.shape).partial()}}},params:m.object({id:m.string()}),headers:m.object({"tenant-id":m.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:Mn}},description:"The update application"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),{id:t}=r.req.valid("param"),s=r.req.valid("json");await r.env.data.applications.update(e,t,s);const i=await r.env.data.applications.get(e,t);if(!i)throw new de(404,{message:"Application not found"});return r.json(i)}).openapi(ge({tags:["clients"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:m.object(ic.shape)}}},headers:m.object({"tenant-id":m.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:m.object(Mn.shape)}},description:"An application"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),t=r.req.valid("json"),n={...t,id:t.id||fc(),client_secret:t.client_secret||fc()},s=await r.env.data.applications.create(e,n);return r.json(s,{status:201})});var $e;(function(r){r.assertEqual=s=>s;function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{const i={};for(const a of s)i[a]=a;return i},r.getValidEnumValues=s=>{const i=r.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),a={};for(const o of i)a[o]=s[o];return r.objectValues(a)},r.objectValues=s=>r.objectKeys(s).map(function(i){return s[i]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const i=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&i.push(a);return i},r.find=(s,i)=>{for(const a of s)if(i(a))return a},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function n(s,i=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}r.joinValues=n,r.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})($e||($e={}));var tf;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(tf||(tf={}));const J=$e.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),on=r=>{switch(typeof r){case"undefined":return J.undefined;case"string":return J.string;case"number":return isNaN(r)?J.nan:J.number;case"boolean":return J.boolean;case"function":return J.function;case"bigint":return J.bigint;case"symbol":return J.symbol;case"object":return Array.isArray(r)?J.array:r===null?J.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?J.promise:typeof Map<"u"&&r instanceof Map?J.map:typeof Set<"u"&&r instanceof Set?J.set:typeof Date<"u"&&r instanceof Date?J.date:J.object;default:return J.unknown}},M=$e.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"]),lk=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:");class Zt extends Error{constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){const t=e||function(i){return i.message},n={_errors:[]},s=i=>{for(const a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)n._errors.push(t(a));else{let o=n,c=0;for(;c<a.path.length;){const u=a.path[c];c===a.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(t(a))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return s(this),n}static assert(e){if(!(e instanceof Zt))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,$e.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},n=[];for(const s of this.issues)s.path.length>0?(t[s.path[0]]=t[s.path[0]]||[],t[s.path[0]].push(e(s))):n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}Zt.create=r=>new Zt(r);const si=(r,e)=>{let t;switch(r.code){case M.invalid_type:r.received===J.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case M.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,$e.jsonStringifyReplacer)}`;break;case M.unrecognized_keys:t=`Unrecognized key(s) in object: ${$e.joinValues(r.keys,", ")}`;break;case M.invalid_union:t="Invalid input";break;case M.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${$e.joinValues(r.options)}`;break;case M.invalid_enum_value:t=`Invalid enum value. Expected ${$e.joinValues(r.options)}, received '${r.received}'`;break;case M.invalid_arguments:t="Invalid function arguments";break;case M.invalid_return_type:t="Invalid function return type";break;case M.invalid_date:t="Invalid date";break;case M.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}"`:$e.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case M.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 M.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 M.custom:t="Invalid input";break;case M.invalid_intersection_types:t="Intersection results could not be merged";break;case M.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case M.not_finite:t="Number must be finite";break;default:t=e.defaultError,$e.assertNever(r)}return{message:t}};let R0=si;function dk(r){R0=r}function Wc(){return R0}const zc=r=>{const{data:e,path:t,errorMaps:n,issueData:s}=r,i=[...t,...s.path||[]],a={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let o="";const c=n.filter(u=>!!u).slice().reverse();for(const u of c)o=u(a,{data:e,defaultError:o}).message;return{...s,path:i,message:o}},fk=[];function K(r,e){const t=Wc(),n=zc({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===si?void 0:si].filter(s=>!!s)});r.common.issues.push(n)}class vt{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const n=[];for(const s of t){if(s.status==="aborted")return ye;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const s of t){const i=await s.key,a=await s.value;n.push({key:i,value:a})}return vt.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const s of t){const{key:i,value:a}=s;if(i.status==="aborted"||a.status==="aborted")return ye;i.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(n[i.value]=a.value)}return{status:e.value,value:n}}}const ye=Object.freeze({status:"aborted"}),Cs=r=>({status:"dirty",value:r}),kt=r=>({status:"valid",value:r}),rf=r=>r.status==="aborted",nf=r=>r.status==="dirty",ja=r=>r.status==="valid",Ta=r=>typeof Promise<"u"&&r instanceof Promise;function Gc(r,e,t,n){if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(r)}function P0(r,e,t,n,s){if(typeof e=="function"?r!==e||!s:!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 ce;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(ce||(ce={}));var Ni,Bi;class Ir{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=s}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}}const lm=(r,e)=>{if(ja(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new Zt(r.common.issues);return this._error=t,this._error}}};function ke(r){if(!r)return{};const{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(a,o)=>{var c,u;const{message:f}=r;return a.code==="invalid_enum_value"?{message:f??o.defaultError}:typeof o.data>"u"?{message:(c=f??n)!==null&&c!==void 0?c:o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:(u=f??t)!==null&&u!==void 0?u:o.defaultError}},description:s}}class Ie{constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(e){return on(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:on(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new vt,ctx:{common:e.parent.common,data:e.data,parsedType:on(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(Ta(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){var n;const s={common:{issues:[],async:(n=t==null?void 0:t.async)!==null&&n!==void 0?n:!1,contextualErrorMap:t==null?void 0:t.errorMap},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:on(e)},i=this._parseSync({data:e,path:s.path,parent:s});return lm(s,i)}async parseAsync(e,t){const n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){const n={common:{issues:[],contextualErrorMap:t==null?void 0:t.errorMap,async:!0},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:on(e)},s=this._parse({data:e,path:n.path,parent:n}),i=await(Ta(s)?s:Promise.resolve(s));return lm(n,i)}refine(e,t){const n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,i)=>{const a=e(s),o=()=>i.addIssue({code:M.custom,...n(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new hr({schema:this,typeName:pe.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return kr.create(this,this._def)}nullable(){return Cn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return lr.create(this,this._def)}promise(){return ai.create(this,this._def)}or(e){return Pa.create([this,e],this._def)}and(e){return $a.create(this,e,this._def)}transform(e){return new hr({...ke(this._def),schema:this,typeName:pe.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new Va({...ke(this._def),innerType:this,defaultValue:t,typeName:pe.ZodDefault})}brand(){return new oh({typeName:pe.ZodBranded,type:this,...ke(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new La({...ke(this._def),innerType:this,catchValue:t,typeName:pe.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return vo.create(this,e)}readonly(){return qa.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const hk=/^c[^\s-]{8,}$/i,pk=/^[0-9a-z]+$/,mk=/^[0-9A-HJKMNP-TV-Z]{26}$/,yk=/^[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,gk=/^[a-z0-9_-]{21}$/i,vk=/^[-+]?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)?)??$/,bk=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,xk="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let ml;const _k=/^(?:(?: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])$/,wk=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,kk=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,$0="((\\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])))",Sk=new RegExp(`^${$0}$`);function D0(r){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`),e}function Ak(r){return new RegExp(`^${D0(r)}$`)}function Z0(r){let e=`${$0}T${D0(r)}`;const t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Ok(r,e){return!!((e==="v4"||!e)&&_k.test(r)||(e==="v6"||!e)&&wk.test(r))}class ar extends Ie{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==J.string){const i=this._getOrReturnCtx(e);return K(i,{code:M.invalid_type,expected:J.string,received:i.parsedType}),ye}const n=new vt;let s;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),K(s,{code:M.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),K(s,{code:M.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){const a=e.data.length>i.value,o=e.data.length<i.value;(a||o)&&(s=this._getOrReturnCtx(e,s),a?K(s,{code:M.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):o&&K(s,{code:M.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")bk.test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{validation:"email",code:M.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")ml||(ml=new RegExp(xk,"u")),ml.test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{validation:"emoji",code:M.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")yk.test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{validation:"uuid",code:M.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")gk.test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{validation:"nanoid",code:M.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")hk.test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{validation:"cuid",code:M.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")pk.test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{validation:"cuid2",code:M.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")mk.test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{validation:"ulid",code:M.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),K(s,{validation:"url",code:M.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{validation:"regex",code:M.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),K(s,{code:M.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),K(s,{code:M.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),K(s,{code:M.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?Z0(i).test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{code:M.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?Sk.test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{code:M.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?Ak(i).test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{code:M.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?vk.test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{validation:"duration",code:M.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?Ok(e.data,i.version)||(s=this._getOrReturnCtx(e,s),K(s,{validation:"ip",code:M.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?kk.test(e.data)||(s=this._getOrReturnCtx(e,s),K(s,{validation:"base64",code:M.invalid_string,message:i.message}),n.dirty()):$e.assertNever(i);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:M.invalid_string,...ce.errToObj(n)})}_addCheck(e){return new ar({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...ce.errToObj(e)})}url(e){return this._addCheck({kind:"url",...ce.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...ce.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...ce.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...ce.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...ce.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...ce.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...ce.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...ce.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...ce.errToObj(e)})}datetime(e){var t,n;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(t=e==null?void 0:e.offset)!==null&&t!==void 0?t:!1,local:(n=e==null?void 0:e.local)!==null&&n!==void 0?n:!1,...ce.errToObj(e==null?void 0: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==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...ce.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...ce.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...ce.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...ce.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...ce.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...ce.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...ce.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...ce.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...ce.errToObj(t)})}nonempty(e){return this.min(1,ce.errToObj(e))}trim(){return new ar({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ar({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ar({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}ar.create=r=>{var e;return new ar({checks:[],typeName:pe.ZodString,coerce:(e=r==null?void 0:r.coerce)!==null&&e!==void 0?e:!1,...ke(r)})};function Ek(r,e){const t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,i=parseInt(r.toFixed(s).replace(".","")),a=parseInt(e.toFixed(s).replace(".",""));return i%a/Math.pow(10,s)}class On extends Ie{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)!==J.number){const i=this._getOrReturnCtx(e);return K(i,{code:M.invalid_type,expected:J.number,received:i.parsedType}),ye}let n;const s=new vt;for(const i of this._def.checks)i.kind==="int"?$e.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{code:M.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),K(n,{code:M.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),K(n,{code:M.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Ek(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),K(n,{code:M.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),K(n,{code:M.not_finite,message:i.message}),s.dirty()):$e.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,ce.toString(t))}gt(e,t){return this.setLimit("min",e,!1,ce.toString(t))}lte(e,t){return this.setLimit("max",e,!0,ce.toString(t))}lt(e,t){return this.setLimit("max",e,!1,ce.toString(t))}setLimit(e,t,n,s){return new On({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:ce.toString(s)}]})}_addCheck(e){return new On({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:ce.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ce.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ce.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ce.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ce.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:ce.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:ce.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ce.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ce.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const 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"&&$e.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}}On.create=r=>new On({checks:[],typeName:pe.ZodNumber,coerce:(r==null?void 0:r.coerce)||!1,...ke(r)});class En extends Ie{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce&&(e.data=BigInt(e.data)),this._getType(e)!==J.bigint){const i=this._getOrReturnCtx(e);return K(i,{code:M.invalid_type,expected:J.bigint,received:i.parsedType}),ye}let n;const s=new vt;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),K(n,{code:M.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),K(n,{code:M.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),K(n,{code:M.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):$e.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,ce.toString(t))}gt(e,t){return this.setLimit("min",e,!1,ce.toString(t))}lte(e,t){return this.setLimit("max",e,!0,ce.toString(t))}lt(e,t){return this.setLimit("max",e,!1,ce.toString(t))}setLimit(e,t,n,s){return new En({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:ce.toString(s)}]})}_addCheck(e){return new En({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ce.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ce.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ce.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ce.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:ce.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}En.create=r=>{var e;return new En({checks:[],typeName:pe.ZodBigInt,coerce:(e=r==null?void 0:r.coerce)!==null&&e!==void 0?e:!1,...ke(r)})};class Na extends Ie{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==J.boolean){const n=this._getOrReturnCtx(e);return K(n,{code:M.invalid_type,expected:J.boolean,received:n.parsedType}),ye}return kt(e.data)}}Na.create=r=>new Na({typeName:pe.ZodBoolean,coerce:(r==null?void 0:r.coerce)||!1,...ke(r)});class ms extends Ie{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==J.date){const i=this._getOrReturnCtx(e);return K(i,{code:M.invalid_type,expected:J.date,received:i.parsedType}),ye}if(isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return K(i,{code:M.invalid_date}),ye}const n=new vt;let s;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),K(s,{code:M.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),K(s,{code:M.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):$e.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ms({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:ce.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:ce.toString(t)})}get minDate(){let e=null;for(const 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(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}ms.create=r=>new ms({checks:[],coerce:(r==null?void 0:r.coerce)||!1,typeName:pe.ZodDate,...ke(r)});class Jc extends Ie{_parse(e){if(this._getType(e)!==J.symbol){const n=this._getOrReturnCtx(e);return K(n,{code:M.invalid_type,expected:J.symbol,received:n.parsedType}),ye}return kt(e.data)}}Jc.create=r=>new Jc({typeName:pe.ZodSymbol,...ke(r)});class Ba extends Ie{_parse(e){if(this._getType(e)!==J.undefined){const n=this._getOrReturnCtx(e);return K(n,{code:M.invalid_type,expected:J.undefined,received:n.parsedType}),ye}return kt(e.data)}}Ba.create=r=>new Ba({typeName:pe.ZodUndefined,...ke(r)});class Ra extends Ie{_parse(e){if(this._getType(e)!==J.null){const n=this._getOrReturnCtx(e);return K(n,{code:M.invalid_type,expected:J.null,received:n.parsedType}),ye}return kt(e.data)}}Ra.create=r=>new Ra({typeName:pe.ZodNull,...ke(r)});class ii extends Ie{constructor(){super(...arguments),this._any=!0}_parse(e){return kt(e.data)}}ii.create=r=>new ii({typeName:pe.ZodAny,...ke(r)});class Xn extends Ie{constructor(){super(...arguments),this._unknown=!0}_parse(e){return kt(e.data)}}Xn.create=r=>new Xn({typeName:pe.ZodUnknown,...ke(r)});class Yr extends Ie{_parse(e){const t=this._getOrReturnCtx(e);return K(t,{code:M.invalid_type,expected:J.never,received:t.parsedType}),ye}}Yr.create=r=>new Yr({typeName:pe.ZodNever,...ke(r)});class Yc extends Ie{_parse(e){if(this._getType(e)!==J.undefined){const n=this._getOrReturnCtx(e);return K(n,{code:M.invalid_type,expected:J.void,received:n.parsedType}),ye}return kt(e.data)}}Yc.create=r=>new Yc({typeName:pe.ZodVoid,...ke(r)});class lr extends Ie{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==J.array)return K(t,{code:M.invalid_type,expected:J.array,received:t.parsedType}),ye;if(s.exactLength!==null){const a=t.data.length>s.exactLength.value,o=t.data.length<s.exactLength.value;(a||o)&&(K(t,{code:a?M.too_big:M.too_small,minimum:o?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(K(t,{code:M.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(K(t,{code:M.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((a,o)=>s.type._parseAsync(new Ir(t,a,t.path,o)))).then(a=>vt.mergeArray(n,a));const i=[...t.data].map((a,o)=>s.type._parseSync(new Ir(t,a,t.path,o)));return vt.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new lr({...this._def,minLength:{value:e,message:ce.toString(t)}})}max(e,t){return new lr({...this._def,maxLength:{value:e,message:ce.toString(t)}})}length(e,t){return new lr({...this._def,exactLength:{value:e,message:ce.toString(t)}})}nonempty(e){return this.min(1,e)}}lr.create=(r,e)=>new lr({type:r,minLength:null,maxLength:null,exactLength:null,typeName:pe.ZodArray,...ke(e)});function As(r){if(r instanceof Ye){const e={};for(const t in r.shape){const n=r.shape[t];e[t]=kr.create(As(n))}return new Ye({...r._def,shape:()=>e})}else return r instanceof lr?new lr({...r._def,type:As(r.element)}):r instanceof kr?kr.create(As(r.unwrap())):r instanceof Cn?Cn.create(As(r.unwrap())):r instanceof Cr?Cr.create(r.items.map(e=>As(e))):r}class Ye extends Ie{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=$e.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==J.object){const u=this._getOrReturnCtx(e);return K(u,{code:M.invalid_type,expected:J.object,received:u.parsedType}),ye}const{status:n,ctx:s}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof Yr&&this._def.unknownKeys==="strip"))for(const u in s.data)a.includes(u)||o.push(u);const c=[];for(const u of a){const f=i[u],y=s.data[u];c.push({key:{status:"valid",value:u},value:f._parse(new Ir(s,y,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof Yr){const u=this._def.unknownKeys;if(u==="passthrough")for(const f of o)c.push({key:{status:"valid",value:f},value:{status:"valid",value:s.data[f]}});else if(u==="strict")o.length>0&&(K(s,{code:M.unrecognized_keys,keys:o}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const f of o){const y=s.data[f];c.push({key:{status:"valid",value:f},value:u._parse(new Ir(s,y,s.path,f)),alwaysSet:f in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const u=[];for(const f of c){const y=await f.key,B=await f.value;u.push({key:y,value:B,alwaysSet:f.alwaysSet})}return u}).then(u=>vt.mergeObjectSync(n,u)):vt.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return ce.errToObj,new Ye({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{var s,i,a,o;const c=(a=(i=(s=this._def).errorMap)===null||i===void 0?void 0:i.call(s,t,n).message)!==null&&a!==void 0?a:n.defaultError;return t.code==="unrecognized_keys"?{message:(o=ce.errToObj(e).message)!==null&&o!==void 0?o:c}:{message:c}}}:{}})}strip(){return new Ye({...this._def,unknownKeys:"strip"})}passthrough(){return new Ye({...this._def,unknownKeys:"passthrough"})}extend(e){return new Ye({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Ye({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:pe.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new Ye({...this._def,catchall:e})}pick(e){const t={};return $e.objectKeys(e).forEach(n=>{e[n]&&this.shape[n]&&(t[n]=this.shape[n])}),new Ye({...this._def,shape:()=>t})}omit(e){const t={};return $e.objectKeys(this.shape).forEach(n=>{e[n]||(t[n]=this.shape[n])}),new Ye({...this._def,shape:()=>t})}deepPartial(){return As(this)}partial(e){const t={};return $e.objectKeys(this.shape).forEach(n=>{const s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}),new Ye({...this._def,shape:()=>t})}required(e){const t={};return $e.objectKeys(this.shape).forEach(n=>{if(e&&!e[n])t[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof kr;)i=i._def.innerType;t[n]=i}}),new Ye({...this._def,shape:()=>t})}keyof(){return M0($e.objectKeys(this.shape))}}Ye.create=(r,e)=>new Ye({shape:()=>r,unknownKeys:"strip",catchall:Yr.create(),typeName:pe.ZodObject,...ke(e)});Ye.strictCreate=(r,e)=>new Ye({shape:()=>r,unknownKeys:"strict",catchall:Yr.create(),typeName:pe.ZodObject,...ke(e)});Ye.lazycreate=(r,e)=>new Ye({shape:r,unknownKeys:"strip",catchall:Yr.create(),typeName:pe.ZodObject,...ke(e)});class Pa extends Ie{_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;function s(i){for(const o of i)if(o.result.status==="valid")return o.result;for(const o of i)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;const a=i.map(o=>new Zt(o.ctx.common.issues));return K(t,{code:M.invalid_union,unionErrors:a}),ye}if(t.common.async)return Promise.all(n.map(async i=>{const a={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(s);{let i;const a=[];for(const c of n){const u={...t,common:{...t.common,issues:[]},parent:null},f=c._parseSync({data:t.data,path:t.path,parent:u});if(f.status==="valid")return f;f.status==="dirty"&&!i&&(i={result:f,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;const o=a.map(c=>new Zt(c));return K(t,{code:M.invalid_union,unionErrors:o}),ye}}get options(){return this._def.options}}Pa.create=(r,e)=>new Pa({options:r,typeName:pe.ZodUnion,...ke(e)});const Rr=r=>r instanceof Za?Rr(r.schema):r instanceof hr?Rr(r.innerType()):r instanceof Ma?[r.value]:r instanceof In?r.options:r instanceof Ua?$e.objectValues(r.enum):r instanceof Va?Rr(r._def.innerType):r instanceof Ba?[void 0]:r instanceof Ra?[null]:r instanceof kr?[void 0,...Rr(r.unwrap())]:r instanceof Cn?[null,...Rr(r.unwrap())]:r instanceof oh||r instanceof qa?Rr(r.unwrap()):r instanceof La?Rr(r._def.innerType):[];class zu extends Ie{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==J.object)return K(t,{code:M.invalid_type,expected:J.object,received:t.parsedType}),ye;const n=this.discriminator,s=t.data[n],i=this.optionsMap.get(s);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(K(t,{code:M.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),ye)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){const s=new Map;for(const i of t){const a=Rr(i.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const o of a){if(s.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);s.set(o,i)}}return new zu({typeName:pe.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...ke(n)})}}function sf(r,e){const t=on(r),n=on(e);if(r===e)return{valid:!0,data:r};if(t===J.object&&n===J.object){const s=$e.objectKeys(e),i=$e.objectKeys(r).filter(o=>s.indexOf(o)!==-1),a={...r,...e};for(const o of i){const c=sf(r[o],e[o]);if(!c.valid)return{valid:!1};a[o]=c.data}return{valid:!0,data:a}}else if(t===J.array&&n===J.array){if(r.length!==e.length)return{valid:!1};const s=[];for(let i=0;i<r.length;i++){const a=r[i],o=e[i],c=sf(a,o);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return t===J.date&&n===J.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}class $a extends Ie{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),s=(i,a)=>{if(rf(i)||rf(a))return ye;const o=sf(i.value,a.value);return o.valid?((nf(i)||nf(a))&&t.dirty(),{status:t.value,value:o.data}):(K(n,{code:M.invalid_intersection_types}),ye)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,a])=>s(i,a)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}$a.create=(r,e,t)=>new $a({left:r,right:e,typeName:pe.ZodIntersection,...ke(t)});class Cr extends Ie{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==J.array)return K(n,{code:M.invalid_type,expected:J.array,received:n.parsedType}),ye;if(n.data.length<this._def.items.length)return K(n,{code:M.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ye;!this._def.rest&&n.data.length>this._def.items.length&&(K(n,{code:M.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const i=[...n.data].map((a,o)=>{const c=this._def.items[o]||this._def.rest;return c?c._parse(new Ir(n,a,n.path,o)):null}).filter(a=>!!a);return n.common.async?Promise.all(i).then(a=>vt.mergeArray(t,a)):vt.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new Cr({...this._def,rest:e})}}Cr.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Cr({items:r,typeName:pe.ZodTuple,rest:null,...ke(e)})};class Da extends Ie{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==J.object)return K(n,{code:M.invalid_type,expected:J.object,received:n.parsedType}),ye;const s=[],i=this._def.keyType,a=this._def.valueType;for(const o in n.data)s.push({key:i._parse(new Ir(n,o,n.path,o)),value:a._parse(new Ir(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?vt.mergeObjectAsync(t,s):vt.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof Ie?new Da({keyType:e,valueType:t,typeName:pe.ZodRecord,...ke(n)}):new Da({keyType:ar.create(),valueType:e,typeName:pe.ZodRecord,...ke(t)})}}class Xc extends Ie{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==J.map)return K(n,{code:M.invalid_type,expected:J.map,received:n.parsedType}),ye;const s=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([o,c],u)=>({key:s._parse(new Ir(n,o,n.path,[u,"key"])),value:i._parse(new Ir(n,c,n.path,[u,"value"]))}));if(n.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const c of a){const u=await c.key,f=await c.value;if(u.status==="aborted"||f.status==="aborted")return ye;(u.status==="dirty"||f.status==="dirty")&&t.dirty(),o.set(u.value,f.value)}return{status:t.value,value:o}})}else{const o=new Map;for(const c of a){const u=c.key,f=c.value;if(u.status==="aborted"||f.status==="aborted")return ye;(u.status==="dirty"||f.status==="dirty")&&t.dirty(),o.set(u.value,f.value)}return{status:t.value,value:o}}}}Xc.create=(r,e,t)=>new Xc({valueType:e,keyType:r,typeName:pe.ZodMap,...ke(t)});class ys extends Ie{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==J.set)return K(n,{code:M.invalid_type,expected:J.set,received:n.parsedType}),ye;const s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(K(n,{code:M.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(K(n,{code:M.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const i=this._def.valueType;function a(c){const u=new Set;for(const f of c){if(f.status==="aborted")return ye;f.status==="dirty"&&t.dirty(),u.add(f.value)}return{status:t.value,value:u}}const o=[...n.data.values()].map((c,u)=>i._parse(new Ir(n,c,n.path,u)));return n.common.async?Promise.all(o).then(c=>a(c)):a(o)}min(e,t){return new ys({...this._def,minSize:{value:e,message:ce.toString(t)}})}max(e,t){return new ys({...this._def,maxSize:{value:e,message:ce.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ys.create=(r,e)=>new ys({valueType:r,minSize:null,maxSize:null,typeName:pe.ZodSet,...ke(e)});class Ps extends Ie{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==J.function)return K(t,{code:M.invalid_type,expected:J.function,received:t.parsedType}),ye;function n(o,c){return zc({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Wc(),si].filter(u=>!!u),issueData:{code:M.invalid_arguments,argumentsError:c}})}function s(o,c){return zc({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Wc(),si].filter(u=>!!u),issueData:{code:M.invalid_return_type,returnTypeError:c}})}const i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof ai){const o=this;return kt(async function(...c){const u=new Zt([]),f=await o._def.args.parseAsync(c,i).catch(C=>{throw u.addIssue(n(c,C)),u}),y=await Reflect.apply(a,this,f);return await o._def.returns._def.type.parseAsync(y,i).catch(C=>{throw u.addIssue(s(y,C)),u})})}else{const o=this;return kt(function(...c){const u=o._def.args.safeParse(c,i);if(!u.success)throw new Zt([n(c,u.error)]);const f=Reflect.apply(a,this,u.data),y=o._def.returns.safeParse(f,i);if(!y.success)throw new Zt([s(f,y.error)]);return y.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new Ps({...this._def,args:Cr.create(e).rest(Xn.create())})}returns(e){return new Ps({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new Ps({args:e||Cr.create([]).rest(Xn.create()),returns:t||Xn.create(),typeName:pe.ZodFunction,...ke(n)})}}class Za extends Ie{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Za.create=(r,e)=>new Za({getter:r,typeName:pe.ZodLazy,...ke(e)});class Ma extends Ie{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return K(t,{received:t.data,code:M.invalid_literal,expected:this._def.value}),ye}return{status:"valid",value:e.data}}get value(){return this._def.value}}Ma.create=(r,e)=>new Ma({value:r,typeName:pe.ZodLiteral,...ke(e)});function M0(r,e){return new In({values:r,typeName:pe.ZodEnum,...ke(e)})}class In extends Ie{constructor(){super(...arguments),Ni.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),n=this._def.values;return K(t,{expected:$e.joinValues(n),received:t.parsedType,code:M.invalid_type}),ye}if(Gc(this,Ni)||P0(this,Ni,new Set(this._def.values)),!Gc(this,Ni).has(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return K(t,{received:t.data,code:M.invalid_enum_value,options:n}),ye}return kt(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return In.create(e,{...this._def,...t})}exclude(e,t=this._def){return In.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}}Ni=new WeakMap;In.create=M0;class Ua extends Ie{constructor(){super(...arguments),Bi.set(this,void 0)}_parse(e){const t=$e.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==J.string&&n.parsedType!==J.number){const s=$e.objectValues(t);return K(n,{expected:$e.joinValues(s),received:n.parsedType,code:M.invalid_type}),ye}if(Gc(this,Bi)||P0(this,Bi,new Set($e.getValidEnumValues(this._def.values))),!Gc(this,Bi).has(e.data)){const s=$e.objectValues(t);return K(n,{received:n.data,code:M.invalid_enum_value,options:s}),ye}return kt(e.data)}get enum(){return this._def.values}}Bi=new WeakMap;Ua.create=(r,e)=>new Ua({values:r,typeName:pe.ZodNativeEnum,...ke(e)});class ai extends Ie{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==J.promise&&t.common.async===!1)return K(t,{code:M.invalid_type,expected:J.promise,received:t.parsedType}),ye;const n=t.parsedType===J.promise?t.data:Promise.resolve(t.data);return kt(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}}ai.create=(r,e)=>new ai({type:r,typeName:pe.ZodPromise,...ke(e)});class hr extends Ie{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===pe.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:a=>{K(n,a),a.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){const a=s.transform(n.data,i);if(n.common.async)return Promise.resolve(a).then(async o=>{if(t.value==="aborted")return ye;const c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?ye:c.status==="dirty"||t.value==="dirty"?Cs(c.value):c});{if(t.value==="aborted")return ye;const o=this._def.schema._parseSync({data:a,path:n.path,parent:n});return o.status==="aborted"?ye:o.status==="dirty"||t.value==="dirty"?Cs(o.value):o}}if(s.type==="refinement"){const a=o=>{const c=s.refinement(o,i);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){const o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?ye:(o.status==="dirty"&&t.dirty(),a(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?ye:(o.status==="dirty"&&t.dirty(),a(o.value).then(()=>({status:t.value,value:o.value}))))}if(s.type==="transform")if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!ja(a))return a;const o=s.transform(a.value,i);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:n.data,path:n.path,parent:n}).then(a=>ja(a)?Promise.resolve(s.transform(a.value,i)).then(o=>({status:t.value,value:o})):a);$e.assertNever(s)}}hr.create=(r,e,t)=>new hr({schema:r,typeName:pe.ZodEffects,effect:e,...ke(t)});hr.createWithPreprocess=(r,e,t)=>new hr({schema:e,effect:{type:"preprocess",transform:r},typeName:pe.ZodEffects,...ke(t)});class kr extends Ie{_parse(e){return this._getType(e)===J.undefined?kt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}kr.create=(r,e)=>new kr({innerType:r,typeName:pe.ZodOptional,...ke(e)});class Cn extends Ie{_parse(e){return this._getType(e)===J.null?kt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Cn.create=(r,e)=>new Cn({innerType:r,typeName:pe.ZodNullable,...ke(e)});class Va extends Ie{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===J.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Va.create=(r,e)=>new Va({innerType:r,typeName:pe.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ke(e)});class La extends Ie{_parse(e){const{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Ta(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Zt(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Zt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}La.create=(r,e)=>new La({innerType:r,typeName:pe.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ke(e)});class Qc extends Ie{_parse(e){if(this._getType(e)!==J.nan){const n=this._getOrReturnCtx(e);return K(n,{code:M.invalid_type,expected:J.nan,received:n.parsedType}),ye}return{status:"valid",value:e.data}}}Qc.create=r=>new Qc({typeName:pe.ZodNaN,...ke(r)});const Ik=Symbol("zod_brand");class oh extends Ie{_parse(e){const{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class vo extends Ie{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?ye:i.status==="dirty"?(t.dirty(),Cs(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{const s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?ye:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new vo({in:e,out:t,typeName:pe.ZodPipeline})}}class qa extends Ie{_parse(e){const t=this._def.innerType._parse(e),n=s=>(ja(s)&&(s.value=Object.freeze(s.value)),s);return Ta(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}}qa.create=(r,e)=>new qa({innerType:r,typeName:pe.ZodReadonly,...ke(e)});function U0(r,e={},t){return r?ii.create().superRefine((n,s)=>{var i,a;if(!r(n)){const o=typeof e=="function"?e(n):typeof e=="string"?{message:e}:e,c=(a=(i=o.fatal)!==null&&i!==void 0?i:t)!==null&&a!==void 0?a:!0,u=typeof o=="string"?{message:o}:o;s.addIssue({code:"custom",...u,fatal:c})}}):ii.create()}const Ck={object:Ye.lazycreate};var pe;(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"})(pe||(pe={}));const jk=(r,e={message:`Input not instance of ${r.name}`})=>U0(t=>t instanceof r,e),V0=ar.create,L0=On.create,Tk=Qc.create,Nk=En.create,q0=Na.create,Bk=ms.create,Rk=Jc.create,Pk=Ba.create,$k=Ra.create,Dk=ii.create,Zk=Xn.create,Mk=Yr.create,Uk=Yc.create,Vk=lr.create,Lk=Ye.create,qk=Ye.strictCreate,Hk=Pa.create,Fk=zu.create,Kk=$a.create,Wk=Cr.create,zk=Da.create,Gk=Xc.create,Jk=ys.create,Yk=Ps.create,Xk=Za.create,Qk=Ma.create,eS=In.create,tS=Ua.create,rS=ai.create,dm=hr.create,nS=kr.create,sS=Cn.create,iS=hr.createWithPreprocess,aS=vo.create,oS=()=>V0().optional(),cS=()=>L0().optional(),uS=()=>q0().optional(),lS={string:r=>ar.create({...r,coerce:!0}),number:r=>On.create({...r,coerce:!0}),boolean:r=>Na.create({...r,coerce:!0}),bigint:r=>En.create({...r,coerce:!0}),date:r=>ms.create({...r,coerce:!0})},dS=ye;var Lt=Object.freeze({__proto__:null,defaultErrorMap:si,setErrorMap:dk,getErrorMap:Wc,makeIssue:zc,EMPTY_PATH:fk,addIssueToContext:K,ParseStatus:vt,INVALID:ye,DIRTY:Cs,OK:kt,isAborted:rf,isDirty:nf,isValid:ja,isAsync:Ta,get util(){return $e},get objectUtil(){return tf},ZodParsedType:J,getParsedType:on,ZodType:Ie,datetimeRegex:Z0,ZodString:ar,ZodNumber:On,ZodBigInt:En,ZodBoolean:Na,ZodDate:ms,ZodSymbol:Jc,ZodUndefined:Ba,ZodNull:Ra,ZodAny:ii,ZodUnknown:Xn,ZodNever:Yr,ZodVoid:Yc,ZodArray:lr,ZodObject:Ye,ZodUnion:Pa,ZodDiscriminatedUnion:zu,ZodIntersection:$a,ZodTuple:Cr,ZodRecord:Da,ZodMap:Xc,ZodSet:ys,ZodFunction:Ps,ZodLazy:Za,ZodLiteral:Ma,ZodEnum:In,ZodNativeEnum:Ua,ZodPromise:ai,ZodEffects:hr,ZodTransformer:hr,ZodOptional:kr,ZodNullable:Cn,ZodDefault:Va,ZodCatch:La,ZodNaN:Qc,BRAND:Ik,ZodBranded:oh,ZodPipeline:vo,ZodReadonly:qa,custom:U0,Schema:Ie,ZodSchema:Ie,late:Ck,get ZodFirstPartyTypeKind(){return pe},coerce:lS,any:Dk,array:Vk,bigint:Nk,boolean:q0,date:Bk,discriminatedUnion:Fk,effect:dm,enum:eS,function:Yk,instanceof:jk,intersection:Kk,lazy:Xk,literal:Qk,map:Gk,nan:Tk,nativeEnum:tS,never:Mk,null:$k,nullable:sS,number:L0,object:Lk,oboolean:uS,onumber:cS,optional:nS,ostring:oS,pipeline:aS,preprocess:iS,promise:rS,record:zk,set:Jk,strictObject:qk,string:V0,symbol:Rk,transformer:dm,tuple:Wk,undefined:Pk,union:Hk,unknown:Zk,void:Uk,NEVER:dS,ZodIssueCode:M,quotelessJson:lk,ZodError:Zt});Lt.object({start:Lt.number(),limit:Lt.number(),length:Lt.number()});su.extend({email:Lt.string(),login_count:Lt.number(),multifactor:Lt.array(Lt.string()).optional(),last_ip:Lt.string().optional(),last_login:Lt.string().optional(),user_id:Lt.string()}).catchall(Lt.any());const fS=jn.extend({tenants:m.array(Ns)}),hS=new ut().openapi(ge({tags:["tenants"],method:"get",path:"/",request:{query:rs},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"tenant/json":{schema:m.union([m.array(Ns),fS])}},description:"List of tenants"}}}),async r=>{const{page:e,per_page:t,include_totals:n,sort:s,q:i}=r.req.valid("query"),a=await r.env.data.tenants.list({page:e,per_page:t,include_totals:n,sort:ci(s),q:i});return n?r.json(a):r.json(a.tenants)}).openapi(ge({tags:["tenants"],method:"get",path:"/{id}",request:{params:m.object({id:m.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"tenant/json":{schema:Ns}},description:"A tenant"}}}),async r=>{const{id:e}=r.req.valid("param"),t=await r.env.data.tenants.get(e);if(!t)throw new de(404);return r.json(t)}).openapi(ge({tags:["tenants"],method:"delete",path:"/{id}",request:{params:m.object({id:m.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async r=>{const{id:e}=r.req.valid("param");return await r.env.data.tenants.remove(e),r.text("OK")}).openapi(ge({tags:["tenants"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:m.object(oc.shape).partial()}}},params:m.object({id:m.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async r=>{const{id:e}=r.req.valid("param"),t=r.req.valid("json");return await r.env.data.tenants.update(e,t),r.text("OK")}).openapi(ge({tags:["tenants"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:m.object(oc.shape)}}}},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"tenant/json":{schema:Ns}},description:"An tenant"}}}),async r=>{const e=r.req.valid("json"),t=await r.env.data.tenants.create(e);return r.json(t,{status:201})}),pS=jn.extend({logs:m.array(uc)}),mS=new ut().openapi(ge({tags:["logs"],method:"get",path:"/",request:{query:rs,headers:m.object({"tenant-id":m.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:m.union([m.array(uc),pS])}},description:"List of log rows"}}}),async r=>{const{page:e,per_page:t,include_totals:n,sort:s,q:i}=r.req.valid("query"),{"tenant-id":a}=r.req.valid("header"),o=await r.env.data.logs.list(a,{page:e,per_page:t,include_totals:n,sort:ci(s),q:i});return n?r.json(o):r.json(o.logs)}).openapi(ge({tags:["logs"],method:"get",path:"/{id}",request:{headers:m.object({"tenant-id":m.string()}),params:m.object({id:m.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:uc}},description:"A log entry"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),{id:t}=r.req.valid("param"),n=await r.env.data.logs.get(e,t);if(!n)throw new de(404);return r.json(n)}),yS=jn.extend({hooks:m.array(Es)}),gS=new ut().openapi(ge({tags:["hooks"],method:"get",path:"/",request:{query:rs,headers:m.object({"tenant-id":m.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:m.union([m.array(Es),yS])}},description:"List of hooks"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),{page:t,per_page:n,include_totals:s,sort:i,q:a}=r.req.valid("query"),o=await r.env.data.hooks.list(e,{page:t,per_page:n,include_totals:s,sort:ci(i),q:a});return s?r.json(o):r.json(o.hooks)}).openapi(ge({tags:["hooks"],method:"post",path:"/",request:{headers:m.object({"tenant-id":m.string()}),body:{content:{"application/json":{schema:m.object(cc.shape)}}}},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:Es}},description:"The created hook"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),t=r.req.valid("json"),n=await r.env.data.hooks.create(e,t);return r.json(n,{status:201})}).openapi(ge({tags:["hooks"],method:"patch",path:"/{hook_id}",request:{headers:m.object({"tenant-id":m.string()}),params:m.object({hook_id:m.string()}),body:{content:{"application/json":{schema:m.object(cc.shape).omit({hook_id:!0}).partial()}}}},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:Es.shape}},description:"The updated hook"},404:{description:"Hook not found"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),{hook_id:t}=r.req.valid("param"),n=r.req.valid("json");await r.env.data.hooks.update(e,t,n);const s=await r.env.data.hooks.get(e,t);if(!s)throw new de(404,{message:"Hook not found"});return r.json(s)}).openapi(ge({tags:["hooks"],method:"get",path:"/{hook_id}",request:{headers:m.object({"tenant-id":m.string()}),params:m.object({hook_id:m.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Es}},description:"A hook"},404:{description:"Hook not found"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),{hook_id:t}=r.req.valid("param"),n=await r.env.data.hooks.get(e,t);if(!n)throw new de(404,{message:"Hook not found"});return r.json(n)}).openapi(ge({tags:["hooks"],method:"delete",path:"/{hook_id}",request:{headers:m.object({"tenant-id":m.string()}),params:m.object({hook_id:m.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{description:"A hook"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),{hook_id:t}=r.req.valid("param");if(!await r.env.data.hooks.remove(e,t))throw new de(404,{message:"Hook not found"});return r.text("OK")}),vS=jn.extend({connections:m.array(Un)}),bS=new ut().openapi(ge({tags:["connections"],method:"get",path:"/",request:{query:rs,headers:m.object({"tenant-id":m.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:m.union([m.array(Un),vS])}},description:"List of connectionss"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),{page:t,per_page:n,include_totals:s=!1,sort:i,q:a}=r.req.valid("query"),o=await r.env.data.connections.list(e,{page:t,per_page:n,include_totals:s,sort:ci(i),q:a});return s?r.json(o):r.json(o.connections)}).openapi(ge({tags:["connections"],method:"get",path:"/{id}",request:{params:m.object({id:m.string()}),headers:m.object({"tenant-id":m.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Un}},description:"A connection"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),{id:t}=r.req.valid("param"),n=await r.env.data.connections.get(e,t);if(!n)throw new de(404);return r.json(n)}).openapi(ge({tags:["connections"],method:"delete",path:"/{id}",request:{params:m.object({id:m.string()}),headers:m.object({"tenant-id":m.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),{id:t}=r.req.valid("param");if(!await r.env.data.connections.remove(e,t))throw new de(404,{message:"Connection not found"});return r.text("OK")}).openapi(ge({tags:["connections"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:m.object(ac.shape).partial()}}},params:m.object({id:m.string()}),headers:m.object({"tenant-id":m.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:Un}},description:"The updated connection"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),{id:t}=r.req.valid("param"),n=r.req.valid("json");if(!await r.env.data.connections.update(e,t,n))throw new de(404,{message:"Connection not found"});const i=await r.env.data.connections.get(e,t);if(!i)throw new de(404,{message:"Connection not found"});return r.json(i)}).openapi(ge({tags:["connections"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:m.object(ac.shape)}}},headers:m.object({"tenant-id":m.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:Un}},description:"A connection"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),t=r.req.valid("json"),n=await r.env.data.connections.create(e,t);return r.json(n,{status:201})}),xS=new ut().openapi(ge({tags:["prompts"],method:"get",path:"/",request:{headers:m.object({"tenant-id":m.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:To}},description:"Branding settings"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),t=await r.env.data.promptSettings.get(e);return t?r.json(t):r.json(To.parse({}))}).openapi(ge({tags:["prompts"],method:"patch",path:"/",request:{headers:m.object({"tenant-id":m.string()}),body:{content:{"application/json":{schema:m.object(To.shape).partial()}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Prompts settings"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),t=r.req.valid("json"),n=await r.env.data.promptSettings.get(e);return Object.assign(n,t),await r.env.data.promptSettings.set(e,n),r.json(n)});let fm=!1;function H0(r){r.use(async(e,t)=>(fm||(r.openAPIRegistry.registerComponent("securitySchemes","Bearer",{type:"oauth2",scheme:"bearer",flows:{implicit:{authorizationUrl:`${e.env.AUTH_URL}/authorize`,scopes:{openid:"Basic user information",email:"User email",profile:"User profile information"}}}}),fm=!0),await t()))}m.object({alg:m.literal("RS256"),kty:m.literal("RSA"),use:m.literal("sig"),n:m.string(),e:m.string(),kid:m.string(),x5t:m.string(),x5c:m.array(m.string())});async function _S(r){try{const e=await r.JWKS_SERVICE.fetch(r.JWKS_URL);if(!e.ok)throw new Error("Failed to fetch jwks");return(await e.json()).keys}catch(e){throw new de(500,{message:`Failed to fetch jwks: ${e.message}`})}}async function wS(r,e){const n=new TextEncoder().encode([e.raw.header,e.raw.payload].join(".")),s=new Uint8Array(Array.from(e.signature).map(c=>c.charCodeAt(0))),a=(await _S(r.env)).find(c=>c.kid===e.header.kid);if(!a)return console.log("No matching kid found"),!1;const o=await crypto.subtle.importKey("jwk",a,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);return crypto.subtle.verify("RSASSA-PKCS1-v1_5",o,s,n)}function kS(r){const[e,t,n]=r.split(".");if(!e||!t||!n)return null;const s=JSON.parse(atob(e)),i=JSON.parse(atob(t)),a=atob(n.replace(/-/g,"+").replace(/_/g,"/"));return{header:s,payload:i,signature:a,raw:{header:e,payload:t,signature:n}}}function F0(r){return async(e,t)=>{var s,i,a;const n=r.openAPIRegistry.definitions.find(o=>"route"in o&&o.route.path===e.req.path&&o.route.method.toUpperCase()===e.req.method);if(n&&"route"in n){const o=(i=(s=n.route.security)==null?void 0:s[0])==null?void 0:i.Bearer;if(!(o!=null&&o.length))return await t();const c=e.req.header("authorization")||"",[u,f]=c.split(" ");if((u==null?void 0:u.toLowerCase())!=="bearer"||!f)throw new de(401,{message:"Missing bearer token"});const y=kS(f);if(!y||!await wS(e,y))throw new de(403,{message:"Invalid JWT signature"});e.set("user_id",y.payload.sub),e.set("user",y.payload);const B=y.payload.permissions||[],C=((a=y.payload.scope)==null?void 0:a.split(" "))||[];if(o.length&&!(o.some(p=>B.includes(p))||o.some(p=>C.includes(p))))throw new de(403,{message:"Unauthorized"})}return await t()}}const SS=new ut().openapi(ge({tags:["emails"],method:"get",path:"/",request:{headers:m.object({"tenant-id":m.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:No}},description:"Email provider"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),t=await r.env.data.emailProviders.get(e);if(!t)throw new de(404,{message:"Email provider not found"});return r.json(t)}).openapi(ge({tags:["emails"],method:"post",path:"/",request:{headers:m.object({"tenant-id":m.string()}),body:{content:{"application/json":{schema:m.object(No.shape)}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Branding settings"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),t=r.req.valid("json");return await r.env.data.emailProviders.create(e,t),r.text("OK",{status:201})}).openapi(ge({tags:["emails"],method:"patch",path:"/",request:{headers:m.object({"tenant-id":m.string()}),body:{content:{"application/json":{schema:m.object(No.shape).partial()}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Branding settings"}}}),async r=>{const{"tenant-id":e}=r.req.valid("header"),t=r.req.valid("json");return await r.env.data.emailProviders.update(e,t),r.text("OK")});function AS(){const r=new ut;r.use(F0(r));const e=r.route("/branding",M_).route("/email/providers",SS).route("/users",aw).route("/keys",ak).route("/users-by-email",ok).route("/clients",uk).route("/tenants",hS).route("/logs",mS).route("/hooks",gS).route("/connections",bS).route("/prompts",xS);return H0(e),e.doc("/spec",{openapi:"3.0.0",info:{version:"1.0.0",title:"Management api"}}),e}const Ao=60*5,K0=30*24*60*60,OS="auth-token",ES=new ut().openapi(ge({tags:["well known"],method:"get",path:"/jwks.json",request:{},responses:{200:{content:{"application/json":{schema:Iy}},description:"List of tenants"}}}),async r=>{const e=await r.env.data.keys.list(),t=await Promise.all(e.map(async n=>{const i=await new ah(n.cert).publicKey.export(),a=await crypto.subtle.exportKey("jwk",i);return mf.parse({...a,kid:n.kid})}));return r.json({keys:t},{headers:{"access-control-allow-origin":"*","access-control-allow-method":"GET","cache-control":`public, max-age=${Ao}, stale-while-revalidate=${Ao*2}, stale-if-error=86400`}})}).openapi(ge({tags:["well known"],method:"get",path:"/openid-configuration",request:{},responses:{200:{content:{"application/json":{schema:Rl}},description:"List of tenants"}}}),async r=>{const e=r.env.ISSUER,t=Rl.parse({issuer:e,authorization_endpoint:`${e}authorize`,token_endpoint:`${e}oauth/token`,device_authorization_endpoint:`${e}oauth/device/code`,userinfo_endpoint:`${e}userinfo`,mfa_challenge_endpoint:`${e}mfa/challenge`,jwks_uri:`${e}.well-known/jwks.json`,registration_endpoint:`${e}oidc/register`,revocation_endpoint:`${e}oauth/revoke`,scopes_supported:["openid","profile","offline_access","name","given_name","family_name","nickname","email","email_verified","picture","created_at","identities","phone","address"],response_types_supported:["code","token","id_token","code token","code id_token","token id_token","code token id_token"],code_challenge_methods_supported:["S256","plain"],response_modes_supported:["query","fragment","form_post"],subject_types_supported:["public"],id_token_signing_alg_values_supported:["RS256"],token_endpoint_auth_methods_supported:["client_secret_basic","client_secret_post"],claims_supported:["aud","auth_time","created_at","email","email_verified","exp","family_name","given_name","iat","identities","iss","name","nickname","phone_number","picture","sub"],request_uri_parameter_supported:!1,request_parameter_supported:!1,token_endpoint_auth_signing_alg_values_supported:["RS256","RS384","PS256"]});return r.json(t,{headers:{"access-control-allow-origin":"*","access-control-allow-method":"GET","cache-control":`public, max-age=${Ao}, stale-while-revalidate=${Ao*2}, stale-if-error=86400`}})});class eu{constructor(e,t){ne(this,"value");ne(this,"unit");this.value=e,this.unit=t}milliseconds(){return this.unit==="ms"?this.value:this.unit==="s"?this.value*1e3:this.unit==="m"?this.value*1e3*60:this.unit==="h"?this.value*1e3*60*60:this.unit==="d"?this.value*1e3*60*60*24:this.value*1e3*60*60*24*7}seconds(){return this.milliseconds()/1e3}transform(e){return new eu(Math.round(this.milliseconds()*e),"ms")}}async function hm(r,e,t,n){const s={alg:r,typ:"JWT",...n==null?void 0:n.headers},i={...t};(n==null?void 0:n.audiences)!==void 0&&(i.aud=n.audiences),(n==null?void 0:n.subject)!==void 0&&(i.sub=n.subject),(n==null?void 0:n.issuer)!==void 0&&(i.iss=n.issuer),(n==null?void 0:n.jwtId)!==void 0&&(i.jti=n.jwtId),(n==null?void 0:n.expiresIn)!==void 0&&(i.exp=Math.floor(Date.now()/1e3)+n.expiresIn.seconds()),(n==null?void 0:n.notBefore)!==void 0&&(i.nbf=Math.floor(n.notBefore.getTime()/1e3)),(n==null?void 0:n.includeIssuedTimestamp)===!0&&(i.iat=Math.floor(Date.now()/1e3));const a=new TextEncoder,o=Do.encode(a.encode(JSON.stringify(s)),{includePadding:!1}),c=Do.encode(a.encode(JSON.stringify(i)),{includePadding:!1}),u=a.encode([o,c].join(".")),f=await IS(r).sign(e,u),y=Do.encode(new Uint8Array(f),{includePadding:!1});return[o,c,y].join(".")}function IS(r){return new rk(CS[r])}const CS={RS256:"SHA-256",RS384:"SHA-384",RS512:"SHA-512"};function jS(r){try{const t=/-----BEGIN (?:RSA )?(?:PRIVATE|PUBLIC) KEY-----([^-]*)-----END (?:RSA )?(?:PRIVATE|PUBLIC) KEY-----/.exec(r);if(!t||!t[1])throw new Error("Invalid PEM format");return Uint8Array.from(atob(t[1].replace(/\s/g,"")),n=>n.charCodeAt(0)).buffer}finally{r=r.replace(/./g,"\0")}}async function TS(r,e){if(e==="plain")return r;const t=new TextEncoder().encode(r),n=await B0(t);return Do.encode(new Uint8Array(n))}async function W0(r,e){var y;const{authParams:t,user:n,sid:s}=e,a=(await r.env.data.keys.list()).filter(B=>!B.revoked_at||new Date(B.revoked_at)>new Date),o=a[a.length-1];if(!(o!=null&&o.pkcs7))throw new de(500,{message:"No signing key available"});const c=jS(o.pkcs7),u=await hm("RS256",c,{aud:t.audience||"default",scope:t.scope||"",sub:(n==null?void 0:n.user_id)||t.client_id,iss:r.env.ISSUER,tenant_id:r.var.tenant_id,sid:s},{includeIssuedTimestamp:!0,expiresIn:new eu(1,"d"),headers:{kid:o.kid}}),f=n&&((y=t.scope)!=null&&y.split(" ").includes("openid"))?await hm("RS256",c,{aud:t.client_id,sub:n.user_id,iss:r.env.ISSUER,sid:s,nonce:t.nonce,given_name:n.given_name,family_name:n.family_name,nickname:n.nickname,picture:n.picture,locale:n.locale,name:n.name,email:n.email,email_verified:n.email_verified},{includeIssuedTimestamp:!0,expiresIn:new eu(1,"d"),headers:{kid:o.kid}}):void 0;return{access_token:u,id_token:f,token_type:"Bearer",expires_in:86400}}function Zo(r,e){if(!r||!e||r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r.charCodeAt(n)^e.charCodeAt(n);return t===0}const z0=m.object({grant_type:m.literal("client_credentials"),scope:m.string().optional(),client_secret:m.string(),client_id:m.string(),audience:m.string().optional()});async function NS(r,e){const t=await r.env.data.clients.get(e.client_id);if(!t)throw new de(403,{message:"Invalid client credentials"});if(t.client_secret&&!Zo(t.client_secret,e.client_secret))throw new de(403,{message:"Invalid client credentials"});const n={client_id:t.id,scope:e.scope,audience:e.audience},s=await W0(r,{authParams:n});return r.json(s)}function G0(r,e,t){const n=[];return n.push([encodeURIComponent(r),encodeURIComponent(e)]),(t==null?void 0:t.domain)!==void 0&&n.push(["Domain",t.domain]),(t==null?void 0:t.expires)!==void 0&&n.push(["Expires",t.expires.toUTCString()]),t!=null&&t.httpOnly&&n.push(["HttpOnly"]),(t==null?void 0:t.maxAge)!==void 0&&n.push(["Max-Age",t.maxAge.toString()]),(t==null?void 0:t.path)!==void 0&&n.push(["Path",t.path]),(t==null?void 0:t.sameSite)==="lax"&&n.push(["SameSite","Lax"]),(t==null?void 0:t.sameSite)==="none"&&n.push(["SameSite","None"]),(t==null?void 0:t.sameSite)==="strict"&&n.push(["SameSite","Strict"]),t!=null&&t.secure&&n.push(["Secure"]),n.map(s=>s.join("=")).join("; ")}function BS(r){const e=new Map,t=r.split("; ");for(const n of t){const s=n.split("="),i=s[0],a=s[1]??"";i&&e.set(decodeURIComponent(i),decodeURIComponent(a))}return e}function ch(r){return`${r}-${OS}`}function RS(r,e){return e?BS(e).get(ch(r)):void 0}function PS(r){const e={path:"/",httpOnly:!0,secure:!0,maxAge:0};return G0(ch(r),"",{...e,sameSite:"none"})}function $S(r,e){const t={path:"/",httpOnly:!0,secure:!0,maxAge:K0};return G0(ch(r),e,{...t,sameSite:"none"})}const DS=m.object({grant_type:m.literal("authorization_code"),client_id:m.string(),code:m.string(),redirect_uri:m.string().optional(),client_secret:m.string().optional(),code_verifier:m.string().optional()}).refine(r=>"client_secret"in r&&!("code_verifier"in r)||!("client_secret"in r)&&"code_verifier"in r,{message:"Must provide either client_secret (standard flow) or code_verifier/code_verifier_mode (PKCE flow), but not both"});async function ZS(r,e){const t=await r.env.data.clients.get(e.client_id);if(!t)throw new de(403,{message:"Client not found"});const n=await r.env.data.codes.get(t.tenant.id,e.code,"authorization_code");if(!n||!n.user_id)throw new de(403,{message:"Invalid client credentials"});if(new Date(n.expires_at)<new Date)throw new de(403,{message:"Code expired"});const s=await r.env.data.logins.get(t.tenant.id,n.login_id);if(!s)throw new de(403,{message:"Invalid login"});if("client_secret"in e){const c=await r.env.data.clients.get("DEFAULT_CLIENT");if(!Zo(t.client_secret,e.client_secret)&&!Zo(c==null?void 0:c.client_secret,e.client_secret))throw new de(403,{message:"Invalid client credentials"})}else if("code_verifier"in e&&typeof e.code_verifier=="string"&&"code_challenge_method"in s.authParams&&typeof s.authParams.code_challenge_method=="string"){const c=await TS(e.code_verifier,s.authParams.code_challenge_method);if(!Zo(c,s.authParams.code_challenge||""))throw new de(403,{message:"Invalid client credentials"})}if(s.authParams.redirect_uri&&s.authParams.redirect_uri!==e.redirect_uri)throw new de(403,{message:"Invalid redirect uri"});const i=await r.env.data.users.get(t.tenant.id,n.user_id);if(!i)throw new de(403,{message:"User not found"});await r.env.data.codes.used(t.tenant.id,e.code);const a=await r.env.data.sessions.create(t.tenant.id,{session_id:fc(),user_id:i.user_id,client_id:t.id,expires_at:new Date(Date.now()+K0*1e3).toISOString(),used_at:new Date().toISOString()}),o=await W0(r,{authParams:s.authParams,user:i,sid:a.session_id});return r.json(o,{headers:{"set-cookie":$S(t.tenant.id,a.session_id)}})}const pm=m.object({client_id:m.string().optional(),client_secret:m.string().optional()}),MS=m.union([z0.extend(pm.shape),m.object({grant_type:m.literal("authorization_code"),client_id:m.string(),code:m.string(),redirect_uri:m.string(),code_verifier:m.string().min(43).max(128)}),m.object({grant_type:m.literal("authorization_code"),code:m.string(),redirect_uri:m.string().optional(),...pm.shape})]);function US(r){if(!r)return{};const[e,t]=r.split(" ");if((e==null?void 0:e.toLowerCase())==="basic"&&t){const[n,s]=atob(t).split(":");return{client_id:n,client_secret:s}}return{}}const VS=new ut().openapi(ge({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:MS}}}},responses:{200:{content:{"application/json":{schema:m.object({access_token:m.string(),id_token:m.string().optional(),refresh_token:m.string().optional(),token_type:m.string(),expires_in:m.number()})}},description:"Tokens"}}}),async r=>{const e=r.req.valid("form"),t=US(r.req.header("Authorization")),n={...e,...t};if(!n.client_id)throw new de(400,{message:"client_id is required"});switch(e.grant_type){case lc.AuthorizationCode:return ZS(r,DS.parse(n));case lc.ClientCredential:return NS(r,z0.parse(n));default:throw new de(400,{message:"Not implemented"})}});function LS(r,e){try{const t=new URL(r);return e.some(n=>{try{return qS(t,new URL(n))}catch{return!1}})}catch{return!1}}function qS(r,e){if(r.protocol!==e.protocol||r.pathname!==e.pathname)return!1;if(e.hostname.startsWith("*.")&&e.hostname.split(".").length>2&&["http:","https:"].includes(e.protocol)){const t=e.hostname.split(".").slice(1).join(".");return r.hostname.endsWith(t)}return r.hostname===e.hostname}const HS=new ut().openapi(ge({tags:["oauth2"],method:"get",path:"/",request:{query:m.object({client_id:m.string(),returnTo:m.string().optional()}),header:m.object({cookie:m.string().optional()})},responses:{302:{description:"Log the user out"}}}),async r=>{const{client_id:e,returnTo:t}=r.req.valid("query"),n=await r.env.data.clients.get(e);if(!n)return r.text("OK");const s=await r.env.data.clients.get("DEFAULT_CLIENT");r.set("client_id",e),r.set("tenant_id",n.tenant.id);const i=t||r.req.header("referer");if(!i)return r.text("OK");if(!LS(i,[...n.allowed_logout_urls||[],...(s==null?void 0:s.allowed_logout_urls)||[]]))throw new de(400,{message:"Invalid redirect uri"});const a=r.req.header("cookie");if(a){const c=RS(n.tenant.id,a);if(c){const u=await r.env.data.sessions.get(n.tenant.id,c);if(u){const f=await r.env.data.users.get(n.tenant.id,u.user_id);f&&(r.set("user_id",f.user_id),r.set("connection",f.connection))}await r.env.data.sessions.remove(n.tenant.id,c)}}const o=gf(r,{type:Xa.SUCCESS_LOGOUT,description:"User successfully logged out"});return await r.env.data.logs.create(n.tenant.id,o),new Response("Redirecting",{status:302,headers:{"set-cookie":PS(n.tenant.id),location:i}})}),mm=m.object({sub:m.string(),email:m.string().optional(),family_name:m.string().optional(),given_name:m.string().optional(),email_verified:m.boolean()}),FS=new ut().openapi(ge({tags:["oauth2"],method:"get",path:"/",request:{},security:[{Bearer:["openid"]}],responses:{200:{content:{"application/json":{schema:mm}},description:"Userinfo"}}}),async r=>{if(!r.var.user)throw new de(404,{message:"User not found"});const e=await r.env.data.users.get(r.var.user.tenant_id,r.var.user.sub);if(!e)throw new de(404,{message:"User not found"});return r.json(mm.parse({...e,sub:e.user_id}))});function KS(){const r=new ut;r.use(F0(r));const e=r.route("/v2/logout",HS).route("/userinfo",FS).route("/.well-known",ES).route("/oauth/token",VS);return e.doc("/spec",{openapi:"3.0.0",info:{version:"1.0.0",title:"Oauth API"}}),H0(e),e}function WS(r){return async(e,t)=>{if(!t.email||!t.email_verified)return r.users.create(e,t);const n=await ew({userAdapter:r.users,tenant_id:e,email:t.email});return n?(await r.users.create(e,{...t,linked_to:n.user_id}),n):r.users.create(e,t)}}async function zS(r,e,t){for await(const n of e)if(!(await fetch(n.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).ok){const i=gf(r,{type:Xa.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid password"});await t.logs.create(r.var.tenant_id,i)}}function GS(r,e){return async(t,n)=>{const{hooks:s}=await e.hooks.list(t,{q:"trigger_id:post-user-registration",page:0,per_page:100,include_totals:!1});return await zS(r,s,{tenant_id:t,user:n,trigger_id:"post-user-registration"}),n}}function JS(r,e){return async(t,n)=>{let s=await WS(e)(t,n);return await GS(r,e)(t,s),s}}function YS(r,e){return{...e,users:{...e.users,create:JS(r,e)}}}function XS(r){const e=new ut;e.use(async(s,i)=>(s.env.data=YS(s,r.dataAdapter),i())),e.get("/",s=>s.json({name:"authhero"}));const t=AS();e.route("/api/v2",t);const n=KS();return e.route("/",n),{app:e,managementApp:t,oauthApp:n,createX509Certificate:ef}}exports.Auth0Client=jy;exports.AuthorizationResponseMode=hf;exports.AuthorizationResponseType=ff;exports.CodeChallengeMethod=pf;exports.GrantType=lc;exports.LogTypes=Xa;exports.applicationInsertSchema=ic;exports.applicationSchema=Mn;exports.auth0UserResponseSchema=vr;exports.authParamsSchema=Sy;exports.baseUserSchema=su;exports.bordersSchema=By;exports.brandingSchema=Bl;exports.codeInsertSchema=Oy;exports.codeSchema=N_;exports.codeTypeSchema=Ay;exports.colorsSchema=Ry;exports.connectionInsertSchema=ac;exports.connectionSchema=Un;exports.domainInsertSchema=Ey;exports.domainSchema=B_;exports.emailProviderSchema=No;exports.fontDetailsSchema=Dn;exports.fontsSchema=Py;exports.hookInsertSchema=cc;exports.hookSchema=Es;exports.identitySchema=wy;exports.init=XS;exports.jwksKeySchema=Iy;exports.jwksSchema=mf;exports.logSchema=uc;exports.loginInsertSchema=Cy;exports.loginSchema=R_;exports.openIDConfigurationSchema=Rl;exports.pageBackgroundSchema=$y;exports.parseUserId=Z_;exports.passwordInsertSchema=Ty;exports.passwordSchema=$_;exports.profileDataSchema=_y;exports.promptSettingSchema=To;exports.samlpAddon=ky;exports.sessionInsertSchema=Ny;exports.sessionSchema=yf;exports.signingKeySchema=Pl;exports.tenantInsertSchema=oc;exports.tenantSchema=Ns;exports.themeInsertSchema=Zy;exports.themeSchema=D_;exports.totalsSchema=jn;exports.userInsertSchema=sc;exports.userResponseSchema=E_;exports.userSchema=df;exports.vendorSettingsSchema=j_;exports.widgetSchema=Dy;
@@ -4278,10 +4278,11 @@ export interface ListCodesResponse extends Totals {
4278
4278
  codes: Code[];
4279
4279
  }
4280
4280
  export interface CodesAdapter {
4281
- create: (tenant_id: string, authCode: CodeInsert) => Promise<Code>;
4281
+ create: (tenant_id: string, code: CodeInsert) => Promise<Code>;
4282
4282
  get: (tenant_id: string, code_id: string, type: CodeType) => Promise<Code | null>;
4283
4283
  list: (tenant_id: string, params: ListParams) => Promise<ListCodesResponse>;
4284
- remove: (tenant_id: string, code: string) => Promise<boolean>;
4284
+ used: (tenant_id: string, code_id: string) => Promise<boolean>;
4285
+ remove: (tenant_id: string, code_id: string) => Promise<boolean>;
4285
4286
  }
4286
4287
  export interface PasswordsAdapter {
4287
4288
  create: (tenant_id: string, params: PasswordInsert) => Promise<Password>;
@@ -6204,35 +6205,6 @@ export declare function init(config: AuthHeroConfig): {
6204
6205
  Bindings: Bindings;
6205
6206
  Variables: Variables;
6206
6207
  }, import("hono/types").MergeSchemaPath<{
6207
- "/": {
6208
- $get: {
6209
- input: {};
6210
- output: {
6211
- sub: string;
6212
- email_verified: boolean;
6213
- email?: string | undefined;
6214
- given_name?: string | undefined;
6215
- family_name?: string | undefined;
6216
- };
6217
- outputFormat: "json" | "text";
6218
- status: 200;
6219
- };
6220
- };
6221
- }, "/userinfo"> & import("hono/types").MergeSchemaPath<{
6222
- "/": {
6223
- $get: {
6224
- input: {
6225
- query: {
6226
- client_id: string;
6227
- returnTo?: string | undefined;
6228
- };
6229
- };
6230
- output: {};
6231
- outputFormat: string;
6232
- status: 302;
6233
- };
6234
- };
6235
- }, "/v2/logout"> & import("hono/types").MergeSchemaPath<{
6236
6208
  "/": {
6237
6209
  $post: {
6238
6210
  input: {
@@ -6317,7 +6289,36 @@ export declare function init(config: AuthHeroConfig): {
6317
6289
  status: 200;
6318
6290
  };
6319
6291
  };
6320
- }, "/.well-known">, "/">;
6292
+ }, "/.well-known"> & import("hono/types").MergeSchemaPath<{
6293
+ "/": {
6294
+ $get: {
6295
+ input: {};
6296
+ output: {
6297
+ sub: string;
6298
+ email_verified: boolean;
6299
+ email?: string | undefined;
6300
+ given_name?: string | undefined;
6301
+ family_name?: string | undefined;
6302
+ };
6303
+ outputFormat: "json" | "text";
6304
+ status: 200;
6305
+ };
6306
+ };
6307
+ }, "/userinfo"> & import("hono/types").MergeSchemaPath<{
6308
+ "/": {
6309
+ $get: {
6310
+ input: {
6311
+ query: {
6312
+ client_id: string;
6313
+ returnTo?: string | undefined;
6314
+ };
6315
+ };
6316
+ output: {};
6317
+ outputFormat: string;
6318
+ status: 302;
6319
+ };
6320
+ };
6321
+ }, "/v2/logout">, "/">;
6321
6322
  createX509Certificate: typeof createX509Certificate;
6322
6323
  };
6323
6324
 
package/dist/authhero.mjs CHANGED
@@ -24123,7 +24123,7 @@ function gS() {
24123
24123
  }
24124
24124
  const So = 60 * 5, I0 = 30 * 24 * 60 * 60, vS = "auth-token", bS = new ut().openapi(
24125
24125
  ge({
24126
- tags: ["jwks"],
24126
+ tags: ["well known"],
24127
24127
  method: "get",
24128
24128
  path: "/jwks.json",
24129
24129
  request: {},
@@ -24494,7 +24494,7 @@ async function jS(r, e) {
24494
24494
  const i = await r.env.data.users.get(t.tenant.id, n.user_id);
24495
24495
  if (!i)
24496
24496
  throw new de(403, { message: "User not found" });
24497
- await r.env.data.codes.remove(t.tenant.id, e.code);
24497
+ await r.env.data.codes.used(t.tenant.id, e.code);
24498
24498
  const a = await r.env.data.sessions.create(t.tenant.id, {
24499
24499
  session_id: rc(),
24500
24500
  user_id: i.user_id,
@@ -24735,7 +24735,7 @@ const $S = new ut().openapi(
24735
24735
  function ZS() {
24736
24736
  const r = new ut();
24737
24737
  r.use(E0(r));
24738
- const e = r.route("/.well-known", bS).route("/oauth/token", BS).route("/v2/logout", $S).route("/userinfo", DS);
24738
+ const e = r.route("/v2/logout", $S).route("/userinfo", DS).route("/.well-known", bS).route("/oauth/token", BS);
24739
24739
  return e.doc("/spec", {
24740
24740
  openapi: "3.0.0",
24741
24741
  info: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "authhero",
3
- "version": "0.22.0",
3
+ "version": "0.23.0",
4
4
  "files": [
5
5
  "dist"
6
6
  ],
@@ -24,14 +24,14 @@
24
24
  "vite": "^5.4.11",
25
25
  "vite-plugin-dts": "^4.3.0",
26
26
  "vitest": "^2.1.5",
27
- "@authhero/kysely-adapter": "^0.24.4"
27
+ "@authhero/kysely-adapter": "^0.25.0"
28
28
  },
29
29
  "dependencies": {
30
30
  "@peculiar/x509": "^1.12.3",
31
31
  "bcrypt": "^5.1.1",
32
32
  "bcryptjs": "^2.4.3",
33
33
  "oslo": "^1.2.1",
34
- "@authhero/adapter-interfaces": "^0.30.0"
34
+ "@authhero/adapter-interfaces": "^0.31.0"
35
35
  },
36
36
  "peerDependencies": {
37
37
  "@hono/zod-openapi": "^0.18.0",