zaileys 0.29.19-beta → 0.29.20

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/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var e=require("baileys"),t=require("node-cache"),a=require("pino"),s=require("better-sqlite3"),n=require("fs"),r=require("kysely"),i=require("mysql2"),o=require("path"),d=require("pg"),c=require("url"),u=require("crypto"),l=require("libsignal");function h(e){return e&&e.__esModule?e:{default:e}}var p,m,f,y=h(e),v=h(t),g=h(a),_=h(s),x=h(i),b=h(o),k=l.curve,w=()=>{const{pubKey:e,privKey:t}=k.generateKeyPair();return{private:Buffer.from(t),public:Buffer.from(e.slice(1))}},Z=(e,t)=>{const a=w(),s=(e=>33===e.length?e:Buffer.concat([Buffer.from([5]),e]))(a.public);var n,r;return{keyPair:a,signature:(n=e.private,r=s,k.calculateSignature(n,r)),keyId:t}},T=e=>{const t={...e.fingerprint,deviceIndexes:Array.isArray(e.fingerprint.deviceIndexes)?e.fingerprint.deviceIndexes:[]},a={keyData:Array.isArray(e.keyData)?e.keyData:new Uint8Array,fingerprint:{rawId:t.rawId||0,currentIndex:t.rawId||0,deviceIndexes:t.deviceIndexes},timestamp:(s=e.timestamp,"string"==typeof s?parseInt(s,10):s)};var s;return"string"==typeof e.keyData&&(a.keyData=(e=>{let t=e.length;if(!t)return new Uint8Array(1);let a=0;for(;--t%4>1&&"="===e.charAt(t);)++a;return new Uint8Array(Math.ceil(3*e.length)/4-a).fill(0)})(e.keyData)),a},C=(e,t)=>"Buffer"===t?.type&&Array.isArray(t?.data)?{type:"Buffer",data:Buffer.from(t?.data).toString("base64")}:t,N=(e,t)=>"Buffer"===t?.type?Buffer.from(t?.data,"base64"):t,O=async(e,t)=>{const a="auth";await(async e=>{await e.schema.createTable("auth").ifNotExists().addColumn("session","varchar(50)",(e=>e.notNull())).addColumn("id","varchar(80)",(e=>e.notNull())).addColumn("value","text",(e=>e.defaultTo(null))).addUniqueConstraint("auth_session_id_unique",["session","id"]).execute(),await e.schema.createTable("chats").ifNotExists().addColumn("session","varchar(50)",(e=>e.notNull())).addColumn("id","varchar(80)",(e=>e.notNull())).addColumn("value","text",(e=>e.defaultTo(null))).addUniqueConstraint("chats_session_id_unique",["session","id"]).execute(),await e.schema.createTable("contacts").ifNotExists().addColumn("session","varchar(50)",(e=>e.notNull())).addColumn("id","varchar(80)",(e=>e.notNull())).addColumn("value","text",(e=>e.defaultTo(null))).addUniqueConstraint("contacts_session_id_unique",["session","id"]).execute(),await e.schema.createTable("messages").ifNotExists().addColumn("session","varchar(50)",(e=>e.notNull())).addColumn("id","varchar(80)",(e=>e.notNull())).addColumn("value","text",(e=>e.defaultTo(null))).addUniqueConstraint("messages_session_id_unique",["session","id"]).execute(),await e.schema.createIndex("auth_session_idx").ifNotExists().on("auth").column("session").execute(),await e.schema.createIndex("auth_id_idx").ifNotExists().on("auth").column("id").execute(),await e.schema.createIndex("chats_session_idx").ifNotExists().on("chats").column("session").execute(),await e.schema.createIndex("chats_id_idx").ifNotExists().on("chats").column("id").execute(),await e.schema.createIndex("contacts_session_idx").ifNotExists().on("contacts").column("session").execute(),await e.schema.createIndex("contacts_id_idx").ifNotExists().on("contacts").column("id").execute(),await e.schema.createIndex("messages_session_idx").ifNotExists().on("messages").column("session").execute(),await e.schema.createIndex("messages_id_idx").ifNotExists().on("messages").column("id").execute()})(e);const s=async e=>{for(let t=0;t<10;t++)try{return await e()}catch(e){await new Promise((e=>setTimeout(e,200)))}throw new Error("Max retries reached")},n=async n=>{const r=await s((()=>e.selectFrom(a).select(["value"]).where("id","=",n).where("session","=",t).executeTakeFirst()));if(!r?.value)return null;const i="object"==typeof r.value?JSON.stringify(r.value):r.value;return JSON.parse(i,N)},r=async(n,r)=>{const i=JSON.stringify(r,C);await s((()=>e.insertInto(a).values({session:t,id:n,value:i}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:i}))).execute()))},i=async n=>{await s((()=>e.deleteFrom(a).where("id","=",n).where("session","=",t).execute()))},o=await n("creds")||(()=>{const e=w();return{noiseKey:w(),pairingEphemeralKeyPair:w(),signedIdentityKey:e,signedPreKey:Z(e,1),registrationId:16383&Uint16Array.from(u.randomBytes(2))[0],advSecretKey:u.randomBytes(32).toString("base64"),processedHistoryMessages:[],nextPreKeyId:1,firstUnuploadedPreKeyId:1,accountSyncCounter:0,accountSettings:{unarchiveChats:!1},deviceId:Buffer.from(u.randomUUID().replace(/-/g,""),"hex").toString("base64url"),phoneId:u.randomUUID(),identityId:u.randomBytes(20),backupToken:u.randomBytes(20),registered:!1,registration:{},pairingCode:void 0,lastPropHash:void 0,routingInfo:void 0}})();return{state:{creds:o,keys:{get:async(e,t)=>{const a={};for(const s of t){let t=await n(`${e}-${s}`);"app-state-sync-key"===e&&t&&(t=T(t)),a[s]=t}return a},set:async e=>{for(const t in e)for(const a in e[t]){const s=e[t][a],n=`${t}-${a}`;s?await r(n,s):await i(n)}}}},saveCreds:async()=>{await r("creds",o)},clear:async()=>{await(async()=>{await s((()=>e.deleteFrom(a).where("session","=",t).where("id","!=","creds").execute()))})()},removeCreds:async()=>{await(async()=>{await s((()=>e.deleteFrom(a).where("session","=",t).execute()))})()}}};(m=p||(p={})).assertEqual=e=>e,m.assertIs=function(e){},m.assertNever=function(e){throw new Error},m.arrayToEnum=e=>{const t={};for(const a of e)t[a]=a;return t},m.getValidEnumValues=e=>{const t=m.objectKeys(e).filter((t=>"number"!=typeof e[e[t]])),a={};for(const s of t)a[s]=e[s];return m.objectValues(a)},m.objectValues=e=>m.objectKeys(e).map((function(t){return e[t]})),m.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const a in e)Object.prototype.hasOwnProperty.call(e,a)&&t.push(a);return t},m.find=(e,t)=>{for(const a of e)if(t(a))return a},m.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&isFinite(e)&&Math.floor(e)===e,m.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)},m.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(f||(f={})).mergeShapes=(e,t)=>({...e,...t});var S=p.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),I=e=>{switch(typeof e){case"undefined":return S.undefined;case"string":return S.string;case"number":return isNaN(e)?S.nan:S.number;case"boolean":return S.boolean;case"function":return S.function;case"bigint":return S.bigint;case"symbol":return S.symbol;case"object":return Array.isArray(e)?S.array:null===e?S.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?S.promise:"undefined"!=typeof Map&&e instanceof Map?S.map:"undefined"!=typeof Set&&e instanceof Set?S.set:"undefined"!=typeof Date&&e instanceof Date?S.date:S.object;default:return S.unknown}},A=p.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"]),E=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},a={_errors:[]},s=e=>{for(const n of e.issues)if("invalid_union"===n.code)n.unionErrors.map(s);else if("invalid_return_type"===n.code)s(n.returnTypeError);else if("invalid_arguments"===n.code)s(n.argumentsError);else if(0===n.path.length)a._errors.push(t(n));else{let e=a,s=0;for(;s<n.path.length;){const a=n.path[s];s===n.path.length-1?(e[a]=e[a]||{_errors:[]},e[a]._errors.push(t(n))):e[a]=e[a]||{_errors:[]},e=e[a],s++}}};return s(this),a}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,p.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},a=[];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))):a.push(e(s));return{formErrors:a,fieldErrors:t}}get formErrors(){return this.flatten()}};E.create=e=>new E(e);var j=(e,t)=>{let a;switch(e.code){case A.invalid_type:a=e.received===S.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case A.invalid_literal:a=`Invalid literal value, expected ${JSON.stringify(e.expected,p.jsonStringifyReplacer)}`;break;case A.unrecognized_keys:a=`Unrecognized key(s) in object: ${p.joinValues(e.keys,", ")}`;break;case A.invalid_union:a="Invalid input";break;case A.invalid_union_discriminator:a=`Invalid discriminator value. Expected ${p.joinValues(e.options)}`;break;case A.invalid_enum_value:a=`Invalid enum value. Expected ${p.joinValues(e.options)}, received '${e.received}'`;break;case A.invalid_arguments:a="Invalid function arguments";break;case A.invalid_return_type:a="Invalid function return type";break;case A.invalid_date:a="Invalid date";break;case A.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(a=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(a=`${a} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?a=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?a=`Invalid input: must end with "${e.validation.endsWith}"`:p.assertNever(e.validation):a="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case A.too_small:a="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case A.too_big:a="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case A.custom:a="Invalid input";break;case A.invalid_intersection_types:a="Intersection results could not be merged";break;case A.not_multiple_of:a=`Number must be a multiple of ${e.multipleOf}`;break;case A.not_finite:a="Number must be finite";break;default:a=t.defaultError,p.assertNever(e)}return{message:a}},P=j;function R(){return P}var $=e=>{const{data:t,path:a,errorMaps:s,issueData:n}=e,r=[...a,...n.path||[]],i={...n,path:r};if(void 0!==n.message)return{...n,path:r,message:n.message};let o="";const d=s.filter((e=>!!e)).slice().reverse();for(const e of d)o=e(i,{data:t,defaultError:o}).message;return{...n,path:r,message:o}};function M(e,t){const a=R(),s=$({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,a,a===j?void 0:j].filter((e=>!!e))});e.common.issues.push(s)}var F,D,U,L,q=class e{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const a=[];for(const s of t){if("aborted"===s.status)return z;"dirty"===s.status&&e.dirty(),a.push(s.value)}return{status:e.value,value:a}}static async mergeObjectAsync(t,a){const s=[];for(const e of a){const t=await e.key,a=await e.value;s.push({key:t,value:a})}return e.mergeObjectSync(t,s)}static mergeObjectSync(e,t){const a={};for(const s of t){const{key:t,value:n}=s;if("aborted"===t.status)return z;if("aborted"===n.status)return z;"dirty"===t.status&&e.dirty(),"dirty"===n.status&&e.dirty(),"__proto__"===t.value||void 0===n.value&&!s.alwaysSet||(a[t.value]=n.value)}return{status:e.value,value:a}}},z=Object.freeze({status:"aborted"}),K=e=>({status:"dirty",value:e}),B=e=>({status:"valid",value:e}),V=e=>"aborted"===e.status,J=e=>"dirty"===e.status,W=e=>"valid"===e.status,H=e=>"undefined"!=typeof Promise&&e instanceof Promise;function Y(e,t,a,s){if("function"==typeof t||!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t.get(e)}function G(e,t,a,s,n){if("function"==typeof t||!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,a),a}(D=F||(F={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},D.toString=e=>"string"==typeof e?e:null==e?void 0:e.message;var Q=class{constructor(e,t,a,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=a,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}},X=(e,t)=>{if(W(t))return{success:!0,data:t.value};if(!e.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 E(e.common.issues);return this._error=t,this._error}}};function ee(e){if(!e)return{};const{errorMap:t,invalid_type_error:a,required_error:s,description:n}=e;if(t&&(a||s))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:n};return{errorMap:(t,n)=>{var r,i;const{message:o}=e;return"invalid_enum_value"===t.code?{message:null!=o?o:n.defaultError}:void 0===n.data?{message:null!==(r=null!=o?o:s)&&void 0!==r?r:n.defaultError}:"invalid_type"!==t.code?{message:n.defaultError}:{message:null!==(i=null!=o?o:a)&&void 0!==i?i:n.defaultError}},description:n}}var te,ae=class{get description(){return this._def.description}_getType(e){return I(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:I(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new q,ctx:{common:e.parent.common,data:e.data,parsedType:I(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(H(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 a=this.safeParse(e,t);if(a.success)return a.data;throw a.error}safeParse(e,t){var a;const s={common:{issues:[],async:null!==(a=null==t?void 0:t.async)&&void 0!==a&&a,contextualErrorMap:null==t?void 0:t.errorMap},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:I(e)},n=this._parseSync({data:e,path:s.path,parent:s});return X(s,n)}"~validate"(e){var t,a;const s={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:I(e)};if(!this["~standard"].async)try{const t=this._parseSync({data:e,path:[],parent:s});return W(t)?{value:t.value}:{issues:s.common.issues}}catch(e){(null===(a=null===(t=null==e?void 0:e.message)||void 0===t?void 0:t.toLowerCase())||void 0===a?void 0:a.includes("encountered"))&&(this["~standard"].async=!0),s.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:s}).then((e=>W(e)?{value:e.value}:{issues:s.common.issues}))}async parseAsync(e,t){const a=await this.safeParseAsync(e,t);if(a.success)return a.data;throw a.error}async safeParseAsync(e,t){const a={common:{issues:[],contextualErrorMap:null==t?void 0:t.errorMap,async:!0},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:I(e)},s=this._parse({data:e,path:a.path,parent:a}),n=await(H(s)?s:Promise.resolve(s));return X(a,n)}refine(e,t){const a=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement(((t,s)=>{const n=e(t),r=()=>s.addIssue({code:A.custom,...a(t)});return"undefined"!=typeof Promise&&n instanceof Promise?n.then((e=>!!e||(r(),!1))):!!n||(r(),!1)}))}refinement(e,t){return this._refinement(((a,s)=>!!e(a)||(s.addIssue("function"==typeof t?t(a,s):t),!1)))}_refinement(e){return new tt({schema:this,typeName:pt.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return at.create(this,this._def)}nullable(){return st.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return $e.create(this)}promise(){return et.create(this,this._def)}or(e){return De.create([this,e],this._def)}and(e){return ze.create(this,e,this._def)}transform(e){return new tt({...ee(this._def),schema:this,typeName:pt.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new nt({...ee(this._def),innerType:this,defaultValue:t,typeName:pt.ZodDefault})}brand(){return new dt({typeName:pt.ZodBranded,type:this,...ee(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new rt({...ee(this._def),innerType:this,catchValue:t,typeName:pt.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return ct.create(this,e)}readonly(){return ut.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},se=/^c[^\s-]{8,}$/i,ne=/^[0-9a-z]+$/,re=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ie=/^[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,oe=/^[a-z0-9_-]{21}$/i,de=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ce=/^[-+]?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)?)??$/,ue=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,le=/^(?:(?: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])$/,he=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,pe=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,me=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,fe=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ye=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ve="((\\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])))",ge=new RegExp(`^${ve}$`);function _e(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function xe(e){let t=`${ve}T${_e(e)}`;const a=[];return a.push(e.local?"Z?":"Z"),e.offset&&a.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${a.join("|")})`,new RegExp(`^${t}$`)}function be(e,t){if(!de.test(e))return!1;try{const[a]=e.split("."),s=a.replace(/-/g,"+").replace(/_/g,"/").padEnd(a.length+(4-a.length%4)%4,"="),n=JSON.parse(atob(s));return"object"==typeof n&&null!==n&&(!(!n.typ||!n.alg)&&(!t||n.alg===t))}catch(e){return!1}}function ke(e,t){return!("v4"!==t&&t||!he.test(e))||!("v6"!==t&&t||!me.test(e))}var we=class e extends ae{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==S.string){const t=this._getOrReturnCtx(e);return M(t,{code:A.invalid_type,expected:S.string,received:t.parsedType}),z}const t=new q;let a;for(const r of this._def.checks)if("min"===r.kind)e.data.length<r.value&&(a=this._getOrReturnCtx(e,a),M(a,{code:A.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),t.dirty());else if("max"===r.kind)e.data.length>r.value&&(a=this._getOrReturnCtx(e,a),M(a,{code:A.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),t.dirty());else if("length"===r.kind){const s=e.data.length>r.value,n=e.data.length<r.value;(s||n)&&(a=this._getOrReturnCtx(e,a),s?M(a,{code:A.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}):n&&M(a,{code:A.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if("email"===r.kind)ue.test(e.data)||(a=this._getOrReturnCtx(e,a),M(a,{validation:"email",code:A.invalid_string,message:r.message}),t.dirty());else if("emoji"===r.kind)te||(te=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),te.test(e.data)||(a=this._getOrReturnCtx(e,a),M(a,{validation:"emoji",code:A.invalid_string,message:r.message}),t.dirty());else if("uuid"===r.kind)ie.test(e.data)||(a=this._getOrReturnCtx(e,a),M(a,{validation:"uuid",code:A.invalid_string,message:r.message}),t.dirty());else if("nanoid"===r.kind)oe.test(e.data)||(a=this._getOrReturnCtx(e,a),M(a,{validation:"nanoid",code:A.invalid_string,message:r.message}),t.dirty());else if("cuid"===r.kind)se.test(e.data)||(a=this._getOrReturnCtx(e,a),M(a,{validation:"cuid",code:A.invalid_string,message:r.message}),t.dirty());else if("cuid2"===r.kind)ne.test(e.data)||(a=this._getOrReturnCtx(e,a),M(a,{validation:"cuid2",code:A.invalid_string,message:r.message}),t.dirty());else if("ulid"===r.kind)re.test(e.data)||(a=this._getOrReturnCtx(e,a),M(a,{validation:"ulid",code:A.invalid_string,message:r.message}),t.dirty());else if("url"===r.kind)try{new URL(e.data)}catch(s){a=this._getOrReturnCtx(e,a),M(a,{validation:"url",code:A.invalid_string,message:r.message}),t.dirty()}else if("regex"===r.kind){r.regex.lastIndex=0;r.regex.test(e.data)||(a=this._getOrReturnCtx(e,a),M(a,{validation:"regex",code:A.invalid_string,message:r.message}),t.dirty())}else if("trim"===r.kind)e.data=e.data.trim();else if("includes"===r.kind)e.data.includes(r.value,r.position)||(a=this._getOrReturnCtx(e,a),M(a,{code:A.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty());else if("toLowerCase"===r.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===r.kind)e.data=e.data.toUpperCase();else if("startsWith"===r.kind)e.data.startsWith(r.value)||(a=this._getOrReturnCtx(e,a),M(a,{code:A.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty());else if("endsWith"===r.kind)e.data.endsWith(r.value)||(a=this._getOrReturnCtx(e,a),M(a,{code:A.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty());else if("datetime"===r.kind){xe(r).test(e.data)||(a=this._getOrReturnCtx(e,a),M(a,{code:A.invalid_string,validation:"datetime",message:r.message}),t.dirty())}else if("date"===r.kind){ge.test(e.data)||(a=this._getOrReturnCtx(e,a),M(a,{code:A.invalid_string,validation:"date",message:r.message}),t.dirty())}else if("time"===r.kind){new RegExp(`^${_e(r)}$`).test(e.data)||(a=this._getOrReturnCtx(e,a),M(a,{code:A.invalid_string,validation:"time",message:r.message}),t.dirty())}else"duration"===r.kind?ce.test(e.data)||(a=this._getOrReturnCtx(e,a),M(a,{validation:"duration",code:A.invalid_string,message:r.message}),t.dirty()):"ip"===r.kind?(s=e.data,("v4"!==(n=r.version)&&n||!le.test(s))&&("v6"!==n&&n||!pe.test(s))&&(a=this._getOrReturnCtx(e,a),M(a,{validation:"ip",code:A.invalid_string,message:r.message}),t.dirty())):"jwt"===r.kind?be(e.data,r.alg)||(a=this._getOrReturnCtx(e,a),M(a,{validation:"jwt",code:A.invalid_string,message:r.message}),t.dirty()):"cidr"===r.kind?ke(e.data,r.version)||(a=this._getOrReturnCtx(e,a),M(a,{validation:"cidr",code:A.invalid_string,message:r.message}),t.dirty()):"base64"===r.kind?fe.test(e.data)||(a=this._getOrReturnCtx(e,a),M(a,{validation:"base64",code:A.invalid_string,message:r.message}),t.dirty()):"base64url"===r.kind?ye.test(e.data)||(a=this._getOrReturnCtx(e,a),M(a,{validation:"base64url",code:A.invalid_string,message:r.message}),t.dirty()):p.assertNever(r);var s,n;return{status:t.value,value:e.data}}_regex(e,t,a){return this.refinement((t=>e.test(t)),{validation:t,code:A.invalid_string,...F.errToObj(a)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:"email",...F.errToObj(e)})}url(e){return this._addCheck({kind:"url",...F.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...F.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...F.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...F.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...F.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...F.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...F.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...F.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...F.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...F.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...F.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...F.errToObj(e)})}datetime(e){var t,a;return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,offset:null!==(t=null==e?void 0:e.offset)&&void 0!==t&&t,local:null!==(a=null==e?void 0:e.local)&&void 0!==a&&a,...F.errToObj(null==e?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,...F.errToObj(null==e?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...F.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...F.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:null==t?void 0:t.position,...F.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...F.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...F.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...F.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...F.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...F.errToObj(t)})}nonempty(e){return this.min(1,F.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e=>"datetime"===e.kind))}get isDate(){return!!this._def.checks.find((e=>"date"===e.kind))}get isTime(){return!!this._def.checks.find((e=>"time"===e.kind))}get isDuration(){return!!this._def.checks.find((e=>"duration"===e.kind))}get isEmail(){return!!this._def.checks.find((e=>"email"===e.kind))}get isURL(){return!!this._def.checks.find((e=>"url"===e.kind))}get isEmoji(){return!!this._def.checks.find((e=>"emoji"===e.kind))}get isUUID(){return!!this._def.checks.find((e=>"uuid"===e.kind))}get isNANOID(){return!!this._def.checks.find((e=>"nanoid"===e.kind))}get isCUID(){return!!this._def.checks.find((e=>"cuid"===e.kind))}get isCUID2(){return!!this._def.checks.find((e=>"cuid2"===e.kind))}get isULID(){return!!this._def.checks.find((e=>"ulid"===e.kind))}get isIP(){return!!this._def.checks.find((e=>"ip"===e.kind))}get isCIDR(){return!!this._def.checks.find((e=>"cidr"===e.kind))}get isBase64(){return!!this._def.checks.find((e=>"base64"===e.kind))}get isBase64url(){return!!this._def.checks.find((e=>"base64url"===e.kind))}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}};function Ze(e,t){const a=(e.toString().split(".")[1]||"").length,s=(t.toString().split(".")[1]||"").length,n=a>s?a:s;return parseInt(e.toFixed(n).replace(".",""))%parseInt(t.toFixed(n).replace(".",""))/Math.pow(10,n)}we.create=e=>{var t;return new we({checks:[],typeName:pt.ZodString,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...ee(e)})};var Te=class e extends ae{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==S.number){const t=this._getOrReturnCtx(e);return M(t,{code:A.invalid_type,expected:S.number,received:t.parsedType}),z}let t;const a=new q;for(const s of this._def.checks)if("int"===s.kind)p.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),M(t,{code:A.invalid_type,expected:"integer",received:"float",message:s.message}),a.dirty());else if("min"===s.kind){(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),M(t,{code:A.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),a.dirty())}else if("max"===s.kind){(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),M(t,{code:A.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),a.dirty())}else"multipleOf"===s.kind?0!==Ze(e.data,s.value)&&(t=this._getOrReturnCtx(e,t),M(t,{code:A.not_multiple_of,multipleOf:s.value,message:s.message}),a.dirty()):"finite"===s.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),M(t,{code:A.not_finite,message:s.message}),a.dirty()):p.assertNever(s);return{status:a.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,F.toString(t))}gt(e,t){return this.setLimit("min",e,!1,F.toString(t))}lte(e,t){return this.setLimit("max",e,!0,F.toString(t))}lt(e,t){return this.setLimit("max",e,!1,F.toString(t))}setLimit(t,a,s,n){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:a,inclusive:s,message:F.toString(n)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:"int",message:F.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:F.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:F.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:F.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:F.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:F.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:F.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:F.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:F.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find((e=>"int"===e.kind||"multipleOf"===e.kind&&p.isInteger(e.value)))}get isFinite(){let e=null,t=null;for(const a of this._def.checks){if("finite"===a.kind||"int"===a.kind||"multipleOf"===a.kind)return!0;"min"===a.kind?(null===t||a.value>t)&&(t=a.value):"max"===a.kind&&(null===e||a.value<e)&&(e=a.value)}return Number.isFinite(t)&&Number.isFinite(e)}};Te.create=e=>new Te({checks:[],typeName:pt.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...ee(e)});var Ce=class e extends ae{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch(t){return this._getInvalidInput(e)}if(this._getType(e)!==S.bigint)return this._getInvalidInput(e);let t;const a=new q;for(const s of this._def.checks)if("min"===s.kind){(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),M(t,{code:A.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),a.dirty())}else if("max"===s.kind){(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),M(t,{code:A.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),a.dirty())}else"multipleOf"===s.kind?e.data%s.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),M(t,{code:A.not_multiple_of,multipleOf:s.value,message:s.message}),a.dirty()):p.assertNever(s);return{status:a.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return M(t,{code:A.invalid_type,expected:S.bigint,received:t.parsedType}),z}gte(e,t){return this.setLimit("min",e,!0,F.toString(t))}gt(e,t){return this.setLimit("min",e,!1,F.toString(t))}lte(e,t){return this.setLimit("max",e,!0,F.toString(t))}lt(e,t){return this.setLimit("max",e,!1,F.toString(t))}setLimit(t,a,s,n){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:a,inclusive:s,message:F.toString(n)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:F.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:F.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:F.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:F.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:F.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}};Ce.create=e=>{var t;return new Ce({checks:[],typeName:pt.ZodBigInt,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...ee(e)})};var Ne=class extends ae{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==S.boolean){const t=this._getOrReturnCtx(e);return M(t,{code:A.invalid_type,expected:S.boolean,received:t.parsedType}),z}return B(e.data)}};Ne.create=e=>new Ne({typeName:pt.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...ee(e)});var Oe=class e extends ae{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==S.date){const t=this._getOrReturnCtx(e);return M(t,{code:A.invalid_type,expected:S.date,received:t.parsedType}),z}if(isNaN(e.data.getTime())){return M(this._getOrReturnCtx(e),{code:A.invalid_date}),z}const t=new q;let a;for(const s of this._def.checks)"min"===s.kind?e.data.getTime()<s.value&&(a=this._getOrReturnCtx(e,a),M(a,{code:A.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),t.dirty()):"max"===s.kind?e.data.getTime()>s.value&&(a=this._getOrReturnCtx(e,a),M(a,{code:A.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),t.dirty()):p.assertNever(s);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:F.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:F.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}};Oe.create=e=>new Oe({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:pt.ZodDate,...ee(e)});var Se=class extends ae{_parse(e){if(this._getType(e)!==S.symbol){const t=this._getOrReturnCtx(e);return M(t,{code:A.invalid_type,expected:S.symbol,received:t.parsedType}),z}return B(e.data)}};Se.create=e=>new Se({typeName:pt.ZodSymbol,...ee(e)});var Ie=class extends ae{_parse(e){if(this._getType(e)!==S.undefined){const t=this._getOrReturnCtx(e);return M(t,{code:A.invalid_type,expected:S.undefined,received:t.parsedType}),z}return B(e.data)}};Ie.create=e=>new Ie({typeName:pt.ZodUndefined,...ee(e)});var Ae=class extends ae{_parse(e){if(this._getType(e)!==S.null){const t=this._getOrReturnCtx(e);return M(t,{code:A.invalid_type,expected:S.null,received:t.parsedType}),z}return B(e.data)}};Ae.create=e=>new Ae({typeName:pt.ZodNull,...ee(e)});var Ee=class extends ae{constructor(){super(...arguments),this._any=!0}_parse(e){return B(e.data)}};Ee.create=e=>new Ee({typeName:pt.ZodAny,...ee(e)});var je=class extends ae{constructor(){super(...arguments),this._unknown=!0}_parse(e){return B(e.data)}};je.create=e=>new je({typeName:pt.ZodUnknown,...ee(e)});var Pe=class extends ae{_parse(e){const t=this._getOrReturnCtx(e);return M(t,{code:A.invalid_type,expected:S.never,received:t.parsedType}),z}};Pe.create=e=>new Pe({typeName:pt.ZodNever,...ee(e)});var Re=class extends ae{_parse(e){if(this._getType(e)!==S.undefined){const t=this._getOrReturnCtx(e);return M(t,{code:A.invalid_type,expected:S.void,received:t.parsedType}),z}return B(e.data)}};Re.create=e=>new Re({typeName:pt.ZodVoid,...ee(e)});var $e=class e extends ae{_parse(e){const{ctx:t,status:a}=this._processInputParams(e),s=this._def;if(t.parsedType!==S.array)return M(t,{code:A.invalid_type,expected:S.array,received:t.parsedType}),z;if(null!==s.exactLength){const e=t.data.length>s.exactLength.value,n=t.data.length<s.exactLength.value;(e||n)&&(M(t,{code:e?A.too_big:A.too_small,minimum:n?s.exactLength.value:void 0,maximum:e?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),a.dirty())}if(null!==s.minLength&&t.data.length<s.minLength.value&&(M(t,{code:A.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),a.dirty()),null!==s.maxLength&&t.data.length>s.maxLength.value&&(M(t,{code:A.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),a.dirty()),t.common.async)return Promise.all([...t.data].map(((e,a)=>s.type._parseAsync(new Q(t,e,t.path,a))))).then((e=>q.mergeArray(a,e)));const n=[...t.data].map(((e,a)=>s.type._parseSync(new Q(t,e,t.path,a))));return q.mergeArray(a,n)}get element(){return this._def.type}min(t,a){return new e({...this._def,minLength:{value:t,message:F.toString(a)}})}max(t,a){return new e({...this._def,maxLength:{value:t,message:F.toString(a)}})}length(t,a){return new e({...this._def,exactLength:{value:t,message:F.toString(a)}})}nonempty(e){return this.min(1,e)}};function Me(e){if(e instanceof Fe){const t={};for(const a in e.shape){const s=e.shape[a];t[a]=at.create(Me(s))}return new Fe({...e._def,shape:()=>t})}return e instanceof $e?new $e({...e._def,type:Me(e.element)}):e instanceof at?at.create(Me(e.unwrap())):e instanceof st?st.create(Me(e.unwrap())):e instanceof Ke?Ke.create(e.items.map((e=>Me(e)))):e}$e.create=(e,t)=>new $e({type:e,minLength:null,maxLength:null,exactLength:null,typeName:pt.ZodArray,...ee(t)});var Fe=class e extends ae{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=p.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==S.object){const t=this._getOrReturnCtx(e);return M(t,{code:A.invalid_type,expected:S.object,received:t.parsedType}),z}const{status:t,ctx:a}=this._processInputParams(e),{shape:s,keys:n}=this._getCached(),r=[];if(!(this._def.catchall instanceof Pe&&"strip"===this._def.unknownKeys))for(const e in a.data)n.includes(e)||r.push(e);const i=[];for(const e of n){const t=s[e],n=a.data[e];i.push({key:{status:"valid",value:e},value:t._parse(new Q(a,n,a.path,e)),alwaysSet:e in a.data})}if(this._def.catchall instanceof Pe){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of r)i.push({key:{status:"valid",value:e},value:{status:"valid",value:a.data[e]}});else if("strict"===e)r.length>0&&(M(a,{code:A.unrecognized_keys,keys:r}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of r){const s=a.data[t];i.push({key:{status:"valid",value:t},value:e._parse(new Q(a,s,a.path,t)),alwaysSet:t in a.data})}}return a.common.async?Promise.resolve().then((async()=>{const e=[];for(const t of i){const a=await t.key,s=await t.value;e.push({key:a,value:s,alwaysSet:t.alwaysSet})}return e})).then((e=>q.mergeObjectSync(t,e))):q.mergeObjectSync(t,i)}get shape(){return this._def.shape()}strict(t){return F.errToObj,new e({...this._def,unknownKeys:"strict",...void 0!==t?{errorMap:(e,a)=>{var s,n,r,i;const o=null!==(r=null===(n=(s=this._def).errorMap)||void 0===n?void 0:n.call(s,e,a).message)&&void 0!==r?r:a.defaultError;return"unrecognized_keys"===e.code?{message:null!==(i=F.errToObj(t).message)&&void 0!==i?i:o}:{message:o}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:pt.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){const a={};return p.objectKeys(t).forEach((e=>{t[e]&&this.shape[e]&&(a[e]=this.shape[e])})),new e({...this._def,shape:()=>a})}omit(t){const a={};return p.objectKeys(this.shape).forEach((e=>{t[e]||(a[e]=this.shape[e])})),new e({...this._def,shape:()=>a})}deepPartial(){return Me(this)}partial(t){const a={};return p.objectKeys(this.shape).forEach((e=>{const s=this.shape[e];t&&!t[e]?a[e]=s:a[e]=s.optional()})),new e({...this._def,shape:()=>a})}required(t){const a={};return p.objectKeys(this.shape).forEach((e=>{if(t&&!t[e])a[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof at;)t=t._def.innerType;a[e]=t}})),new e({...this._def,shape:()=>a})}keyof(){return Ge(p.objectKeys(this.shape))}};Fe.create=(e,t)=>new Fe({shape:()=>e,unknownKeys:"strip",catchall:Pe.create(),typeName:pt.ZodObject,...ee(t)}),Fe.strictCreate=(e,t)=>new Fe({shape:()=>e,unknownKeys:"strict",catchall:Pe.create(),typeName:pt.ZodObject,...ee(t)}),Fe.lazycreate=(e,t)=>new Fe({shape:e,unknownKeys:"strip",catchall:Pe.create(),typeName:pt.ZodObject,...ee(t)});var De=class extends ae{_parse(e){const{ctx:t}=this._processInputParams(e),a=this._def.options;if(t.common.async)return Promise.all(a.map((async e=>{const a={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}}))).then((function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const a of e)if("dirty"===a.result.status)return t.common.issues.push(...a.ctx.common.issues),a.result;const a=e.map((e=>new E(e.ctx.common.issues)));return M(t,{code:A.invalid_union,unionErrors:a}),z}));{let e;const s=[];for(const n of a){const a={...t,common:{...t.common,issues:[]},parent:null},r=n._parseSync({data:t.data,path:t.path,parent:a});if("valid"===r.status)return r;"dirty"!==r.status||e||(e={result:r,ctx:a}),a.common.issues.length&&s.push(a.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const n=s.map((e=>new E(e)));return M(t,{code:A.invalid_union,unionErrors:n}),z}}get options(){return this._def.options}};De.create=(e,t)=>new De({options:e,typeName:pt.ZodUnion,...ee(t)});var Ue=e=>e instanceof He?Ue(e.schema):e instanceof tt?Ue(e.innerType()):e instanceof Ye?[e.value]:e instanceof Qe?e.options:e instanceof Xe?p.objectValues(e.enum):e instanceof nt?Ue(e._def.innerType):e instanceof Ie?[void 0]:e instanceof Ae?[null]:e instanceof at?[void 0,...Ue(e.unwrap())]:e instanceof st?[null,...Ue(e.unwrap())]:e instanceof dt||e instanceof ut?Ue(e.unwrap()):e instanceof rt?Ue(e._def.innerType):[],Le=class e extends ae{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==S.object)return M(t,{code:A.invalid_type,expected:S.object,received:t.parsedType}),z;const a=this.discriminator,s=t.data[a],n=this.optionsMap.get(s);return n?t.common.async?n._parseAsync({data:t.data,path:t.path,parent:t}):n._parseSync({data:t.data,path:t.path,parent:t}):(M(t,{code:A.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[a]}),z)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,a,s){const n=new Map;for(const e of a){const a=Ue(e.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const s of a){if(n.has(s))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(s)}`);n.set(s,e)}}return new e({typeName:pt.ZodDiscriminatedUnion,discriminator:t,options:a,optionsMap:n,...ee(s)})}};function qe(e,t){const a=I(e),s=I(t);if(e===t)return{valid:!0,data:e};if(a===S.object&&s===S.object){const a=p.objectKeys(t),s=p.objectKeys(e).filter((e=>-1!==a.indexOf(e))),n={...e,...t};for(const a of s){const s=qe(e[a],t[a]);if(!s.valid)return{valid:!1};n[a]=s.data}return{valid:!0,data:n}}if(a===S.array&&s===S.array){if(e.length!==t.length)return{valid:!1};const a=[];for(let s=0;s<e.length;s++){const n=qe(e[s],t[s]);if(!n.valid)return{valid:!1};a.push(n.data)}return{valid:!0,data:a}}return a===S.date&&s===S.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var ze=class extends ae{_parse(e){const{status:t,ctx:a}=this._processInputParams(e),s=(e,s)=>{if(V(e)||V(s))return z;const n=qe(e.value,s.value);return n.valid?((J(e)||J(s))&&t.dirty(),{status:t.value,value:n.data}):(M(a,{code:A.invalid_intersection_types}),z)};return a.common.async?Promise.all([this._def.left._parseAsync({data:a.data,path:a.path,parent:a}),this._def.right._parseAsync({data:a.data,path:a.path,parent:a})]).then((([e,t])=>s(e,t))):s(this._def.left._parseSync({data:a.data,path:a.path,parent:a}),this._def.right._parseSync({data:a.data,path:a.path,parent:a}))}};ze.create=(e,t,a)=>new ze({left:e,right:t,typeName:pt.ZodIntersection,...ee(a)});var Ke=class e extends ae{_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==S.array)return M(a,{code:A.invalid_type,expected:S.array,received:a.parsedType}),z;if(a.data.length<this._def.items.length)return M(a,{code:A.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),z;!this._def.rest&&a.data.length>this._def.items.length&&(M(a,{code:A.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const s=[...a.data].map(((e,t)=>{const s=this._def.items[t]||this._def.rest;return s?s._parse(new Q(a,e,a.path,t)):null})).filter((e=>!!e));return a.common.async?Promise.all(s).then((e=>q.mergeArray(t,e))):q.mergeArray(t,s)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Ke.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ke({items:e,typeName:pt.ZodTuple,rest:null,...ee(t)})};var Be=class e extends ae{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==S.object)return M(a,{code:A.invalid_type,expected:S.object,received:a.parsedType}),z;const s=[],n=this._def.keyType,r=this._def.valueType;for(const e in a.data)s.push({key:n._parse(new Q(a,e,a.path,e)),value:r._parse(new Q(a,a.data[e],a.path,e)),alwaysSet:e in a.data});return a.common.async?q.mergeObjectAsync(t,s):q.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(t,a,s){return new e(a instanceof ae?{keyType:t,valueType:a,typeName:pt.ZodRecord,...ee(s)}:{keyType:we.create(),valueType:t,typeName:pt.ZodRecord,...ee(a)})}},Ve=class extends ae{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==S.map)return M(a,{code:A.invalid_type,expected:S.map,received:a.parsedType}),z;const s=this._def.keyType,n=this._def.valueType,r=[...a.data.entries()].map((([e,t],r)=>({key:s._parse(new Q(a,e,a.path,[r,"key"])),value:n._parse(new Q(a,t,a.path,[r,"value"]))})));if(a.common.async){const e=new Map;return Promise.resolve().then((async()=>{for(const a of r){const s=await a.key,n=await a.value;if("aborted"===s.status||"aborted"===n.status)return z;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}}))}{const e=new Map;for(const a of r){const s=a.key,n=a.value;if("aborted"===s.status||"aborted"===n.status)return z;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}}}};Ve.create=(e,t,a)=>new Ve({valueType:t,keyType:e,typeName:pt.ZodMap,...ee(a)});var Je=class e extends ae{_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==S.set)return M(a,{code:A.invalid_type,expected:S.set,received:a.parsedType}),z;const s=this._def;null!==s.minSize&&a.data.size<s.minSize.value&&(M(a,{code:A.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),null!==s.maxSize&&a.data.size>s.maxSize.value&&(M(a,{code:A.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const n=this._def.valueType;function r(e){const a=new Set;for(const s of e){if("aborted"===s.status)return z;"dirty"===s.status&&t.dirty(),a.add(s.value)}return{status:t.value,value:a}}const i=[...a.data.values()].map(((e,t)=>n._parse(new Q(a,e,a.path,t))));return a.common.async?Promise.all(i).then((e=>r(e))):r(i)}min(t,a){return new e({...this._def,minSize:{value:t,message:F.toString(a)}})}max(t,a){return new e({...this._def,maxSize:{value:t,message:F.toString(a)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Je.create=(e,t)=>new Je({valueType:e,minSize:null,maxSize:null,typeName:pt.ZodSet,...ee(t)});var We=class e extends ae{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==S.function)return M(t,{code:A.invalid_type,expected:S.function,received:t.parsedType}),z;function a(e,a){return $({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,R(),j].filter((e=>!!e)),issueData:{code:A.invalid_arguments,argumentsError:a}})}function s(e,a){return $({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,R(),j].filter((e=>!!e)),issueData:{code:A.invalid_return_type,returnTypeError:a}})}const n={errorMap:t.common.contextualErrorMap},r=t.data;if(this._def.returns instanceof et){const e=this;return B((async function(...t){const i=new E([]),o=await e._def.args.parseAsync(t,n).catch((e=>{throw i.addIssue(a(t,e)),i})),d=await Reflect.apply(r,this,o);return await e._def.returns._def.type.parseAsync(d,n).catch((e=>{throw i.addIssue(s(d,e)),i}))}))}{const e=this;return B((function(...t){const i=e._def.args.safeParse(t,n);if(!i.success)throw new E([a(t,i.error)]);const o=Reflect.apply(r,this,i.data),d=e._def.returns.safeParse(o,n);if(!d.success)throw new E([s(o,d.error)]);return d.data}))}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Ke.create(t).rest(je.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,a,s){return new e({args:t||Ke.create([]).rest(je.create()),returns:a||je.create(),typeName:pt.ZodFunction,...ee(s)})}},He=class extends ae{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})}};He.create=(e,t)=>new He({getter:e,typeName:pt.ZodLazy,...ee(t)});var Ye=class extends ae{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return M(t,{received:t.data,code:A.invalid_literal,expected:this._def.value}),z}return{status:"valid",value:e.data}}get value(){return this._def.value}};function Ge(e,t){return new Qe({values:e,typeName:pt.ZodEnum,...ee(t)})}Ye.create=(e,t)=>new Ye({value:e,typeName:pt.ZodLiteral,...ee(t)});var Qe=class e extends ae{constructor(){super(...arguments),U.set(this,void 0)}_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),a=this._def.values;return M(t,{expected:p.joinValues(a),received:t.parsedType,code:A.invalid_type}),z}if(Y(this,U)||G(this,U,new Set(this._def.values)),!Y(this,U).has(e.data)){const t=this._getOrReturnCtx(e),a=this._def.values;return M(t,{received:t.data,code:A.invalid_enum_value,options:a}),z}return B(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(t,a=this._def){return e.create(t,{...this._def,...a})}exclude(t,a=this._def){return e.create(this.options.filter((e=>!t.includes(e))),{...this._def,...a})}};U=new WeakMap,Qe.create=Ge;var Xe=class extends ae{constructor(){super(...arguments),L.set(this,void 0)}_parse(e){const t=p.getValidEnumValues(this._def.values),a=this._getOrReturnCtx(e);if(a.parsedType!==S.string&&a.parsedType!==S.number){const e=p.objectValues(t);return M(a,{expected:p.joinValues(e),received:a.parsedType,code:A.invalid_type}),z}if(Y(this,L)||G(this,L,new Set(p.getValidEnumValues(this._def.values))),!Y(this,L).has(e.data)){const e=p.objectValues(t);return M(a,{received:a.data,code:A.invalid_enum_value,options:e}),z}return B(e.data)}get enum(){return this._def.values}};L=new WeakMap,Xe.create=(e,t)=>new Xe({values:e,typeName:pt.ZodNativeEnum,...ee(t)});var et=class extends ae{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==S.promise&&!1===t.common.async)return M(t,{code:A.invalid_type,expected:S.promise,received:t.parsedType}),z;const a=t.parsedType===S.promise?t.data:Promise.resolve(t.data);return B(a.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}};et.create=(e,t)=>new et({type:e,typeName:pt.ZodPromise,...ee(t)});var tt=class extends ae{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===pt.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:a}=this._processInputParams(e),s=this._def.effect||null,n={addIssue:e=>{M(a,e),e.fatal?t.abort():t.dirty()},get path(){return a.path}};if(n.addIssue=n.addIssue.bind(n),"preprocess"===s.type){const e=s.transform(a.data,n);if(a.common.async)return Promise.resolve(e).then((async e=>{if("aborted"===t.value)return z;const s=await this._def.schema._parseAsync({data:e,path:a.path,parent:a});return"aborted"===s.status?z:"dirty"===s.status||"dirty"===t.value?K(s.value):s}));{if("aborted"===t.value)return z;const s=this._def.schema._parseSync({data:e,path:a.path,parent:a});return"aborted"===s.status?z:"dirty"===s.status||"dirty"===t.value?K(s.value):s}}if("refinement"===s.type){const e=e=>{const t=s.refinement(e,n);if(a.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===a.common.async){const s=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});return"aborted"===s.status?z:("dirty"===s.status&&t.dirty(),e(s.value),{status:t.value,value:s.value})}return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then((a=>"aborted"===a.status?z:("dirty"===a.status&&t.dirty(),e(a.value).then((()=>({status:t.value,value:a.value}))))))}if("transform"===s.type){if(!1===a.common.async){const e=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});if(!W(e))return e;const r=s.transform(e.value,n);if(r instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:r}}return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then((e=>W(e)?Promise.resolve(s.transform(e.value,n)).then((e=>({status:t.value,value:e}))):e))}p.assertNever(s)}};tt.create=(e,t,a)=>new tt({schema:e,typeName:pt.ZodEffects,effect:t,...ee(a)}),tt.createWithPreprocess=(e,t,a)=>new tt({schema:t,effect:{type:"preprocess",transform:e},typeName:pt.ZodEffects,...ee(a)});var at=class extends ae{_parse(e){return this._getType(e)===S.undefined?B(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};at.create=(e,t)=>new at({innerType:e,typeName:pt.ZodOptional,...ee(t)});var st=class extends ae{_parse(e){return this._getType(e)===S.null?B(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};st.create=(e,t)=>new st({innerType:e,typeName:pt.ZodNullable,...ee(t)});var nt=class extends ae{_parse(e){const{ctx:t}=this._processInputParams(e);let a=t.data;return t.parsedType===S.undefined&&(a=this._def.defaultValue()),this._def.innerType._parse({data:a,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};nt.create=(e,t)=>new nt({innerType:e,typeName:pt.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...ee(t)});var rt=class extends ae{_parse(e){const{ctx:t}=this._processInputParams(e),a={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:a.data,path:a.path,parent:{...a}});return H(s)?s.then((e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new E(a.common.issues)},input:a.data})}))):{status:"valid",value:"valid"===s.status?s.value:this._def.catchValue({get error(){return new E(a.common.issues)},input:a.data})}}removeCatch(){return this._def.innerType}};rt.create=(e,t)=>new rt({innerType:e,typeName:pt.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...ee(t)});var it=class extends ae{_parse(e){if(this._getType(e)!==S.nan){const t=this._getOrReturnCtx(e);return M(t,{code:A.invalid_type,expected:S.nan,received:t.parsedType}),z}return{status:"valid",value:e.data}}};it.create=e=>new it({typeName:pt.ZodNaN,...ee(e)});var ot=Symbol("zod_brand"),dt=class extends ae{_parse(e){const{ctx:t}=this._processInputParams(e),a=t.data;return this._def.type._parse({data:a,path:t.path,parent:t})}unwrap(){return this._def.type}},ct=class e extends ae{_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:a.data,path:a.path,parent:a});return"aborted"===e.status?z:"dirty"===e.status?(t.dirty(),K(e.value)):this._def.out._parseAsync({data:e.value,path:a.path,parent:a})})()}{const e=this._def.in._parseSync({data:a.data,path:a.path,parent:a});return"aborted"===e.status?z:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:a.path,parent:a})}}static create(t,a){return new e({in:t,out:a,typeName:pt.ZodPipeline})}},ut=class extends ae{_parse(e){const t=this._def.innerType._parse(e),a=e=>(W(e)&&(e.value=Object.freeze(e.value)),e);return H(t)?t.then((e=>a(e))):a(t)}unwrap(){return this._def.innerType}};function lt(e,t){const a="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof a?{message:a}:a}function ht(e,t={},a){return e?Ee.create().superRefine(((s,n)=>{var r,i;const o=e(s);if(o instanceof Promise)return o.then((e=>{var r,i;if(!e){const e=lt(t,s),o=null===(i=null!==(r=e.fatal)&&void 0!==r?r:a)||void 0===i||i;n.addIssue({code:"custom",...e,fatal:o})}}));if(!o){const e=lt(t,s),o=null===(i=null!==(r=e.fatal)&&void 0!==r?r:a)||void 0===i||i;n.addIssue({code:"custom",...e,fatal:o})}})):Ee.create()}ut.create=(e,t)=>new ut({innerType:e,typeName:pt.ZodReadonly,...ee(t)});var pt,mt,ft={object:Fe.lazycreate};(mt=pt||(pt={})).ZodString="ZodString",mt.ZodNumber="ZodNumber",mt.ZodNaN="ZodNaN",mt.ZodBigInt="ZodBigInt",mt.ZodBoolean="ZodBoolean",mt.ZodDate="ZodDate",mt.ZodSymbol="ZodSymbol",mt.ZodUndefined="ZodUndefined",mt.ZodNull="ZodNull",mt.ZodAny="ZodAny",mt.ZodUnknown="ZodUnknown",mt.ZodNever="ZodNever",mt.ZodVoid="ZodVoid",mt.ZodArray="ZodArray",mt.ZodObject="ZodObject",mt.ZodUnion="ZodUnion",mt.ZodDiscriminatedUnion="ZodDiscriminatedUnion",mt.ZodIntersection="ZodIntersection",mt.ZodTuple="ZodTuple",mt.ZodRecord="ZodRecord",mt.ZodMap="ZodMap",mt.ZodSet="ZodSet",mt.ZodFunction="ZodFunction",mt.ZodLazy="ZodLazy",mt.ZodLiteral="ZodLiteral",mt.ZodEnum="ZodEnum",mt.ZodEffects="ZodEffects",mt.ZodNativeEnum="ZodNativeEnum",mt.ZodOptional="ZodOptional",mt.ZodNullable="ZodNullable",mt.ZodDefault="ZodDefault",mt.ZodCatch="ZodCatch",mt.ZodPromise="ZodPromise",mt.ZodBranded="ZodBranded",mt.ZodPipeline="ZodPipeline",mt.ZodReadonly="ZodReadonly";var yt=we.create,vt=Te.create,gt=it.create,_t=Ce.create,xt=Ne.create,bt=Oe.create,kt=Se.create,wt=Ie.create,Zt=Ae.create,Tt=Ee.create,Ct=je.create,Nt=Pe.create,Ot=Re.create,St=$e.create,It=Fe.create,At=Fe.strictCreate,Et=De.create,jt=Le.create,Pt=ze.create,Rt=Ke.create,$t=Be.create,Mt=Ve.create,Ft=Je.create,Dt=We.create,Ut=He.create,Lt=Ye.create,qt=Qe.create,zt=Xe.create,Kt=et.create,Bt=tt.create,Vt=at.create,Jt=st.create,Wt=tt.createWithPreprocess,Ht=ct.create,Yt={string:e=>we.create({...e,coerce:!0}),number:e=>Te.create({...e,coerce:!0}),boolean:e=>Ne.create({...e,coerce:!0}),bigint:e=>Ce.create({...e,coerce:!0}),date:e=>Oe.create({...e,coerce:!0})},Gt=z,Qt=Object.freeze({__proto__:null,defaultErrorMap:j,setErrorMap:function(e){P=e},getErrorMap:R,makeIssue:$,EMPTY_PATH:[],addIssueToContext:M,ParseStatus:q,INVALID:z,DIRTY:K,OK:B,isAborted:V,isDirty:J,isValid:W,isAsync:H,get util(){return p},get objectUtil(){return f},ZodParsedType:S,getParsedType:I,ZodType:ae,datetimeRegex:xe,ZodString:we,ZodNumber:Te,ZodBigInt:Ce,ZodBoolean:Ne,ZodDate:Oe,ZodSymbol:Se,ZodUndefined:Ie,ZodNull:Ae,ZodAny:Ee,ZodUnknown:je,ZodNever:Pe,ZodVoid:Re,ZodArray:$e,ZodObject:Fe,ZodUnion:De,ZodDiscriminatedUnion:Le,ZodIntersection:ze,ZodTuple:Ke,ZodRecord:Be,ZodMap:Ve,ZodSet:Je,ZodFunction:We,ZodLazy:He,ZodLiteral:Ye,ZodEnum:Qe,ZodNativeEnum:Xe,ZodPromise:et,ZodEffects:tt,ZodTransformer:tt,ZodOptional:at,ZodNullable:st,ZodDefault:nt,ZodCatch:rt,ZodNaN:it,BRAND:ot,ZodBranded:dt,ZodPipeline:ct,ZodReadonly:ut,custom:ht,Schema:ae,ZodSchema:ae,late:ft,get ZodFirstPartyTypeKind(){return pt},coerce:Yt,any:Tt,array:St,bigint:_t,boolean:xt,date:bt,discriminatedUnion:jt,effect:Bt,enum:qt,function:Dt,instanceof:(e,t={message:`Input not instance of ${e.name}`})=>ht((t=>t instanceof e),t),intersection:Pt,lazy:Ut,literal:Lt,map:Mt,nan:gt,nativeEnum:zt,never:Nt,null:Zt,nullable:Jt,number:vt,object:It,oboolean:()=>xt().optional(),onumber:()=>vt().optional(),optional:Vt,ostring:()=>yt().optional(),pipeline:Ht,preprocess:Wt,promise:Kt,record:$t,set:Ft,strictObject:At,string:yt,symbol:kt,transformer:Bt,tuple:Rt,undefined:wt,union:Et,unknown:Ct,void:Ot,NEVER:Gt,ZodIssueCode:A,quotelessJson:e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ZodError:E}),Xt=Qt.object({type:Qt.enum(["sqlite","postgresql","mysql"]).default("sqlite"),connection:Qt.object({url:Qt.string().default("./db/zaileys.db")}).optional().default({})}).optional().default({}),ea={prefix:Qt.string().optional(),ignoreMe:Qt.boolean().optional().default(!0),showLogs:Qt.boolean().optional().default(!0),autoMentions:Qt.boolean().optional().default(!0),autoOnline:Qt.boolean().optional().default(!0),autoRead:Qt.boolean().optional().default(!0),autoRejectCall:Qt.boolean().optional().default(!0),database:Xt,citation:Qt.record(Qt.function().returns(Qt.union([Qt.number().array(),Qt.promise(Qt.number().array())]))).optional().transform((async e=>{const t={};if(e)for(const a of Object.keys(e)){const s=`is${a.charAt(0).toUpperCase()+a.slice(1)}`,n=await e[a]();t[s]=n}return t}))},ta=Qt.object({authType:Qt.literal("pairing"),phoneNumber:Qt.number(),...ea}),aa=Qt.object({authType:Qt.literal("qr"),phoneNumber:Qt.undefined().optional(),...ea}),sa=Qt.discriminatedUnion("authType",[ta,aa]),na=class{constructor(e){this.client=e}events=new Map;setup(t){t.ev.on("connection.update",(async t=>{const{connection:a,lastDisconnect:s,qr:n}=t;if(this.emit("connection",{status:a||"connecting"}),"qr"==this.client.options?.authType&&n&&console.log("Scan qrcode with your whatsapp: "),"close"===a){const t=s?.error?.output?.statusCode,a=t!==e.DisconnectReason.loggedOut;if(console.log(s?.error?.message),401==t||405==t||500==t)return;a&&await this.client.initialize()}else"open"===a&&this.emit("connection",{status:"open"})})),t.ev.on("messages.upsert",(({messages:e})=>{this.emit("messages",e)})),t.ev.on("call",(e=>{this.emit("call",e)}))}on(e,t){this.events.has(e)||this.events.set(e,[]),this.events.get(e).push(t)}emit(e,t){(this.events.get(e)||[]).forEach((e=>e(t)))}},ra=class{constructor(e){this.props=e,this.initialize(),this.event=new na(this)}options;chatId="zaileys-chats";logger=g.default({level:"silent",enabled:!1});event;db;socket;groupCache=new v.default({stdTTL:300,useClones:!1});async initialize(){this.options=await sa.parseAsync(this.props),this.db=((e,t)=>{if("sqlite"===e){const e=t||"./db/zaileys.db",a=b.default.resolve(e);return n.mkdirSync(b.default.dirname(a),{recursive:!0}),n.writeFileSync(a,"",{flag:"a"}),new r.Kysely({dialect:new r.SqliteDialect({database:new _.default(a)})})}const a=new c.URL(t),s=a.protocol.replace(":","");if("mysql"===e)return new r.Kysely({dialect:new r.MysqlDialect({pool:x.default.createPool({host:a.hostname,user:a.username,password:a.password,database:a.pathname.replace("/",""),port:parseInt(a.port||"3306",10)})})});if("postgresql"===e)return new r.Kysely({dialect:new r.PostgresDialect({pool:new d.Pool({host:a.hostname,user:a.username,password:a.password,database:a.pathname.replace("/",""),port:parseInt(a.port||"5432",10)})})});throw new Error(`Unsupported database protocol: ${s}`)})(this.options.database.type,this.options.database.connection.url);const{state:t,saveCreds:a,removeCreds:s}=await O(this.db,this.chatId),i=await(async(e,t)=>({bind:a=>{a.on("messaging-history.set",(async a=>{const{chats:s,contacts:n,messages:r}=a;for(const a of s)await e.insertInto("chats").values({session:t,id:a.id,value:JSON.stringify(a)}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:JSON.stringify(a)}))).execute();for(const a of n)await e.insertInto("contacts").values({session:t,id:a.id,value:JSON.stringify(a)}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:JSON.stringify(a)}))).execute();for(const a of r)await e.insertInto("messages").values({session:t,id:a.key.id,value:JSON.stringify(a)}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:JSON.stringify(a)}))).execute()})),a.on("messages.upsert",(async({messages:a})=>{for(const s of a)await e.insertInto("messages").values({session:t,id:s.key.id,value:JSON.stringify(s)}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:JSON.stringify(s)}))).execute()})),a.on("chats.upsert",(async a=>{for(const s of a)await e.insertInto("chats").values({session:t,id:s.id,value:JSON.stringify(s)}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:JSON.stringify(s)}))).execute()})),a.on("contacts.upsert",(async a=>{for(const s of a)await e.insertInto("contacts").values({session:t,id:s.id,value:JSON.stringify(s)}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:JSON.stringify(s)}))).execute()}))}}))(this.db,this.chatId);this.socket=y.default({logger:this.logger,markOnlineOnConnect:this.options.autoOnline,syncFullHistory:!1,defaultQueryTimeoutMs:void 0,msgRetryCounterCache:new v.default,cachedGroupMetadata:async e=>this.groupCache.get(e),printQRInTerminal:"qr"==this.options.authType,browser:e.Browsers.ubuntu("qr"==this.options.authType?"Zaileys Library":"Firefox"),auth:{creds:t.creds,keys:e.makeCacheableSignalKeyStore(t.keys,this.logger)}}),"pairing"==this.options.authType&&this.options.phoneNumber&&!this.socket?.authState.creds.registered&&setTimeout((async()=>{try{if("pairing"==this.options?.authType){const e=await(this.socket?.requestPairingCode(this.options.phoneNumber.toString()));console.log("🚀 ~ Client.ts:53 ~ Client ~ setTimeout ~ code:",e)}}catch{console.log("Connection failed"),process.exit(1)}}),5e3),this.socket?.ev.on("creds.update",a),i.bind(this.socket?.ev),this.event.setup(this.socket)}on(e,t){this.event.on(e,t)}};module.exports=ra;
1
+ "use strict";var e=require("baileys"),t=require("events"),s=require("figlet"),a=require("node-cache"),n=require("ora"),i=require("pino"),r=require("better-sqlite3"),o=require("fs"),d=require("kysely"),c=require("mysql2"),u=require("path"),l=require("pg"),p=require("url"),h=require("crypto"),m=require("libsignal"),f=require("stream");function g(e){return e&&e.__esModule?e:{default:e}}var y,v,_,b=g(e),w=g(s),k=g(a),x=g(n),I=g(i),C=g(r),T=g(c),N=g(u),S=m.curve,M=()=>{const{pubKey:e,privKey:t}=S.generateKeyPair();return{private:Buffer.from(t),public:Buffer.from(e.slice(1))}},O=(e,t)=>{const s=M(),a=(e=>33===e.length?e:Buffer.concat([Buffer.from([5]),e]))(s.public);var n,i;return{keyPair:s,signature:(n=e.private,i=a,S.calculateSignature(n,i)),keyId:t}},Z=e=>{const t={...e.fingerprint,deviceIndexes:Array.isArray(e.fingerprint.deviceIndexes)?e.fingerprint.deviceIndexes:[]},s={keyData:Array.isArray(e.keyData)?e.keyData:new Uint8Array,fingerprint:{rawId:t.rawId||0,currentIndex:t.rawId||0,deviceIndexes:t.deviceIndexes},timestamp:(a=e.timestamp,"string"==typeof a?parseInt(a,10):a)};var a;return"string"==typeof e.keyData&&(s.keyData=(e=>{let t=e.length;if(!t)return new Uint8Array(1);let s=0;for(;--t%4>1&&"="===e.charAt(t);)++s;return new Uint8Array(Math.ceil(3*e.length)/4-s).fill(0)})(e.keyData)),s},A=(e,t)=>"Buffer"===t?.type&&Array.isArray(t?.data)?{type:"Buffer",data:Buffer.from(t?.data).toString("base64")}:t,E=(e,t)=>"Buffer"===t?.type?Buffer.from(t?.data,"base64"):t,j=async(e,t)=>{const s="auth";await(async e=>{await e.schema.createTable("auth").ifNotExists().addColumn("session","varchar(50)",(e=>e.notNull())).addColumn("id","varchar(80)",(e=>e.notNull())).addColumn("value","text",(e=>e.defaultTo(null))).addUniqueConstraint("auth_session_id_unique",["session","id"]).execute(),await e.schema.createTable("chats").ifNotExists().addColumn("session","varchar(50)",(e=>e.notNull())).addColumn("id","varchar(80)",(e=>e.notNull())).addColumn("value","text",(e=>e.defaultTo(null))).addUniqueConstraint("chats_session_id_unique",["session","id"]).execute(),await e.schema.createTable("contacts").ifNotExists().addColumn("session","varchar(50)",(e=>e.notNull())).addColumn("id","varchar(80)",(e=>e.notNull())).addColumn("value","text",(e=>e.defaultTo(null))).addUniqueConstraint("contacts_session_id_unique",["session","id"]).execute(),await e.schema.createTable("messages").ifNotExists().addColumn("session","varchar(50)",(e=>e.notNull())).addColumn("id","varchar(80)",(e=>e.notNull())).addColumn("value","text",(e=>e.defaultTo(null))).addUniqueConstraint("messages_session_id_unique",["session","id"]).execute(),await e.schema.createIndex("auth_session_idx").ifNotExists().on("auth").column("session").execute(),await e.schema.createIndex("auth_id_idx").ifNotExists().on("auth").column("id").execute(),await e.schema.createIndex("chats_session_idx").ifNotExists().on("chats").column("session").execute(),await e.schema.createIndex("chats_id_idx").ifNotExists().on("chats").column("id").execute(),await e.schema.createIndex("contacts_session_idx").ifNotExists().on("contacts").column("session").execute(),await e.schema.createIndex("contacts_id_idx").ifNotExists().on("contacts").column("id").execute(),await e.schema.createIndex("messages_session_idx").ifNotExists().on("messages").column("session").execute(),await e.schema.createIndex("messages_id_idx").ifNotExists().on("messages").column("id").execute()})(e);const a=async e=>{for(let t=0;t<10;t++)try{return await e()}catch(e){await new Promise((e=>setTimeout(e,200)))}throw new Error("Max retries reached")},n=async n=>{const i=await a((()=>e.selectFrom(s).select(["value"]).where("id","=",n).where("session","=",t).executeTakeFirst()));if(!i?.value)return null;const r="object"==typeof i.value?JSON.stringify(i.value):i.value;return JSON.parse(r,E)},i=async(n,i)=>{const r=JSON.stringify(i,A);await a((()=>e.insertInto(s).values({session:t,id:n,value:r}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:r}))).execute()))},r=async n=>{await a((()=>e.deleteFrom(s).where("id","=",n).where("session","=",t).execute()))},o=await n("creds")||(()=>{const e=M();return{noiseKey:M(),pairingEphemeralKeyPair:M(),signedIdentityKey:e,signedPreKey:O(e,1),registrationId:16383&Uint16Array.from(h.randomBytes(2))[0],advSecretKey:h.randomBytes(32).toString("base64"),processedHistoryMessages:[],nextPreKeyId:1,firstUnuploadedPreKeyId:1,accountSyncCounter:0,accountSettings:{unarchiveChats:!1},deviceId:Buffer.from(h.randomUUID().replace(/-/g,""),"hex").toString("base64url"),phoneId:h.randomUUID(),identityId:h.randomBytes(20),backupToken:h.randomBytes(20),registered:!1,registration:{},pairingCode:void 0,lastPropHash:void 0,routingInfo:void 0}})();return{state:{creds:o,keys:{get:async(e,t)=>{const s={};for(const a of t){let t=await n(`${e}-${a}`);"app-state-sync-key"===e&&t&&(t=Z(t)),s[a]=t}return s},set:async e=>{for(const t in e)for(const s in e[t]){const a=e[t][s],n=`${t}-${s}`;a?await i(n,a):await r(n)}}}},saveCreds:async()=>{await i("creds",o)},clear:async()=>{await(async()=>{await a((()=>e.deleteFrom(s).where("session","=",t).where("id","!=","creds").execute()))})()},removeCreds:async()=>{await(async()=>{await a((()=>e.deleteFrom(s).where("session","=",t).execute()))})()}}};(v=y||(y={})).assertEqual=e=>e,v.assertIs=function(e){},v.assertNever=function(e){throw new Error},v.arrayToEnum=e=>{const t={};for(const s of e)t[s]=s;return t},v.getValidEnumValues=e=>{const t=v.objectKeys(e).filter((t=>"number"!=typeof e[e[t]])),s={};for(const a of t)s[a]=e[a];return v.objectValues(s)},v.objectValues=e=>v.objectKeys(e).map((function(t){return e[t]})),v.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.push(s);return t},v.find=(e,t)=>{for(const s of e)if(t(s))return s},v.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&isFinite(e)&&Math.floor(e)===e,v.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)},v.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(_||(_={})).mergeShapes=(e,t)=>({...e,...t});var P=y.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),R=e=>{switch(typeof e){case"undefined":return P.undefined;case"string":return P.string;case"number":return isNaN(e)?P.nan:P.number;case"boolean":return P.boolean;case"function":return P.function;case"bigint":return P.bigint;case"symbol":return P.symbol;case"object":return Array.isArray(e)?P.array:null===e?P.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?P.promise:"undefined"!=typeof Map&&e instanceof Map?P.map:"undefined"!=typeof Set&&e instanceof Set?P.set:"undefined"!=typeof Date&&e instanceof Date?P.date:P.object;default:return P.unknown}},$=y.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"]),F=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},s={_errors:[]},a=e=>{for(const n of e.issues)if("invalid_union"===n.code)n.unionErrors.map(a);else if("invalid_return_type"===n.code)a(n.returnTypeError);else if("invalid_arguments"===n.code)a(n.argumentsError);else if(0===n.path.length)s._errors.push(t(n));else{let e=s,a=0;for(;a<n.path.length;){const s=n.path[a];a===n.path.length-1?(e[s]=e[s]||{_errors:[]},e[s]._errors.push(t(n))):e[s]=e[s]||{_errors:[]},e=e[s],a++}}};return a(this),s}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,y.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},s=[];for(const a of this.issues)a.path.length>0?(t[a.path[0]]=t[a.path[0]]||[],t[a.path[0]].push(e(a))):s.push(e(a));return{formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}};F.create=e=>new F(e);var U=(e,t)=>{let s;switch(e.code){case $.invalid_type:s=e.received===P.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case $.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(e.expected,y.jsonStringifyReplacer)}`;break;case $.unrecognized_keys:s=`Unrecognized key(s) in object: ${y.joinValues(e.keys,", ")}`;break;case $.invalid_union:s="Invalid input";break;case $.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${y.joinValues(e.options)}`;break;case $.invalid_enum_value:s=`Invalid enum value. Expected ${y.joinValues(e.options)}, received '${e.received}'`;break;case $.invalid_arguments:s="Invalid function arguments";break;case $.invalid_return_type:s="Invalid function return type";break;case $.invalid_date:s="Invalid date";break;case $.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(s=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(s=`${s} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?s=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?s=`Invalid input: must end with "${e.validation.endsWith}"`:y.assertNever(e.validation):s="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case $.too_small:s="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case $.too_big:s="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case $.custom:s="Invalid input";break;case $.invalid_intersection_types:s="Intersection results could not be merged";break;case $.not_multiple_of:s=`Number must be a multiple of ${e.multipleOf}`;break;case $.not_finite:s="Number must be finite";break;default:s=t.defaultError,y.assertNever(e)}return{message:s}},q=U;function D(){return q}var L=e=>{const{data:t,path:s,errorMaps:a,issueData:n}=e,i=[...s,...n.path||[]],r={...n,path:i};if(void 0!==n.message)return{...n,path:i,message:n.message};let o="";const d=a.filter((e=>!!e)).slice().reverse();for(const e of d)o=e(r,{data:t,defaultError:o}).message;return{...n,path:i,message:o}};function z(e,t){const s=D(),a=L({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,s,s===U?void 0:U].filter((e=>!!e))});e.common.issues.push(a)}var V,K,B,J,W=class e{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const s=[];for(const a of t){if("aborted"===a.status)return Y;"dirty"===a.status&&e.dirty(),s.push(a.value)}return{status:e.value,value:s}}static async mergeObjectAsync(t,s){const a=[];for(const e of s){const t=await e.key,s=await e.value;a.push({key:t,value:s})}return e.mergeObjectSync(t,a)}static mergeObjectSync(e,t){const s={};for(const a of t){const{key:t,value:n}=a;if("aborted"===t.status)return Y;if("aborted"===n.status)return Y;"dirty"===t.status&&e.dirty(),"dirty"===n.status&&e.dirty(),"__proto__"===t.value||void 0===n.value&&!a.alwaysSet||(s[t.value]=n.value)}return{status:e.value,value:s}}},Y=Object.freeze({status:"aborted"}),G=e=>({status:"dirty",value:e}),H=e=>({status:"valid",value:e}),Q=e=>"aborted"===e.status,X=e=>"dirty"===e.status,ee=e=>"valid"===e.status,te=e=>"undefined"!=typeof Promise&&e instanceof Promise;function se(e,t,s,a){if("function"==typeof t||!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t.get(e)}function ae(e,t,s,a,n){if("function"==typeof t||!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,s),s}(K=V||(V={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},K.toString=e=>"string"==typeof e?e:null==e?void 0:e.message;var ne=class{constructor(e,t,s,a){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=a}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},ie=(e,t)=>{if(ee(t))return{success:!0,data:t.value};if(!e.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 F(e.common.issues);return this._error=t,this._error}}};function re(e){if(!e)return{};const{errorMap:t,invalid_type_error:s,required_error:a,description:n}=e;if(t&&(s||a))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:n};return{errorMap:(t,n)=>{var i,r;const{message:o}=e;return"invalid_enum_value"===t.code?{message:null!=o?o:n.defaultError}:void 0===n.data?{message:null!==(i=null!=o?o:a)&&void 0!==i?i:n.defaultError}:"invalid_type"!==t.code?{message:n.defaultError}:{message:null!==(r=null!=o?o:s)&&void 0!==r?r:n.defaultError}},description:n}}var oe,de=class{get description(){return this._def.description}_getType(e){return R(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:R(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new W,ctx:{common:e.parent.common,data:e.data,parsedType:R(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(te(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 s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){var s;const a={common:{issues:[],async:null!==(s=null==t?void 0:t.async)&&void 0!==s&&s,contextualErrorMap:null==t?void 0:t.errorMap},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:R(e)},n=this._parseSync({data:e,path:a.path,parent:a});return ie(a,n)}"~validate"(e){var t,s;const a={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:R(e)};if(!this["~standard"].async)try{const t=this._parseSync({data:e,path:[],parent:a});return ee(t)?{value:t.value}:{issues:a.common.issues}}catch(e){(null===(s=null===(t=null==e?void 0:e.message)||void 0===t?void 0:t.toLowerCase())||void 0===s?void 0:s.includes("encountered"))&&(this["~standard"].async=!0),a.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:a}).then((e=>ee(e)?{value:e.value}:{issues:a.common.issues}))}async parseAsync(e,t){const s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){const s={common:{issues:[],contextualErrorMap:null==t?void 0:t.errorMap,async:!0},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:R(e)},a=this._parse({data:e,path:s.path,parent:s}),n=await(te(a)?a:Promise.resolve(a));return ie(s,n)}refine(e,t){const s=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement(((t,a)=>{const n=e(t),i=()=>a.addIssue({code:$.custom,...s(t)});return"undefined"!=typeof Promise&&n instanceof Promise?n.then((e=>!!e||(i(),!1))):!!n||(i(),!1)}))}refinement(e,t){return this._refinement(((s,a)=>!!e(s)||(a.addIssue("function"==typeof t?t(s,a):t),!1)))}_refinement(e){return new ot({schema:this,typeName:_t.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return dt.create(this,this._def)}nullable(){return ct.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Le.create(this)}promise(){return rt.create(this,this._def)}or(e){return Ke.create([this,e],this._def)}and(e){return Ye.create(this,e,this._def)}transform(e){return new ot({...re(this._def),schema:this,typeName:_t.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new ut({...re(this._def),innerType:this,defaultValue:t,typeName:_t.ZodDefault})}brand(){return new mt({typeName:_t.ZodBranded,type:this,...re(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new lt({...re(this._def),innerType:this,catchValue:t,typeName:_t.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return ft.create(this,e)}readonly(){return gt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},ce=/^c[^\s-]{8,}$/i,ue=/^[0-9a-z]+$/,le=/^[0-9A-HJKMNP-TV-Z]{26}$/i,pe=/^[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,he=/^[a-z0-9_-]{21}$/i,me=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,fe=/^[-+]?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)?)??$/,ge=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ye=/^(?:(?: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])$/,ve=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,_e=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,be=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,we=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ke=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,xe="((\\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])))",Ie=new RegExp(`^${xe}$`);function Ce(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function Te(e){let t=`${xe}T${Ce(e)}`;const s=[];return s.push(e.local?"Z?":"Z"),e.offset&&s.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${s.join("|")})`,new RegExp(`^${t}$`)}function Ne(e,t){if(!me.test(e))return!1;try{const[s]=e.split("."),a=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(s.length+(4-s.length%4)%4,"="),n=JSON.parse(atob(a));return"object"==typeof n&&null!==n&&(!(!n.typ||!n.alg)&&(!t||n.alg===t))}catch(e){return!1}}function Se(e,t){return!("v4"!==t&&t||!ve.test(e))||!("v6"!==t&&t||!be.test(e))}var Me=class e extends de{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==P.string){const t=this._getOrReturnCtx(e);return z(t,{code:$.invalid_type,expected:P.string,received:t.parsedType}),Y}const t=new W;let s;for(const i of this._def.checks)if("min"===i.kind)e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),z(s,{code:$.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),t.dirty());else if("max"===i.kind)e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),z(s,{code:$.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),t.dirty());else if("length"===i.kind){const a=e.data.length>i.value,n=e.data.length<i.value;(a||n)&&(s=this._getOrReturnCtx(e,s),a?z(s,{code:$.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):n&&z(s,{code:$.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),t.dirty())}else if("email"===i.kind)ge.test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"email",code:$.invalid_string,message:i.message}),t.dirty());else if("emoji"===i.kind)oe||(oe=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),oe.test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"emoji",code:$.invalid_string,message:i.message}),t.dirty());else if("uuid"===i.kind)pe.test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"uuid",code:$.invalid_string,message:i.message}),t.dirty());else if("nanoid"===i.kind)he.test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"nanoid",code:$.invalid_string,message:i.message}),t.dirty());else if("cuid"===i.kind)ce.test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"cuid",code:$.invalid_string,message:i.message}),t.dirty());else if("cuid2"===i.kind)ue.test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"cuid2",code:$.invalid_string,message:i.message}),t.dirty());else if("ulid"===i.kind)le.test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"ulid",code:$.invalid_string,message:i.message}),t.dirty());else if("url"===i.kind)try{new URL(e.data)}catch(a){s=this._getOrReturnCtx(e,s),z(s,{validation:"url",code:$.invalid_string,message:i.message}),t.dirty()}else if("regex"===i.kind){i.regex.lastIndex=0;i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"regex",code:$.invalid_string,message:i.message}),t.dirty())}else if("trim"===i.kind)e.data=e.data.trim();else if("includes"===i.kind)e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),z(s,{code:$.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),t.dirty());else if("toLowerCase"===i.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===i.kind)e.data=e.data.toUpperCase();else if("startsWith"===i.kind)e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),z(s,{code:$.invalid_string,validation:{startsWith:i.value},message:i.message}),t.dirty());else if("endsWith"===i.kind)e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),z(s,{code:$.invalid_string,validation:{endsWith:i.value},message:i.message}),t.dirty());else if("datetime"===i.kind){Te(i).test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{code:$.invalid_string,validation:"datetime",message:i.message}),t.dirty())}else if("date"===i.kind){Ie.test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{code:$.invalid_string,validation:"date",message:i.message}),t.dirty())}else if("time"===i.kind){new RegExp(`^${Ce(i)}$`).test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{code:$.invalid_string,validation:"time",message:i.message}),t.dirty())}else"duration"===i.kind?fe.test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"duration",code:$.invalid_string,message:i.message}),t.dirty()):"ip"===i.kind?(a=e.data,("v4"!==(n=i.version)&&n||!ye.test(a))&&("v6"!==n&&n||!_e.test(a))&&(s=this._getOrReturnCtx(e,s),z(s,{validation:"ip",code:$.invalid_string,message:i.message}),t.dirty())):"jwt"===i.kind?Ne(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"jwt",code:$.invalid_string,message:i.message}),t.dirty()):"cidr"===i.kind?Se(e.data,i.version)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"cidr",code:$.invalid_string,message:i.message}),t.dirty()):"base64"===i.kind?we.test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"base64",code:$.invalid_string,message:i.message}),t.dirty()):"base64url"===i.kind?ke.test(e.data)||(s=this._getOrReturnCtx(e,s),z(s,{validation:"base64url",code:$.invalid_string,message:i.message}),t.dirty()):y.assertNever(i);var a,n;return{status:t.value,value:e.data}}_regex(e,t,s){return this.refinement((t=>e.test(t)),{validation:t,code:$.invalid_string,...V.errToObj(s)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:"email",...V.errToObj(e)})}url(e){return this._addCheck({kind:"url",...V.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...V.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...V.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...V.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...V.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...V.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...V.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...V.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...V.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...V.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...V.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...V.errToObj(e)})}datetime(e){var t,s;return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,offset:null!==(t=null==e?void 0:e.offset)&&void 0!==t&&t,local:null!==(s=null==e?void 0:e.local)&&void 0!==s&&s,...V.errToObj(null==e?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,...V.errToObj(null==e?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...V.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...V.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:null==t?void 0:t.position,...V.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...V.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...V.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...V.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...V.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...V.errToObj(t)})}nonempty(e){return this.min(1,V.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e=>"datetime"===e.kind))}get isDate(){return!!this._def.checks.find((e=>"date"===e.kind))}get isTime(){return!!this._def.checks.find((e=>"time"===e.kind))}get isDuration(){return!!this._def.checks.find((e=>"duration"===e.kind))}get isEmail(){return!!this._def.checks.find((e=>"email"===e.kind))}get isURL(){return!!this._def.checks.find((e=>"url"===e.kind))}get isEmoji(){return!!this._def.checks.find((e=>"emoji"===e.kind))}get isUUID(){return!!this._def.checks.find((e=>"uuid"===e.kind))}get isNANOID(){return!!this._def.checks.find((e=>"nanoid"===e.kind))}get isCUID(){return!!this._def.checks.find((e=>"cuid"===e.kind))}get isCUID2(){return!!this._def.checks.find((e=>"cuid2"===e.kind))}get isULID(){return!!this._def.checks.find((e=>"ulid"===e.kind))}get isIP(){return!!this._def.checks.find((e=>"ip"===e.kind))}get isCIDR(){return!!this._def.checks.find((e=>"cidr"===e.kind))}get isBase64(){return!!this._def.checks.find((e=>"base64"===e.kind))}get isBase64url(){return!!this._def.checks.find((e=>"base64url"===e.kind))}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}};function Oe(e,t){const s=(e.toString().split(".")[1]||"").length,a=(t.toString().split(".")[1]||"").length,n=s>a?s:a;return parseInt(e.toFixed(n).replace(".",""))%parseInt(t.toFixed(n).replace(".",""))/Math.pow(10,n)}Me.create=e=>{var t;return new Me({checks:[],typeName:_t.ZodString,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...re(e)})};var Ze=class e extends de{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==P.number){const t=this._getOrReturnCtx(e);return z(t,{code:$.invalid_type,expected:P.number,received:t.parsedType}),Y}let t;const s=new W;for(const a of this._def.checks)if("int"===a.kind)y.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),z(t,{code:$.invalid_type,expected:"integer",received:"float",message:a.message}),s.dirty());else if("min"===a.kind){(a.inclusive?e.data<a.value:e.data<=a.value)&&(t=this._getOrReturnCtx(e,t),z(t,{code:$.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty())}else if("max"===a.kind){(a.inclusive?e.data>a.value:e.data>=a.value)&&(t=this._getOrReturnCtx(e,t),z(t,{code:$.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty())}else"multipleOf"===a.kind?0!==Oe(e.data,a.value)&&(t=this._getOrReturnCtx(e,t),z(t,{code:$.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):"finite"===a.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),z(t,{code:$.not_finite,message:a.message}),s.dirty()):y.assertNever(a);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,V.toString(t))}gt(e,t){return this.setLimit("min",e,!1,V.toString(t))}lte(e,t){return this.setLimit("max",e,!0,V.toString(t))}lt(e,t){return this.setLimit("max",e,!1,V.toString(t))}setLimit(t,s,a,n){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:a,message:V.toString(n)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:"int",message:V.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:V.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:V.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:V.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:V.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:V.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:V.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:V.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:V.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find((e=>"int"===e.kind||"multipleOf"===e.kind&&y.isInteger(e.value)))}get isFinite(){let e=null,t=null;for(const s of this._def.checks){if("finite"===s.kind||"int"===s.kind||"multipleOf"===s.kind)return!0;"min"===s.kind?(null===t||s.value>t)&&(t=s.value):"max"===s.kind&&(null===e||s.value<e)&&(e=s.value)}return Number.isFinite(t)&&Number.isFinite(e)}};Ze.create=e=>new Ze({checks:[],typeName:_t.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...re(e)});var Ae=class e extends de{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch(t){return this._getInvalidInput(e)}if(this._getType(e)!==P.bigint)return this._getInvalidInput(e);let t;const s=new W;for(const a of this._def.checks)if("min"===a.kind){(a.inclusive?e.data<a.value:e.data<=a.value)&&(t=this._getOrReturnCtx(e,t),z(t,{code:$.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty())}else if("max"===a.kind){(a.inclusive?e.data>a.value:e.data>=a.value)&&(t=this._getOrReturnCtx(e,t),z(t,{code:$.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty())}else"multipleOf"===a.kind?e.data%a.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),z(t,{code:$.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):y.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return z(t,{code:$.invalid_type,expected:P.bigint,received:t.parsedType}),Y}gte(e,t){return this.setLimit("min",e,!0,V.toString(t))}gt(e,t){return this.setLimit("min",e,!1,V.toString(t))}lte(e,t){return this.setLimit("max",e,!0,V.toString(t))}lt(e,t){return this.setLimit("max",e,!1,V.toString(t))}setLimit(t,s,a,n){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:a,message:V.toString(n)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:V.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:V.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:V.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:V.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:V.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}};Ae.create=e=>{var t;return new Ae({checks:[],typeName:_t.ZodBigInt,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...re(e)})};var Ee=class extends de{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==P.boolean){const t=this._getOrReturnCtx(e);return z(t,{code:$.invalid_type,expected:P.boolean,received:t.parsedType}),Y}return H(e.data)}};Ee.create=e=>new Ee({typeName:_t.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...re(e)});var je=class e extends de{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==P.date){const t=this._getOrReturnCtx(e);return z(t,{code:$.invalid_type,expected:P.date,received:t.parsedType}),Y}if(isNaN(e.data.getTime())){return z(this._getOrReturnCtx(e),{code:$.invalid_date}),Y}const t=new W;let s;for(const a of this._def.checks)"min"===a.kind?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),z(s,{code:$.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),t.dirty()):"max"===a.kind?e.data.getTime()>a.value&&(s=this._getOrReturnCtx(e,s),z(s,{code:$.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),t.dirty()):y.assertNever(a);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:V.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:V.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}};je.create=e=>new je({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:_t.ZodDate,...re(e)});var Pe=class extends de{_parse(e){if(this._getType(e)!==P.symbol){const t=this._getOrReturnCtx(e);return z(t,{code:$.invalid_type,expected:P.symbol,received:t.parsedType}),Y}return H(e.data)}};Pe.create=e=>new Pe({typeName:_t.ZodSymbol,...re(e)});var Re=class extends de{_parse(e){if(this._getType(e)!==P.undefined){const t=this._getOrReturnCtx(e);return z(t,{code:$.invalid_type,expected:P.undefined,received:t.parsedType}),Y}return H(e.data)}};Re.create=e=>new Re({typeName:_t.ZodUndefined,...re(e)});var $e=class extends de{_parse(e){if(this._getType(e)!==P.null){const t=this._getOrReturnCtx(e);return z(t,{code:$.invalid_type,expected:P.null,received:t.parsedType}),Y}return H(e.data)}};$e.create=e=>new $e({typeName:_t.ZodNull,...re(e)});var Fe=class extends de{constructor(){super(...arguments),this._any=!0}_parse(e){return H(e.data)}};Fe.create=e=>new Fe({typeName:_t.ZodAny,...re(e)});var Ue=class extends de{constructor(){super(...arguments),this._unknown=!0}_parse(e){return H(e.data)}};Ue.create=e=>new Ue({typeName:_t.ZodUnknown,...re(e)});var qe=class extends de{_parse(e){const t=this._getOrReturnCtx(e);return z(t,{code:$.invalid_type,expected:P.never,received:t.parsedType}),Y}};qe.create=e=>new qe({typeName:_t.ZodNever,...re(e)});var De=class extends de{_parse(e){if(this._getType(e)!==P.undefined){const t=this._getOrReturnCtx(e);return z(t,{code:$.invalid_type,expected:P.void,received:t.parsedType}),Y}return H(e.data)}};De.create=e=>new De({typeName:_t.ZodVoid,...re(e)});var Le=class e extends de{_parse(e){const{ctx:t,status:s}=this._processInputParams(e),a=this._def;if(t.parsedType!==P.array)return z(t,{code:$.invalid_type,expected:P.array,received:t.parsedType}),Y;if(null!==a.exactLength){const e=t.data.length>a.exactLength.value,n=t.data.length<a.exactLength.value;(e||n)&&(z(t,{code:e?$.too_big:$.too_small,minimum:n?a.exactLength.value:void 0,maximum:e?a.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:a.exactLength.message}),s.dirty())}if(null!==a.minLength&&t.data.length<a.minLength.value&&(z(t,{code:$.too_small,minimum:a.minLength.value,type:"array",inclusive:!0,exact:!1,message:a.minLength.message}),s.dirty()),null!==a.maxLength&&t.data.length>a.maxLength.value&&(z(t,{code:$.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map(((e,s)=>a.type._parseAsync(new ne(t,e,t.path,s))))).then((e=>W.mergeArray(s,e)));const n=[...t.data].map(((e,s)=>a.type._parseSync(new ne(t,e,t.path,s))));return W.mergeArray(s,n)}get element(){return this._def.type}min(t,s){return new e({...this._def,minLength:{value:t,message:V.toString(s)}})}max(t,s){return new e({...this._def,maxLength:{value:t,message:V.toString(s)}})}length(t,s){return new e({...this._def,exactLength:{value:t,message:V.toString(s)}})}nonempty(e){return this.min(1,e)}};function ze(e){if(e instanceof Ve){const t={};for(const s in e.shape){const a=e.shape[s];t[s]=dt.create(ze(a))}return new Ve({...e._def,shape:()=>t})}return e instanceof Le?new Le({...e._def,type:ze(e.element)}):e instanceof dt?dt.create(ze(e.unwrap())):e instanceof ct?ct.create(ze(e.unwrap())):e instanceof Ge?Ge.create(e.items.map((e=>ze(e)))):e}Le.create=(e,t)=>new Le({type:e,minLength:null,maxLength:null,exactLength:null,typeName:_t.ZodArray,...re(t)});var Ve=class e extends de{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=y.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==P.object){const t=this._getOrReturnCtx(e);return z(t,{code:$.invalid_type,expected:P.object,received:t.parsedType}),Y}const{status:t,ctx:s}=this._processInputParams(e),{shape:a,keys:n}=this._getCached(),i=[];if(!(this._def.catchall instanceof qe&&"strip"===this._def.unknownKeys))for(const e in s.data)n.includes(e)||i.push(e);const r=[];for(const e of n){const t=a[e],n=s.data[e];r.push({key:{status:"valid",value:e},value:t._parse(new ne(s,n,s.path,e)),alwaysSet:e in s.data})}if(this._def.catchall instanceof qe){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of i)r.push({key:{status:"valid",value:e},value:{status:"valid",value:s.data[e]}});else if("strict"===e)i.length>0&&(z(s,{code:$.unrecognized_keys,keys:i}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of i){const a=s.data[t];r.push({key:{status:"valid",value:t},value:e._parse(new ne(s,a,s.path,t)),alwaysSet:t in s.data})}}return s.common.async?Promise.resolve().then((async()=>{const e=[];for(const t of r){const s=await t.key,a=await t.value;e.push({key:s,value:a,alwaysSet:t.alwaysSet})}return e})).then((e=>W.mergeObjectSync(t,e))):W.mergeObjectSync(t,r)}get shape(){return this._def.shape()}strict(t){return V.errToObj,new e({...this._def,unknownKeys:"strict",...void 0!==t?{errorMap:(e,s)=>{var a,n,i,r;const o=null!==(i=null===(n=(a=this._def).errorMap)||void 0===n?void 0:n.call(a,e,s).message)&&void 0!==i?i:s.defaultError;return"unrecognized_keys"===e.code?{message:null!==(r=V.errToObj(t).message)&&void 0!==r?r:o}:{message:o}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:_t.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){const s={};return y.objectKeys(t).forEach((e=>{t[e]&&this.shape[e]&&(s[e]=this.shape[e])})),new e({...this._def,shape:()=>s})}omit(t){const s={};return y.objectKeys(this.shape).forEach((e=>{t[e]||(s[e]=this.shape[e])})),new e({...this._def,shape:()=>s})}deepPartial(){return ze(this)}partial(t){const s={};return y.objectKeys(this.shape).forEach((e=>{const a=this.shape[e];t&&!t[e]?s[e]=a:s[e]=a.optional()})),new e({...this._def,shape:()=>s})}required(t){const s={};return y.objectKeys(this.shape).forEach((e=>{if(t&&!t[e])s[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof dt;)t=t._def.innerType;s[e]=t}})),new e({...this._def,shape:()=>s})}keyof(){return at(y.objectKeys(this.shape))}};Ve.create=(e,t)=>new Ve({shape:()=>e,unknownKeys:"strip",catchall:qe.create(),typeName:_t.ZodObject,...re(t)}),Ve.strictCreate=(e,t)=>new Ve({shape:()=>e,unknownKeys:"strict",catchall:qe.create(),typeName:_t.ZodObject,...re(t)}),Ve.lazycreate=(e,t)=>new Ve({shape:e,unknownKeys:"strip",catchall:qe.create(),typeName:_t.ZodObject,...re(t)});var Ke=class extends de{_parse(e){const{ctx:t}=this._processInputParams(e),s=this._def.options;if(t.common.async)return Promise.all(s.map((async e=>{const s={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:s}),ctx:s}}))).then((function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const s of e)if("dirty"===s.result.status)return t.common.issues.push(...s.ctx.common.issues),s.result;const s=e.map((e=>new F(e.ctx.common.issues)));return z(t,{code:$.invalid_union,unionErrors:s}),Y}));{let e;const a=[];for(const n of s){const s={...t,common:{...t.common,issues:[]},parent:null},i=n._parseSync({data:t.data,path:t.path,parent:s});if("valid"===i.status)return i;"dirty"!==i.status||e||(e={result:i,ctx:s}),s.common.issues.length&&a.push(s.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const n=a.map((e=>new F(e)));return z(t,{code:$.invalid_union,unionErrors:n}),Y}}get options(){return this._def.options}};Ke.create=(e,t)=>new Ke({options:e,typeName:_t.ZodUnion,...re(t)});var Be=e=>e instanceof tt?Be(e.schema):e instanceof ot?Be(e.innerType()):e instanceof st?[e.value]:e instanceof nt?e.options:e instanceof it?y.objectValues(e.enum):e instanceof ut?Be(e._def.innerType):e instanceof Re?[void 0]:e instanceof $e?[null]:e instanceof dt?[void 0,...Be(e.unwrap())]:e instanceof ct?[null,...Be(e.unwrap())]:e instanceof mt||e instanceof gt?Be(e.unwrap()):e instanceof lt?Be(e._def.innerType):[],Je=class e extends de{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==P.object)return z(t,{code:$.invalid_type,expected:P.object,received:t.parsedType}),Y;const s=this.discriminator,a=t.data[s],n=this.optionsMap.get(a);return n?t.common.async?n._parseAsync({data:t.data,path:t.path,parent:t}):n._parseSync({data:t.data,path:t.path,parent:t}):(z(t,{code:$.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),Y)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,s,a){const n=new Map;for(const e of s){const s=Be(e.shape[t]);if(!s.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const a of s){if(n.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);n.set(a,e)}}return new e({typeName:_t.ZodDiscriminatedUnion,discriminator:t,options:s,optionsMap:n,...re(a)})}};function We(e,t){const s=R(e),a=R(t);if(e===t)return{valid:!0,data:e};if(s===P.object&&a===P.object){const s=y.objectKeys(t),a=y.objectKeys(e).filter((e=>-1!==s.indexOf(e))),n={...e,...t};for(const s of a){const a=We(e[s],t[s]);if(!a.valid)return{valid:!1};n[s]=a.data}return{valid:!0,data:n}}if(s===P.array&&a===P.array){if(e.length!==t.length)return{valid:!1};const s=[];for(let a=0;a<e.length;a++){const n=We(e[a],t[a]);if(!n.valid)return{valid:!1};s.push(n.data)}return{valid:!0,data:s}}return s===P.date&&a===P.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var Ye=class extends de{_parse(e){const{status:t,ctx:s}=this._processInputParams(e),a=(e,a)=>{if(Q(e)||Q(a))return Y;const n=We(e.value,a.value);return n.valid?((X(e)||X(a))&&t.dirty(),{status:t.value,value:n.data}):(z(s,{code:$.invalid_intersection_types}),Y)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then((([e,t])=>a(e,t))):a(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}};Ye.create=(e,t,s)=>new Ye({left:e,right:t,typeName:_t.ZodIntersection,...re(s)});var Ge=class e extends de{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==P.array)return z(s,{code:$.invalid_type,expected:P.array,received:s.parsedType}),Y;if(s.data.length<this._def.items.length)return z(s,{code:$.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Y;!this._def.rest&&s.data.length>this._def.items.length&&(z(s,{code:$.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const a=[...s.data].map(((e,t)=>{const a=this._def.items[t]||this._def.rest;return a?a._parse(new ne(s,e,s.path,t)):null})).filter((e=>!!e));return s.common.async?Promise.all(a).then((e=>W.mergeArray(t,e))):W.mergeArray(t,a)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Ge.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ge({items:e,typeName:_t.ZodTuple,rest:null,...re(t)})};var He=class e extends de{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==P.object)return z(s,{code:$.invalid_type,expected:P.object,received:s.parsedType}),Y;const a=[],n=this._def.keyType,i=this._def.valueType;for(const e in s.data)a.push({key:n._parse(new ne(s,e,s.path,e)),value:i._parse(new ne(s,s.data[e],s.path,e)),alwaysSet:e in s.data});return s.common.async?W.mergeObjectAsync(t,a):W.mergeObjectSync(t,a)}get element(){return this._def.valueType}static create(t,s,a){return new e(s instanceof de?{keyType:t,valueType:s,typeName:_t.ZodRecord,...re(a)}:{keyType:Me.create(),valueType:t,typeName:_t.ZodRecord,...re(s)})}},Qe=class extends de{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==P.map)return z(s,{code:$.invalid_type,expected:P.map,received:s.parsedType}),Y;const a=this._def.keyType,n=this._def.valueType,i=[...s.data.entries()].map((([e,t],i)=>({key:a._parse(new ne(s,e,s.path,[i,"key"])),value:n._parse(new ne(s,t,s.path,[i,"value"]))})));if(s.common.async){const e=new Map;return Promise.resolve().then((async()=>{for(const s of i){const a=await s.key,n=await s.value;if("aborted"===a.status||"aborted"===n.status)return Y;"dirty"!==a.status&&"dirty"!==n.status||t.dirty(),e.set(a.value,n.value)}return{status:t.value,value:e}}))}{const e=new Map;for(const s of i){const a=s.key,n=s.value;if("aborted"===a.status||"aborted"===n.status)return Y;"dirty"!==a.status&&"dirty"!==n.status||t.dirty(),e.set(a.value,n.value)}return{status:t.value,value:e}}}};Qe.create=(e,t,s)=>new Qe({valueType:t,keyType:e,typeName:_t.ZodMap,...re(s)});var Xe=class e extends de{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==P.set)return z(s,{code:$.invalid_type,expected:P.set,received:s.parsedType}),Y;const a=this._def;null!==a.minSize&&s.data.size<a.minSize.value&&(z(s,{code:$.too_small,minimum:a.minSize.value,type:"set",inclusive:!0,exact:!1,message:a.minSize.message}),t.dirty()),null!==a.maxSize&&s.data.size>a.maxSize.value&&(z(s,{code:$.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),t.dirty());const n=this._def.valueType;function i(e){const s=new Set;for(const a of e){if("aborted"===a.status)return Y;"dirty"===a.status&&t.dirty(),s.add(a.value)}return{status:t.value,value:s}}const r=[...s.data.values()].map(((e,t)=>n._parse(new ne(s,e,s.path,t))));return s.common.async?Promise.all(r).then((e=>i(e))):i(r)}min(t,s){return new e({...this._def,minSize:{value:t,message:V.toString(s)}})}max(t,s){return new e({...this._def,maxSize:{value:t,message:V.toString(s)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Xe.create=(e,t)=>new Xe({valueType:e,minSize:null,maxSize:null,typeName:_t.ZodSet,...re(t)});var et=class e extends de{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==P.function)return z(t,{code:$.invalid_type,expected:P.function,received:t.parsedType}),Y;function s(e,s){return L({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,D(),U].filter((e=>!!e)),issueData:{code:$.invalid_arguments,argumentsError:s}})}function a(e,s){return L({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,D(),U].filter((e=>!!e)),issueData:{code:$.invalid_return_type,returnTypeError:s}})}const n={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof rt){const e=this;return H((async function(...t){const r=new F([]),o=await e._def.args.parseAsync(t,n).catch((e=>{throw r.addIssue(s(t,e)),r})),d=await Reflect.apply(i,this,o);return await e._def.returns._def.type.parseAsync(d,n).catch((e=>{throw r.addIssue(a(d,e)),r}))}))}{const e=this;return H((function(...t){const r=e._def.args.safeParse(t,n);if(!r.success)throw new F([s(t,r.error)]);const o=Reflect.apply(i,this,r.data),d=e._def.returns.safeParse(o,n);if(!d.success)throw new F([a(o,d.error)]);return d.data}))}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Ge.create(t).rest(Ue.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,s,a){return new e({args:t||Ge.create([]).rest(Ue.create()),returns:s||Ue.create(),typeName:_t.ZodFunction,...re(a)})}},tt=class extends de{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})}};tt.create=(e,t)=>new tt({getter:e,typeName:_t.ZodLazy,...re(t)});var st=class extends de{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return z(t,{received:t.data,code:$.invalid_literal,expected:this._def.value}),Y}return{status:"valid",value:e.data}}get value(){return this._def.value}};function at(e,t){return new nt({values:e,typeName:_t.ZodEnum,...re(t)})}st.create=(e,t)=>new st({value:e,typeName:_t.ZodLiteral,...re(t)});var nt=class e extends de{constructor(){super(...arguments),B.set(this,void 0)}_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),s=this._def.values;return z(t,{expected:y.joinValues(s),received:t.parsedType,code:$.invalid_type}),Y}if(se(this,B)||ae(this,B,new Set(this._def.values)),!se(this,B).has(e.data)){const t=this._getOrReturnCtx(e),s=this._def.values;return z(t,{received:t.data,code:$.invalid_enum_value,options:s}),Y}return H(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(t,s=this._def){return e.create(t,{...this._def,...s})}exclude(t,s=this._def){return e.create(this.options.filter((e=>!t.includes(e))),{...this._def,...s})}};B=new WeakMap,nt.create=at;var it=class extends de{constructor(){super(...arguments),J.set(this,void 0)}_parse(e){const t=y.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==P.string&&s.parsedType!==P.number){const e=y.objectValues(t);return z(s,{expected:y.joinValues(e),received:s.parsedType,code:$.invalid_type}),Y}if(se(this,J)||ae(this,J,new Set(y.getValidEnumValues(this._def.values))),!se(this,J).has(e.data)){const e=y.objectValues(t);return z(s,{received:s.data,code:$.invalid_enum_value,options:e}),Y}return H(e.data)}get enum(){return this._def.values}};J=new WeakMap,it.create=(e,t)=>new it({values:e,typeName:_t.ZodNativeEnum,...re(t)});var rt=class extends de{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==P.promise&&!1===t.common.async)return z(t,{code:$.invalid_type,expected:P.promise,received:t.parsedType}),Y;const s=t.parsedType===P.promise?t.data:Promise.resolve(t.data);return H(s.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}};rt.create=(e,t)=>new rt({type:e,typeName:_t.ZodPromise,...re(t)});var ot=class extends de{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===_t.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:s}=this._processInputParams(e),a=this._def.effect||null,n={addIssue:e=>{z(s,e),e.fatal?t.abort():t.dirty()},get path(){return s.path}};if(n.addIssue=n.addIssue.bind(n),"preprocess"===a.type){const e=a.transform(s.data,n);if(s.common.async)return Promise.resolve(e).then((async e=>{if("aborted"===t.value)return Y;const a=await this._def.schema._parseAsync({data:e,path:s.path,parent:s});return"aborted"===a.status?Y:"dirty"===a.status||"dirty"===t.value?G(a.value):a}));{if("aborted"===t.value)return Y;const a=this._def.schema._parseSync({data:e,path:s.path,parent:s});return"aborted"===a.status?Y:"dirty"===a.status||"dirty"===t.value?G(a.value):a}}if("refinement"===a.type){const e=e=>{const t=a.refinement(e,n);if(s.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===s.common.async){const a=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return"aborted"===a.status?Y:("dirty"===a.status&&t.dirty(),e(a.value),{status:t.value,value:a.value})}return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then((s=>"aborted"===s.status?Y:("dirty"===s.status&&t.dirty(),e(s.value).then((()=>({status:t.value,value:s.value}))))))}if("transform"===a.type){if(!1===s.common.async){const e=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!ee(e))return e;const i=a.transform(e.value,n);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then((e=>ee(e)?Promise.resolve(a.transform(e.value,n)).then((e=>({status:t.value,value:e}))):e))}y.assertNever(a)}};ot.create=(e,t,s)=>new ot({schema:e,typeName:_t.ZodEffects,effect:t,...re(s)}),ot.createWithPreprocess=(e,t,s)=>new ot({schema:t,effect:{type:"preprocess",transform:e},typeName:_t.ZodEffects,...re(s)});var dt=class extends de{_parse(e){return this._getType(e)===P.undefined?H(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};dt.create=(e,t)=>new dt({innerType:e,typeName:_t.ZodOptional,...re(t)});var ct=class extends de{_parse(e){return this._getType(e)===P.null?H(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ct.create=(e,t)=>new ct({innerType:e,typeName:_t.ZodNullable,...re(t)});var ut=class extends de{_parse(e){const{ctx:t}=this._processInputParams(e);let s=t.data;return t.parsedType===P.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ut.create=(e,t)=>new ut({innerType:e,typeName:_t.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...re(t)});var lt=class extends de{_parse(e){const{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},a=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return te(a)?a.then((e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new F(s.common.issues)},input:s.data})}))):{status:"valid",value:"valid"===a.status?a.value:this._def.catchValue({get error(){return new F(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};lt.create=(e,t)=>new lt({innerType:e,typeName:_t.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...re(t)});var pt=class extends de{_parse(e){if(this._getType(e)!==P.nan){const t=this._getOrReturnCtx(e);return z(t,{code:$.invalid_type,expected:P.nan,received:t.parsedType}),Y}return{status:"valid",value:e.data}}};pt.create=e=>new pt({typeName:_t.ZodNaN,...re(e)});var ht=Symbol("zod_brand"),mt=class extends de{_parse(e){const{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}},ft=class e extends de{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return"aborted"===e.status?Y:"dirty"===e.status?(t.dirty(),G(e.value)):this._def.out._parseAsync({data:e.value,path:s.path,parent:s})})()}{const e=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return"aborted"===e.status?Y:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:s.path,parent:s})}}static create(t,s){return new e({in:t,out:s,typeName:_t.ZodPipeline})}},gt=class extends de{_parse(e){const t=this._def.innerType._parse(e),s=e=>(ee(e)&&(e.value=Object.freeze(e.value)),e);return te(t)?t.then((e=>s(e))):s(t)}unwrap(){return this._def.innerType}};function yt(e,t){const s="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof s?{message:s}:s}function vt(e,t={},s){return e?Fe.create().superRefine(((a,n)=>{var i,r;const o=e(a);if(o instanceof Promise)return o.then((e=>{var i,r;if(!e){const e=yt(t,a),o=null===(r=null!==(i=e.fatal)&&void 0!==i?i:s)||void 0===r||r;n.addIssue({code:"custom",...e,fatal:o})}}));if(!o){const e=yt(t,a),o=null===(r=null!==(i=e.fatal)&&void 0!==i?i:s)||void 0===r||r;n.addIssue({code:"custom",...e,fatal:o})}})):Fe.create()}gt.create=(e,t)=>new gt({innerType:e,typeName:_t.ZodReadonly,...re(t)});var _t,bt,wt={object:Ve.lazycreate};(bt=_t||(_t={})).ZodString="ZodString",bt.ZodNumber="ZodNumber",bt.ZodNaN="ZodNaN",bt.ZodBigInt="ZodBigInt",bt.ZodBoolean="ZodBoolean",bt.ZodDate="ZodDate",bt.ZodSymbol="ZodSymbol",bt.ZodUndefined="ZodUndefined",bt.ZodNull="ZodNull",bt.ZodAny="ZodAny",bt.ZodUnknown="ZodUnknown",bt.ZodNever="ZodNever",bt.ZodVoid="ZodVoid",bt.ZodArray="ZodArray",bt.ZodObject="ZodObject",bt.ZodUnion="ZodUnion",bt.ZodDiscriminatedUnion="ZodDiscriminatedUnion",bt.ZodIntersection="ZodIntersection",bt.ZodTuple="ZodTuple",bt.ZodRecord="ZodRecord",bt.ZodMap="ZodMap",bt.ZodSet="ZodSet",bt.ZodFunction="ZodFunction",bt.ZodLazy="ZodLazy",bt.ZodLiteral="ZodLiteral",bt.ZodEnum="ZodEnum",bt.ZodEffects="ZodEffects",bt.ZodNativeEnum="ZodNativeEnum",bt.ZodOptional="ZodOptional",bt.ZodNullable="ZodNullable",bt.ZodDefault="ZodDefault",bt.ZodCatch="ZodCatch",bt.ZodPromise="ZodPromise",bt.ZodBranded="ZodBranded",bt.ZodPipeline="ZodPipeline",bt.ZodReadonly="ZodReadonly";var kt=Me.create,xt=Ze.create,It=pt.create,Ct=Ae.create,Tt=Ee.create,Nt=je.create,St=Pe.create,Mt=Re.create,Ot=$e.create,Zt=Fe.create,At=Ue.create,Et=qe.create,jt=De.create,Pt=Le.create,Rt=Ve.create,$t=Ve.strictCreate,Ft=Ke.create,Ut=Je.create,qt=Ye.create,Dt=Ge.create,Lt=He.create,zt=Qe.create,Vt=Xe.create,Kt=et.create,Bt=tt.create,Jt=st.create,Wt=nt.create,Yt=it.create,Gt=rt.create,Ht=ot.create,Qt=dt.create,Xt=ct.create,es=ot.createWithPreprocess,ts=ft.create,ss={string:e=>Me.create({...e,coerce:!0}),number:e=>Ze.create({...e,coerce:!0}),boolean:e=>Ee.create({...e,coerce:!0}),bigint:e=>Ae.create({...e,coerce:!0}),date:e=>je.create({...e,coerce:!0})},as=Y,ns=Object.freeze({__proto__:null,defaultErrorMap:U,setErrorMap:function(e){q=e},getErrorMap:D,makeIssue:L,EMPTY_PATH:[],addIssueToContext:z,ParseStatus:W,INVALID:Y,DIRTY:G,OK:H,isAborted:Q,isDirty:X,isValid:ee,isAsync:te,get util(){return y},get objectUtil(){return _},ZodParsedType:P,getParsedType:R,ZodType:de,datetimeRegex:Te,ZodString:Me,ZodNumber:Ze,ZodBigInt:Ae,ZodBoolean:Ee,ZodDate:je,ZodSymbol:Pe,ZodUndefined:Re,ZodNull:$e,ZodAny:Fe,ZodUnknown:Ue,ZodNever:qe,ZodVoid:De,ZodArray:Le,ZodObject:Ve,ZodUnion:Ke,ZodDiscriminatedUnion:Je,ZodIntersection:Ye,ZodTuple:Ge,ZodRecord:He,ZodMap:Qe,ZodSet:Xe,ZodFunction:et,ZodLazy:tt,ZodLiteral:st,ZodEnum:nt,ZodNativeEnum:it,ZodPromise:rt,ZodEffects:ot,ZodTransformer:ot,ZodOptional:dt,ZodNullable:ct,ZodDefault:ut,ZodCatch:lt,ZodNaN:pt,BRAND:ht,ZodBranded:mt,ZodPipeline:ft,ZodReadonly:gt,custom:vt,Schema:de,ZodSchema:de,late:wt,get ZodFirstPartyTypeKind(){return _t},coerce:ss,any:Zt,array:Pt,bigint:Ct,boolean:Tt,date:Nt,discriminatedUnion:Ut,effect:Ht,enum:Wt,function:Kt,instanceof:(e,t={message:`Input not instance of ${e.name}`})=>vt((t=>t instanceof e),t),intersection:qt,lazy:Bt,literal:Jt,map:zt,nan:It,nativeEnum:Yt,never:Et,null:Ot,nullable:Xt,number:xt,object:Rt,oboolean:()=>Tt().optional(),onumber:()=>xt().optional(),optional:Qt,ostring:()=>kt().optional(),pipeline:ts,preprocess:es,promise:Gt,record:Lt,set:Vt,strictObject:$t,string:kt,symbol:St,transformer:Ht,tuple:Dt,undefined:Mt,union:Ft,unknown:At,void:jt,NEVER:as,ZodIssueCode:$,quotelessJson:e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ZodError:F}),is=ns.object({type:ns.enum(["sqlite","postgresql","mysql"]).default("sqlite"),connection:ns.object({url:ns.string().default("./session/zaileys.db")}).optional().default({})}).optional().default({}),rs=ns.record(ns.function().returns(ns.union([ns.number().array(),ns.promise(ns.number().array())]))).optional().transform((async e=>{if(!e)return{};const t={};for(const[s,a]of Object.entries(e)){t[`is${s.charAt(0).toUpperCase()}${s.slice(1)}`]=await a()}return t})),os=ns.object({prefix:ns.string().optional(),ignoreMe:ns.boolean().optional().default(!0),showLogs:ns.boolean().optional().default(!0),autoMentions:ns.boolean().optional().default(!0),autoOnline:ns.boolean().optional().default(!0),autoRead:ns.boolean().optional().default(!0),autoPresence:ns.boolean().optional().default(!0),autoRejectCall:ns.boolean().optional().default(!0),database:is,citation:rs}),ds=ns.object({authType:ns.literal("pairing"),phoneNumber:ns.number()}).extend(os.shape),cs=ns.object({authType:ns.literal("qr"),phoneNumber:ns.undefined().optional()}).extend(os.shape),us=ns.discriminatedUnion("authType",[ds,cs]),ls=(e="")=>{try{return JSON.parse(e)}catch{return JSON.parse(JSON.stringify(e))}},ps=(e={})=>{try{return JSON.stringify(e)}catch{return JSON.stringify(JSON.parse(JSON.stringify(e)))}},hs=(e="",t="")=>e?e.toLowerCase().includes(t.toLowerCase()):null,ms=(e,t)=>e&&"object"==typeof e?Array.isArray(e)?e.map((e=>ms(e,t))):Object.fromEntries(Object.entries(e).filter((([e])=>!t.includes(e))).map((([e,s])=>[e,"object"==typeof s?ms(s,t):s]))):e,fs={text:"text",conversation:"text",imageMessage:"image",contactMessage:"contact",locationMessage:"location",documentMessage:"document",audioMessage:"audio",videoMessage:"video",protocolMessage:"protocol",contactsArrayMessage:"contactsArray",highlyStructuredMessage:"highlyStructured",sendPaymentMessage:"sendPayment",liveLocationMessage:"liveLocation",requestPaymentMessage:"requestPayment",declinePaymentRequestMessage:"declinePaymentRequest",cancelPaymentRequestMessage:"cancelPaymentRequest",templateMessage:"template",stickerMessage:"sticker",groupInviteMessage:"groupInvite",templateButtonReplyMessage:"templateButtonReply",productMessage:"product",deviceSentMessage:"deviceSent",listMessage:"list",viewOnceMessage:"viewOnce",orderMessage:"order",listResponseMessage:"listResponse",ephemeralMessage:"ephemeral",invoiceMessage:"invoice",buttonsMessage:"buttons",buttonsResponseMessage:"buttonsResponse",paymentInviteMessage:"paymentInvite",interactiveMessage:"interactive",reactionMessage:"reaction",stickerSyncRmrMessage:"sticker",interactiveResponseMessage:"interactiveResponse",pollCreationMessage:"pollCreation",pollUpdateMessage:"pollUpdate",keepInChatMessage:"keepInChat",documentWithCaptionMessage:"document",requestPhoneNumberMessage:"requestPhoneNumber",viewOnceMessageV2:"viewOnce",encReactionMessage:"reaction",editedMessage:"text",viewOnceMessageV2Extension:"viewOnce",pollCreationMessageV2:"pollCreation",scheduledCallCreationMessage:"scheduledCallCreation",groupMentionedMessage:"groupMentioned",pinInChatMessage:"pinInChat",pollCreationMessageV3:"pollCreation",scheduledCallEditMessage:"scheduledCallEdit",ptvMessage:"ptv",botInvokeMessage:"botInvoke",callLogMesssage:"callLog",encCommentMessage:"encComment",bcallMessage:"bcall",lottieStickerMessage:"lottieSticker",eventMessage:"event",commentMessage:"comment",newsletterAdminInviteMessage:"text",extendedTextMessageWithParentKey:"text",extendedTextMessage:"text",placeholderMessage:"placeholder",encEventUpdateMessage:"encEventUpdate"},gs={whatsapp:"0@s.whatsapp.net",meta:"13135550002@s.whatsapp.net",chatgpt:"18002428478@s.whatsapp.net",copilot:"18772241042@s.whatsapp.net",instagram:"447723442971@s.whatsapp.net",tiktok:"6285574670498@s.whatsapp.net"},ys=ns.enum(["text","text","image","contact","location","document","audio","video","protocol","contactsArray","highlyStructured","sendPayment","liveLocation","requestPayment","declinePaymentRequest","cancelPaymentRequest","template","sticker","groupInvite","templateButtonReply","product","deviceSent","list","viewOnce","order","listResponse","ephemeral","invoice","buttons","buttonsResponse","paymentInvite","interactive","reaction","sticker","interactiveResponse","pollCreation","pollUpdate","keepInChat","document","requestPhoneNumber","viewOnce","reaction","text","viewOnce","pollCreation","scheduledCallCreation","groupMentioned","pinInChat","pollCreation","scheduledCallEdit","ptv","botInvoke","callLog","encComment","bcall","lottieSticker","event","comment","text","text","placeholder","encEventUpdate"]),vs=ns.enum(["unknown","android","ios","desktop","web"]),_s=ns.object({chatId:ns.string(),channelId:ns.string(),receiverId:ns.string(),receiverName:ns.string(),roomId:ns.string(),roomName:ns.string(),senderId:ns.string(),senderName:ns.string(),senderDevice:vs,chatType:ys,timestamp:ns.number(),mentions:ns.string().array(),text:ns.string().nullable(),links:ns.string().array(),isPrefix:ns.boolean(),isFromMe:ns.boolean(),isTagMe:ns.boolean(),isGroup:ns.boolean(),isStory:ns.boolean(),isViewOnce:ns.boolean(),isEdited:ns.boolean(),isDeleted:ns.boolean(),isPinned:ns.boolean(),isUnPinned:ns.boolean(),isChannel:ns.boolean(),isBroadcast:ns.boolean(),isEphemeral:ns.boolean(),isForwarded:ns.boolean(),citation:ns.record(ns.string(),ns.boolean()).nullable(),media:ns.object({buffer:ns.function().returns(ns.unknown()),stream:ns.function().returns(ns.unknown())}).passthrough().nullable(),message:ns.function().returns(ns.record(ns.string(),ns.any()))});_s.extend({replied:_s.nullable()});var bs=class{constructor(e,t,s){this.socket=e,this.client=t,this.db=s}maxReplies=0;async connection(t){const{connection:s,lastDisconnect:a,qr:n}=t;if(this.client.startSpinner("connection","Connecting to WhatsApp..."),this.client.emit("connection",{status:"connecting"}),"qr"===this.client.options?.authType&&n)return this.client.stopSpinner("connection",!1),this.client.startSpinner("qr","Waiting for QR code scan..."),void this.socket?.ev.on("connection.update",(()=>this.client.stopSpinner("qr",!1)));if("close"===s){this.client.failSpinner("connection","Connection closed");const t=a?.error?.output?.statusCode,s=t!==e.DisconnectReason.loggedOut;if(console.log(a?.error?.message),401===t||405===t||500===t)return;s&&this.client.options&&await this.client.initialize()}else"open"===s&&(this.client.stopSpinner("connection",!0,"Connected to WhatsApp\n"),this.client.emit("connection",{status:"open"}))}async messages(t,s){if(t?.messageStubType||t?.messageStubParameters?.length||t?.message?.protocolMessage?.peerDataOperationRequestResponseMessage||t?.message?.botInvokeMessage||!t?.key?.id||!t?.message)return null;if(this.client.options?.ignoreMe&&t?.key?.fromMe&&"status@broadcast"!=t?.key?.remoteJid&&!t?.participant)return null;this.client.options?.autoRead&&await this.socket.readMessages([t?.key]);const a=t,n=t?.message?.pinInChatMessage?.key?.id,i=1==t?.message?.pinInChatMessage?.type,r=2==t?.message?.pinInChatMessage?.type;if(n){const e=await this.db.selectFrom("messages").select("value").where("id","=",n).executeTakeFirst(),s=ls(e?.value);t=s}const o=!t?.message?.protocolMessage?.editedMessage&&t?.message?.protocolMessage?.key?.id,d=!!o;if(o){const e=await this.db.selectFrom("messages").select("value").where("id","=",o).executeTakeFirst(),s=ls(e?.value);t=s}const c={},u=e.getContentType(t?.message?.protocolMessage?.editedMessage||t?.message);c.chatId=t?.message?.protocolMessage?.key?.id||t?.key?.id,c.channelId="",c.receiverId=e.jidNormalizedUser(this.socket.user?.id),c.receiverName=this.socket.user?.name||this.socket.user?.verifiedName,c.roomId=e.jidNormalizedUser(t?.key?.remoteJid);const l=await this.db.selectFrom("chats").select("value").where("id","=",c.roomId).executeTakeFirst();c.roomName=ls(l?.value)?.name,c.senderId=e.jidNormalizedUser(t?.participant||t?.key?.participant||t?.key?.remoteJid);const p=await this.db.selectFrom("chats").select("value").where("id","=",c.senderId).executeTakeFirst();c.senderName=t?.pushName||t?.verifiedBizName||ls(p?.value)?.name||c.receiverName,c.roomName=c.roomName||c.senderName,c.senderDevice=e.getDevice(c.chatId),c.chatType=fs[u],c.timestamp=t?.messageTimestamp?.low||t?.messageTimestamp||0,c.mentions=[],c.text=null,c.links=[],c.isPrefix=!1,c.isFromMe=t?.key?.fromMe,c.isTagMe=!1,c.isGroup=c.roomId.includes("@g.us"),c.isStory=c.roomId.includes("@broadcast"),c.isViewOnce=!1,c.isEdited=!1,c.isDeleted=d,c.isPinned=i,c.isUnPinned=r,c.isChannel=c.roomId.includes("@newsletter"),c.isBroadcast=!!t?.broadcast,c.isEphemeral=!1,c.isForwarded=!1,c.citation=null,c.media=null,c.replied=null,c.channelId=c.roomId.split("@")[0]+"-"+c.senderId.split("@")[0];const h=this.client.options?.citation;if(Object.keys(h).length){c.citation={};for(const e of Object.keys(h))c.citation[e]=h[e].includes(Number(c.senderId.split("@")[0]))||h[e].includes(Number(c.roomId.split("@")[0]))}const m=(t?.message?.protocolMessage?.editedMessage?.[u]||t?.message[u])?.message?.documentMessage||t?.message[u];"text"!=c.chatType&&(c.media={...ms(m,["url","contextInfo","fileSha256","fileEncSha256","mediaKey","directPath","waveform","thumbnail","jpegThumbnail","thumbnailEncSha256","thumbnailSha256","thumbnailDirectPath","firstFrameSidecar","streamingSidecar","scansSidecar","callKey","midQualityFileSha256"]),buffer:async()=>await e.downloadMediaMessage(t,"buffer",{}),stream:async()=>await e.downloadMediaMessage(t,"stream",{})});const f=t?.message?.[u]?.contextInfo?.stanzaId;if(f&&this.maxReplies<1){this.maxReplies++;const s=await this.db.selectFrom("messages").select("value").where("id","=",f).executeTakeFirst(),a=ls(s?.value);if(a)c.replied=await this.messages(a,!0);else{const s=t,a=e.getContentType(s.message?.extendedTextMessage?.contextInfo.quotedMessage);s.key.id=s.message?.extendedTextMessage?.contextInfo.stanzaId,s.message[a]=s.message?.extendedTextMessage?.contextInfo.quotedMessage[a],delete s.message?.extendedTextMessage,c.replied=await this.messages(s,!0)}}const g="string"==typeof m?m:m?.text||m?.caption||m?.name||m?.displayName||"";c.text=((e="")=>e?e.replace(/\u202E([\s\S]*?)\u202C/g,((e,t)=>Array.from(t).reverse().join(""))).replace(/[\u202A-\u202E\u202C]/g,""):null)(g)||null,c.mentions=((e="")=>{if(!e)return[];const t=new Set;for(const s of e.matchAll(/@(\d+)/g))t.add(s[1]);return[...t]})(c.text),c.links=((e="")=>e&&e.match(/(?:https?:\/\/)?[^\s<>"']+\.[^\s<>"']+/g)||[])(c.text);const y=t?.message?.[u];return c.isPrefix=!!this.client.options?.prefix&&!!c.text?.startsWith(this.client.options?.prefix),c.isTagMe=c.mentions.includes(c.receiverId.split("@")[0]),c.isEdited=hs(ps(t),"editedMessage"),c.isEphemeral=hs(ps(y?.contextInfo),"ephemeralSettingTimestamp"),c.isForwarded=hs(ps(y?.contextInfo),"forwardingScore"),c.isViewOnce=!!y?.viewOnce,c.message=()=>a,s||this.client.emit("messages",c),c}async calls(e){this.client.options?.autoRejectCall&&await this.socket.rejectCall(e.id,e.from);const t={};t.callId=e.id,t.roomId=e.chatId,t.callerId=e.from,t.date=e.date,t.offline=e.offline,t.status=e.status,t.isVideo=!!e.isVideo,t.isGroup=!!e.isGroup,this.client.emit("calls",t)}},ws=ns.union([ns.string().url(),ns.instanceof(Buffer).or(ns.instanceof(f.Readable))]),ks=ns.union([ns.string(),ns.object({image:ws,text:ns.string().optional()}),ns.object({video:ws,text:ns.string().optional()}),ns.object({videoNote:ws}),ns.object({gif:ws,text:ns.string().optional()}),ns.object({audio:ws}),ns.object({audioNote:ws}),ns.object({sticker:ws})]),xs=ns.object({roomId:ns.string(),asForwarded:ns.boolean().optional(),asViewOnce:ns.boolean().optional(),verifiedReply:ns.enum(["whatsapp","meta","chatgpt","copilot","instagram","tiktok"]).optional(),quoted:ns.function().returns(ns.record(ns.string(),ns.any())).optional()}),Is=xs,Cs=ns.object({latitude:ns.number(),longitude:ns.number(),title:ns.string().optional(),footer:ns.string().optional()}),Ts=xs,Ns=ns.object({fullname:ns.string(),nickname:ns.string().optional(),organization:ns.string().optional(),role:ns.string().optional(),email:ns.string().email().optional(),whatsAppNumber:ns.number(),callNumber:ns.number().optional(),voiceNumber:ns.number().optional(),website:ns.string().url().optional(),homeAddress:ns.string().optional(),workAddress:ns.string().optional(),avatar:ns.string().url().optional()}),Ss=xs.pick({roomId:!0}).merge(ns.object({message:ns.function().returns(ns.record(ns.string(),ns.any()))})),Ms=ns.string(),Os=xs.pick({roomId:!0}).merge(ns.object({message:ns.function().returns(ns.record(ns.string(),ns.any()))})),Zs=ns.object({action:ns.enum(["pin","unpin"]),expired:ns.enum(["24h","7d","30d"])}),As=xs.pick({roomId:!0}),Es=ns.object({name:ns.string(),answers:ns.string().array(),multipleAnswers:ns.boolean().optional()}),js=xs.pick({roomId:!0}).merge(ns.object({message:ns.function().returns(ns.record(ns.string(),ns.any()))})),Ps=ns.string(),Rs=xs.pick({roomId:!0}),$s=ns.object({message:ns.function().returns(ns.record(ns.string(),ns.any()))}),Fs=ns.object({callId:ns.string(),callerId:ns.string()}),Us=xs.pick({roomId:!0}),qs=ns.object({expired:ns.enum(["remove","8h","7d"])}),Ds=ns.string();ns.object({type:ns.enum(["group","user"]),id:ns.string(),name:ns.string(),bio:ns.string(),avatar:ns.string().url(),ephemeralDuration:ns.number().optional(),isRestrict:ns.boolean().optional(),isAnnounce:ns.boolean().optional(),isCommunity:ns.boolean().optional(),isCommunityAnnounce:ns.boolean().optional(),isJoinApprovalMode:ns.boolean().optional(),isMemberAddMode:ns.boolean().optional(),owner:ns.object({type:ns.literal("user"),id:ns.string()}).nullable(),roomCreatedAt:ns.number().optional(),nameUpdatedAt:ns.number().optional(),bioUpdatedAt:ns.number().optional(),membersLength:ns.number().optional(),members:ns.object({type:ns.enum(["user","admin","superadmin"]),id:ns.string()}).array().optional()});var Ls=xs.pick({roomId:!0}),zs=ns.enum(["typing","recording","online","offline","paused"]),Vs=class{constructor(e){this.wa=e}async sendMessage(e,t,s){let a=[];this.wa.client.options?.autoMentions&&(a=((e="")=>{if(!e)return[];const t=new Set;for(const s of e.matchAll(/@(\d+)/g))t.add(s[1]);return[...t].flatMap((e=>[`${e}@s.whatsapp.net`,`${e}@g.us`]))})(t?.text||t?.caption)),this.wa.client.options?.autoPresence&&this.wa.socket?.sendPresenceUpdate("composing",e),this.wa.client.options?.autoPresence&&t?.audio&&this.wa.socket?.sendPresenceUpdate("recording",e);const n=t,i={contextInfo:{isForwarded:!!n?.asForwarded}};if("function"==typeof n?.quoted){let t=n?.quoted();t.key.participant=gs[n?.verifiedReply]||t.key.participant;const r=await(this.wa.socket?.sendMessage(e,{...n,mentions:a,...i},{quoted:t,...s}));return await new bs(this.wa.socket,this.wa.client,this.wa.db).messages(r)}{const t=await(this.wa.socket?.sendMessage(e,{...n,mentions:a,...i},s));return await new bs(this.wa.socket,this.wa.client,this.wa.db).messages(t)}}async text(e,t){if(e=ks.parse(e),t=xs.parse(t),"string"==typeof e)return await this.sendMessage(t.roomId,{text:e,...t});if("object"==typeof e){const s=Object.keys(e),a=e;if(s.includes("image")){const e="string"==typeof a.image?{url:a.image}:a.image;return await this.sendMessage(t.roomId,{caption:a?.text,image:e,viewOnce:!!t.asViewOnce,...t})}if(s.includes("video")){const e="string"==typeof a.video?{url:a.video}:a.video;return await this.sendMessage(t.roomId,{caption:a?.text,video:e,ptv:!1,viewOnce:!!t.asViewOnce,...t})}if(s.includes("videoNote")){const e="string"==typeof a.videoNote?{url:a.videoNote}:a.videoNote;return await this.sendMessage(t.roomId,{caption:a?.text,video:e,ptv:!0,...t})}if(s.includes("gif")){const e="string"==typeof a.gif?{url:a.gif}:a.gif;return await this.sendMessage(t.roomId,{caption:a?.text,video:e,gifPlayback:!0,viewOnce:!!t.asViewOnce,...t})}if(s.includes("audio")){const e="string"==typeof a.audio?{url:a.audio}:a.audio;return await this.sendMessage(t.roomId,{caption:a?.text,audio:e,viewOnce:!!t.asViewOnce,...t})}if(s.includes("audioNote")){const e="string"==typeof a.audioNote?{url:a.audioNote}:a.audioNote;return await this.sendMessage(t.roomId,{caption:a?.text,audio:e,ptt:!0,viewOnce:!!t.asViewOnce,...t})}if(s.includes("sticker")){const e="string"==typeof a.sticker?{url:a.sticker}:a.sticker;return await this.sendMessage(t.roomId,{caption:a?.text,sticker:e,...t})}}}async location(e,t){return e=Cs.parse(e),t=Is.parse(t),await this.sendMessage(t.roomId,{location:{degreesLatitude:e.latitude,degreesLongitude:e.longitude,url:e.title,address:e.footer,name:e.title},...t})}async contact(e,t){e=Ns.parse(e),t=Ts.parse(t);const s=["BEGIN:VCARD","VERSION:3.0",`N:;${e.fullname};;;`,`FN:${e.fullname}`,e.nickname?`NICKNAME:${e.nickname}`:"",e.organization||e.role?`ORG:${e.organization??""};`:"",e.role?`TITLE:${e.role}`:"",`TEL;TYPE=CELL,VOICE;waid=${e.whatsAppNumber}:+${e.whatsAppNumber}`,e.callNumber?`TEL;TYPE=WORK,VOICE:+${e.callNumber}`:"",e.voiceNumber?`TEL;TYPE=VOICE:+${e.voiceNumber}`:"",e.email?`EMAIL;TYPE=INTERNET:${e.email}`:"",e.website?`URL;TYPE=WORK:${e.website}`:"",e.homeAddress?`ADR;TYPE=HOME:;;${e.homeAddress};;;;`:"",e.workAddress?`ADR;TYPE=WORK:;;${e.workAddress};;;;`:"",e.avatar?`PHOTO;VALUE=URI;TYPE=JPEG:${e.avatar}`:"","END:VCARD"].join("\n");return await this.sendMessage(t.roomId,{contacts:{displayName:e.fullname,contacts:[{vcard:s}]},...t})}async reaction(e,t){return e=Ms.parse(e),t=Ss.parse(t),await this.sendMessage(t.roomId,{react:{text:e,key:t.message()?.key},...t})}async pin(e,t){e=Zs.parse(e),t=Os.parse(t);return await this.sendMessage(t.roomId,{pin:{type:"pin"==e.action?1:0,time:{"24h":86400,"7d":604800,"30d":2592e3}[e.expired],key:t.message()?.key},...t})}async poll(e,t){return e=Es.parse(e),t=As.parse(t),await this.sendMessage(t.roomId,{poll:{name:e.name,values:e.answers,selectableCount:e.multipleAnswers?1:0,toAnnouncementGroup:!0},...t})}async edit(e,t){return e=Ps.parse(e),t=js.parse(t),await this.sendMessage(t.roomId,{text:e,edit:t.message()?.key,...t})}async delete(e,t){return e=$s.parse(e),t=Rs.parse(t),await this.sendMessage(t.roomId,{delete:e.message()?.key,...t})}async rejectCall(e){return e=Fs.parse(e),await(this.wa.socket?.rejectCall(e.callId,e.callerId))}async mute(e,t){e=qs.parse(e),t=Us.parse(t);return await(this.wa.socket?.chatModify({mute:{remove:null,"8h":864e5,"7d":6048e5}[e.expired]},t.roomId))}async profile(t){const s=(t=Ds.parse(t)).includes("@g.us"),a={};a.id=t;if(e.jidNormalizedUser(this.wa.socket?.user?.id)==t)a.name=this.wa.socket?.user?.name||this.wa.socket?.user?.verifiedName;else if(s){const e=await(this.wa.socket?.groupMetadata(t));a.type="group",a.name=e?.subject,a.bio=e?.desc,a.avatar=await(this.wa.socket?.profilePictureUrl(t)),a.ephemeralDuration=e?.ephemeralDuration,a.isRestrict=e?.restrict,a.isAnnounce=e?.announce,a.isCommunity=e?.isCommunity,a.isCommunityAnnounce=e?.isCommunityAnnounce,a.isJoinApprovalMode=e?.joinApprovalMode,a.isMemberAddMode=e?.memberAddMode,a.owner={type:"user",id:e?.owner},a.roomCreatedAt=e?.creation,a.nameUpdatedAt=e?.subjectTime,a.membersLength=e?.size,a.members=e?.participants.map((e=>({id:e.id,type:"admin"==e.admin||"superadmin"==e.admin?e.admin:"user"})))}else{const e=await(this.wa.db?.selectFrom("chats").select("value").where("id","=",t).executeTakeFirst()),s=ls(e?.value),n=(await(this.wa?.socket?.fetchStatus(t)))[0]?.status;a.type="user",a.name=s?.name,a.bio=n?.status,a.avatar=await(this.wa?.socket?.profilePictureUrl(t)),a.bioUpdatedAt=new Date(n?.setAt).getTime()}return a}async presence(e,t){e=zs.parse(e),t=Ls.parse(t);return await(this.wa.socket?.sendPresenceUpdate({typing:"composing",recording:"recording",online:"available",offline:"unavailable",paused:"paused"}[e],t.roomId))}},Ks=class{constructor(e){return this.props=e,this.initialize(),this.worker,new Proxy(this,{get:(e,t)=>t in e?e[t]:e.worker[t]})}options;chatId="zaileys-chats";logger=I.default({level:"silent",enabled:!1});db;socket;groupCache=new k.default({stdTTL:300,useClones:!1});events=new t.EventEmitter;spinners=new Map;worker;async initialize(){console.clear(),await((e="ZAILEYS")=>new Promise((t=>{w.default(e,((e,s)=>{if(e)return t("");console.log(s),t(s||"")}))})))(),this.options=await us.parseAsync(this.props),this.startSpinner("db","Initializing database..."),this.db=((e,t)=>{if("sqlite"===e){const e=t||"./db/zaileys.db",s=N.default.resolve(e);return o.mkdirSync(N.default.dirname(s),{recursive:!0}),o.writeFileSync(s,"",{flag:"a"}),new d.Kysely({dialect:new d.SqliteDialect({database:new C.default(s)})})}const s=new p.URL(t),a=s.protocol.replace(":","");if("mysql"===e)return new d.Kysely({dialect:new d.MysqlDialect({pool:T.default.createPool({host:s.hostname,user:s.username,password:s.password,database:s.pathname.replace("/",""),port:parseInt(s.port||"3306",10)})})});if("postgresql"===e)return new d.Kysely({dialect:new d.PostgresDialect({pool:new l.Pool({host:s.hostname,user:s.username,password:s.password,database:s.pathname.replace("/",""),port:parseInt(s.port||"5432",10)})})});throw new Error(`Unsupported database protocol: ${a}`)})(this.options.database.type,this.options.database.connection.url),this.stopSpinner("db",!0,"Database initialized"),this.startSpinner("auth","Setting up auth adapter...");const{state:t,saveCreds:s}=await j(this.db,this.chatId);this.stopSpinner("auth",!0,"Auth adapter ready"),this.startSpinner("store","Setting up store adapter...");const a=await(async(e,t)=>({bind:s=>{s.on("messaging-history.set",(async s=>{const{chats:a,contacts:n,messages:i}=s;for(const s of a)await e.insertInto("chats").values({session:t,id:s.id,value:JSON.stringify(s)}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:JSON.stringify(s)}))).execute();for(const s of n)await e.insertInto("contacts").values({session:t,id:s.id,value:JSON.stringify(s)}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:JSON.stringify(s)}))).execute();for(const s of i){if(!s.message)return;if(s.message?.protocolMessage)return;await e.insertInto("messages").values({session:t,id:s.key.id,value:JSON.stringify(s)}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:JSON.stringify(s)}))).execute()}})),s.on("messages.upsert",(async({messages:s})=>{for(const a of s){if(!a.message)return;if(a.message?.protocolMessage)return;await e.insertInto("messages").values({session:t,id:a.key.id,value:JSON.stringify(a)}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:JSON.stringify(a)}))).execute()}})),s.on("chats.upsert",(async s=>{for(const a of s)await e.insertInto("chats").values({session:t,id:a.id,value:JSON.stringify(a)}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:JSON.stringify(a)}))).execute()})),s.on("contacts.upsert",(async s=>{for(const a of s)await e.insertInto("contacts").values({session:t,id:a.id,value:JSON.stringify(a)}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:JSON.stringify(a)}))).execute()}))}}))(this.db,this.chatId);if(this.stopSpinner("store",!0,"Store adapter ready"),this.socket=b.default({logger:this.logger,markOnlineOnConnect:this.options.autoOnline,syncFullHistory:!1,defaultQueryTimeoutMs:void 0,msgRetryCounterCache:new k.default,cachedGroupMetadata:async e=>this.groupCache.get(e),printQRInTerminal:"qr"===this.options.authType,browser:e.Browsers.ubuntu("qr"===this.options.authType?"Zaileys Library":"Firefox"),auth:{creds:t.creds,keys:e.makeCacheableSignalKeyStore(t.keys,this.logger)}}),"pairing"===this.options.authType&&this.options.phoneNumber&&!this.socket?.authState.creds.registered){this.startSpinner("pairing","Generating pairing code...");(await this.socket.onWhatsApp(this.options.phoneNumber.toString()+"@s.whatsapp.net"))[0].exists||(this.failSpinner("pairing","Phone is not registered in WhatsApp"),process.exit(1)),setTimeout((async()=>{try{if("pairing"===this.options?.authType){const e=await(this.socket?.requestPairingCode(this.options.phoneNumber.toString()));this.stopSpinner("pairing",!0,`Pairing code: ${e}`)}}catch{this.failSpinner("pairing","Connection failed"),process.exit(1)}}),5e3)}this.socket?.ev.on("creds.update",s),a.bind(this.socket?.ev),this.worker=new Vs({client:this,db:this.db,socket:this.socket}),this.socket.ev.on("connection.update",(async e=>{await new bs(this.socket,this,this.db).connection(e)})),this.socket.ev.on("messages.upsert",(async({messages:e})=>{for(const t of e)await new bs(this.socket,this,this.db).messages(t)})),this.socket.ev.on("call",(async e=>{for(const t of e)await new bs(this.socket,this,this.db).calls(t)}))}startSpinner(e,t){let s=this.spinners.get(e);return s||(s=x.default(t).start(),this.spinners.set(e,s)),s}stopSpinner(e,t,s){const a=this.spinners.get(e);a&&(t?a.succeed(s):a.stop(),this.spinners.delete(e))}failSpinner(e,t){const s=this.spinners.get(e);s&&(s.fail(t),this.spinners.delete(e))}on(e,t){this.events.on(e,t)}emit(e,...t){this.events.emit(e,...t)}};module.exports=Ks;