@temboplus/tembo-dashboard 0.2.4 → 0.2.5

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.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var e=require("uuid"),t=require("zod"),r=require("@temboplus/frontend-core");function n(e){return e&&e.__esModule?e:{default:e}}var a,s,i=n(t);!function(e){e.assertEqual=e=>e,e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},e.getValidEnumValues=t=>{const r=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),n={};for(const e of r)n[e]=t[e];return e.objectValues(n)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(const r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(a||(a={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(s||(s={}));const o=a.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),c=e=>{switch(typeof e){case"undefined":return o.undefined;case"string":return o.string;case"number":return isNaN(e)?o.nan:o.number;case"boolean":return o.boolean;case"function":return o.function;case"bigint":return o.bigint;case"symbol":return o.symbol;case"object":return Array.isArray(e)?o.array:null===e?o.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?o.promise:"undefined"!=typeof Map&&e instanceof Map?o.map:"undefined"!=typeof Set&&e instanceof Set?o.set:"undefined"!=typeof Date&&e instanceof Date?o.date:o.object;default:return o.unknown}},u=a.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"]);class d extends Error{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}get errors(){return this.issues}format(e){const t=e||function(e){return e.message},r={_errors:[]},n=e=>{for(const a of e.issues)if("invalid_union"===a.code)a.unionErrors.map(n);else if("invalid_return_type"===a.code)n(a.returnTypeError);else if("invalid_arguments"===a.code)n(a.argumentsError);else if(0===a.path.length)r._errors.push(t(a));else{let e=r,n=0;for(;n<a.path.length;){const r=a.path[n];n===a.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(a))):e[r]=e[r]||{_errors:[]},e=e[r],n++}}};return n(this),r}toString(){return this.message}get message(){return JSON.stringify(this.issues,a.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},r=[];for(const n of this.issues)n.path.length>0?(t[n.path[0]]=t[n.path[0]]||[],t[n.path[0]].push(e(n))):r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}d.create=e=>new d(e);const l=(e,t)=>{let r;switch(e.code){case u.invalid_type:r=e.received===o.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case u.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,a.jsonStringifyReplacer)}`;break;case u.unrecognized_keys:r=`Unrecognized key(s) in object: ${a.joinValues(e.keys,", ")}`;break;case u.invalid_union:r="Invalid input";break;case u.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${a.joinValues(e.options)}`;break;case u.invalid_enum_value:r=`Invalid enum value. Expected ${a.joinValues(e.options)}, received '${e.received}'`;break;case u.invalid_arguments:r="Invalid function arguments";break;case u.invalid_return_type:r="Invalid function return type";break;case u.invalid_date:r="Invalid date";break;case u.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:a.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case u.too_small:r="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 u.too_big:r="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 u.custom:r="Invalid input";break;case u.invalid_intersection_types:r="Intersection results could not be merged";break;case u.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case u.not_finite:r="Number must be finite";break;default:r=t.defaultError,a.assertNever(e)}return{message:r}};let h=l;function m(){return h}const p=e=>{const{data:t,path:r,errorMaps:n,issueData:a}=e,s=[...r,...a.path||[]],i={...a,path:s};let o="";const c=n.filter(e=>!!e).slice().reverse();for(const e of c)o=e(i,{data:t,defaultError:o}).message;return{...a,path:s,message:a.message||o}};function f(e,t){const r=p({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,m(),l].filter(e=>!!e)});e.common.issues.push(r)}class y{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const n of t){if("aborted"===n.status)return g;"dirty"===n.status&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const e of t)r.push({key:await e.key,value:await e.value});return y.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const n of t){const{key:t,value:a}=n;if("aborted"===t.status)return g;if("aborted"===a.status)return g;"dirty"===t.status&&e.dirty(),"dirty"===a.status&&e.dirty(),"__proto__"===t.value||void 0===a.value&&!n.alwaysSet||(r[t.value]=a.value)}return{status:e.value,value:r}}}const g=Object.freeze({status:"aborted"}),v=e=>({status:"dirty",value:e}),_=e=>({status:"valid",value:e}),A=e=>"aborted"===e.status,N=e=>"dirty"===e.status,I=e=>"valid"===e.status,T=e=>"undefined"!=typeof Promise&&e instanceof Promise;var w;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:null==e?void 0:e.message}(w||(w={}));class b{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const E=(e,t)=>{if(I(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 d(e.common.issues);return this._error=t,this._error}}};function C(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:a}=e;if(t&&(r||n))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:a};return{errorMap:(e,t)=>"invalid_type"!==e.code?{message:t.defaultError}:void 0===t.data?{message:null!=n?n:t.defaultError}:{message:null!=r?r:t.defaultError},description:a}}class S{constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(e){return c(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:c(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new y,ctx:{common:e.parent.common,data:e.data,parsedType:c(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(T(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 r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){var r;const n={common:{issues:[],async:null!==(r=null==t?void 0:t.async)&&void 0!==r&&r,contextualErrorMap:null==t?void 0:t.errorMap},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:c(e)},a=this._parseSync({data:e,path:n.path,parent:n});return E(n,a)}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={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:c(e)},n=this._parse({data:e,path:r.path,parent:r}),a=await(T(n)?n:Promise.resolve(n));return E(r,a)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,n)=>{const a=e(t),s=()=>n.addIssue({code:u.custom,...r(t)});return"undefined"!=typeof Promise&&a instanceof Promise?a.then(e=>!!e||(s(),!1)):!!a||(s(),!1)})}refinement(e,t){return this._refinement((r,n)=>!!e(r)||(n.addIssue("function"==typeof t?t(r,n):t),!1))}_refinement(e){return new ge({schema:this,typeName:Oe.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return ve.create(this,this._def)}nullable(){return _e.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Q.create(this,this._def)}promise(){return ye.create(this,this._def)}or(e){return te.create([this,e],this._def)}and(e){return se.create(this,e,this._def)}transform(e){return new ge({...C(this._def),schema:this,typeName:Oe.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Ae({...C(this._def),innerType:this,defaultValue:t,typeName:Oe.ZodDefault})}brand(){return new we({typeName:Oe.ZodBranded,type:this,...C(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Ne({...C(this._def),innerType:this,catchValue:t,typeName:Oe.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return be.create(this,e)}readonly(){return Ee.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const O=/^c[^\s-]{8,}$/i,x=/^[a-z][a-z0-9]*$/,R=/[0-9A-HJKMNP-TV-Z]{26}/,P=/^[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,D=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,L=/^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u,k=/^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/,F=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,z=e=>e.precision?e.offset?new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`):new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}Z$`):0===e.precision?e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$"):e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$");function U(e,t){return!("v4"!==t&&t||!k.test(e))||!("v6"!==t&&t||!F.test(e))}class M extends S{constructor(){super(...arguments),this._regex=(e,t,r)=>this.refinement(t=>e.test(t),{validation:t,code:u.invalid_string,...w.errToObj(r)}),this.nonempty=e=>this.min(1,w.errToObj(e)),this.trim=()=>new M({...this._def,checks:[...this._def.checks,{kind:"trim"}]}),this.toLowerCase=()=>new M({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]}),this.toUpperCase=()=>new M({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==o.string){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:o.string,received:t.parsedType}),g}const t=new y;let r;for(const n of this._def.checks)if("min"===n.kind)e.data.length<n.value&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),t.dirty());else if("max"===n.kind)e.data.length>n.value&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),t.dirty());else if("length"===n.kind){const a=e.data.length>n.value,s=e.data.length<n.value;(a||s)&&(r=this._getOrReturnCtx(e,r),a?f(r,{code:u.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):s&&f(r,{code:u.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),t.dirty())}else if("email"===n.kind)D.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"email",code:u.invalid_string,message:n.message}),t.dirty());else if("emoji"===n.kind)L.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"emoji",code:u.invalid_string,message:n.message}),t.dirty());else if("uuid"===n.kind)P.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"uuid",code:u.invalid_string,message:n.message}),t.dirty());else if("cuid"===n.kind)O.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"cuid",code:u.invalid_string,message:n.message}),t.dirty());else if("cuid2"===n.kind)x.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"cuid2",code:u.invalid_string,message:n.message}),t.dirty());else if("ulid"===n.kind)R.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"ulid",code:u.invalid_string,message:n.message}),t.dirty());else if("url"===n.kind)try{new URL(e.data)}catch(a){r=this._getOrReturnCtx(e,r),f(r,{validation:"url",code:u.invalid_string,message:n.message}),t.dirty()}else if("regex"===n.kind){n.regex.lastIndex=0;n.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"regex",code:u.invalid_string,message:n.message}),t.dirty())}else if("trim"===n.kind)e.data=e.data.trim();else if("includes"===n.kind)e.data.includes(n.value,n.position)||(r=this._getOrReturnCtx(e,r),f(r,{code:u.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),t.dirty());else if("toLowerCase"===n.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===n.kind)e.data=e.data.toUpperCase();else if("startsWith"===n.kind)e.data.startsWith(n.value)||(r=this._getOrReturnCtx(e,r),f(r,{code:u.invalid_string,validation:{startsWith:n.value},message:n.message}),t.dirty());else if("endsWith"===n.kind)e.data.endsWith(n.value)||(r=this._getOrReturnCtx(e,r),f(r,{code:u.invalid_string,validation:{endsWith:n.value},message:n.message}),t.dirty());else if("datetime"===n.kind){z(n).test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{code:u.invalid_string,validation:"datetime",message:n.message}),t.dirty())}else"ip"===n.kind?U(e.data,n.version)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"ip",code:u.invalid_string,message:n.message}),t.dirty()):a.assertNever(n);return{status:t.value,value:e.data}}_addCheck(e){return new M({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...w.errToObj(e)})}url(e){return this._addCheck({kind:"url",...w.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...w.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...w.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...w.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...w.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...w.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...w.errToObj(e)})}datetime(e){var t;return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!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,...w.errToObj(null==e?void 0:e.message)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...w.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:null==t?void 0:t.position,...w.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...w.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...w.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...w.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...w.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...w.errToObj(t)})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===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 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 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 j(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,a=r>n?r:n;return parseInt(e.toFixed(a).replace(".",""))%parseInt(t.toFixed(a).replace(".",""))/Math.pow(10,a)}M.create=e=>{var t;return new M({checks:[],typeName:Oe.ZodString,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...C(e)})};class Z extends S{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)!==o.number){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:o.number,received:t.parsedType}),g}let t;const r=new y;for(const n of this._def.checks)if("int"===n.kind)a.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),f(t,{code:u.invalid_type,expected:"integer",received:"float",message:n.message}),r.dirty());else if("min"===n.kind){(n.inclusive?e.data<n.value:e.data<=n.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:u.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty())}else if("max"===n.kind){(n.inclusive?e.data>n.value:e.data>=n.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:u.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty())}else"multipleOf"===n.kind?0!==j(e.data,n.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:u.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):"finite"===n.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),f(t,{code:u.not_finite,message:n.message}),r.dirty()):a.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,w.toString(t))}gt(e,t){return this.setLimit("min",e,!1,w.toString(t))}lte(e,t){return this.setLimit("max",e,!0,w.toString(t))}lt(e,t){return this.setLimit("max",e,!1,w.toString(t))}setLimit(e,t,r,n){return new Z({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:w.toString(n)}]})}_addCheck(e){return new Z({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:w.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:w.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:w.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:w.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:w.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:w.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:w.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:w.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:w.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&&a.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}Z.create=e=>new Z({checks:[],typeName:Oe.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...C(e)});class B extends S{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){this._def.coerce&&(e.data=BigInt(e.data));if(this._getType(e)!==o.bigint){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:o.bigint,received:t.parsedType}),g}let t;const r=new y;for(const n of this._def.checks)if("min"===n.kind){(n.inclusive?e.data<n.value:e.data<=n.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:u.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty())}else if("max"===n.kind){(n.inclusive?e.data>n.value:e.data>=n.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:u.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty())}else"multipleOf"===n.kind?e.data%n.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),f(t,{code:u.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):a.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,w.toString(t))}gt(e,t){return this.setLimit("min",e,!1,w.toString(t))}lte(e,t){return this.setLimit("max",e,!0,w.toString(t))}lt(e,t){return this.setLimit("max",e,!1,w.toString(t))}setLimit(e,t,r,n){return new B({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:w.toString(n)}]})}_addCheck(e){return new B({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:w.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:w.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:w.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:w.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:w.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}}B.create=e=>{var t;return new B({checks:[],typeName:Oe.ZodBigInt,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...C(e)})};class $ extends S{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==o.boolean){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:o.boolean,received:t.parsedType}),g}return _(e.data)}}$.create=e=>new $({typeName:Oe.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...C(e)});class V extends S{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==o.date){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:o.date,received:t.parsedType}),g}if(isNaN(e.data.getTime())){return f(this._getOrReturnCtx(e),{code:u.invalid_date}),g}const t=new y;let r;for(const n of this._def.checks)"min"===n.kind?e.data.getTime()<n.value&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),t.dirty()):"max"===n.kind?e.data.getTime()>n.value&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),t.dirty()):a.assertNever(n);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new V({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:w.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:w.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}}V.create=e=>new V({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:Oe.ZodDate,...C(e)});class J extends S{_parse(e){if(this._getType(e)!==o.symbol){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:o.symbol,received:t.parsedType}),g}return _(e.data)}}J.create=e=>new J({typeName:Oe.ZodSymbol,...C(e)});class Y extends S{_parse(e){if(this._getType(e)!==o.undefined){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:o.undefined,received:t.parsedType}),g}return _(e.data)}}Y.create=e=>new Y({typeName:Oe.ZodUndefined,...C(e)});class q extends S{_parse(e){if(this._getType(e)!==o.null){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:o.null,received:t.parsedType}),g}return _(e.data)}}q.create=e=>new q({typeName:Oe.ZodNull,...C(e)});class H extends S{constructor(){super(...arguments),this._any=!0}_parse(e){return _(e.data)}}H.create=e=>new H({typeName:Oe.ZodAny,...C(e)});class W extends S{constructor(){super(...arguments),this._unknown=!0}_parse(e){return _(e.data)}}W.create=e=>new W({typeName:Oe.ZodUnknown,...C(e)});class G extends S{_parse(e){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:o.never,received:t.parsedType}),g}}G.create=e=>new G({typeName:Oe.ZodNever,...C(e)});class K extends S{_parse(e){if(this._getType(e)!==o.undefined){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:o.void,received:t.parsedType}),g}return _(e.data)}}K.create=e=>new K({typeName:Oe.ZodVoid,...C(e)});class Q extends S{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==o.array)return f(t,{code:u.invalid_type,expected:o.array,received:t.parsedType}),g;if(null!==n.exactLength){const e=t.data.length>n.exactLength.value,a=t.data.length<n.exactLength.value;(e||a)&&(f(t,{code:e?u.too_big:u.too_small,minimum:a?n.exactLength.value:void 0,maximum:e?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty())}if(null!==n.minLength&&t.data.length<n.minLength.value&&(f(t,{code:u.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()),null!==n.maxLength&&t.data.length>n.maxLength.value&&(f(t,{code:u.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>n.type._parseAsync(new b(t,e,t.path,r)))).then(e=>y.mergeArray(r,e));const a=[...t.data].map((e,r)=>n.type._parseSync(new b(t,e,t.path,r)));return y.mergeArray(r,a)}get element(){return this._def.type}min(e,t){return new Q({...this._def,minLength:{value:e,message:w.toString(t)}})}max(e,t){return new Q({...this._def,maxLength:{value:e,message:w.toString(t)}})}length(e,t){return new Q({...this._def,exactLength:{value:e,message:w.toString(t)}})}nonempty(e){return this.min(1,e)}}function X(e){if(e instanceof ee){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=ve.create(X(n))}return new ee({...e._def,shape:()=>t})}return e instanceof Q?new Q({...e._def,type:X(e.element)}):e instanceof ve?ve.create(X(e.unwrap())):e instanceof _e?_e.create(X(e.unwrap())):e instanceof ie?ie.create(e.items.map(e=>X(e))):e}Q.create=(e,t)=>new Q({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Oe.ZodArray,...C(t)});class ee extends S{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=a.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==o.object){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:o.object,received:t.parsedType}),g}const{status:t,ctx:r}=this._processInputParams(e),{shape:n,keys:a}=this._getCached(),s=[];if(!(this._def.catchall instanceof G&&"strip"===this._def.unknownKeys))for(const e in r.data)a.includes(e)||s.push(e);const i=[];for(const e of a){const t=n[e],a=r.data[e];i.push({key:{status:"valid",value:e},value:t._parse(new b(r,a,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof G){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of s)i.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)s.length>0&&(f(r,{code:u.unrecognized_keys,keys:s}),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 s){const n=r.data[t];i.push({key:{status:"valid",value:t},value:e._parse(new b(r,n,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of i){const r=await t.key;e.push({key:r,value:await t.value,alwaysSet:t.alwaysSet})}return e}).then(e=>y.mergeObjectSync(t,e)):y.mergeObjectSync(t,i)}get shape(){return this._def.shape()}strict(e){return w.errToObj,new ee({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{var n,a,s,i;const o=null!==(s=null===(a=(n=this._def).errorMap)||void 0===a?void 0:a.call(n,t,r).message)&&void 0!==s?s:r.defaultError;return"unrecognized_keys"===t.code?{message:null!==(i=w.errToObj(e).message)&&void 0!==i?i:o}:{message:o}}}:{}})}strip(){return new ee({...this._def,unknownKeys:"strip"})}passthrough(){return new ee({...this._def,unknownKeys:"passthrough"})}extend(e){return new ee({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ee({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Oe.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ee({...this._def,catchall:e})}pick(e){const t={};return a.objectKeys(e).forEach(r=>{e[r]&&this.shape[r]&&(t[r]=this.shape[r])}),new ee({...this._def,shape:()=>t})}omit(e){const t={};return a.objectKeys(this.shape).forEach(r=>{e[r]||(t[r]=this.shape[r])}),new ee({...this._def,shape:()=>t})}deepPartial(){return X(this)}partial(e){const t={};return a.objectKeys(this.shape).forEach(r=>{const n=this.shape[r];e&&!e[r]?t[r]=n:t[r]=n.optional()}),new ee({...this._def,shape:()=>t})}required(e){const t={};return a.objectKeys(this.shape).forEach(r=>{if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof ve;)e=e._def.innerType;t[r]=e}}),new ee({...this._def,shape:()=>t})}keyof(){return me(a.objectKeys(this.shape))}}ee.create=(e,t)=>new ee({shape:()=>e,unknownKeys:"strip",catchall:G.create(),typeName:Oe.ZodObject,...C(t)}),ee.strictCreate=(e,t)=>new ee({shape:()=>e,unknownKeys:"strict",catchall:G.create(),typeName:Oe.ZodObject,...C(t)}),ee.lazycreate=(e,t)=>new ee({shape:e,unknownKeys:"strip",catchall:G.create(),typeName:Oe.ZodObject,...C(t)});class te extends S{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;const r=e.map(e=>new d(e.ctx.common.issues));return f(t,{code:u.invalid_union,unionErrors:r}),g});{let e;const n=[];for(const a of r){const r={...t,common:{...t.common,issues:[]},parent:null},s=a._parseSync({data:t.data,path:t.path,parent:r});if("valid"===s.status)return s;"dirty"!==s.status||e||(e={result:s,ctx:r}),r.common.issues.length&&n.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const a=n.map(e=>new d(e));return f(t,{code:u.invalid_union,unionErrors:a}),g}}get options(){return this._def.options}}te.create=(e,t)=>new te({options:e,typeName:Oe.ZodUnion,...C(t)});const re=e=>e instanceof le?re(e.schema):e instanceof ge?re(e.innerType()):e instanceof he?[e.value]:e instanceof pe?e.options:e instanceof fe?Object.keys(e.enum):e instanceof Ae?re(e._def.innerType):e instanceof Y?[void 0]:e instanceof q?[null]:null;class ne extends S{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==o.object)return f(t,{code:u.invalid_type,expected:o.object,received:t.parsedType}),g;const r=this.discriminator,n=t.data[r],a=this.optionsMap.get(n);return a?t.common.async?a._parseAsync({data:t.data,path:t.path,parent:t}):a._parseSync({data:t.data,path:t.path,parent:t}):(f(t,{code:u.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),g)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){const n=new Map;for(const r of t){const t=re(r.shape[e]);if(!t)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const a of t){if(n.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);n.set(a,r)}}return new ne({typeName:Oe.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...C(r)})}}function ae(e,t){const r=c(e),n=c(t);if(e===t)return{valid:!0,data:e};if(r===o.object&&n===o.object){const r=a.objectKeys(t),n=a.objectKeys(e).filter(e=>-1!==r.indexOf(e)),s={...e,...t};for(const r of n){const n=ae(e[r],t[r]);if(!n.valid)return{valid:!1};s[r]=n.data}return{valid:!0,data:s}}if(r===o.array&&n===o.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let n=0;n<e.length;n++){const a=ae(e[n],t[n]);if(!a.valid)return{valid:!1};r.push(a.data)}return{valid:!0,data:r}}return r===o.date&&n===o.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}class se extends S{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=(e,n)=>{if(A(e)||A(n))return g;const a=ae(e.value,n.value);return a.valid?((N(e)||N(n))&&t.dirty(),{status:t.value,value:a.data}):(f(r,{code:u.invalid_intersection_types}),g)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>n(e,t)):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}se.create=(e,t,r)=>new se({left:e,right:t,typeName:Oe.ZodIntersection,...C(r)});class ie extends S{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==o.array)return f(r,{code:u.invalid_type,expected:o.array,received:r.parsedType}),g;if(r.data.length<this._def.items.length)return f(r,{code:u.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),g;!this._def.rest&&r.data.length>this._def.items.length&&(f(r,{code:u.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const n=[...r.data].map((e,t)=>{const n=this._def.items[t]||this._def.rest;return n?n._parse(new b(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(n).then(e=>y.mergeArray(t,e)):y.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new ie({...this._def,rest:e})}}ie.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ie({items:e,typeName:Oe.ZodTuple,rest:null,...C(t)})};class oe extends S{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==o.object)return f(r,{code:u.invalid_type,expected:o.object,received:r.parsedType}),g;const n=[],a=this._def.keyType,s=this._def.valueType;for(const e in r.data)n.push({key:a._parse(new b(r,e,r.path,e)),value:s._parse(new b(r,r.data[e],r.path,e))});return r.common.async?y.mergeObjectAsync(t,n):y.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){return new oe(t instanceof S?{keyType:e,valueType:t,typeName:Oe.ZodRecord,...C(r)}:{keyType:M.create(),valueType:e,typeName:Oe.ZodRecord,...C(t)})}}class ce extends S{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==o.map)return f(r,{code:u.invalid_type,expected:o.map,received:r.parsedType}),g;const n=this._def.keyType,a=this._def.valueType,s=[...r.data.entries()].map(([e,t],s)=>({key:n._parse(new b(r,e,r.path,[s,"key"])),value:a._parse(new b(r,t,r.path,[s,"value"]))}));if(r.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const r of s){const n=await r.key,a=await r.value;if("aborted"===n.status||"aborted"===a.status)return g;"dirty"!==n.status&&"dirty"!==a.status||t.dirty(),e.set(n.value,a.value)}return{status:t.value,value:e}})}{const e=new Map;for(const r of s){const n=r.key,a=r.value;if("aborted"===n.status||"aborted"===a.status)return g;"dirty"!==n.status&&"dirty"!==a.status||t.dirty(),e.set(n.value,a.value)}return{status:t.value,value:e}}}}ce.create=(e,t,r)=>new ce({valueType:t,keyType:e,typeName:Oe.ZodMap,...C(r)});class ue extends S{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==o.set)return f(r,{code:u.invalid_type,expected:o.set,received:r.parsedType}),g;const n=this._def;null!==n.minSize&&r.data.size<n.minSize.value&&(f(r,{code:u.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),null!==n.maxSize&&r.data.size>n.maxSize.value&&(f(r,{code:u.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const a=this._def.valueType;function s(e){const r=new Set;for(const n of e){if("aborted"===n.status)return g;"dirty"===n.status&&t.dirty(),r.add(n.value)}return{status:t.value,value:r}}const i=[...r.data.values()].map((e,t)=>a._parse(new b(r,e,r.path,t)));return r.common.async?Promise.all(i).then(e=>s(e)):s(i)}min(e,t){return new ue({...this._def,minSize:{value:e,message:w.toString(t)}})}max(e,t){return new ue({...this._def,maxSize:{value:e,message:w.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ue.create=(e,t)=>new ue({valueType:e,minSize:null,maxSize:null,typeName:Oe.ZodSet,...C(t)});class de extends S{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==o.function)return f(t,{code:u.invalid_type,expected:o.function,received:t.parsedType}),g;function r(e,r){return p({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,m(),l].filter(e=>!!e),issueData:{code:u.invalid_arguments,argumentsError:r}})}function n(e,r){return p({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,m(),l].filter(e=>!!e),issueData:{code:u.invalid_return_type,returnTypeError:r}})}const a={errorMap:t.common.contextualErrorMap},s=t.data;if(this._def.returns instanceof ye){const e=this;return _(async function(...t){const i=new d([]),o=await e._def.args.parseAsync(t,a).catch(e=>{throw i.addIssue(r(t,e)),i}),c=await Reflect.apply(s,this,o);return await e._def.returns._def.type.parseAsync(c,a).catch(e=>{throw i.addIssue(n(c,e)),i})})}{const e=this;return _(function(...t){const i=e._def.args.safeParse(t,a);if(!i.success)throw new d([r(t,i.error)]);const o=Reflect.apply(s,this,i.data),c=e._def.returns.safeParse(o,a);if(!c.success)throw new d([n(o,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new de({...this._def,args:ie.create(e).rest(W.create())})}returns(e){return new de({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new de({args:e||ie.create([]).rest(W.create()),returns:t||W.create(),typeName:Oe.ZodFunction,...C(r)})}}class le extends S{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})}}le.create=(e,t)=>new le({getter:e,typeName:Oe.ZodLazy,...C(t)});class he extends S{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return f(t,{received:t.data,code:u.invalid_literal,expected:this._def.value}),g}return{status:"valid",value:e.data}}get value(){return this._def.value}}function me(e,t){return new pe({values:e,typeName:Oe.ZodEnum,...C(t)})}he.create=(e,t)=>new he({value:e,typeName:Oe.ZodLiteral,...C(t)});class pe extends S{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return f(t,{expected:a.joinValues(r),received:t.parsedType,code:u.invalid_type}),g}if(-1===this._def.values.indexOf(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return f(t,{received:t.data,code:u.invalid_enum_value,options:r}),g}return _(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e){return pe.create(e)}exclude(e){return pe.create(this.options.filter(t=>!e.includes(t)))}}pe.create=me;class fe extends S{_parse(e){const t=a.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==o.string&&r.parsedType!==o.number){const e=a.objectValues(t);return f(r,{expected:a.joinValues(e),received:r.parsedType,code:u.invalid_type}),g}if(-1===t.indexOf(e.data)){const e=a.objectValues(t);return f(r,{received:r.data,code:u.invalid_enum_value,options:e}),g}return _(e.data)}get enum(){return this._def.values}}fe.create=(e,t)=>new fe({values:e,typeName:Oe.ZodNativeEnum,...C(t)});class ye extends S{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==o.promise&&!1===t.common.async)return f(t,{code:u.invalid_type,expected:o.promise,received:t.parsedType}),g;const r=t.parsedType===o.promise?t.data:Promise.resolve(t.data);return _(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}ye.create=(e,t)=>new ye({type:e,typeName:Oe.ZodPromise,...C(t)});class ge extends S{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Oe.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,s={addIssue:e=>{f(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),"preprocess"===n.type){const e=n.transform(r.data,s);return r.common.issues.length?{status:"dirty",value:r.data}:r.common.async?Promise.resolve(e).then(e=>this._def.schema._parseAsync({data:e,path:r.path,parent:r})):this._def.schema._parseSync({data:e,path:r.path,parent:r})}if("refinement"===n.type){const e=e=>{const t=n.refinement(e,s);if(r.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===r.common.async){const n=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===n.status?g:("dirty"===n.status&&t.dirty(),e(n.value),{status:t.value,value:n.value})}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?g:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))))}if("transform"===n.type){if(!1===r.common.async){const e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!I(e))return e;const a=n.transform(e.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>I(e)?Promise.resolve(n.transform(e.value,s)).then(e=>({status:t.value,value:e})):e)}a.assertNever(n)}}ge.create=(e,t,r)=>new ge({schema:e,typeName:Oe.ZodEffects,effect:t,...C(r)}),ge.createWithPreprocess=(e,t,r)=>new ge({schema:t,effect:{type:"preprocess",transform:e},typeName:Oe.ZodEffects,...C(r)});class ve extends S{_parse(e){return this._getType(e)===o.undefined?_(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ve.create=(e,t)=>new ve({innerType:e,typeName:Oe.ZodOptional,...C(t)});class _e extends S{_parse(e){return this._getType(e)===o.null?_(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}_e.create=(e,t)=>new _e({innerType:e,typeName:Oe.ZodNullable,...C(t)});class Ae extends S{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===o.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Ae.create=(e,t)=>new Ae({innerType:e,typeName:Oe.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...C(t)});class Ne extends S{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return T(n)?n.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new d(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new d(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Ne.create=(e,t)=>new Ne({innerType:e,typeName:Oe.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...C(t)});class Ie extends S{_parse(e){if(this._getType(e)!==o.nan){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:o.nan,received:t.parsedType}),g}return{status:"valid",value:e.data}}}Ie.create=e=>new Ie({typeName:Oe.ZodNaN,...C(e)});const Te=Symbol("zod_brand");class we extends S{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class be extends S{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?g:"dirty"===e.status?(t.dirty(),v(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})()}{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?g:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new be({in:e,out:t,typeName:Oe.ZodPipeline})}}class Ee extends S{_parse(e){const t=this._def.innerType._parse(e);return I(t)&&(t.value=Object.freeze(t.value)),t}}Ee.create=(e,t)=>new Ee({innerType:e,typeName:Oe.ZodReadonly,...C(t)});const Ce=(e,t={},r)=>e?H.create().superRefine((n,a)=>{var s,i;if(!e(n)){const e="function"==typeof t?t(n):"string"==typeof t?{message:t}:t,o=null===(i=null!==(s=e.fatal)&&void 0!==s?s:r)||void 0===i||i,c="string"==typeof e?{message:e}:e;a.addIssue({code:"custom",...c,fatal:o})}}):H.create(),Se={object:ee.lazycreate};var Oe;!function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(Oe||(Oe={}));const xe=M.create,Re=Z.create,Pe=Ie.create,De=B.create,Le=$.create,ke=V.create,Fe=J.create,ze=Y.create,Ue=q.create,Me=H.create,je=W.create,Ze=G.create,Be=K.create,$e=Q.create,Ve=ee.create,Je=ee.strictCreate,Ye=te.create,qe=ne.create,He=se.create,We=ie.create,Ge=oe.create,Ke=ce.create,Qe=ue.create,Xe=de.create,et=le.create,tt=he.create,rt=pe.create,nt=fe.create,at=ye.create,st=ge.create,it=ve.create,ot=_e.create,ct=ge.createWithPreprocess,ut=be.create,dt={string:e=>M.create({...e,coerce:!0}),number:e=>Z.create({...e,coerce:!0}),boolean:e=>$.create({...e,coerce:!0}),bigint:e=>B.create({...e,coerce:!0}),date:e=>V.create({...e,coerce:!0})},lt=g;var ht=Object.freeze({__proto__:null,defaultErrorMap:l,setErrorMap:function(e){h=e},getErrorMap:m,makeIssue:p,EMPTY_PATH:[],addIssueToContext:f,ParseStatus:y,INVALID:g,DIRTY:v,OK:_,isAborted:A,isDirty:N,isValid:I,isAsync:T,get util(){return a},get objectUtil(){return s},ZodParsedType:o,getParsedType:c,ZodType:S,ZodString:M,ZodNumber:Z,ZodBigInt:B,ZodBoolean:$,ZodDate:V,ZodSymbol:J,ZodUndefined:Y,ZodNull:q,ZodAny:H,ZodUnknown:W,ZodNever:G,ZodVoid:K,ZodArray:Q,ZodObject:ee,ZodUnion:te,ZodDiscriminatedUnion:ne,ZodIntersection:se,ZodTuple:ie,ZodRecord:oe,ZodMap:ce,ZodSet:ue,ZodFunction:de,ZodLazy:le,ZodLiteral:he,ZodEnum:pe,ZodNativeEnum:fe,ZodPromise:ye,ZodEffects:ge,ZodTransformer:ge,ZodOptional:ve,ZodNullable:_e,ZodDefault:Ae,ZodCatch:Ne,ZodNaN:Ie,BRAND:Te,ZodBranded:we,ZodPipeline:be,ZodReadonly:Ee,custom:Ce,Schema:S,ZodSchema:S,late:Se,get ZodFirstPartyTypeKind(){return Oe},coerce:dt,any:Me,array:$e,bigint:De,boolean:Le,date:ke,discriminatedUnion:qe,effect:st,enum:rt,function:Xe,instanceof:(e,t={message:`Input not instance of ${e.name}`})=>Ce(t=>t instanceof e,t),intersection:He,lazy:et,literal:tt,map:Ke,nan:Pe,nativeEnum:nt,never:Ze,null:Ue,nullable:ot,number:Re,object:Ve,oboolean:()=>Le().optional(),onumber:()=>Re().optional(),optional:it,ostring:()=>xe().optional(),pipeline:ut,preprocess:ct,promise:at,record:Ge,set:Qe,strictObject:Je,string:xe,symbol:Fe,transformer:st,tuple:We,undefined:ze,union:Ye,unknown:je,void:Be,NEVER:lt,ZodIssueCode:u,quotelessJson:e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ZodError:d});const mt=e=>"function"==typeof(null==e?void 0:e.passthrough),pt=ht.object({name:ht.literal("ZodError"),issues:ht.array(ht.object({path:ht.array(ht.union([ht.string(),ht.number()])),message:ht.string().optional(),code:ht.nativeEnum(ht.ZodIssueCode)}).catchall(ht.any()))});class ft extends Error{constructor(e){super(JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t,2)),this.name="ValidationError",this.issues=e}toString(){return this.message}}ht.object({message:ht.literal("Request validation failed"),pathParameterErrors:pt.nullable(),headerErrors:pt.nullable(),queryParameterErrors:pt.nullable(),bodyErrors:pt.nullable()}),ht.object({pathParameterErrors:pt.nullable(),headerErrors:pt.nullable(),queryParameterErrors:pt.nullable(),bodyErrors:pt.nullable()}),ht.object({paramsResult:pt.nullable(),headersResult:pt.nullable(),queryResult:pt.nullable(),bodyResult:pt.nullable()});const yt="zod-ts-rest-polyfill",gt=(e,t)=>{if(!e)return t;if(!t)return e;if(e instanceof ee&&t instanceof ee){return n=t,mt(r=e)?mt(n)?r.merge(n):r:mt(n)?n:Object.assign({},r,n)}var r,n;return{...e,...t}},vt=Symbol("ContractNoBody"),_t=e=>"method"in e&&"path"in e,At=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>{var n,a,s;return _t(r)?[e,{...r,path:(null==t?void 0:t.pathPrefix)?t.pathPrefix+r.path:r.path,headers:gt(null==t?void 0:t.baseHeaders,r.headers),strictStatusCodes:null!==(n=r.strictStatusCodes)&&void 0!==n?n:null==t?void 0:t.strictStatusCodes,validateResponseOnClient:null!==(a=r.validateResponseOnClient)&&void 0!==a?a:null==t?void 0:t.validateResponseOnClient,responses:{...null==t?void 0:t.commonResponses,...r.responses},metadata:(null==t?void 0:t.metadata)?{...null==t?void 0:t.metadata,...null!==(s=r.metadata)&&void 0!==s?s:{}}:r.metadata}]:[e,At(r,t)]})),Nt=Symbol("ContractPlainType"),It=()=>({router:(e,t)=>At(e,t),query:e=>e,mutation:e=>e,responses:e=>e,response:()=>Nt,body:()=>Nt,type:()=>Nt,otherResponse:({contentType:e,body:t})=>({contentType:e,body:t}),noBody:()=>vt}),Tt=e=>e?Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>{let r;return r="string"==typeof t&&!["true","false","null"].includes(t.trim())&&isNaN(Number(t))?t:JSON.stringify(t),`${encodeURIComponent(e)}=${encodeURIComponent(r)}`}).join("&"):"",wt=e=>e?Object.keys(e).flatMap(t=>bt(t,e[t])).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",bt=(e,t)=>Array.isArray(t)?t.flatMap((t,r)=>bt(`${e}[${r}]`,t)):t instanceof Date?[[`${e}`,t.toISOString()]]:null===t?[[`${e}`,""]]:void 0===t?[]:"object"==typeof t?Object.keys(t).flatMap(r=>bt(`${e}[${r}]`,t[r])):[[`${e}`,`${t}`]];class Et extends Error{constructor(e,t){super(`Server returned unexpected response. Expected one of: ${t.join(",")} got: ${e.status}`),this.response=e}}const Ct=async({route:e,path:t,method:r,headers:n,body:a,validateResponse:s,fetchOptions:i})=>{const o=await fetch(t,{...i,method:r,headers:n,body:a}),c=o.headers.get("content-type");if((null==c?void 0:c.includes("application/"))&&(null==c?void 0:c.includes("json"))){const t=e.responses[o.status],r={status:o.status,body:t===vt?void 0:await o.json(),headers:o.headers},n=(e=>{if((e=>{if(!e)return!1;const t=null==e?void 0:e["~standard"];return!!t&&1===t.version&&"function"==typeof t.validate})(e))return e;if("function"==typeof(null==(t=e)?void 0:t.safeParse)){const t={vendor:yt,version:1,validate:t=>{const r=e.safeParse(t);return r.success?{value:r.data}:{issues:r.error.issues}}};return Object.assign(e,{"~standard":t}),e}var t;return null})(t);if(n&&(null!=s?s:e.validateResponseOnClient)){const e=((e,t,{passThroughExtraKeys:r=!1}={})=>{const n=t["~standard"].validate(e);if(n instanceof Promise)throw new Error("Schema validation must be synchronous");return n.issues?t["~standard"].vendor===yt?{error:new d(n.issues)}:{error:new ft(n.issues)}:r&&"object"==typeof e&&n.value?{value:{...e,...n.value}}:{value:n.value}})(r.body,n);if(e.error)throw e.error;return{...r,body:e.value}}return r}return(null==c?void 0:c.includes("text/"))?{status:o.status,body:await o.text(),headers:o.headers}:{status:o.status,body:await o.blob(),headers:o.headers}},St=e=>{const t=new FormData,r=(e,r)=>{r instanceof File?t.append(e,r):t.append(e,JSON.stringify(r))};return Object.entries(e).forEach(([e,t])=>{if(Array.isArray(t))for(const n of t)r(e,n);else r(e,t)}),t},Ot=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),xt=(e,t,r,n,a)=>{const s=(({path:e,params:t})=>{const r=t;return e.replace(/\/?:([^/?]+)\??/g,(e,t)=>r[t]?`${e.startsWith("/")?"/":""}${r[t]}`:"")})({path:n.path,params:r}),i=((e,t=!1)=>{const r=t?Tt(e):wt(e);return(null==r?void 0:r.length)>0?"?"+r:""})(e,a);return t.endsWith("/")&&s.startsWith("/")?`${t}${s.substring(1)}${i}`:`${t}${s}${i}`},Rt=(e,t)=>{const r=Object.keys(e.responses);return async n=>{const a=((e,t,r)=>{const{query:n,params:a,body:s,headers:i,extraHeaders:o,overrideClientOptions:c,fetchOptions:u,cache:d,next:l,...h}=r||{},m={...t,...c},p="object"==typeof a?Object.fromEntries(Object.entries(a).map(([e,t])=>[e,String(t)])):{};return{path:xt(n,m.baseUrl,p,e,!!m.jsonQuery),clientArgs:m,route:e,body:s,query:n,extraInputArgs:h,fetchOptions:{...d&&{cache:d},...l&&{next:l},...u},headers:{...o,...i}}})(e,t,n),s=await(e=>{const{path:t,clientArgs:r,route:n,body:a,query:s,extraInputArgs:i,headers:o,fetchOptions:c}=e,u=r.api||Ct,d=r.baseHeaders&&Object.fromEntries(Object.entries(r.baseHeaders).map(([t,r])=>"function"==typeof r?[t,r(e)]:[t,r])),l={...d&&Ot(d),...Ot(o)};Object.keys(l).forEach(e=>{void 0===l[e]&&delete l[e]});let h={route:n,path:t,method:n.method,headers:l,body:void 0,rawBody:a,rawQuery:s,contentType:void 0,validateResponse:r.validateResponse,fetchOptions:{...r.credentials&&{credentials:r.credentials},...c},...(null==c?void 0:c.signal)&&{signal:c.signal},...(null==c?void 0:c.cache)&&{cache:c.cache},...c&&"next"in c&&!!(null==c?void 0:c.next)&&{next:c.next}};return"GET"!==n.method&&("contentType"in n&&"multipart/form-data"===n.contentType?h={...h,contentType:"multipart/form-data",body:a instanceof FormData?a:St(a)}:"contentType"in n&&"application/x-www-form-urlencoded"===n.contentType?h={...h,contentType:"application/x-www-form-urlencoded",headers:{"content-type":"application/x-www-form-urlencoded",...h.headers},body:"string"==typeof a?a:new URLSearchParams(a)}:null!=a&&(h={...h,contentType:"application/json",headers:{"content-type":"application/json",...h.headers},body:JSON.stringify(a)})),u({...h,...i})})(a);if(!t.throwOnUnknownStatus)return s;if(r.includes(s.status.toString()))return s;throw new Et(s,r)}},Pt=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>_t(r)?[e,Rt(r,t)]:[e,Pt(r,t)]));class Dt extends Error{statusCode;error;details;constructor(e){super(e.message),this.name="ApiError",this.statusCode=e.statusCode,e.error&&(this.error=e.error),e.details&&(this.details=e.details)}static is(e){return Dt.schema.safeParse(e).success}static unknown(e){return new Dt({message:e??"An unknown error occurred",statusCode:502})}static get schema(){return t.z.object({message:t.z.string(),statusCode:t.z.number().int(),error:t.z.string().optional(),details:t.z.object({}).optional()})}}const Lt=i.default.object({statusCode:i.default.number().int(),reason:i.default.string().optional(),error:i.default.string().optional(),details:i.default.record(i.default.string(),i.default.unknown()).optional(),message:i.default.string().optional()}),kt=Lt.extend({statusCode:i.default.literal(400)}),Ft=Lt.extend({statusCode:i.default.literal(401)}),zt=Lt.extend({statusCode:i.default.literal(403)}),Ut=Lt.extend({statusCode:i.default.literal(404)}),Mt=Lt.extend({statusCode:i.default.literal(500)}),jt=i.default.object({page:i.default.number().int().positive(),limit:i.default.number().int().positive(),total:i.default.number().int().min(0),totalPages:i.default.number().int().min(0),hasNext:i.default.boolean(),hasPrev:i.default.boolean()}),Zt=i.default.object({balance:i.default.number(),availableBalance:i.default.number(),accountNumber:i.default.string(),accountName:i.default.string()}),Bt=i.default.object({yesterday:i.default.number(),today:i.default.number(),thisMonth:i.default.number(),lastMonth:i.default.number()});const $t=i.default.string().nullish().transform(e=>{if(!e||""===e.trim())return null;try{return function(e){if(!e||""===e.trim())throw new Error("Date string cannot be empty");const[t,r]=e.trim().split(" ");if(!t||!r)throw new Error("Invalid date format. Expected 'YYYY-MM-DD HH:mm:ss'");const n=new Date(`${t}T${r}.000Z`);return new Date(n.getTime()-108e5).toISOString()}(e)}catch(e){throw new Error(`Failed to convert EAT date to UTC: ${e instanceof Error?e.message:"Unknown error"}`)}}),Vt=i.default.object({accountNo:i.default.string().nullish(),debitOrCredit:i.default.enum(["CR","DR"],{error:()=>({message:"Transaction type must be either 'CR' (Credit) or 'DR' (Debit)"})}),tranRefNo:i.default.string().nullish(),cbaRefNo:i.default.string().nullish(),narration:i.default.string().nullish(),txnDate:$t,valueDate:$t,amountCredited:i.default.union([i.default.number().min(0,"Credited amount cannot be negative"),i.default.string().transform(e=>{if(""===e.trim())return 0;const t=parseFloat(e);if(isNaN(t))throw new Error("Invalid credited amount format");return t})],{error:()=>({message:"Credited amount must be a number or numeric string"})}).nullish(),amountDebited:i.default.union([i.default.number().min(0,"Debited amount cannot be negative"),i.default.string().transform(e=>{if(""===e.trim())return 0;const t=parseFloat(e);if(isNaN(t))throw new Error("Invalid debited amount format");return t})],{error:()=>({message:"Debited amount must be a number or numeric string"})}).nullish(),balance:i.default.number({error:e=>void 0===e.input?"Balance is required":"Balance must be a number"})}),Jt={apiError:Lt,validationError:kt,unauthorizedError:Ft,forbiddenError:zt,notFoundError:Ut,serverError:Mt,pagination:jt,transactionSummary:Bt,walletSummary:Zt,statementEntry:Vt};class Yt{contract;endpoint;root;token;constructor(e,t,r){this.contract=t,this.endpoint=e,this.root=r?.root,this.token=r?.token}getToken(){return this.token&&this.token.trim().length>0?this.token:""}get client(){return this.getClientWithHeaders()}getClientWithHeaders(t){const r=this.root?this.root.replace(/\/+$/,""):"",n=this.endpoint?this.endpoint.replace(/^\/+/,""):"",a=r?`${r}/${n}`:`https://gateway.temboplus.com/dashboard/${n}`,s={Authorization:`Bearer ${this.getToken()}`,"x-request-id":e.v4()},i={baseUrl:a,baseHeaders:t?{...s,...t}:s};return Pt(this.contract,i)}setToken(e){this.token=e}getCurrentToken(){return this.token}handleResponse(e,t){if(e.status===t)return e.body;const r=Jt.apiError.safeParse(e.body),n=r.success?r.data:void 0,a=(t,r)=>new Dt({message:n?.message??t,statusCode:n?.statusCode??e.status,error:n?.error??n?.reason??r,details:n?.details});if(400===e.status)throw a("Bad request","BAD_REQUEST");if(401===e.status)throw a("You are not authenticated to perform this action. Please login again","UNAUTHORIZED");if(403===e.status)throw a("You are not authorized to perform this action.","FORBIDDEN");if(404===e.status)throw a("The requested resource was not found.","NOT_FOUND");if(500===e.status)throw a("We encountered an error trying to process your request. Please try again later","SERVER_ERROR");throw a("We encountered an error trying to process your request. Please try again later","UNKNOWN_ERROR")}}class qt{accountNo;debitOrCredit;tranRefNo;cbaRefNo;narration;txnDate;valueDate;amountCredited;amountDebited;balance;currency;constructor(e,t="TZS"){let n="TZS";r.CurrencyHelpers.isCode(t)&&(n=t),this.accountNo=e.accountNo,this.debitOrCredit=e.debitOrCredit,this.tranRefNo=e.tranRefNo,this.cbaRefNo=e.cbaRefNo,this.narration=e.narration,this.txnDate=e.txnDate?new Date(e.txnDate):null,this.valueDate=e.valueDate?new Date(e.valueDate):null,this.currency=n;const a=e.amountCredited?this.parseAmountValue(e.amountCredited):null;this.amountCredited=null===a?null:a>0?r.Amount.from(a,n)??r.Amount.from(0,n):null;const s=e.amountDebited?this.parseAmountValue(e.amountDebited):null;this.amountDebited=null===s?null:s>0?r.Amount.from(s,n)??r.Amount.from(0,n):null,this.balance=r.Amount.from(e.balance,n)??r.Amount.from(0,n)}parseAmountValue(e){if("number"==typeof e)return e;if("string"==typeof e&&""!==e.trim()){const t=parseFloat(e);return isNaN(t)?0:t}return 0}isCredit(){return"CR"===this.debitOrCredit}isDebit(){return"DR"===this.debitOrCredit}getTransactionAmount(){return this.amountCredited||this.amountDebited}getTransactionValue(){const e=this.getTransactionAmount();return e?e.numericValue:0}static from(e,t="TZS"){try{return!1===Jt.statementEntry.safeParse(e).success?void console.error("Missing required StatementEntry fields:",e):new qt(e,t)}catch(e){return void console.error("Error creating StatementEntry:",e)}}static createMany(e,t="TZS"){const r=[];for(const n of e){const e=qt.from(n,t);if(!e)return;r.push(e)}return r}toJSON(){return{accountNo:this.accountNo,debitOrCredit:this.debitOrCredit,tranRefNo:this.tranRefNo,cbaRefNo:this.cbaRefNo,narration:this.narration,txnDate:this.txnDate?.toISOString(),valueDate:this.valueDate?.toISOString(),amountCredited:this.amountCredited?.toJSON()??null,amountDebited:this.amountDebited?.toJSON()??null,balance:this.balance.toJSON(),currency:this.currency}}static fromJSON(e){try{if(!r.AmountFactory.getInstance().isAmountJSON(e.balance))return void console.error("Invalid balance AmountJson structure:",e.balance);if(e.amountCredited&&!r.AmountFactory.getInstance().isAmountJSON(e.amountCredited))return void console.error("Invalid amountCredited AmountJson structure:",e.amountCredited);if(e.amountDebited&&!r.AmountFactory.getInstance().isAmountJSON(e.amountDebited))return void console.error("Invalid amountDebited AmountJson structure:",e.amountDebited);const t=r.Amount.fromJSON(e.balance);if(!t)return void console.error("Failed to reconstruct balance Amount from JSON:",e.balance);let n=0;if(e.amountCredited){const t=r.Amount.fromJSON(e.amountCredited);if(!t)return void console.error("Failed to reconstruct amountCredited Amount from JSON:",e.amountCredited);n=t.numericValue}let a=0;if(e.amountDebited){const t=r.Amount.fromJSON(e.amountDebited);if(!t)return void console.error("Failed to reconstruct amountDebited Amount from JSON:",e.amountDebited);a=t.numericValue}const s={accountNo:e.accountNo,debitOrCredit:e.debitOrCredit,tranRefNo:e.tranRefNo,cbaRefNo:e.cbaRefNo,narration:e.narration,txnDate:e.txnDate?e.txnDate:null,valueDate:e.valueDate?e.valueDate:null,amountCredited:n,amountDebited:a,balance:t.numericValue};return new qt(s,e.currency)}catch(e){return void console.error("Error creating StatementEntry from JSON:",e)}}static createManyFromJson(e){const t=[];for(const r of e){const e=qt.fromJSON(r);if(!e)return;t.push(e)}return t}static getTotalCredits(e){const t=e.length>0?e[0].currency:"TZS",n=e.reduce((e,t)=>t.isCredit()&&t.amountCredited?e+t.amountCredited.numericValue:e,0);return r.Amount.from(n,t)??r.Amount.from(0,t)}static getTotalDebits(e){const t=e.length>0?e[0].currency:"TZS",n=e.reduce((e,t)=>t.isDebit()&&t.amountDebited?e+t.amountDebited.numericValue:e,0);return r.Amount.from(n,t)??r.Amount.from(0,t)}static getNetChange(e){const t=e.length>0?e[0].currency:"TZS",n=qt.getTotalCredits(e).numericValue,a=qt.getTotalDebits(e).numericValue;return r.Amount.from(n-a,t)??r.Amount.from(0,t)}}class Ht{yesterday;today;thisMonth;lastMonth;currency;constructor(e,t="TZS"){this.currency=t,this.yesterday=r.Amount.from(e.yesterday,t)??r.Amount.from(0,t),this.today=r.Amount.from(e.today,t)??r.Amount.from(0,t),this.thisMonth=r.Amount.from(e.thisMonth,t)??r.Amount.from(0,t),this.lastMonth=r.Amount.from(e.lastMonth,t)??r.Amount.from(0,t)}getMonthlyGrowthRate(){return 0===this.lastMonth.numericValue?this.thisMonth.numericValue>0?100:0:(this.thisMonth.numericValue-this.lastMonth.numericValue)/this.lastMonth.numericValue*100}getRecentTotal(){return r.Amount.from(this.today.numericValue+this.yesterday.numericValue,this.currency)}static from(e,t="TZS"){return new Ht(e,t)}toJSON(){return{yesterday:this.yesterday.toJSON(),today:this.today.toJSON(),thisMonth:this.thisMonth.toJSON(),lastMonth:this.lastMonth.toJSON(),currency:this.currency}}static fromJSON(e){try{if(!(r.AmountFactory.getInstance().isAmountJSON(e.yesterday)&&r.AmountFactory.getInstance().isAmountJSON(e.today)&&r.AmountFactory.getInstance().isAmountJSON(e.thisMonth)&&r.AmountFactory.getInstance().isAmountJSON(e.lastMonth)))return void console.error("Invalid AmountJson structure in TransactionSummary JSON:",e);const t=r.Amount.fromJSON(e.yesterday),n=r.Amount.fromJSON(e.today),a=r.Amount.fromJSON(e.thisMonth),s=r.Amount.fromJSON(e.lastMonth);if(!(t&&n&&a&&s))return void console.error("Failed to reconstruct Amount instances from JSON:",e);const i={yesterday:t.numericValue,today:n.numericValue,thisMonth:a.numericValue,lastMonth:s.numericValue};return new Ht(i,e.currency)}catch(e){return void console.error("Error creating TransactionSummary from JSON:",e)}}}class Wt{accountName;accountNo;accountNumber;availableBalance;currentBalance;actualBalance;accountStatus;type;currencyCode;countryCode;currency;constructor(e){let t="TZS";e.currencyCode&&r.CurrencyHelpers.isCode(e.currencyCode)&&(t=e.currencyCode),this.accountName=e.accountName,this.accountNo=e.accountNo,this.accountNumber=e.accountNo,this.currency=t,this.currencyCode=t,this.countryCode=e.countryCode,this.availableBalance=r.Amount.from(e.availableBalance,t)??r.Amount.from(0,t),this.currentBalance=r.Amount.from(e.currentBalance,t)??r.Amount.from(0,t),this.actualBalance=this.currentBalance,this.accountStatus=e.accountStatus,this.type=e.type}hasSufficientBalance(e){return this.availableBalance.numericValue>=e}static from(e){return new Wt(e)}toJSON(){return{accountName:this.accountName,accountNo:this.accountNo,accountNumber:this.accountNumber,availableBalance:this.availableBalance.toJSON(),currentBalance:this.currentBalance.toJSON(),actualBalance:this.actualBalance.toJSON(),accountStatus:this.accountStatus,type:this.type,currencyCode:this.currencyCode,countryCode:this.countryCode,currency:this.currency}}static fromJSON(e){try{if(!r.AmountFactory.getInstance().isAmountJSON(e.availableBalance)||!r.AmountFactory.getInstance().isAmountJSON(e.actualBalance))return void console.error("Invalid AmountJson structure in WalletInfo JSON:",e);const t=r.Amount.fromJSON(e.availableBalance),n=e.currentBalance??e.actualBalance;if(!r.AmountFactory.getInstance().isAmountJSON(n))return void console.error("Invalid currentBalance AmountJson structure in WalletInfo JSON:",e);const a=r.Amount.fromJSON(n);if(!t||!a)return void console.error("Failed to reconstruct Amount instances from JSON:",e);const s=e.accountNo||e.accountNumber;if(!s)return void console.error("Missing account number in WalletInfo JSON:",e);const i={accountName:e.accountName,accountNo:s,availableBalance:t.numericValue,currentBalance:a.numericValue,accountStatus:e.accountStatus||"UNKNOWN",type:e.type,currencyCode:e.currencyCode||e.currency,countryCode:e.countryCode};return new Wt(i)}catch(e){return void console.error("Error creating WalletInfo from JSON:",e)}}static createManyFromJson(e){const t=[];for(const r of e){const e=Wt.fromJSON(r);if(!e)return;t.push(e)}return t}}var Gt,Kt;exports.FilterOperator=void 0,(Gt=exports.FilterOperator||(exports.FilterOperator={})).EQUALS="eq",Gt.NOT_EQUALS="neq",Gt.LESS_THAN="lt",Gt.LESS_THAN_OR_EQUAL="lte",Gt.GREATER_THAN="gt",Gt.GREATER_THAN_OR_EQUAL="gte",Gt.LIKE="like",Gt.LIKE_LOWER="likeLower",Gt.IS_NULL="isNull",Gt.IS_NOT_NULL="isNotNull",Gt.IN="in",exports.SortDirection=void 0,(Kt=exports.SortDirection||(exports.SortDirection={})).ASC="asc",Kt.DESC="desc";const Qt=Symbol("query-builder-type");class Xt{options={filters:[],sort:[],includes:[],groupBy:[],join:[],count:"*",page:1,limit:8};constructor(e={}){this.options={filters:e.filters||[],sort:e.sort||[],includes:e.includes||[],groupBy:e.groupBy||[],join:e.join||[],page:e.page,limit:e.limit}}[Qt]="query-builder";static is(e){return null!==e&&"object"==typeof e&&Qt in e&&"query-builder"===e[Qt]}addFilter(e){return this.options.filters=[...this.options.filters||[],e],this}where(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.EQUALS,value:t})}whereNot(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.NOT_EQUALS,value:t})}whereLike(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE,value:t})}whereLikeLower(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:t})}whereContains(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:`%${t}%`})}whereStartsWith(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:`${t}%`})}whereEndsWith(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:`%${t}`})}whereIn(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.IN,value:t})}whereNull(e){return this.addFilter({field:e,operator:exports.FilterOperator.IS_NULL})}whereNotNull(e){return this.addFilter({field:e,operator:exports.FilterOperator.IS_NOT_NULL})}whereGreaterThan(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.GREATER_THAN,value:t})}whereGreaterThanOrEqual(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.GREATER_THAN_OR_EQUAL,value:t})}whereLessThan(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LESS_THAN,value:t})}whereLessThanOrEqual(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LESS_THAN_OR_EQUAL,value:t})}whereBetween(e,t,r){return this.whereGreaterThanOrEqual(e,t).whereLessThanOrEqual(e,r)}whereDateBetween(e,t){return e&&this.whereGreaterThanOrEqual("createdAt",e),t&&this.whereLessThanOrEqual("createdAt",t),this}addSort(e){return this.options.sort=[...this.options.sort||[],e],this}orderBy(e,t=exports.SortDirection.ASC){return this.addSort({field:e,direction:t})}orderByAsc(e){return this.orderBy(e,exports.SortDirection.ASC)}orderByDesc(e){return this.orderBy(e,exports.SortDirection.DESC)}paginate(e,t){return this.options.page=e,this.options.limit=t,this}with(e){const t=Array.isArray(e)?e:[e];return this.options.includes=[...this.options.includes||[],...t],this}join(e){const t=Array.isArray(e)?e:[e];return this.options.join=[...this.options.join||[],...t],this}groupBy(e){const t=Array.isArray(e)?e:[e];return this.options.groupBy=[...this.options.groupBy||[],...t],this}count(e="*"){return this.options.count=e,this}countAs(e,t){return this.options.count=`${e} as ${t}`,this}build(){const e={};if(void 0!==this.options.page&&void 0!==this.options.limit){const t=(this.options.page-1)*this.options.limit,r=t+this.options.limit-1;e.rangeStart=t,e.rangeEnd=r}if(this.options.filters&&this.options.filters.length>0)for(const t of this.options.filters)switch(t.operator){case exports.FilterOperator.IS_NULL:e[`${t.field}:isNull`]=1;break;case exports.FilterOperator.IS_NOT_NULL:e[`${t.field}:notNull`]=1;break;case exports.FilterOperator.IN:e[`${t.field}:in`]=Array.isArray(t.value)?t.value.join(","):t.value;break;case exports.FilterOperator.LIKE:e[`${t.field}:like`]=t.value;break;case exports.FilterOperator.LIKE_LOWER:e[`${t.field}:likeLower`]=t.value;break;case exports.FilterOperator.GREATER_THAN_OR_EQUAL:e[`${t.field}:gte`]=t.value;break;case exports.FilterOperator.LESS_THAN_OR_EQUAL:e[`${t.field}:lte`]=t.value;break;default:e[`${t.field}:${t.operator}`]=t.value}if(this.options.sort&&this.options.sort.length>0){const t=[],r=[];for(const e of this.options.sort)e.direction===exports.SortDirection.ASC?t.push(e.field):r.push(e.field);t.length>0&&(e.orderBy=t.join(",")),r.length>0&&(e.orderByDesc=r.join(","))}return this.options.includes&&this.options.includes.length>0&&(1===this.options.includes.length?e.eager=this.options.includes[0]:e.eager=`[${this.options.includes.join(",")}]`),this.options.join&&this.options.join.length>0&&(e.join=this.options.join.join(",")),this.options.groupBy&&this.options.groupBy.length>0&&(e.groupBy=this.options.groupBy.join(",")),this.options.count&&(e.count=this.options.count),e}clone(){return new(0,this.constructor)({...this.options,filters:this.options.filters?[...this.options.filters]:[],sort:this.options.sort?[...this.options.sort]:[],includes:this.options.includes?[...this.options.includes]:[],groupBy:this.options.groupBy?[...this.options.groupBy]:[],join:this.options.join?[...this.options.join]:[]})}static create(e){return new Xt(e)}}const er={AIRTEL:{key:"AIRTEL",networkOperator:"Airtel",serviceName:"Airtel Money"},VODACOM:{key:"VODACOM",networkOperator:"Vodacom",serviceName:"M-Pesa"},TIGO:{key:"TIGO",networkOperator:"Yas",serviceName:"Mixx by Yas"},HALOTEL:{key:"HALOTEL",networkOperator:"Halotel",serviceName:"HaloPesa"},SAFARICOM:{key:"SAFARICOM",networkOperator:"Safaricom",serviceName:"M-Pesa"}},tr={user:t.z.object({token:t.z.string(),identity:t.z.string(),name:t.z.string()}),loginRequest:t.z.object({identity:t.z.string().email(),password:t.z.string()}),updatePassword:t.z.object({currentPassword:t.z.string(),newPassword:t.z.string()})},rr=It().router({login:{method:"POST",path:"/login",body:tr.loginRequest,responses:{201:tr.user,400:Jt.validationError,401:Jt.unauthorizedError,500:Jt.serverError},summary:"User login",description:"Authenticate user with email and password"},updatePassword:{method:"POST",path:"/change-password",body:tr.updatePassword,responses:{201:i.default.object({}),400:Jt.validationError,401:Jt.unauthorizedError,500:Jt.serverError},summary:"Update password",description:"Update user password"}});class nr{identity;name;constructor(e){this.identity=e.identity,this.name=e.name}static from(e){return new nr(e)}static fromJson(e){return nr.from(e)}toJson(){return{identity:this.identity,name:this.name}}get email(){return this.identity}getDisplayName(){return this.name||this.identity}isEmailIdentity(){return/^[^\s@]+@[^\s@]+\.[a-z]{2,}$/i.test(this.identity)}getInitials(){return this.getDisplayName().split(" ").map(e=>e.charAt(0).toUpperCase()).slice(0,2).join("")}equals(e){return this.identity===e.identity&&this.name===e.name}}var ar,sr;exports.COLLECTION_STATUS=void 0,(ar=exports.COLLECTION_STATUS||(exports.COLLECTION_STATUS={})).PAYMENT_ACCEPTED="PAYMENT_ACCEPTED",ar.GENERIC_FAILURE="GENERIC_FAILURE",ar.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",ar.PAYMENT_REJECTED="PAYMENT_REJECTED",ar.PENDING_ACK="PENDING_ACK",ar.PROVIDER_FAILED="PROVIDER_FAILED",exports.COLLECTION_CHANNEL=void 0,(sr=exports.COLLECTION_CHANNEL||(exports.COLLECTION_CHANNEL={})).AIRTEL="TZ-AIRTEL-C2B",sr.TIGO="TZ-TIGO-C2B",sr.HALOTEL="TZ-HALOTEL-C2B",sr.SAFARICOM="KE-SAFARICOM-C2B",sr.VODACOM="TZ-VODACOM-C2B";const ir=t.z.nativeEnum(exports.COLLECTION_STATUS),or=t.z.nativeEnum(exports.COLLECTION_CHANNEL),cr=e=>{const t=Array.isArray(e)?e.flatMap(e=>cr(e)):"string"==typeof e?e.split(","):[];return Array.from(new Set(t.map(e=>e.trim()).filter(e=>e.length>0)))},ur=t.z.union([t.z.string(),t.z.array(t.z.string())]),dr={collection:t.z.object({id:t.z.string().min(1),status:ir,statusMessage:t.z.string(),accountNo:t.z.string().min(1),walletId:t.z.string(),transactionDate:t.z.string().datetime(),narration:t.z.string(),msisdn:t.z.string().min(1),channel:or,amount:t.z.number().min(0),serviceFee:t.z.string().optional(),postedAmount:t.z.string().optional(),reference:t.z.string(),partnerReference:t.z.string().nullable().optional(),payerName:t.z.string().nullable().optional(),payerReference:t.z.string().nullable().optional(),merchantName:t.z.string().nullable().optional(),merchantReference:t.z.string().nullable().optional(),transactionId:t.z.string().nullable().optional(),serviceFeeTransactionId:t.z.string().nullable().optional(),requestId:t.z.string().nullable().optional(),completedAt:t.z.string().datetime().nullable().optional(),createdAt:t.z.string().datetime(),updatedAt:t.z.string().datetime(),notes:t.z.string().optional(),currencyCode:t.z.string().default("TZS")}),collectionFilters:t.z.object({page:t.z.number().int().positive().default(1),limit:t.z.number().int().positive().max(1e4).default(20),sortBy:t.z.string().default("createdAt"),sortOrder:t.z.enum(["asc","desc"]).default("desc"),startDate:t.z.string().datetime().optional(),endDate:t.z.string().datetime().optional(),msisdn:t.z.string().optional(),id:t.z.string().optional(),idIn:t.z.array(t.z.string()).optional(),reference:t.z.string().optional(),referenceIn:t.z.array(t.z.string()).optional(),accountNo:t.z.string().optional(),walletId:t.z.string().optional(),partnerReference:t.z.string().optional(),channel:or.optional(),channelIn:t.z.array(or).optional(),status:ir.optional(),statusIn:t.z.array(ir).optional(),minAmount:t.z.number().min(0).optional(),maxAmount:t.z.number().min(0).optional(),search:t.z.string().optional()}),collectionURLQueryParams:t.z.object({page:t.z.string().transform(e=>parseInt(e)||1).optional(),limit:t.z.string().transform(e=>parseInt(e)||20).optional(),sortBy:t.z.string().default("createdAt"),sortOrder:t.z.enum(["asc","desc"]).default("desc"),startDate:t.z.string().optional(),endDate:t.z.string().optional(),msisdn:t.z.string().optional(),id:t.z.string().optional(),idIn:ur.transform(cr).optional(),reference:t.z.string().optional(),referenceIn:ur.transform(cr).optional(),accountNo:t.z.string().optional(),walletId:t.z.string().optional(),partnerReference:t.z.string().optional(),channel:t.z.string().refine(e=>Object.values(exports.COLLECTION_CHANNEL).includes(e)).transform(e=>e).optional(),channelIn:ur.transform(cr).pipe(t.z.array(or)).optional(),status:t.z.string().refine(e=>Object.values(exports.COLLECTION_STATUS).includes(e)).transform(e=>e).optional(),statusIn:ur.transform(cr).pipe(t.z.array(ir)).optional(),minAmount:t.z.string().transform(e=>parseFloat(e)).optional(),maxAmount:t.z.string().transform(e=>parseFloat(e)).optional(),search:t.z.string().optional()}),paymentStatus:ir,paymentChannel:or},lr=It().router({getCollections:{method:"GET",path:"/",query:dr.collectionURLQueryParams,responses:{200:t.z.object({results:t.z.array(dr.collection),total:t.z.number()}),401:Jt.unauthorizedError,403:Jt.forbiddenError,500:Jt.serverError},summary:"List collections",description:"Retrieve a paginated list of collections with optional filtering"},getCollection:{method:"GET",path:"/:id",pathParams:t.z.object({id:t.z.string()}),responses:{200:dr.collection,401:Jt.unauthorizedError,403:Jt.forbiddenError,404:Jt.notFoundError,500:Jt.serverError},summary:"Get collection details",description:"Retrieve detailed information about a specific collection"},getSummary:{method:"GET",path:"/summary",responses:{200:Jt.transactionSummary,401:Jt.unauthorizedError,403:Jt.forbiddenError,500:Jt.serverError},summary:"Get collections summary",description:"Retrieve collection summary statistics for different time periods"}}),hr={[exports.COLLECTION_STATUS.PAYMENT_ACCEPTED]:{label:"Payment Accepted",description:"The payment was successfully accepted",category:"success",color:"success",userFriendlyMessage:"Payment received successfully"},[exports.COLLECTION_STATUS.PENDING_ACK]:{label:"Pending Acknowledgment",description:"The payment is pending acknowledgment",category:"pending",color:"warning",userFriendlyMessage:"Payment is being processed"},[exports.COLLECTION_STATUS.PAYMENT_REJECTED]:{label:"Payment Rejected",description:"The payment was rejected and could not be processed",category:"failed",color:"error",userFriendlyMessage:"Payment was rejected. Please try again"},[exports.COLLECTION_STATUS.GENERIC_FAILURE]:{label:"Payment Failed",description:"A general error occurred during payment processing",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to an unexpected error"},[exports.COLLECTION_STATUS.INSUFFICIENT_FUNDS]:{label:"Insufficient Funds",description:"The payer has insufficient funds to complete the payment",category:"failed",color:"error",userFriendlyMessage:"Insufficient funds to complete the payment"},[exports.COLLECTION_STATUS.PROVIDER_FAILED]:{label:"Provider Failed",description:"An error occurred on the telecom provider's side, and the payment request was not successfully processed",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to an issue with the provider"}},mr={[exports.COLLECTION_CHANNEL.AIRTEL]:er.AIRTEL,[exports.COLLECTION_CHANNEL.TIGO]:er.TIGO,[exports.COLLECTION_CHANNEL.HALOTEL]:er.HALOTEL,[exports.COLLECTION_CHANNEL.VODACOM]:er.VODACOM,[exports.COLLECTION_CHANNEL.SAFARICOM]:er.SAFARICOM};class pr{id;status;statusMessage;accountNo;walletId;transactionDate;narration;msisdn;channel;amount;serviceFee;postedAmount;reference;partnerReference;payerName;payerReference;merchantName;merchantReference;transactionId;serviceFeeTransactionId;requestId;completedAt;createdAt;updatedAt;notes;currencyCode;_originalData;constructor(e){this._originalData={...e};let t="TZS";r.CurrencyHelpers.isCode(e.currencyCode)&&(t=e.currencyCode),this.id=e.id,this.status=e.status,this.statusMessage=e.statusMessage,this.accountNo=e.accountNo,this.walletId=e.walletId,this.transactionDate=new Date(e.transactionDate),this.narration=e.narration,this.msisdn=e.msisdn,this.channel=e.channel,this.amount=r.Amount.from(e.amount,t)??r.Amount.from(0,t),this.serviceFee=e.serviceFee?r.Amount.from(parseFloat(e.serviceFee),t)??r.Amount.from(0,t):void 0,this.postedAmount=e.postedAmount?r.Amount.from(parseFloat(e.postedAmount),t)??r.Amount.from(0,t):void 0,this.reference=e.reference,this.partnerReference=e.partnerReference,this.payerName=e.payerName,this.payerReference=e.payerReference,this.merchantName=e.merchantName,this.merchantReference=e.merchantReference,this.transactionId=e.transactionId,this.serviceFeeTransactionId=e.serviceFeeTransactionId,this.requestId=e.requestId,this.completedAt=e.completedAt?new Date(e.completedAt):null,this.createdAt=new Date(e.createdAt),this.updatedAt=new Date(e.updatedAt),this.notes=e.notes,this.currencyCode=e.currencyCode}getOriginalData(){return this._originalData}getOriginalField(e){return this._originalData[e]}getOriginalFieldUnsafe(e){return this._originalData[e]}isPending(){return this.status===exports.COLLECTION_STATUS.PENDING_ACK}isSuccessful(){return this.status===exports.COLLECTION_STATUS.PAYMENT_ACCEPTED}isFailed(){return Object.entries(hr).filter(([e,t])=>"failed"===t.category).map(([e])=>e).includes(this.status)}getStatusInfo(){return hr[this.status]}getChannelInfo(){return mr[this.channel]}getProviderName(){return this.getChannelInfo().networkOperator}getServiceName(){return this.getChannelInfo().serviceName}isMobileCollection(){return e=this.channel,Object.values(exports.COLLECTION_CHANNEL).includes(e);var e}static from(e){try{return e?.id&&e?.msisdn&&void 0!==e?.amount?new pr(e):void console.error("Missing required Collection fields:",e)}catch(e){return void console.error("Error creating Collection:",e)}}static createMany(e){const t=[];for(const r of e){const e=pr.from(r);e&&t.push(e)}return t}static fromJSON(e){try{if(!e?.id||!e?.msisdn||!e?.amount)return void console.error("Missing required Collection JSON fields:",e);if(!r.AmountFactory.getInstance().isAmountJSON(e.amount))return void console.error("Invalid amount AmountJson structure:",e.amount);if(e.serviceFee&&!r.AmountFactory.getInstance().isAmountJSON(e.serviceFee))return void console.error("Invalid serviceFee AmountJson structure:",e.serviceFee);if(e.postedAmount&&!r.AmountFactory.getInstance().isAmountJSON(e.postedAmount))return void console.error("Invalid postedAmount AmountJson structure:",e.postedAmount);const t=r.Amount.fromJSON(e.amount);if(!t)return void console.error("Failed to reconstruct Amount from JSON:",e.amount);let n,a;if(e.serviceFee){const t=r.Amount.fromJSON(e.serviceFee);if(!t)return void console.error("Failed to reconstruct serviceFee Amount from JSON:",e.serviceFee);n=t.numericValue.toString()}if(e.postedAmount){const t=r.Amount.fromJSON(e.postedAmount);if(!t)return void console.error("Failed to reconstruct postedAmount Amount from JSON:",e.postedAmount);a=t.numericValue.toString()}const s={id:e.id,status:e.status,statusMessage:e.statusMessage,accountNo:e.accountNo,walletId:e.walletId,transactionDate:e.transactionDate,narration:e.narration,msisdn:e.msisdn,channel:e.channel,amount:t.numericValue,serviceFee:n,postedAmount:a,reference:e.reference,partnerReference:e.partnerReference,payerName:e.payerName,payerReference:e.payerReference,merchantName:e.merchantName,merchantReference:e.merchantReference,transactionId:e.transactionId,serviceFeeTransactionId:e.serviceFeeTransactionId,requestId:e.requestId,completedAt:e.completedAt,createdAt:e.createdAt,updatedAt:e.updatedAt,notes:e.notes,currencyCode:e.currencyCode};return new pr(s)}catch(e){return void console.error("Error creating Collection from JSON:",e)}}static createManyFromJson(e){const t=[];for(const r of e){const e=pr.fromJSON(r);e&&t.push(e)}return t}toJSON(){return{id:this.id,status:this.status,statusMessage:this.statusMessage,accountNo:this.accountNo,walletId:this.walletId,transactionDate:this.transactionDate.toISOString(),narration:this.narration,msisdn:this.msisdn,channel:this.channel,amount:this.amount.toJSON(),serviceFee:this.serviceFee?.toJSON(),postedAmount:this.postedAmount?.toJSON(),reference:this.reference,partnerReference:this.partnerReference,payerName:this.payerName,payerReference:this.payerReference,merchantName:this.merchantName,merchantReference:this.merchantReference,transactionId:this.transactionId,serviceFeeTransactionId:this.serviceFeeTransactionId,requestId:this.requestId,completedAt:this.completedAt?.toISOString()??null,createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt.toISOString(),notes:this.notes,currencyCode:this.currencyCode}}}const fr=["id","reference","channel","status"];class yr extends Xt{static create(){return new yr}static fromFilters(e){return(new yr).applyFilters(e)}static fromUrlParams(e){try{const t=dr.collectionURLQueryParams.parse(yr.normalizeUrlParams(e)),r=dr.collectionFilters.parse(t);return yr.fromFilters(r)}catch(e){throw new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){return yr.fromUrlParams(yr.searchParamsToRecord(e))}static fromRequest(e){const{searchParams:t}=new URL(e.url);return yr.fromSearchParams(t)}static from(e){try{return null==e?new yr:Xt.is(e)?new yr(e.options):e instanceof URLSearchParams?yr.fromSearchParams(e):yr.isUrlParamsRecord(e)?yr.fromUrlParams(e):yr.fromFilters(e)}catch(e){throw new Error("Invalid input! Could not create a CollectionQuery instance.")}}static isUrlParamsRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!(e instanceof URLSearchParams)&&Object.values(e).every(e=>"string"==typeof e||Array.isArray(e)&&e.every(e=>"string"==typeof e))}static searchParamsToRecord(e){const t={};return e.forEach((e,r)=>{const n=t[r];void 0===n?t[r]=e:Array.isArray(n)?t[r]=[...n,e]:t[r]=[n,e]}),t}static normalizeUrlParams(e){const t={...e};for(const e of fr){const r=e,n=`${e}In`,a=`${e}:in`,s=`${e}[]`,i=`${e}In[]`,o=t[r],c=cr([t[n],t[a],t[s],t[i],Array.isArray(o)?o:void 0]);c.length>0&&(t[n]=c),Array.isArray(o)&&delete t[r],delete t[a],delete t[s],delete t[i]}return t}whereStatus(e){return this.where("status",e)}whereStatusIn(e){return this.whereInValues("status",e)}whereChannel(e){return this.where("channel",e)}whereChannelIn(e){return this.whereInValues("channel",e)}whereIdIn(e){return this.whereInValues("id",e)}whereReferenceIn(e){return this.whereInValues("reference",e)}wherePending(){return this.whereStatus(exports.COLLECTION_STATUS.PENDING_ACK)}whereSuccessful(){return this.whereStatus(exports.COLLECTION_STATUS.PAYMENT_ACCEPTED)}whereFailed(){return this.whereIn("status",[exports.COLLECTION_STATUS.PAYMENT_REJECTED,exports.COLLECTION_STATUS.GENERIC_FAILURE,exports.COLLECTION_STATUS.INSUFFICIENT_FUNDS,exports.COLLECTION_STATUS.PROVIDER_FAILED])}whereAmountBetween(e,t){return this.whereBetween("amount",e,t)}whereSender(e){return this.whereContains("msisdn",e)}whereAccount(e){return this.whereContains("accountNo",e)}whereWalletId(e){return this.whereContains("walletId",e)}whereReference(e){return this.whereContains("reference",e)}wherePartnerReference(e){return this.whereContains("partnerReference",e)}whereSearch(e){return this.where("search",e)}applyFilters(e){return(e.page||e.limit)&&this.paginate(e.page||1,e.limit||20),e.sortBy&&e.sortOrder&&("asc"===e.sortOrder?this.orderByAsc(e.sortBy):this.orderByDesc(e.sortBy)),(e.startDate||e.endDate)&&this.whereDateBetween(e.startDate,e.endDate),e.statusIn?.length?this.whereStatusIn(e.statusIn):e.status&&this.whereStatus(e.status),e.channelIn?.length?this.whereChannelIn(e.channelIn):e.channel&&this.whereChannel(e.channel),e.msisdn&&this.whereSender(e.msisdn),e.accountNo&&this.whereAccount(e.accountNo),e.walletId&&this.whereWalletId(e.walletId),e.referenceIn?.length?this.whereReferenceIn(e.referenceIn):e.reference&&this.whereReference(e.reference),e.partnerReference&&this.wherePartnerReference(e.partnerReference),e.idIn?.length?this.whereIdIn(e.idIn):e.id&&this.where("id",e.id),void 0===e.minAmount&&void 0===e.maxAmount||(void 0!==e.minAmount&&void 0!==e.maxAmount?this.whereAmountBetween(e.minAmount,e.maxAmount):void 0!==e.minAmount?this.whereGreaterThanOrEqual("amount",e.minAmount):void 0!==e.maxAmount&&this.whereLessThanOrEqual("amount",e.maxAmount)),e.search&&this.whereSearch(e.search),this}toFilters(){const e=this.extractFilterValues();return{page:this.options.page||1,limit:this.options.limit||20,sortBy:this.extractSortField()||"createdAt",sortOrder:this.extractSortOrder()||"desc",startDate:e.startDate,endDate:e.endDate,msisdn:e.msisdn,id:e.id,idIn:e.idIn,reference:e.reference,referenceIn:e.referenceIn,accountNo:e.accountNo,walletId:e.walletId,partnerReference:e.partnerReference,channel:this.isValidChannel(e.channel)?e.channel:void 0,channelIn:this.getValidChannels(e.channelIn),status:this.isValidStatus(e.status)?e.status:void 0,statusIn:this.getValidStatuses(e.statusIn),minAmount:e.minAmount,maxAmount:e.maxAmount,search:e.search}}toUrlParams(){const e=this.toFilters(),t={};return Object.entries(e).forEach(([e,r])=>{null!=r&&(Array.isArray(r)?r.length>0&&(t[e]=r.join(",")):t[e]=String(r))}),t}toSearchParams(){return new URLSearchParams(this.toUrlParams())}toQueryString(){return this.toSearchParams().toString()}withPagination(e,t){const r=this.clone();return r.paginate(e,t||r.options.limit||20),r}withSorting(e,t="desc"){const r=this.clone();return"asc"===t?r.orderByAsc(e):r.orderByDesc(e),r}withDateRange(e,t){const r=this.clone();return r.whereDateBetween(e,t),r}withStatus(e){const t=this.clone();return e&&t.whereStatus(e),t}withChannel(e){const t=this.clone();return e&&t.whereChannel(e),t}resetPage(){return this.withPagination(1)}hasFilters(){const e=this.toFilters();return!!(e.startDate||e.endDate||e.msisdn||e.id||e.idIn?.length||e.reference||e.referenceIn?.length||e.accountNo||e.walletId||e.partnerReference||e.channel||e.channelIn?.length||e.status||e.statusIn?.length||e.minAmount||e.maxAmount||e.search)}getActiveFilters(){const e=[],t=this.toFilters();return t.statusIn?.length?e.push(`Status: ${t.statusIn.join(", ")}`):t.status&&e.push(`Status: ${t.status}`),t.channelIn?.length?e.push(`Channel: ${t.channelIn.join(", ")}`):t.channel&&e.push(`Channel: ${t.channel}`),t.startDate&&t.endDate?e.push(`Date: ${t.startDate} to ${t.endDate}`):t.startDate?e.push(`From: ${t.startDate}`):t.endDate&&e.push(`Until: ${t.endDate}`),t.minAmount&&t.maxAmount?e.push(`Amount: ${t.minAmount} - ${t.maxAmount}`):t.minAmount?e.push(`Min Amount: ${t.minAmount}`):t.maxAmount&&e.push(`Max Amount: ${t.maxAmount}`),t.search&&e.push(`Search: "${t.search}"`),t.msisdn&&e.push(`Phone: ${t.msisdn}`),t.accountNo&&e.push(`Account: ${t.accountNo}`),t.walletId&&e.push(`Wallet ID: ${t.walletId}`),t.referenceIn?.length?e.push(`Reference: ${t.referenceIn.join(", ")}`):t.reference&&e.push(`Reference: ${t.reference}`),t.idIn?.length&&e.push(`ID: ${t.idIn.join(", ")}`),e}extractFilterValues(){const e={};if(!this.options.filters)return e;for(const t of this.options.filters){if("in"===t.operator){const r=cr(t.value);r.length>0&&(e[`${t.field}In`]=r);continue}switch(t.field){case"createdAt":"gte"===t.operator?e.startDate=t.value:"lte"===t.operator&&(e.endDate=t.value);break;case"amount":"gte"===t.operator?e.minAmount=t.value:"lte"===t.operator&&(e.maxAmount=t.value);break;case"msisdn":case"reference":case"accountNo":case"walletId":case"partnerReference":"likeLower"===t.operator&&"string"==typeof t.value?e[t.field]=t.value.replace(/%/g,""):"eq"===t.operator&&(e[t.field]=t.value);break;default:"eq"===t.operator&&(e[t.field]=t.value)}}return e}whereInValues(e,t){const r=cr(t);return 0===r.length?this:this.whereIn(e,r)}getValidStatuses(e){const t=cr(e).filter(e=>this.isValidStatus(e));return t.length>0?t:void 0}getValidChannels(e){const t=cr(e).filter(e=>this.isValidChannel(e));return t.length>0?t:void 0}extractSortField(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].field}extractSortOrder(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].direction}isValidChannel(e){return Object.values(exports.COLLECTION_CHANNEL).includes(e)}isValidStatus(e){return Object.values(exports.COLLECTION_STATUS).includes(e)}}var gr,vr;exports.PAYOUT_STATUS=void 0,(gr=exports.PAYOUT_STATUS||(exports.PAYOUT_STATUS={})).PAYMENT_ACCEPTED="PAYMENT_ACCEPTED",gr.GENERIC_FAILURE="GENERIC_FAILURE",gr.WALLET_DEBITED="WALLET_DEBITED",gr.PAYMENT_REJECTED="PAYMENT_REJECTED",gr.PENDING="PENDING",gr.AMOUNT_EXCEED_MAXIMUM="AMOUNT_EXCEED_MAXIMUM",gr.PENDING_ACK="PENDING_ACK",gr.REVERSED="REVERSED",gr.INVALID_SERVICE="INVALID_SERVICE",gr.INVALID_NUMBER="INVALID_NUMBER",gr.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",gr.THIRDPARTY_FAILED="THIRDPARTY_FAILED",gr.PROVIDER_FAILED="PROVIDER_FAILED",exports.MOBILE_PAYOUT_CHANNEL=void 0,(vr=exports.MOBILE_PAYOUT_CHANNEL||(exports.MOBILE_PAYOUT_CHANNEL={})).AIRTEL="TZ-AIRTEL-B2C",vr.VODACOM="TZ-VODACOM-B2C",vr.TIGO="TZ-TIGO-B2C",vr.HALOTEL="TZ-HALOTEL-B2C",vr.SAFARICOM="TZ-SAFARICOM-B2C",exports.BANK_PAYOUT_CHANNEL=void 0,(exports.BANK_PAYOUT_CHANNEL||(exports.BANK_PAYOUT_CHANNEL={})).BANK="TZ-BANK-B2C";const _r=t.z.nativeEnum(exports.PAYOUT_STATUS),Ar=t.z.nativeEnum(exports.MOBILE_PAYOUT_CHANNEL),Nr=t.z.nativeEnum(exports.BANK_PAYOUT_CHANNEL),Ir=t.z.union([Ar,Nr]),Tr=e=>{const t=Array.isArray(e)?e.flatMap(e=>Tr(e)):"string"==typeof e?e.split(","):[];return Array.from(new Set(t.map(e=>e.trim()).filter(e=>e.length>0)))},wr=t.z.union([t.z.string(),t.z.array(t.z.string())]),br={payout:t.z.object({id:t.z.string().min(1),statusCode:t.z.string(),statusCodeText:_r,statusDescription:t.z.string(),countryCode:t.z.string(),serviceCode:Ir,amount:t.z.number().min(0),serviceFee:t.z.string().optional(),postedAmount:t.z.string().optional(),walletId:t.z.string().optional(),msisdn:t.z.string().min(1),narration:t.z.string(),currencyCode:t.z.string(),recipientNames:t.z.string().optional(),transactionRef:t.z.string(),transactionDate:t.z.string().datetime(),externalId:t.z.string().nullable().optional(),cbaReferenceNo:t.z.string().optional(),beepTransactionId:t.z.string().optional(),receiptNumber:t.z.string().optional(),createdAt:t.z.string().datetime(),reversedTransactionId:t.z.string().nullable().optional(),transactionId:t.z.string(),serviceFeeTransactionId:t.z.string().optional(),isReconciled:t.z.number().optional(),requestId:t.z.string().optional(),notes:t.z.string().optional(),updatedAt:t.z.string().datetime().optional()}),payoutFilters:t.z.object({page:t.z.number().int().positive().default(1),limit:t.z.number().int().positive().max(5e4).default(20),sortBy:t.z.string().default("createdAt"),sortOrder:t.z.enum(["asc","desc"]).default("desc"),startDate:t.z.string().datetime().optional(),endDate:t.z.string().datetime().optional(),msisdn:t.z.string().optional(),accountNo:t.z.string().optional(),walletId:t.z.string().optional(),id:t.z.string().optional(),idIn:t.z.array(t.z.string()).optional(),ref:t.z.string().optional(),refIn:t.z.array(t.z.string()).optional(),channelRef:t.z.string().optional(),channelRefIn:t.z.array(t.z.string()).optional(),channel:Ir.optional(),channelIn:t.z.array(Ir).optional(),status:_r.optional(),statusIn:t.z.array(_r).optional(),minAmount:t.z.number().min(0).optional(),maxAmount:t.z.number().min(0).optional(),search:t.z.string().optional()}),payoutURLQueryParams:t.z.object({page:t.z.string().transform(e=>parseInt(e)||1).optional(),limit:t.z.string().transform(e=>parseInt(e)||20).optional(),sortBy:t.z.string().default("createdAt"),sortOrder:t.z.enum(["asc","desc"]).default("desc"),startDate:t.z.string().optional(),endDate:t.z.string().optional(),msisdn:t.z.string().optional(),accountNo:t.z.string().optional(),walletId:t.z.string().optional(),id:t.z.string().optional(),idIn:wr.transform(Tr).optional(),ref:t.z.string().optional(),refIn:wr.transform(Tr).optional(),channelRef:t.z.string().optional(),channelRefIn:wr.transform(Tr).optional(),channel:t.z.string().refine(e=>Object.values(exports.MOBILE_PAYOUT_CHANNEL).includes(e)||e===exports.BANK_PAYOUT_CHANNEL.BANK).transform(e=>e).optional(),channelIn:wr.transform(Tr).pipe(t.z.array(Ir)).optional(),status:t.z.string().refine(e=>Object.values(exports.PAYOUT_STATUS).includes(e)).transform(e=>e).optional(),statusIn:wr.transform(Tr).pipe(t.z.array(_r)).optional(),minAmount:t.z.string().transform(e=>parseFloat(e)).optional(),maxAmount:t.z.string().transform(e=>parseFloat(e)).optional(),search:t.z.string().optional()}),payoutStatus:_r,payoutChannel:Ir,mobileChannel:Ar,bankChannel:Nr,walletSummary:t.z.object({balance:t.z.number(),currency:t.z.string(),lastUpdated:t.z.string().datetime()}),transactionSummary:t.z.object({yesterday:t.z.number(),today:t.z.number(),thisMonth:t.z.number(),lastMonth:t.z.number()}),pagination:t.z.object({page:t.z.number(),limit:t.z.number(),total:t.z.number(),totalPages:t.z.number(),hasNext:t.z.boolean(),hasPrev:t.z.boolean()})},Er=It().router({getPayouts:{method:"GET",path:"",query:br.payoutURLQueryParams,responses:{200:t.z.object({results:t.z.array(br.payout),total:t.z.number()}),401:Jt.unauthorizedError,403:Jt.forbiddenError,500:Jt.serverError},summary:"List payouts",description:"Retrieve a paginated list of payouts with optional filtering"},getPayout:{method:"GET",path:"/:id",pathParams:t.z.object({id:t.z.string()}),responses:{200:br.payout,401:Jt.unauthorizedError,403:Jt.forbiddenError,404:Jt.notFoundError,500:Jt.serverError},summary:"Get payout details",description:"Retrieve detailed information about a specific payout"},getPayoutSummary:{method:"GET",path:"/summary",responses:{200:Jt.transactionSummary,401:Jt.unauthorizedError,403:Jt.forbiddenError,500:Jt.serverError},summary:"Get payout summary",description:"Retrieve payout statistics including yesterday, today, this month, and last month totals"}}),Cr={[exports.PAYOUT_STATUS.PAYMENT_ACCEPTED]:{label:"Payment Accepted",description:"The payment was successfully accepted",category:"success",color:"success",userFriendlyMessage:"Payment completed successfully"},[exports.PAYOUT_STATUS.PENDING_ACK]:{label:"Pending Acknowledgment",description:"The payment is pending acknowledgment",category:"pending",color:"warning",userFriendlyMessage:"Payment is being processed"},[exports.PAYOUT_STATUS.PENDING]:{label:"Pending",description:"Payment is being processed",category:"pending",color:"warning",userFriendlyMessage:"Payment is in progress"},[exports.PAYOUT_STATUS.PAYMENT_REJECTED]:{label:"Payment Rejected",description:"The payment was rejected and could not be processed",category:"failed",color:"error",userFriendlyMessage:"Payment was rejected. Check payment details and try again"},[exports.PAYOUT_STATUS.GENERIC_FAILURE]:{label:"Payment Failed",description:"A general error occurred",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to an unexpected error"},[exports.PAYOUT_STATUS.INSUFFICIENT_BALANCE]:{label:"Insufficient Balance",description:"Insufficient funds are available to process the payment",category:"failed",color:"error",userFriendlyMessage:"Insufficient funds to complete the payment"},[exports.PAYOUT_STATUS.THIRDPARTY_FAILED]:{label:"Service Provider Error",description:"There was an error with the third-party service provider",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to service provider issue"},[exports.PAYOUT_STATUS.PROVIDER_FAILED]:{label:"Service Provider Error",description:"There was an error with the third-party service provider",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to service provider issue"},[exports.PAYOUT_STATUS.AMOUNT_EXCEED_MAXIMUM]:{label:"Amount Exceeds Limit",description:"Payment amount exceeds the maximum allowed limit",category:"failed",color:"error",userFriendlyMessage:"Payment amount exceeds the allowed limit"},[exports.PAYOUT_STATUS.WALLET_DEBITED]:{label:"Wallet Debited",description:"Wallet has been debited but payment is not yet complete",category:"failed",color:"error",userFriendlyMessage:"Payment incomplete - wallet debited but recipient may not have received funds"},[exports.PAYOUT_STATUS.REVERSED]:{label:"Payment Reversed",description:"Payment has been reversed and funds returned",category:"failed",color:"error",userFriendlyMessage:"Payment was reversed and funds have been returned"},[exports.PAYOUT_STATUS.INVALID_SERVICE]:{label:"Invalid Service",description:"The requested payment service is not valid or available",category:"failed",color:"error",userFriendlyMessage:"Selected payment service is not available"},[exports.PAYOUT_STATUS.INVALID_NUMBER]:{label:"Invalid Number",description:"The number used is either barred or invalid",category:"failed",color:"error",userFriendlyMessage:"Recipient’s number is invalid, inactive, or temporarily blocked."}},Sr={[exports.MOBILE_PAYOUT_CHANNEL.AIRTEL]:er.AIRTEL,[exports.MOBILE_PAYOUT_CHANNEL.VODACOM]:er.VODACOM,[exports.MOBILE_PAYOUT_CHANNEL.TIGO]:er.TIGO,[exports.MOBILE_PAYOUT_CHANNEL.HALOTEL]:er.HALOTEL,[exports.MOBILE_PAYOUT_CHANNEL.SAFARICOM]:er.SAFARICOM};function Or(e){return Object.values(exports.MOBILE_PAYOUT_CHANNEL).includes(e)}function xr(e){return e===exports.BANK_PAYOUT_CHANNEL.BANK}class Rr{id;serviceCode;msisdn;amount;transactionDate;statusDescription;statusCodeText;transactionId;transactionRef;recipientNames;narration;serviceFee;notes;swiftCode;createdAt;updatedAt;statusCode;countryCode;postedAmount;walletId;currencyCode;externalId;cbaReferenceNo;beepTransactionId;receiptNumber;reversedTransactionId;serviceFeeTransactionId;isReconciled;requestId;_originalData;constructor(e){this._originalData={...e};let t="TZS";r.CurrencyHelpers.isCode(e.currencyCode)&&(t=e.currencyCode),this.id=e.id,this.serviceCode=e.serviceCode,this.msisdn=e.msisdn,this.amount=r.Amount.from(e.amount,t)??r.Amount.from(0,t),this.transactionDate=new Date(e.transactionDate),this.statusDescription=e.statusDescription,this.statusCodeText=e.statusCodeText,this.transactionId=e.transactionId,this.transactionRef=e.transactionRef,this.recipientNames=e.recipientNames,this.narration=e.narration,this.serviceFee=void 0===e.serviceFee?void 0:r.Amount.from(e.serviceFee,t)??r.Amount.from(0,t),this.notes=e.notes,this.swiftCode=e.swiftCode,this.createdAt=new Date(e.createdAt),this.updatedAt=e.updatedAt?new Date(e.updatedAt):void 0,this.statusCode=e.statusCode,this.countryCode=e.countryCode,this.postedAmount=e.postedAmount?r.Amount.from(parseFloat(e.postedAmount),t):void 0,this.walletId=e.walletId,this.currencyCode=e.currencyCode,this.externalId=e.externalId,this.cbaReferenceNo=e.cbaReferenceNo,this.beepTransactionId=e.beepTransactionId,this.receiptNumber=e.receiptNumber,this.reversedTransactionId=e.reversedTransactionId,this.serviceFeeTransactionId=e.serviceFeeTransactionId,this.isReconciled=e.isReconciled,this.requestId=e.requestId}getOriginalData(){return this._originalData}getOriginalField(e){return this._originalData[e]}getOriginalFieldUnsafe(e){return this._originalData[e]}isPending(){return[exports.PAYOUT_STATUS.PENDING,exports.PAYOUT_STATUS.PENDING_ACK].includes(this.statusCodeText)}isSuccessful(){return this.statusCodeText===exports.PAYOUT_STATUS.PAYMENT_ACCEPTED}isFailed(){return Object.entries(Cr).filter(([e,t])=>"failed"===t.category).map(([e])=>e).includes(this.statusCodeText)}getStatusInfo(){return Cr[this.statusCodeText]}getChannelInfo(){if(Or(this.serviceCode))return Sr[this.serviceCode];if(xr(this.serviceCode)){const e=this.msisdn.split(":")[0];if(e&&r.BankHelpers.validateSwiftCode(e)){if(r.BankHelpers.getCountryFromSwiftCode(e))try{return r.BankRegistry.getInstance().detectBank(e)}catch(t){console.warn(`Failed to create Bank instance for SWIFT code ${e}:`,t)}}if(this.swiftCode&&r.BankHelpers.getCountryFromSwiftCode(this.swiftCode)){if(r.BankHelpers.getCountryFromSwiftCode(this.swiftCode))try{return r.BankRegistry.getInstance().detectBank(this.swiftCode)}catch(e){console.warn(`Failed to create Bank instance for SWIFT code ${this.swiftCode}:`,e)}}}}getAccountNumber(){try{if(Or(this.serviceCode))return this.msisdn;if(xr(this.serviceCode)){return this.msisdn.split(":")[1]||this.msisdn}}catch(e){console.warn("failed to get the account number from payout msisdn: ",this.msisdn)}return this.msisdn}getProviderName(){const e=this.getChannelInfo();return Or(this.serviceCode)&&e?e.networkOperator:r.Bank.is(e)?e.shortName:"Bank Transfer"}static from(e){try{return e?.id&&e?.msisdn&&void 0!==e?.amount?new Rr(e):void console.error("Missing required Payout fields:",e)}catch(e){return void console.error("Error creating Payout:",e)}}static createMany(e){const t=[];for(const r of e){const e=Rr.from(r);e&&t.push(e)}return t}static fromJSON(e){try{if(!e?.id||!e?.msisdn||!e?.amount)return void console.error("Missing required Payout JSON fields:",e);if(!r.AmountFactory.getInstance().isAmountJSON(e.amount))return void console.error("Invalid amount AmountJson structure:",e.amount);if(e.serviceFee&&!r.AmountFactory.getInstance().isAmountJSON(e.serviceFee))return void console.error("Invalid serviceFee AmountJson structure:",e.serviceFee);if(e.postedAmount&&!r.AmountFactory.getInstance().isAmountJSON(e.postedAmount))return void console.error("Invalid postedAmount AmountJson structure:",e.postedAmount);const t=r.Amount.fromJSON(e.amount);if(!t)return void console.error("Failed to reconstruct Amount from JSON:",e.amount);let n,a;if(e.serviceFee){const t=r.Amount.fromJSON(e.serviceFee);if(!t)return void console.error("Failed to reconstruct serviceFee Amount from JSON:",e.serviceFee);n=t.numericValue}if(e.postedAmount){const t=r.Amount.fromJSON(e.postedAmount);if(!t)return void console.error("Failed to reconstruct postedAmount Amount from JSON:",e.postedAmount);a=t.numericValue.toString()}const s={id:e.id,serviceCode:e.serviceCode,msisdn:e.msisdn,amount:t.numericValue,transactionDate:e.transactionDate,statusDescription:e.statusDescription,statusCodeText:e.statusCodeText,transactionId:e.transactionId,transactionRef:e.transactionRef,recipientNames:e.recipientNames,narration:e.narration,serviceFee:n,notes:e.notes,swiftCode:e.swiftCode,createdAt:e.createdAt,updatedAt:e.updatedAt,statusCode:e.statusCode,countryCode:e.countryCode,postedAmount:a,walletId:e.walletId,currencyCode:e.currencyCode,externalId:e.externalId,cbaReferenceNo:e.cbaReferenceNo,beepTransactionId:e.beepTransactionId,receiptNumber:e.receiptNumber,reversedTransactionId:e.reversedTransactionId,serviceFeeTransactionId:e.serviceFeeTransactionId,isReconciled:e.isReconciled,requestId:e.requestId};return new Rr(s)}catch(e){return void console.error("Error creating Payout from JSON:",e)}}static createManyFromJson(e){const t=[];for(const r of e){const e=Rr.fromJSON(r);e&&t.push(e)}return t}toJSON(){return{id:this.id,serviceCode:this.serviceCode,msisdn:this.msisdn,amount:this.amount.toJSON(),transactionDate:this.transactionDate.toISOString(),statusDescription:this.statusDescription,statusCodeText:this.statusCodeText,transactionId:this.transactionId,transactionRef:this.transactionRef,recipientNames:this.recipientNames,narration:this.narration,serviceFee:this.serviceFee?.toJSON(),notes:this.notes,swiftCode:this.swiftCode,createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt?.toISOString(),statusCode:this.statusCode,countryCode:this.countryCode,postedAmount:this.postedAmount?.toJSON(),walletId:this.walletId,currencyCode:this.currencyCode,externalId:this.externalId,cbaReferenceNo:this.cbaReferenceNo,beepTransactionId:this.beepTransactionId,receiptNumber:this.receiptNumber,reversedTransactionId:this.reversedTransactionId,serviceFeeTransactionId:this.serviceFeeTransactionId,isReconciled:this.isReconciled,requestId:this.requestId}}}const Pr=["status","channel","id","ref","channelRef"],Dr=Object.fromEntries(Object.entries({status:"statusCodeText",channel:"serviceCode",id:"id",ref:"transactionRef",channelRef:"channelReference"}).map(([e,t])=>[t,e]));class Lr extends Xt{static create(){return new Lr}static fromFilters(e){return(new Lr).applyFilters(e)}static fromUrlParams(e){try{const t=br.payoutURLQueryParams.parse(Lr.normalizeUrlParams(e)),r=br.payoutFilters.parse(t);return Lr.fromFilters(r)}catch(e){throw new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){return Lr.fromUrlParams(Lr.searchParamsToRecord(e))}static fromRequest(e){const{searchParams:t}=new URL(e.url);return Lr.fromSearchParams(t)}static from(e){return null==e?new Lr:Xt.is(e)?new Lr(e.options):e instanceof URLSearchParams?Lr.fromSearchParams(e):Lr.isUrlParamsRecord(e)?Lr.fromUrlParams(e):Lr.fromFilters(e)}static isUrlParamsRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!(e instanceof URLSearchParams)&&Object.values(e).every(e=>"string"==typeof e||Array.isArray(e)&&e.every(e=>"string"==typeof e))}static searchParamsToRecord(e){const t={};return e.forEach((e,r)=>{const n=t[r];void 0===n?t[r]=e:Array.isArray(n)?t[r]=[...n,e]:t[r]=[n,e]}),t}static normalizeUrlParams(e){const t={...e};for(const e of Pr){const r=e,n=`${e}In`,a=`${e}:in`,s=`${e}[]`,i=`${e}In[]`,o=t[r],c=Tr([t[n],t[a],t[s],t[i],Array.isArray(o)?o:void 0]);c.length>0&&(t[n]=c),Array.isArray(o)&&delete t[r],delete t[a],delete t[s],delete t[i]}return t}whereStatus(e){return this.where("statusCodeText",e)}whereStatusIn(e){return this.whereInValues("statusCodeText",e)}whereChannel(e){return this.where("serviceCode",e)}whereChannelIn(e){return this.whereInValues("serviceCode",e)}whereIdIn(e){return this.whereInValues("id",e)}whereRefIn(e){return this.whereInValues("transactionRef",e)}whereChannelRef(e){return this.whereContains("channelReference",e)}whereChannelRefIn(e){return this.whereInValues("channelReference",e)}wherePending(){return this.whereIn("statusCodeText",[exports.PAYOUT_STATUS.PENDING,exports.PAYOUT_STATUS.PENDING_ACK])}whereSuccessful(){return this.whereStatus(exports.PAYOUT_STATUS.PAYMENT_ACCEPTED)}whereFailed(){return this.whereIn("statusCodeText",[exports.PAYOUT_STATUS.PAYMENT_REJECTED,exports.PAYOUT_STATUS.GENERIC_FAILURE,exports.PAYOUT_STATUS.AMOUNT_EXCEED_MAXIMUM,exports.PAYOUT_STATUS.INVALID_SERVICE,exports.PAYOUT_STATUS.INSUFFICIENT_BALANCE,exports.PAYOUT_STATUS.THIRDPARTY_FAILED,exports.PAYOUT_STATUS.WALLET_DEBITED,exports.PAYOUT_STATUS.REVERSED])}whereAmountBetween(e,t){return this.whereBetween("amount",e,t)}whereRecipient(e){return this.whereContains("msisdn",e)}whereAccount(e){return this.whereContains("accountNo",e)}whereWalletId(e){return this.whereContains("walletId",e)}whereReference(e){return this.whereContains("transactionRef",e)}whereMobile(){return this.whereIn("serviceCode",Object.values(exports.MOBILE_PAYOUT_CHANNEL))}whereBank(){return this.whereChannel(exports.BANK_PAYOUT_CHANNEL.BANK)}whereSearch(e){return this.where("search",e)}applyFilters(e){return(e.page||e.limit)&&this.paginate(e.page||1,e.limit||20),e.sortBy&&e.sortOrder&&("asc"===e.sortOrder?this.orderByAsc(e.sortBy):this.orderByDesc(e.sortBy)),(e.startDate||e.endDate)&&this.whereDateBetween(e.startDate,e.endDate),e.statusIn?.length?this.whereStatusIn(e.statusIn):e.status&&this.whereStatus(e.status),e.channelIn?.length?this.whereChannelIn(e.channelIn):e.channel&&this.whereChannel(e.channel),e.msisdn&&this.whereRecipient(e.msisdn),e.accountNo&&this.whereAccount(e.accountNo),e.walletId&&this.whereWalletId(e.walletId),e.refIn?.length?this.whereRefIn(e.refIn):e.ref&&this.whereReference(e.ref),e.channelRefIn?.length?this.whereChannelRefIn(e.channelRefIn):e.channelRef&&this.whereChannelRef(e.channelRef),e.idIn?.length?this.whereIdIn(e.idIn):e.id&&this.where("id",e.id),void 0===e.minAmount&&void 0===e.maxAmount||(void 0!==e.minAmount&&void 0!==e.maxAmount?this.whereAmountBetween(e.minAmount,e.maxAmount):void 0!==e.minAmount?this.whereGreaterThanOrEqual("amount",e.minAmount):void 0!==e.maxAmount&&this.whereLessThanOrEqual("amount",e.maxAmount)),e.search&&this.whereSearch(e.search),this}toFilters(){const e=this.extractFilterValues();return{page:this.options.page||1,limit:this.options.limit||20,sortBy:this.extractSortField()||"createdAt",sortOrder:this.extractSortOrder()||"desc",startDate:e.startDate,endDate:e.endDate,msisdn:e.msisdn,accountNo:e.accountNo,walletId:e.walletId,id:e.id,idIn:e.idIn,ref:e.transactionRef,refIn:e.refIn,channelRef:e.channelReference,channelRefIn:e.channelRefIn,channel:this.isValidChannel(e.serviceCode)?e.serviceCode:void 0,channelIn:this.getValidChannels(e.channelIn),status:this.isValidStatus(e.statusCodeText)?e.statusCodeText:void 0,statusIn:this.getValidStatuses(e.statusIn),minAmount:e.minAmount,maxAmount:e.maxAmount,search:e.search}}toUrlParams(){const e=this.toFilters(),t={};return Object.entries(e).forEach(([e,r])=>{null!=r&&(Array.isArray(r)?r.length>0&&(t[e]=r.join(",")):t[e]=String(r))}),t}toSearchParams(){return new URLSearchParams(this.toUrlParams())}toQueryString(){return this.toSearchParams().toString()}withPagination(e,t){const r=this.clone();return r.paginate(e,t||r.options.limit||20),r}withSorting(e,t="desc"){const r=this.clone();return"asc"===t?r.orderByAsc(e):r.orderByDesc(e),r}withDateRange(e,t){const r=this.clone();return r.whereDateBetween(e,t),r}withStatus(e){const t=this.clone();return e&&t.whereStatus(e),t}withChannel(e){const t=this.clone();return e&&t.whereChannel(e),t}resetPage(){return this.withPagination(1)}hasFilters(){const e=this.toFilters();return!!(e.startDate||e.endDate||e.msisdn||e.accountNo||e.walletId||e.id||e.idIn?.length||e.ref||e.refIn?.length||e.channelRef||e.channelRefIn?.length||e.channel||e.channelIn?.length||e.status||e.statusIn?.length||e.minAmount||e.maxAmount||e.search)}getActiveFilters(){const e=[],t=this.toFilters();return t.statusIn?.length?e.push(`Status: ${t.statusIn.join(", ")}`):t.status&&e.push(`Status: ${t.status}`),t.channelIn?.length?e.push(`Channel: ${t.channelIn.join(", ")}`):t.channel&&e.push(`Channel: ${t.channel}`),t.startDate&&t.endDate?e.push(`Date: ${t.startDate} to ${t.endDate}`):t.startDate?e.push(`From: ${t.startDate}`):t.endDate&&e.push(`Until: ${t.endDate}`),t.minAmount&&t.maxAmount?e.push(`Amount: ${t.minAmount} - ${t.maxAmount}`):t.minAmount?e.push(`Min Amount: ${t.minAmount}`):t.maxAmount&&e.push(`Max Amount: ${t.maxAmount}`),t.search&&e.push(`Search: "${t.search}"`),t.msisdn&&e.push(`Recipient: ${t.msisdn}`),t.accountNo&&e.push(`Account: ${t.accountNo}`),t.walletId&&e.push(`Wallet ID: ${t.walletId}`),t.refIn?.length?e.push(`Reference: ${t.refIn.join(", ")}`):t.ref&&e.push(`Reference: ${t.ref}`),t.channelRefIn?.length?e.push(`Channel Ref: ${t.channelRefIn.join(", ")}`):t.channelRef&&e.push(`Channel Ref: ${t.channelRef}`),t.idIn?.length&&e.push(`ID: ${t.idIn.join(", ")}`),e}extractFilterValues(){const e={};if(!this.options.filters)return e;for(const t of this.options.filters){if("in"===t.operator){const r=Tr(t.value);if(0===r.length)continue;e[`${Dr[t.field]??t.field}In`]=r;continue}switch(t.field){case"createdAt":"gte"===t.operator?e.startDate=t.value:"lte"===t.operator&&(e.endDate=t.value);break;case"amount":"gte"===t.operator?e.minAmount=t.value:"lte"===t.operator&&(e.maxAmount=t.value);break;case"msisdn":case"accountNo":case"walletId":case"transactionRef":case"channelReference":"likeLower"===t.operator&&"string"==typeof t.value?e[t.field]=t.value.replace(/%/g,""):"eq"===t.operator&&(e[t.field]=t.value);break;default:"eq"===t.operator&&(e[t.field]=t.value)}}return e}whereInValues(e,t){const r=Tr(t);return 0===r.length?this:this.whereIn(e,r)}getValidStatuses(e){const t=Tr(e).filter(e=>this.isValidStatus(e));return t.length>0?t:void 0}getValidChannels(e){const t=Tr(e).filter(e=>this.isValidChannel(e));return t.length>0?t:void 0}extractSortField(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].field}extractSortOrder(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].direction}isValidChannel(e){return Object.values(exports.MOBILE_PAYOUT_CHANNEL).includes(e)||e===exports.BANK_PAYOUT_CHANNEL.BANK}isValidStatus(e){return Object.values(exports.PAYOUT_STATUS).includes(e)}}const kr={localTransferRequest:t.z.object({amount:t.z.number().int().positive(),from:t.z.string().min(1),to:t.z.string().min(1),description:t.z.string().min(1)}),localTransferResponse:t.z.object({transactionId:t.z.string(),from:t.z.string(),to:t.z.string(),transactionDate:t.z.string(),narration:t.z.string(),amount:t.z.number(),transactionRef:t.z.string()})},Fr=It().router({localTransfer:{method:"POST",path:"/local-transfer",body:kr.localTransferRequest,responses:{201:kr.localTransferResponse,400:Jt.validationError,401:Jt.unauthorizedError,404:Jt.notFoundError,500:Jt.serverError},summary:"Local transfer",description:"Transfer funds locally between wallets."}});var zr;exports.WALLET_TYPE=void 0,(zr=exports.WALLET_TYPE||(exports.WALLET_TYPE={})).VENDOR="Vendor",zr.DEFAULT_DISBURSEMENT="DEFAULT DISBURSEMENT",zr.DEFAULT_COLLECTION="DEFAULT COLLECTION",zr.COLLECTION="COLLECTION",zr.DISBURSEMENT="DISBURSEMENT";const Ur=t.z.nativeEnum(exports.WALLET_TYPE),Mr=t.z.object({id:t.z.string().min(1),accountNo:t.z.string().min(1),accountName:t.z.string().min(1),shadowAccountNo:t.z.string().nullish(),externalId:t.z.string().nullish(),reference:t.z.string().nullish(),type:t.z.string().min(1),vendorId:t.z.string().nullish(),balance:t.z.number(),minBalance:t.z.union([t.z.number(),t.z.string()]),approvalLimit:t.z.union([t.z.number(),t.z.string()]),currency:t.z.string().min(1),countryCode:t.z.string().min(1),createdAt:t.z.string().min(1),updatedAt:t.z.string().min(1)}),jr=t.z.object({availableBalance:t.z.number(),currentBalance:t.z.number(),accountStatus:t.z.string().min(1),accountNo:t.z.string().min(1),accountName:t.z.string().min(1)}),Zr={wallet:Mr,walletType:Ur,walletPathParams:t.z.object({accountNo:t.z.string().min(1)}),walletBalance:jr,walletStatementQuery:t.z.object({startDate:t.z.string().regex(/^\d{4}-\d{2}-\d{2}$/),endDate:t.z.string().regex(/^\d{4}-\d{2}-\d{2}$/)})},Br=It().router({listWallets:{method:"GET",path:"",responses:{200:t.z.array(Zr.wallet),401:Jt.unauthorizedError,500:Jt.serverError},summary:"List wallets",description:"Retrieve all wallets linked to the account across supported currencies."},getWalletInfo:{method:"GET",path:"/:accountNo",pathParams:t.z.object({accountNo:t.z.string().min(1)}),responses:{200:Zr.wallet,401:Jt.unauthorizedError,500:Jt.serverError},summary:"Get wallet info",description:"Retrieve wallet metadata including balance, currency, and type for a specific wallet."},getWalletBalance:{method:"GET",path:"/:accountNo/balance",pathParams:Zr.walletPathParams,responses:{200:Zr.walletBalance,401:Jt.unauthorizedError,404:Jt.notFoundError,500:Jt.serverError},summary:"Get wallet balance",description:"Retrieve the current and available balance for a specific wallet account number."},getWalletStatement:{method:"GET",path:"/:accountNo/statement",pathParams:Zr.walletPathParams,query:Zr.walletStatementQuery,responses:{200:t.z.array(Jt.statementEntry),400:Jt.validationError,401:Jt.unauthorizedError,404:Jt.notFoundError,500:Jt.serverError},summary:"Get wallet statement",description:"Retrieve statement entries for a specific wallet within a date range."}});class $r{id;accountNo;accountName;shadowAccountNo;externalId;reference;type;vendorId;balance;minBalance;approvalLimit;currency;countryCode;createdAt;updatedAt;_originalData;constructor(e){this._originalData={...e};let t="TZS";r.CurrencyHelpers.isCode(e.currency)?t=e.currency:"KSH"===e.currency&&(t="KES"),this.id=e.id,this.accountNo=e.accountNo,this.accountName=e.accountName,this.shadowAccountNo=e.shadowAccountNo,this.externalId=e.externalId,this.reference=e.reference,this.type=e.type,this.vendorId=e.vendorId,this.balance=r.Amount.from(e.balance,t)??r.Amount.from(0,t),this.minBalance=r.Amount.from(this.parseAmountValue(e.minBalance),t)??r.Amount.from(0,t),this.approvalLimit=r.Amount.from(this.parseAmountValue(e.approvalLimit),t)??r.Amount.from(0,t),this.currency=t,this.countryCode=e.countryCode,this.createdAt=new Date(e.createdAt),this.updatedAt=new Date(e.updatedAt)}getOriginalData(){return this._originalData}parseAmountValue(e){if("number"==typeof e)return e;const t=parseFloat(e);return Number.isNaN(t)?0:t}isCollectionWallet(){return this.type.includes("COLLECTION")}isDisbursementWallet(){return this.type.includes("DISBURSEMENT")}isDefaultWallet(){return this.type.startsWith("DEFAULT")}static from(e){return new $r(e)}static createMany(e){const t=[];try{for(const r of e)t.push($r.from(r));return t}catch(e){return void console.error("Error creating Wallets:",e)}}toJSON(){return{id:this.id,accountNo:this.accountNo,accountName:this.accountName,shadowAccountNo:this.shadowAccountNo,externalId:this.externalId,reference:this.reference,type:this.type,vendorId:this.vendorId,balance:this.balance.toJSON(),minBalance:this.minBalance.toJSON(),approvalLimit:this.approvalLimit.toJSON(),currency:this.currency,countryCode:this.countryCode,createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt.toISOString()}}static fromJSON(e){try{if(!r.AmountFactory.getInstance().isAmountJSON(e.balance))return void console.error("Invalid balance AmountJson structure in Wallet JSON:",e);if(!r.AmountFactory.getInstance().isAmountJSON(e.minBalance)||!r.AmountFactory.getInstance().isAmountJSON(e.approvalLimit))return void console.error("Invalid wallet threshold AmountJson structure in Wallet JSON:",e);const t=r.Amount.fromJSON(e.balance),n=r.Amount.fromJSON(e.minBalance),a=r.Amount.fromJSON(e.approvalLimit);return t&&n&&a?new $r({id:e.id,accountNo:e.accountNo,accountName:e.accountName,shadowAccountNo:e.shadowAccountNo,externalId:e.externalId,reference:e.reference,type:e.type,vendorId:e.vendorId,balance:t.numericValue,minBalance:n.numericValue,approvalLimit:a.numericValue,currency:e.currency,countryCode:e.countryCode,createdAt:e.createdAt,updatedAt:e.updatedAt}):void console.error("Failed to reconstruct balance Amount from JSON:",e)}catch(e){return void console.error("Error creating Wallet from JSON:",e)}}}exports.APIError=Dt,exports.AuthDTOSchemas=tr,exports.AuthRepository=class extends Yt{constructor(e){super("auth",rr,e)}async login(e){const t={identity:e.email,password:e.password},r=await this.client.login({body:t}),n=this.handleResponse(r,201),a=nr.from(n);if(!a)throw new Error("Invalid user data received from server");return{user:a,token:n.token}}async updatePassword(e){const t=await this.client.updatePassword({body:e});if(201!==t.status){if(400===t.status)throw new Error("Validation error");if(401===t.status)throw new Error("Unauthorized");throw new Error("Failed to update password")}return!0}},exports.BaseRepository=Yt,exports.COLLECTION_STATUS_INFO=hr,exports.Collection=pr,exports.CollectionDTOSchemas=dr,exports.CollectionQuery=yr,exports.CollectionRepository=class extends Yt{constructor(e){super("collection",lr,e)}async getCollections(e){try{const t=yr.from(e),r=t.build(),n=await this.client.getCollections({query:r}),a=this.handleResponse(n,200),s=t.toFilters(),i={page:s.page,limit:s.limit,total:a.total,totalPages:a.total>0?Math.ceil(a.total/s.limit):0,hasNext:s.page*s.limit<a.total,hasPrev:s.page>1},o=pr.createMany(a.results);if(!o)throw new Error("Invalid collection data received from server");return{collections:o,pagination:i}}catch(e){throw new Error(`Failed to fetch collections: ${e instanceof Error?e.message:"Unknown error"}`)}}async getCollectionsFromRequest(e){const t=yr.fromRequest(e);return this.getCollections(t)}async getCollection(e){const t=await this.client.getCollection({params:{id:e}}),r=this.handleResponse(t,200),n=pr.from(r);if(!n)throw new Error("Invalid collection data received from server");return n}async getCollectionStats(){const e=await this.client.getSummary(),t=this.handleResponse(e,200),r=Ht.from(t);if(!r)throw new Error("Invalid summary data received from server");return r}},exports.CommonSchemas=Jt,exports.MobileChannels=er,exports.PAYOUT_STATUS_INFO=Cr,exports.Payout=Rr,exports.PayoutDTOSchemas=br,exports.PayoutQuery=Lr,exports.PayoutRepository=class extends Yt{constructor(e){super("payout",Er,e)}async getPayouts(e){try{const t=Lr.from(e),r=t.build(),n=await this.client.getPayouts({query:r}),a=this.handleResponse(n,200),s=t.toFilters(),i={page:s.page,limit:s.limit,total:a.total,totalPages:a.total>0?Math.ceil(a.total/s.limit):0,hasNext:s.page*s.limit<a.total,hasPrev:s.page>1},o=Rr.createMany(a.results);if(!o)throw new Error("Invalid payout data received from server");return{payouts:o,pagination:i}}catch(e){throw new Error(`Failed to fetch payouts: ${e instanceof Error?e.message:"Unknown error"}`)}}async getPayoutsFromRequest(e){const t=Lr.fromRequest(e);return this.getPayouts(t)}async getPayout(e){const t=await this.client.getPayout({params:{id:e}}),r=this.handleResponse(t,200),n=Rr.from(r);if(!n)throw new Error("Invalid payout data received from server");return n}async getPayoutStats(){const e=await this.client.getPayoutSummary(),t=this.handleResponse(e,200),r=Ht.from(t);if(!r)throw new Error("Invalid summary data received from server");return r}},exports.QUERY_BUILDER_TYPE=Qt,exports.QueryBuilder=Xt,exports.StatementEntry=qt,exports.TransactionDTOSchemas=kr,exports.TransactionRepository=class extends Yt{constructor(e){super("transaction",Fr,e)}async localTransfer(e){const t=await this.client.localTransfer({body:e});return this.handleResponse(t,201)}},exports.TransactionSummary=Ht,exports.User=nr,exports.Wallet=$r,exports.WalletDTOSchemas=Zr,exports.WalletInfo=Wt,exports.WalletRepository=class extends Yt{constructor(e){super("wallet",Br,e)}async listWallets(){const e=await this.client.listWallets(),t=this.handleResponse(e,200),r=$r.createMany(t);if(!r)throw new Error("Invalid wallet data received from server");return r}async getWalletInfo(e){const t=await this.client.getWalletInfo({params:{accountNo:e}}),r=this.handleResponse(t,200);return $r.from(r)}async getWalletBalance(e){const t=await this.client.getWalletBalance({params:{accountNo:e}}),r=this.handleResponse(t,200);return Wt.from(r)}async getWalletStatement(e){const t=await this.client.getWalletStatement({params:{accountNo:e.accountNo},query:{startDate:this.formatStatementDate(e.startDate),endDate:this.formatStatementDate(e.endDate)}}),r=this.handleResponse(t,200),n=qt.createMany(r);if(!n)throw new Error("Invalid statement entry data received from server");return n}formatStatementDate(e){if(e instanceof Date){if(Number.isNaN(e.getTime()))throw new Error("Invalid statement date provided.");return e.toISOString().slice(0,10)}if(/^\d{4}-\d{2}-\d{2}$/.test(e))return e;const t=new Date(e);if(Number.isNaN(t.getTime()))throw new Error(`Invalid statement date: ${e}`);return t.toISOString().slice(0,10)}},exports.authContract=rr,exports.collectionContract=lr,exports.collectionToStringArray=cr,exports.payoutContract=Er,exports.payoutToStringArray=Tr,exports.statementEntrySchema=Vt,exports.transactionContract=Fr,exports.walletContract=Br;
1
+ "use strict";var e=require("uuid"),t=require("zod"),r=require("@temboplus/frontend-core");function n(e){return e&&e.__esModule?e:{default:e}}var a,s,i=n(t);!function(e){e.assertEqual=e=>e,e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},e.getValidEnumValues=t=>{const r=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),n={};for(const e of r)n[e]=t[e];return e.objectValues(n)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(const r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(a||(a={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(s||(s={}));const o=a.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),c=e=>{switch(typeof e){case"undefined":return o.undefined;case"string":return o.string;case"number":return isNaN(e)?o.nan:o.number;case"boolean":return o.boolean;case"function":return o.function;case"bigint":return o.bigint;case"symbol":return o.symbol;case"object":return Array.isArray(e)?o.array:null===e?o.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?o.promise:"undefined"!=typeof Map&&e instanceof Map?o.map:"undefined"!=typeof Set&&e instanceof Set?o.set:"undefined"!=typeof Date&&e instanceof Date?o.date:o.object;default:return o.unknown}},u=a.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"]);class d extends Error{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}get errors(){return this.issues}format(e){const t=e||function(e){return e.message},r={_errors:[]},n=e=>{for(const a of e.issues)if("invalid_union"===a.code)a.unionErrors.map(n);else if("invalid_return_type"===a.code)n(a.returnTypeError);else if("invalid_arguments"===a.code)n(a.argumentsError);else if(0===a.path.length)r._errors.push(t(a));else{let e=r,n=0;for(;n<a.path.length;){const r=a.path[n];n===a.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(a))):e[r]=e[r]||{_errors:[]},e=e[r],n++}}};return n(this),r}toString(){return this.message}get message(){return JSON.stringify(this.issues,a.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},r=[];for(const n of this.issues)n.path.length>0?(t[n.path[0]]=t[n.path[0]]||[],t[n.path[0]].push(e(n))):r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}d.create=e=>new d(e);const l=(e,t)=>{let r;switch(e.code){case u.invalid_type:r=e.received===o.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case u.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,a.jsonStringifyReplacer)}`;break;case u.unrecognized_keys:r=`Unrecognized key(s) in object: ${a.joinValues(e.keys,", ")}`;break;case u.invalid_union:r="Invalid input";break;case u.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${a.joinValues(e.options)}`;break;case u.invalid_enum_value:r=`Invalid enum value. Expected ${a.joinValues(e.options)}, received '${e.received}'`;break;case u.invalid_arguments:r="Invalid function arguments";break;case u.invalid_return_type:r="Invalid function return type";break;case u.invalid_date:r="Invalid date";break;case u.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:a.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case u.too_small:r="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 u.too_big:r="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 u.custom:r="Invalid input";break;case u.invalid_intersection_types:r="Intersection results could not be merged";break;case u.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case u.not_finite:r="Number must be finite";break;default:r=t.defaultError,a.assertNever(e)}return{message:r}};let h=l;function m(){return h}const p=e=>{const{data:t,path:r,errorMaps:n,issueData:a}=e,s=[...r,...a.path||[]],i={...a,path:s};let o="";const c=n.filter(e=>!!e).slice().reverse();for(const e of c)o=e(i,{data:t,defaultError:o}).message;return{...a,path:s,message:a.message||o}};function f(e,t){const r=p({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,m(),l].filter(e=>!!e)});e.common.issues.push(r)}class y{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const n of t){if("aborted"===n.status)return g;"dirty"===n.status&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const e of t)r.push({key:await e.key,value:await e.value});return y.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const n of t){const{key:t,value:a}=n;if("aborted"===t.status)return g;if("aborted"===a.status)return g;"dirty"===t.status&&e.dirty(),"dirty"===a.status&&e.dirty(),"__proto__"===t.value||void 0===a.value&&!n.alwaysSet||(r[t.value]=a.value)}return{status:e.value,value:r}}}const g=Object.freeze({status:"aborted"}),v=e=>({status:"dirty",value:e}),_=e=>({status:"valid",value:e}),A=e=>"aborted"===e.status,N=e=>"dirty"===e.status,I=e=>"valid"===e.status,T=e=>"undefined"!=typeof Promise&&e instanceof Promise;var w;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:null==e?void 0:e.message}(w||(w={}));class b{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const E=(e,t)=>{if(I(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 d(e.common.issues);return this._error=t,this._error}}};function S(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:a}=e;if(t&&(r||n))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:a};return{errorMap:(e,t)=>"invalid_type"!==e.code?{message:t.defaultError}:void 0===t.data?{message:null!=n?n:t.defaultError}:{message:null!=r?r:t.defaultError},description:a}}class C{constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(e){return c(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:c(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new y,ctx:{common:e.parent.common,data:e.data,parsedType:c(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(T(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 r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){var r;const n={common:{issues:[],async:null!==(r=null==t?void 0:t.async)&&void 0!==r&&r,contextualErrorMap:null==t?void 0:t.errorMap},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:c(e)},a=this._parseSync({data:e,path:n.path,parent:n});return E(n,a)}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={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:c(e)},n=this._parse({data:e,path:r.path,parent:r}),a=await(T(n)?n:Promise.resolve(n));return E(r,a)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,n)=>{const a=e(t),s=()=>n.addIssue({code:u.custom,...r(t)});return"undefined"!=typeof Promise&&a instanceof Promise?a.then(e=>!!e||(s(),!1)):!!a||(s(),!1)})}refinement(e,t){return this._refinement((r,n)=>!!e(r)||(n.addIssue("function"==typeof t?t(r,n):t),!1))}_refinement(e){return new ge({schema:this,typeName:Oe.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return ve.create(this,this._def)}nullable(){return _e.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Q.create(this,this._def)}promise(){return ye.create(this,this._def)}or(e){return te.create([this,e],this._def)}and(e){return se.create(this,e,this._def)}transform(e){return new ge({...S(this._def),schema:this,typeName:Oe.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Ae({...S(this._def),innerType:this,defaultValue:t,typeName:Oe.ZodDefault})}brand(){return new we({typeName:Oe.ZodBranded,type:this,...S(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Ne({...S(this._def),innerType:this,catchValue:t,typeName:Oe.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return be.create(this,e)}readonly(){return Ee.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const O=/^c[^\s-]{8,}$/i,x=/^[a-z][a-z0-9]*$/,R=/[0-9A-HJKMNP-TV-Z]{26}/,D=/^[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,P=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,L=/^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u,k=/^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/,F=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,z=e=>e.precision?e.offset?new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`):new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}Z$`):0===e.precision?e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$"):e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$");function U(e,t){return!("v4"!==t&&t||!k.test(e))||!("v6"!==t&&t||!F.test(e))}class M extends C{constructor(){super(...arguments),this._regex=(e,t,r)=>this.refinement(t=>e.test(t),{validation:t,code:u.invalid_string,...w.errToObj(r)}),this.nonempty=e=>this.min(1,w.errToObj(e)),this.trim=()=>new M({...this._def,checks:[...this._def.checks,{kind:"trim"}]}),this.toLowerCase=()=>new M({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]}),this.toUpperCase=()=>new M({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==o.string){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:o.string,received:t.parsedType}),g}const t=new y;let r;for(const n of this._def.checks)if("min"===n.kind)e.data.length<n.value&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),t.dirty());else if("max"===n.kind)e.data.length>n.value&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),t.dirty());else if("length"===n.kind){const a=e.data.length>n.value,s=e.data.length<n.value;(a||s)&&(r=this._getOrReturnCtx(e,r),a?f(r,{code:u.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):s&&f(r,{code:u.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),t.dirty())}else if("email"===n.kind)P.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"email",code:u.invalid_string,message:n.message}),t.dirty());else if("emoji"===n.kind)L.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"emoji",code:u.invalid_string,message:n.message}),t.dirty());else if("uuid"===n.kind)D.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"uuid",code:u.invalid_string,message:n.message}),t.dirty());else if("cuid"===n.kind)O.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"cuid",code:u.invalid_string,message:n.message}),t.dirty());else if("cuid2"===n.kind)x.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"cuid2",code:u.invalid_string,message:n.message}),t.dirty());else if("ulid"===n.kind)R.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"ulid",code:u.invalid_string,message:n.message}),t.dirty());else if("url"===n.kind)try{new URL(e.data)}catch(a){r=this._getOrReturnCtx(e,r),f(r,{validation:"url",code:u.invalid_string,message:n.message}),t.dirty()}else if("regex"===n.kind){n.regex.lastIndex=0;n.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"regex",code:u.invalid_string,message:n.message}),t.dirty())}else if("trim"===n.kind)e.data=e.data.trim();else if("includes"===n.kind)e.data.includes(n.value,n.position)||(r=this._getOrReturnCtx(e,r),f(r,{code:u.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),t.dirty());else if("toLowerCase"===n.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===n.kind)e.data=e.data.toUpperCase();else if("startsWith"===n.kind)e.data.startsWith(n.value)||(r=this._getOrReturnCtx(e,r),f(r,{code:u.invalid_string,validation:{startsWith:n.value},message:n.message}),t.dirty());else if("endsWith"===n.kind)e.data.endsWith(n.value)||(r=this._getOrReturnCtx(e,r),f(r,{code:u.invalid_string,validation:{endsWith:n.value},message:n.message}),t.dirty());else if("datetime"===n.kind){z(n).test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{code:u.invalid_string,validation:"datetime",message:n.message}),t.dirty())}else"ip"===n.kind?U(e.data,n.version)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"ip",code:u.invalid_string,message:n.message}),t.dirty()):a.assertNever(n);return{status:t.value,value:e.data}}_addCheck(e){return new M({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...w.errToObj(e)})}url(e){return this._addCheck({kind:"url",...w.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...w.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...w.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...w.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...w.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...w.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...w.errToObj(e)})}datetime(e){var t;return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!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,...w.errToObj(null==e?void 0:e.message)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...w.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:null==t?void 0:t.position,...w.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...w.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...w.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...w.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...w.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...w.errToObj(t)})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===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 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 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 j(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,a=r>n?r:n;return parseInt(e.toFixed(a).replace(".",""))%parseInt(t.toFixed(a).replace(".",""))/Math.pow(10,a)}M.create=e=>{var t;return new M({checks:[],typeName:Oe.ZodString,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...S(e)})};class Z extends C{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)!==o.number){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:o.number,received:t.parsedType}),g}let t;const r=new y;for(const n of this._def.checks)if("int"===n.kind)a.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),f(t,{code:u.invalid_type,expected:"integer",received:"float",message:n.message}),r.dirty());else if("min"===n.kind){(n.inclusive?e.data<n.value:e.data<=n.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:u.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty())}else if("max"===n.kind){(n.inclusive?e.data>n.value:e.data>=n.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:u.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty())}else"multipleOf"===n.kind?0!==j(e.data,n.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:u.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):"finite"===n.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),f(t,{code:u.not_finite,message:n.message}),r.dirty()):a.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,w.toString(t))}gt(e,t){return this.setLimit("min",e,!1,w.toString(t))}lte(e,t){return this.setLimit("max",e,!0,w.toString(t))}lt(e,t){return this.setLimit("max",e,!1,w.toString(t))}setLimit(e,t,r,n){return new Z({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:w.toString(n)}]})}_addCheck(e){return new Z({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:w.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:w.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:w.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:w.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:w.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:w.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:w.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:w.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:w.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&&a.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}Z.create=e=>new Z({checks:[],typeName:Oe.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...S(e)});class B extends C{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){this._def.coerce&&(e.data=BigInt(e.data));if(this._getType(e)!==o.bigint){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:o.bigint,received:t.parsedType}),g}let t;const r=new y;for(const n of this._def.checks)if("min"===n.kind){(n.inclusive?e.data<n.value:e.data<=n.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:u.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty())}else if("max"===n.kind){(n.inclusive?e.data>n.value:e.data>=n.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:u.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty())}else"multipleOf"===n.kind?e.data%n.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),f(t,{code:u.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):a.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,w.toString(t))}gt(e,t){return this.setLimit("min",e,!1,w.toString(t))}lte(e,t){return this.setLimit("max",e,!0,w.toString(t))}lt(e,t){return this.setLimit("max",e,!1,w.toString(t))}setLimit(e,t,r,n){return new B({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:w.toString(n)}]})}_addCheck(e){return new B({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:w.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:w.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:w.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:w.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:w.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}}B.create=e=>{var t;return new B({checks:[],typeName:Oe.ZodBigInt,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...S(e)})};class $ extends C{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==o.boolean){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:o.boolean,received:t.parsedType}),g}return _(e.data)}}$.create=e=>new $({typeName:Oe.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...S(e)});class V extends C{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==o.date){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:o.date,received:t.parsedType}),g}if(isNaN(e.data.getTime())){return f(this._getOrReturnCtx(e),{code:u.invalid_date}),g}const t=new y;let r;for(const n of this._def.checks)"min"===n.kind?e.data.getTime()<n.value&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),t.dirty()):"max"===n.kind?e.data.getTime()>n.value&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),t.dirty()):a.assertNever(n);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new V({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:w.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:w.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}}V.create=e=>new V({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:Oe.ZodDate,...S(e)});class J extends C{_parse(e){if(this._getType(e)!==o.symbol){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:o.symbol,received:t.parsedType}),g}return _(e.data)}}J.create=e=>new J({typeName:Oe.ZodSymbol,...S(e)});class Y extends C{_parse(e){if(this._getType(e)!==o.undefined){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:o.undefined,received:t.parsedType}),g}return _(e.data)}}Y.create=e=>new Y({typeName:Oe.ZodUndefined,...S(e)});class q extends C{_parse(e){if(this._getType(e)!==o.null){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:o.null,received:t.parsedType}),g}return _(e.data)}}q.create=e=>new q({typeName:Oe.ZodNull,...S(e)});class H extends C{constructor(){super(...arguments),this._any=!0}_parse(e){return _(e.data)}}H.create=e=>new H({typeName:Oe.ZodAny,...S(e)});class W extends C{constructor(){super(...arguments),this._unknown=!0}_parse(e){return _(e.data)}}W.create=e=>new W({typeName:Oe.ZodUnknown,...S(e)});class G extends C{_parse(e){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:o.never,received:t.parsedType}),g}}G.create=e=>new G({typeName:Oe.ZodNever,...S(e)});class K extends C{_parse(e){if(this._getType(e)!==o.undefined){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:o.void,received:t.parsedType}),g}return _(e.data)}}K.create=e=>new K({typeName:Oe.ZodVoid,...S(e)});class Q extends C{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==o.array)return f(t,{code:u.invalid_type,expected:o.array,received:t.parsedType}),g;if(null!==n.exactLength){const e=t.data.length>n.exactLength.value,a=t.data.length<n.exactLength.value;(e||a)&&(f(t,{code:e?u.too_big:u.too_small,minimum:a?n.exactLength.value:void 0,maximum:e?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty())}if(null!==n.minLength&&t.data.length<n.minLength.value&&(f(t,{code:u.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()),null!==n.maxLength&&t.data.length>n.maxLength.value&&(f(t,{code:u.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>n.type._parseAsync(new b(t,e,t.path,r)))).then(e=>y.mergeArray(r,e));const a=[...t.data].map((e,r)=>n.type._parseSync(new b(t,e,t.path,r)));return y.mergeArray(r,a)}get element(){return this._def.type}min(e,t){return new Q({...this._def,minLength:{value:e,message:w.toString(t)}})}max(e,t){return new Q({...this._def,maxLength:{value:e,message:w.toString(t)}})}length(e,t){return new Q({...this._def,exactLength:{value:e,message:w.toString(t)}})}nonempty(e){return this.min(1,e)}}function X(e){if(e instanceof ee){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=ve.create(X(n))}return new ee({...e._def,shape:()=>t})}return e instanceof Q?new Q({...e._def,type:X(e.element)}):e instanceof ve?ve.create(X(e.unwrap())):e instanceof _e?_e.create(X(e.unwrap())):e instanceof ie?ie.create(e.items.map(e=>X(e))):e}Q.create=(e,t)=>new Q({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Oe.ZodArray,...S(t)});class ee extends C{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=a.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==o.object){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:o.object,received:t.parsedType}),g}const{status:t,ctx:r}=this._processInputParams(e),{shape:n,keys:a}=this._getCached(),s=[];if(!(this._def.catchall instanceof G&&"strip"===this._def.unknownKeys))for(const e in r.data)a.includes(e)||s.push(e);const i=[];for(const e of a){const t=n[e],a=r.data[e];i.push({key:{status:"valid",value:e},value:t._parse(new b(r,a,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof G){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of s)i.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)s.length>0&&(f(r,{code:u.unrecognized_keys,keys:s}),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 s){const n=r.data[t];i.push({key:{status:"valid",value:t},value:e._parse(new b(r,n,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of i){const r=await t.key;e.push({key:r,value:await t.value,alwaysSet:t.alwaysSet})}return e}).then(e=>y.mergeObjectSync(t,e)):y.mergeObjectSync(t,i)}get shape(){return this._def.shape()}strict(e){return w.errToObj,new ee({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{var n,a,s,i;const o=null!==(s=null===(a=(n=this._def).errorMap)||void 0===a?void 0:a.call(n,t,r).message)&&void 0!==s?s:r.defaultError;return"unrecognized_keys"===t.code?{message:null!==(i=w.errToObj(e).message)&&void 0!==i?i:o}:{message:o}}}:{}})}strip(){return new ee({...this._def,unknownKeys:"strip"})}passthrough(){return new ee({...this._def,unknownKeys:"passthrough"})}extend(e){return new ee({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ee({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Oe.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ee({...this._def,catchall:e})}pick(e){const t={};return a.objectKeys(e).forEach(r=>{e[r]&&this.shape[r]&&(t[r]=this.shape[r])}),new ee({...this._def,shape:()=>t})}omit(e){const t={};return a.objectKeys(this.shape).forEach(r=>{e[r]||(t[r]=this.shape[r])}),new ee({...this._def,shape:()=>t})}deepPartial(){return X(this)}partial(e){const t={};return a.objectKeys(this.shape).forEach(r=>{const n=this.shape[r];e&&!e[r]?t[r]=n:t[r]=n.optional()}),new ee({...this._def,shape:()=>t})}required(e){const t={};return a.objectKeys(this.shape).forEach(r=>{if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof ve;)e=e._def.innerType;t[r]=e}}),new ee({...this._def,shape:()=>t})}keyof(){return me(a.objectKeys(this.shape))}}ee.create=(e,t)=>new ee({shape:()=>e,unknownKeys:"strip",catchall:G.create(),typeName:Oe.ZodObject,...S(t)}),ee.strictCreate=(e,t)=>new ee({shape:()=>e,unknownKeys:"strict",catchall:G.create(),typeName:Oe.ZodObject,...S(t)}),ee.lazycreate=(e,t)=>new ee({shape:e,unknownKeys:"strip",catchall:G.create(),typeName:Oe.ZodObject,...S(t)});class te extends C{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;const r=e.map(e=>new d(e.ctx.common.issues));return f(t,{code:u.invalid_union,unionErrors:r}),g});{let e;const n=[];for(const a of r){const r={...t,common:{...t.common,issues:[]},parent:null},s=a._parseSync({data:t.data,path:t.path,parent:r});if("valid"===s.status)return s;"dirty"!==s.status||e||(e={result:s,ctx:r}),r.common.issues.length&&n.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const a=n.map(e=>new d(e));return f(t,{code:u.invalid_union,unionErrors:a}),g}}get options(){return this._def.options}}te.create=(e,t)=>new te({options:e,typeName:Oe.ZodUnion,...S(t)});const re=e=>e instanceof le?re(e.schema):e instanceof ge?re(e.innerType()):e instanceof he?[e.value]:e instanceof pe?e.options:e instanceof fe?Object.keys(e.enum):e instanceof Ae?re(e._def.innerType):e instanceof Y?[void 0]:e instanceof q?[null]:null;class ne extends C{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==o.object)return f(t,{code:u.invalid_type,expected:o.object,received:t.parsedType}),g;const r=this.discriminator,n=t.data[r],a=this.optionsMap.get(n);return a?t.common.async?a._parseAsync({data:t.data,path:t.path,parent:t}):a._parseSync({data:t.data,path:t.path,parent:t}):(f(t,{code:u.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),g)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){const n=new Map;for(const r of t){const t=re(r.shape[e]);if(!t)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const a of t){if(n.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);n.set(a,r)}}return new ne({typeName:Oe.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...S(r)})}}function ae(e,t){const r=c(e),n=c(t);if(e===t)return{valid:!0,data:e};if(r===o.object&&n===o.object){const r=a.objectKeys(t),n=a.objectKeys(e).filter(e=>-1!==r.indexOf(e)),s={...e,...t};for(const r of n){const n=ae(e[r],t[r]);if(!n.valid)return{valid:!1};s[r]=n.data}return{valid:!0,data:s}}if(r===o.array&&n===o.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let n=0;n<e.length;n++){const a=ae(e[n],t[n]);if(!a.valid)return{valid:!1};r.push(a.data)}return{valid:!0,data:r}}return r===o.date&&n===o.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}class se extends C{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=(e,n)=>{if(A(e)||A(n))return g;const a=ae(e.value,n.value);return a.valid?((N(e)||N(n))&&t.dirty(),{status:t.value,value:a.data}):(f(r,{code:u.invalid_intersection_types}),g)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>n(e,t)):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}se.create=(e,t,r)=>new se({left:e,right:t,typeName:Oe.ZodIntersection,...S(r)});class ie extends C{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==o.array)return f(r,{code:u.invalid_type,expected:o.array,received:r.parsedType}),g;if(r.data.length<this._def.items.length)return f(r,{code:u.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),g;!this._def.rest&&r.data.length>this._def.items.length&&(f(r,{code:u.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const n=[...r.data].map((e,t)=>{const n=this._def.items[t]||this._def.rest;return n?n._parse(new b(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(n).then(e=>y.mergeArray(t,e)):y.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new ie({...this._def,rest:e})}}ie.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ie({items:e,typeName:Oe.ZodTuple,rest:null,...S(t)})};class oe extends C{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==o.object)return f(r,{code:u.invalid_type,expected:o.object,received:r.parsedType}),g;const n=[],a=this._def.keyType,s=this._def.valueType;for(const e in r.data)n.push({key:a._parse(new b(r,e,r.path,e)),value:s._parse(new b(r,r.data[e],r.path,e))});return r.common.async?y.mergeObjectAsync(t,n):y.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){return new oe(t instanceof C?{keyType:e,valueType:t,typeName:Oe.ZodRecord,...S(r)}:{keyType:M.create(),valueType:e,typeName:Oe.ZodRecord,...S(t)})}}class ce extends C{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==o.map)return f(r,{code:u.invalid_type,expected:o.map,received:r.parsedType}),g;const n=this._def.keyType,a=this._def.valueType,s=[...r.data.entries()].map(([e,t],s)=>({key:n._parse(new b(r,e,r.path,[s,"key"])),value:a._parse(new b(r,t,r.path,[s,"value"]))}));if(r.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const r of s){const n=await r.key,a=await r.value;if("aborted"===n.status||"aborted"===a.status)return g;"dirty"!==n.status&&"dirty"!==a.status||t.dirty(),e.set(n.value,a.value)}return{status:t.value,value:e}})}{const e=new Map;for(const r of s){const n=r.key,a=r.value;if("aborted"===n.status||"aborted"===a.status)return g;"dirty"!==n.status&&"dirty"!==a.status||t.dirty(),e.set(n.value,a.value)}return{status:t.value,value:e}}}}ce.create=(e,t,r)=>new ce({valueType:t,keyType:e,typeName:Oe.ZodMap,...S(r)});class ue extends C{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==o.set)return f(r,{code:u.invalid_type,expected:o.set,received:r.parsedType}),g;const n=this._def;null!==n.minSize&&r.data.size<n.minSize.value&&(f(r,{code:u.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),null!==n.maxSize&&r.data.size>n.maxSize.value&&(f(r,{code:u.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const a=this._def.valueType;function s(e){const r=new Set;for(const n of e){if("aborted"===n.status)return g;"dirty"===n.status&&t.dirty(),r.add(n.value)}return{status:t.value,value:r}}const i=[...r.data.values()].map((e,t)=>a._parse(new b(r,e,r.path,t)));return r.common.async?Promise.all(i).then(e=>s(e)):s(i)}min(e,t){return new ue({...this._def,minSize:{value:e,message:w.toString(t)}})}max(e,t){return new ue({...this._def,maxSize:{value:e,message:w.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ue.create=(e,t)=>new ue({valueType:e,minSize:null,maxSize:null,typeName:Oe.ZodSet,...S(t)});class de extends C{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==o.function)return f(t,{code:u.invalid_type,expected:o.function,received:t.parsedType}),g;function r(e,r){return p({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,m(),l].filter(e=>!!e),issueData:{code:u.invalid_arguments,argumentsError:r}})}function n(e,r){return p({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,m(),l].filter(e=>!!e),issueData:{code:u.invalid_return_type,returnTypeError:r}})}const a={errorMap:t.common.contextualErrorMap},s=t.data;if(this._def.returns instanceof ye){const e=this;return _(async function(...t){const i=new d([]),o=await e._def.args.parseAsync(t,a).catch(e=>{throw i.addIssue(r(t,e)),i}),c=await Reflect.apply(s,this,o);return await e._def.returns._def.type.parseAsync(c,a).catch(e=>{throw i.addIssue(n(c,e)),i})})}{const e=this;return _(function(...t){const i=e._def.args.safeParse(t,a);if(!i.success)throw new d([r(t,i.error)]);const o=Reflect.apply(s,this,i.data),c=e._def.returns.safeParse(o,a);if(!c.success)throw new d([n(o,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new de({...this._def,args:ie.create(e).rest(W.create())})}returns(e){return new de({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new de({args:e||ie.create([]).rest(W.create()),returns:t||W.create(),typeName:Oe.ZodFunction,...S(r)})}}class le extends C{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})}}le.create=(e,t)=>new le({getter:e,typeName:Oe.ZodLazy,...S(t)});class he extends C{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return f(t,{received:t.data,code:u.invalid_literal,expected:this._def.value}),g}return{status:"valid",value:e.data}}get value(){return this._def.value}}function me(e,t){return new pe({values:e,typeName:Oe.ZodEnum,...S(t)})}he.create=(e,t)=>new he({value:e,typeName:Oe.ZodLiteral,...S(t)});class pe extends C{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return f(t,{expected:a.joinValues(r),received:t.parsedType,code:u.invalid_type}),g}if(-1===this._def.values.indexOf(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return f(t,{received:t.data,code:u.invalid_enum_value,options:r}),g}return _(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e){return pe.create(e)}exclude(e){return pe.create(this.options.filter(t=>!e.includes(t)))}}pe.create=me;class fe extends C{_parse(e){const t=a.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==o.string&&r.parsedType!==o.number){const e=a.objectValues(t);return f(r,{expected:a.joinValues(e),received:r.parsedType,code:u.invalid_type}),g}if(-1===t.indexOf(e.data)){const e=a.objectValues(t);return f(r,{received:r.data,code:u.invalid_enum_value,options:e}),g}return _(e.data)}get enum(){return this._def.values}}fe.create=(e,t)=>new fe({values:e,typeName:Oe.ZodNativeEnum,...S(t)});class ye extends C{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==o.promise&&!1===t.common.async)return f(t,{code:u.invalid_type,expected:o.promise,received:t.parsedType}),g;const r=t.parsedType===o.promise?t.data:Promise.resolve(t.data);return _(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}ye.create=(e,t)=>new ye({type:e,typeName:Oe.ZodPromise,...S(t)});class ge extends C{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Oe.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,s={addIssue:e=>{f(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),"preprocess"===n.type){const e=n.transform(r.data,s);return r.common.issues.length?{status:"dirty",value:r.data}:r.common.async?Promise.resolve(e).then(e=>this._def.schema._parseAsync({data:e,path:r.path,parent:r})):this._def.schema._parseSync({data:e,path:r.path,parent:r})}if("refinement"===n.type){const e=e=>{const t=n.refinement(e,s);if(r.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===r.common.async){const n=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===n.status?g:("dirty"===n.status&&t.dirty(),e(n.value),{status:t.value,value:n.value})}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?g:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))))}if("transform"===n.type){if(!1===r.common.async){const e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!I(e))return e;const a=n.transform(e.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>I(e)?Promise.resolve(n.transform(e.value,s)).then(e=>({status:t.value,value:e})):e)}a.assertNever(n)}}ge.create=(e,t,r)=>new ge({schema:e,typeName:Oe.ZodEffects,effect:t,...S(r)}),ge.createWithPreprocess=(e,t,r)=>new ge({schema:t,effect:{type:"preprocess",transform:e},typeName:Oe.ZodEffects,...S(r)});class ve extends C{_parse(e){return this._getType(e)===o.undefined?_(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ve.create=(e,t)=>new ve({innerType:e,typeName:Oe.ZodOptional,...S(t)});class _e extends C{_parse(e){return this._getType(e)===o.null?_(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}_e.create=(e,t)=>new _e({innerType:e,typeName:Oe.ZodNullable,...S(t)});class Ae extends C{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===o.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Ae.create=(e,t)=>new Ae({innerType:e,typeName:Oe.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...S(t)});class Ne extends C{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return T(n)?n.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new d(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new d(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Ne.create=(e,t)=>new Ne({innerType:e,typeName:Oe.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...S(t)});class Ie extends C{_parse(e){if(this._getType(e)!==o.nan){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:o.nan,received:t.parsedType}),g}return{status:"valid",value:e.data}}}Ie.create=e=>new Ie({typeName:Oe.ZodNaN,...S(e)});const Te=Symbol("zod_brand");class we extends C{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class be extends C{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?g:"dirty"===e.status?(t.dirty(),v(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})()}{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?g:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new be({in:e,out:t,typeName:Oe.ZodPipeline})}}class Ee extends C{_parse(e){const t=this._def.innerType._parse(e);return I(t)&&(t.value=Object.freeze(t.value)),t}}Ee.create=(e,t)=>new Ee({innerType:e,typeName:Oe.ZodReadonly,...S(t)});const Se=(e,t={},r)=>e?H.create().superRefine((n,a)=>{var s,i;if(!e(n)){const e="function"==typeof t?t(n):"string"==typeof t?{message:t}:t,o=null===(i=null!==(s=e.fatal)&&void 0!==s?s:r)||void 0===i||i,c="string"==typeof e?{message:e}:e;a.addIssue({code:"custom",...c,fatal:o})}}):H.create(),Ce={object:ee.lazycreate};var Oe;!function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(Oe||(Oe={}));const xe=M.create,Re=Z.create,De=Ie.create,Pe=B.create,Le=$.create,ke=V.create,Fe=J.create,ze=Y.create,Ue=q.create,Me=H.create,je=W.create,Ze=G.create,Be=K.create,$e=Q.create,Ve=ee.create,Je=ee.strictCreate,Ye=te.create,qe=ne.create,He=se.create,We=ie.create,Ge=oe.create,Ke=ce.create,Qe=ue.create,Xe=de.create,et=le.create,tt=he.create,rt=pe.create,nt=fe.create,at=ye.create,st=ge.create,it=ve.create,ot=_e.create,ct=ge.createWithPreprocess,ut=be.create,dt={string:e=>M.create({...e,coerce:!0}),number:e=>Z.create({...e,coerce:!0}),boolean:e=>$.create({...e,coerce:!0}),bigint:e=>B.create({...e,coerce:!0}),date:e=>V.create({...e,coerce:!0})},lt=g;var ht=Object.freeze({__proto__:null,defaultErrorMap:l,setErrorMap:function(e){h=e},getErrorMap:m,makeIssue:p,EMPTY_PATH:[],addIssueToContext:f,ParseStatus:y,INVALID:g,DIRTY:v,OK:_,isAborted:A,isDirty:N,isValid:I,isAsync:T,get util(){return a},get objectUtil(){return s},ZodParsedType:o,getParsedType:c,ZodType:C,ZodString:M,ZodNumber:Z,ZodBigInt:B,ZodBoolean:$,ZodDate:V,ZodSymbol:J,ZodUndefined:Y,ZodNull:q,ZodAny:H,ZodUnknown:W,ZodNever:G,ZodVoid:K,ZodArray:Q,ZodObject:ee,ZodUnion:te,ZodDiscriminatedUnion:ne,ZodIntersection:se,ZodTuple:ie,ZodRecord:oe,ZodMap:ce,ZodSet:ue,ZodFunction:de,ZodLazy:le,ZodLiteral:he,ZodEnum:pe,ZodNativeEnum:fe,ZodPromise:ye,ZodEffects:ge,ZodTransformer:ge,ZodOptional:ve,ZodNullable:_e,ZodDefault:Ae,ZodCatch:Ne,ZodNaN:Ie,BRAND:Te,ZodBranded:we,ZodPipeline:be,ZodReadonly:Ee,custom:Se,Schema:C,ZodSchema:C,late:Ce,get ZodFirstPartyTypeKind(){return Oe},coerce:dt,any:Me,array:$e,bigint:Pe,boolean:Le,date:ke,discriminatedUnion:qe,effect:st,enum:rt,function:Xe,instanceof:(e,t={message:`Input not instance of ${e.name}`})=>Se(t=>t instanceof e,t),intersection:He,lazy:et,literal:tt,map:Ke,nan:De,nativeEnum:nt,never:Ze,null:Ue,nullable:ot,number:Re,object:Ve,oboolean:()=>Le().optional(),onumber:()=>Re().optional(),optional:it,ostring:()=>xe().optional(),pipeline:ut,preprocess:ct,promise:at,record:Ge,set:Qe,strictObject:Je,string:xe,symbol:Fe,transformer:st,tuple:We,undefined:ze,union:Ye,unknown:je,void:Be,NEVER:lt,ZodIssueCode:u,quotelessJson:e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ZodError:d});const mt=e=>"function"==typeof(null==e?void 0:e.passthrough),pt=ht.object({name:ht.literal("ZodError"),issues:ht.array(ht.object({path:ht.array(ht.union([ht.string(),ht.number()])),message:ht.string().optional(),code:ht.nativeEnum(ht.ZodIssueCode)}).catchall(ht.any()))});class ft extends Error{constructor(e){super(JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t,2)),this.name="ValidationError",this.issues=e}toString(){return this.message}}ht.object({message:ht.literal("Request validation failed"),pathParameterErrors:pt.nullable(),headerErrors:pt.nullable(),queryParameterErrors:pt.nullable(),bodyErrors:pt.nullable()}),ht.object({pathParameterErrors:pt.nullable(),headerErrors:pt.nullable(),queryParameterErrors:pt.nullable(),bodyErrors:pt.nullable()}),ht.object({paramsResult:pt.nullable(),headersResult:pt.nullable(),queryResult:pt.nullable(),bodyResult:pt.nullable()});const yt="zod-ts-rest-polyfill",gt=(e,t)=>{if(!e)return t;if(!t)return e;if(e instanceof ee&&t instanceof ee){return n=t,mt(r=e)?mt(n)?r.merge(n):r:mt(n)?n:Object.assign({},r,n)}var r,n;return{...e,...t}},vt=Symbol("ContractNoBody"),_t=e=>"method"in e&&"path"in e,At=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>{var n,a,s;return _t(r)?[e,{...r,path:(null==t?void 0:t.pathPrefix)?t.pathPrefix+r.path:r.path,headers:gt(null==t?void 0:t.baseHeaders,r.headers),strictStatusCodes:null!==(n=r.strictStatusCodes)&&void 0!==n?n:null==t?void 0:t.strictStatusCodes,validateResponseOnClient:null!==(a=r.validateResponseOnClient)&&void 0!==a?a:null==t?void 0:t.validateResponseOnClient,responses:{...null==t?void 0:t.commonResponses,...r.responses},metadata:(null==t?void 0:t.metadata)?{...null==t?void 0:t.metadata,...null!==(s=r.metadata)&&void 0!==s?s:{}}:r.metadata}]:[e,At(r,t)]})),Nt=Symbol("ContractPlainType"),It=()=>({router:(e,t)=>At(e,t),query:e=>e,mutation:e=>e,responses:e=>e,response:()=>Nt,body:()=>Nt,type:()=>Nt,otherResponse:({contentType:e,body:t})=>({contentType:e,body:t}),noBody:()=>vt}),Tt=e=>e?Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>{let r;return r="string"==typeof t&&!["true","false","null"].includes(t.trim())&&isNaN(Number(t))?t:JSON.stringify(t),`${encodeURIComponent(e)}=${encodeURIComponent(r)}`}).join("&"):"",wt=e=>e?Object.keys(e).flatMap(t=>bt(t,e[t])).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",bt=(e,t)=>Array.isArray(t)?t.flatMap((t,r)=>bt(`${e}[${r}]`,t)):t instanceof Date?[[`${e}`,t.toISOString()]]:null===t?[[`${e}`,""]]:void 0===t?[]:"object"==typeof t?Object.keys(t).flatMap(r=>bt(`${e}[${r}]`,t[r])):[[`${e}`,`${t}`]];class Et extends Error{constructor(e,t){super(`Server returned unexpected response. Expected one of: ${t.join(",")} got: ${e.status}`),this.response=e}}const St=async({route:e,path:t,method:r,headers:n,body:a,validateResponse:s,fetchOptions:i})=>{const o=await fetch(t,{...i,method:r,headers:n,body:a}),c=o.headers.get("content-type");if((null==c?void 0:c.includes("application/"))&&(null==c?void 0:c.includes("json"))){const t=e.responses[o.status],r={status:o.status,body:t===vt?void 0:await o.json(),headers:o.headers},n=(e=>{if((e=>{if(!e)return!1;const t=null==e?void 0:e["~standard"];return!!t&&1===t.version&&"function"==typeof t.validate})(e))return e;if("function"==typeof(null==(t=e)?void 0:t.safeParse)){const t={vendor:yt,version:1,validate:t=>{const r=e.safeParse(t);return r.success?{value:r.data}:{issues:r.error.issues}}};return Object.assign(e,{"~standard":t}),e}var t;return null})(t);if(n&&(null!=s?s:e.validateResponseOnClient)){const e=((e,t,{passThroughExtraKeys:r=!1}={})=>{const n=t["~standard"].validate(e);if(n instanceof Promise)throw new Error("Schema validation must be synchronous");return n.issues?t["~standard"].vendor===yt?{error:new d(n.issues)}:{error:new ft(n.issues)}:r&&"object"==typeof e&&n.value?{value:{...e,...n.value}}:{value:n.value}})(r.body,n);if(e.error)throw e.error;return{...r,body:e.value}}return r}return(null==c?void 0:c.includes("text/"))?{status:o.status,body:await o.text(),headers:o.headers}:{status:o.status,body:await o.blob(),headers:o.headers}},Ct=e=>{const t=new FormData,r=(e,r)=>{r instanceof File?t.append(e,r):t.append(e,JSON.stringify(r))};return Object.entries(e).forEach(([e,t])=>{if(Array.isArray(t))for(const n of t)r(e,n);else r(e,t)}),t},Ot=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e.toLowerCase(),t])),xt=(e,t,r,n,a)=>{const s=(({path:e,params:t})=>{const r=t;return e.replace(/\/?:([^/?]+)\??/g,(e,t)=>r[t]?`${e.startsWith("/")?"/":""}${r[t]}`:"")})({path:n.path,params:r}),i=((e,t=!1)=>{const r=t?Tt(e):wt(e);return(null==r?void 0:r.length)>0?"?"+r:""})(e,a);return t.endsWith("/")&&s.startsWith("/")?`${t}${s.substring(1)}${i}`:`${t}${s}${i}`},Rt=(e,t)=>{const r=Object.keys(e.responses);return async n=>{const a=((e,t,r)=>{const{query:n,params:a,body:s,headers:i,extraHeaders:o,overrideClientOptions:c,fetchOptions:u,cache:d,next:l,...h}=r||{},m={...t,...c},p="object"==typeof a?Object.fromEntries(Object.entries(a).map(([e,t])=>[e,String(t)])):{};return{path:xt(n,m.baseUrl,p,e,!!m.jsonQuery),clientArgs:m,route:e,body:s,query:n,extraInputArgs:h,fetchOptions:{...d&&{cache:d},...l&&{next:l},...u},headers:{...o,...i}}})(e,t,n),s=await(e=>{const{path:t,clientArgs:r,route:n,body:a,query:s,extraInputArgs:i,headers:o,fetchOptions:c}=e,u=r.api||St,d=r.baseHeaders&&Object.fromEntries(Object.entries(r.baseHeaders).map(([t,r])=>"function"==typeof r?[t,r(e)]:[t,r])),l={...d&&Ot(d),...Ot(o)};Object.keys(l).forEach(e=>{void 0===l[e]&&delete l[e]});let h={route:n,path:t,method:n.method,headers:l,body:void 0,rawBody:a,rawQuery:s,contentType:void 0,validateResponse:r.validateResponse,fetchOptions:{...r.credentials&&{credentials:r.credentials},...c},...(null==c?void 0:c.signal)&&{signal:c.signal},...(null==c?void 0:c.cache)&&{cache:c.cache},...c&&"next"in c&&!!(null==c?void 0:c.next)&&{next:c.next}};return"GET"!==n.method&&("contentType"in n&&"multipart/form-data"===n.contentType?h={...h,contentType:"multipart/form-data",body:a instanceof FormData?a:Ct(a)}:"contentType"in n&&"application/x-www-form-urlencoded"===n.contentType?h={...h,contentType:"application/x-www-form-urlencoded",headers:{"content-type":"application/x-www-form-urlencoded",...h.headers},body:"string"==typeof a?a:new URLSearchParams(a)}:null!=a&&(h={...h,contentType:"application/json",headers:{"content-type":"application/json",...h.headers},body:JSON.stringify(a)})),u({...h,...i})})(a);if(!t.throwOnUnknownStatus)return s;if(r.includes(s.status.toString()))return s;throw new Et(s,r)}},Dt=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>_t(r)?[e,Rt(r,t)]:[e,Dt(r,t)]));class Pt extends Error{statusCode;error;details;constructor(e){super(e.message),this.name="ApiError",this.statusCode=e.statusCode,e.error&&(this.error=e.error),e.details&&(this.details=e.details)}static is(e){return Pt.schema.safeParse(e).success}static unknown(e){return new Pt({message:e??"An unknown error occurred",statusCode:502})}static get schema(){return t.z.object({message:t.z.string(),statusCode:t.z.number().int(),error:t.z.string().optional(),details:t.z.object({}).optional()})}}const Lt=i.default.object({statusCode:i.default.number().int(),reason:i.default.string().optional(),error:i.default.string().optional(),details:i.default.record(i.default.string(),i.default.unknown()).optional(),message:i.default.string().optional()}),kt=Lt.extend({statusCode:i.default.literal(400)}),Ft=Lt.extend({statusCode:i.default.literal(401)}),zt=Lt.extend({statusCode:i.default.literal(403)}),Ut=Lt.extend({statusCode:i.default.literal(404)}),Mt=Lt.extend({statusCode:i.default.literal(500)}),jt=i.default.object({page:i.default.number().int().positive(),limit:i.default.number().int().positive(),total:i.default.number().int().min(0),totalPages:i.default.number().int().min(0),hasNext:i.default.boolean(),hasPrev:i.default.boolean()}),Zt=i.default.object({balance:i.default.number(),availableBalance:i.default.number(),accountNumber:i.default.string(),accountName:i.default.string()}),Bt=i.default.object({yesterday:i.default.number(),today:i.default.number(),thisMonth:i.default.number(),lastMonth:i.default.number()});const $t=i.default.string().nullish().transform(e=>{if(!e||""===e.trim())return null;try{return function(e){if(!e||""===e.trim())throw new Error("Date string cannot be empty");const[t,r]=e.trim().split(" ");if(!t||!r)throw new Error("Invalid date format. Expected 'YYYY-MM-DD HH:mm:ss'");const n=new Date(`${t}T${r}.000Z`);return new Date(n.getTime()-108e5).toISOString()}(e)}catch(e){throw new Error(`Failed to convert EAT date to UTC: ${e instanceof Error?e.message:"Unknown error"}`)}}),Vt=i.default.object({accountNo:i.default.string().nullish(),debitOrCredit:i.default.enum(["CR","DR"],{error:()=>({message:"Transaction type must be either 'CR' (Credit) or 'DR' (Debit)"})}),tranRefNo:i.default.string().nullish(),cbaRefNo:i.default.string().nullish(),narration:i.default.string().nullish(),txnDate:$t,valueDate:$t,amountCredited:i.default.union([i.default.number().min(0,"Credited amount cannot be negative"),i.default.string().transform(e=>{if(""===e.trim())return 0;const t=parseFloat(e);if(isNaN(t))throw new Error("Invalid credited amount format");return t})],{error:()=>({message:"Credited amount must be a number or numeric string"})}).nullish(),amountDebited:i.default.union([i.default.number().min(0,"Debited amount cannot be negative"),i.default.string().transform(e=>{if(""===e.trim())return 0;const t=parseFloat(e);if(isNaN(t))throw new Error("Invalid debited amount format");return t})],{error:()=>({message:"Debited amount must be a number or numeric string"})}).nullish(),balance:i.default.number({error:e=>void 0===e.input?"Balance is required":"Balance must be a number"})}),Jt={apiError:Lt,validationError:kt,unauthorizedError:Ft,forbiddenError:zt,notFoundError:Ut,serverError:Mt,pagination:jt,transactionSummary:Bt,walletSummary:Zt,statementEntry:Vt};class Yt{contract;endpoint;root;token;constructor(e,t,r){this.contract=t,this.endpoint=e,this.root=r?.root,this.token=r?.token}getToken(){return this.token&&this.token.trim().length>0?this.token:""}get client(){return this.getClientWithHeaders()}getClientWithHeaders(t){const r=this.root?this.root.replace(/\/+$/,""):"",n=this.endpoint?this.endpoint.replace(/^\/+/,""):"",a=r?`${r}/${n}`:`https://gateway.temboplus.com/dashboard/${n}`,s={Authorization:`Bearer ${this.getToken()}`,"x-request-id":e.v4()},i={baseUrl:a,baseHeaders:t?{...s,...t}:s};return Dt(this.contract,i)}setToken(e){this.token=e}getCurrentToken(){return this.token}handleResponse(e,t){if(e.status===t)return e.body;const r=Jt.apiError.safeParse(e.body),n=r.success?r.data:void 0,a=(t,r)=>new Pt({message:n?.message??t,statusCode:n?.statusCode??e.status,error:n?.error??n?.reason??r,details:n?.details});if(400===e.status)throw a("Bad request","BAD_REQUEST");if(401===e.status)throw a("You are not authenticated to perform this action. Please login again","UNAUTHORIZED");if(403===e.status)throw a("You are not authorized to perform this action.","FORBIDDEN");if(404===e.status)throw a("The requested resource was not found.","NOT_FOUND");if(500===e.status)throw a("We encountered an error trying to process your request. Please try again later","SERVER_ERROR");throw a("We encountered an error trying to process your request. Please try again later","UNKNOWN_ERROR")}}class qt{accountNo;debitOrCredit;tranRefNo;cbaRefNo;narration;txnDate;valueDate;amountCredited;amountDebited;balance;currency;constructor(e,t="TZS"){let n="TZS";r.CurrencyHelpers.isCode(t)&&(n=t),this.accountNo=e.accountNo,this.debitOrCredit=e.debitOrCredit,this.tranRefNo=e.tranRefNo,this.cbaRefNo=e.cbaRefNo,this.narration=e.narration,this.txnDate=e.txnDate?new Date(e.txnDate):null,this.valueDate=e.valueDate?new Date(e.valueDate):null,this.currency=n;const a=e.amountCredited?this.parseAmountValue(e.amountCredited):null;this.amountCredited=null===a?null:a>0?r.Amount.from(a,n)??r.Amount.from(0,n):null;const s=e.amountDebited?this.parseAmountValue(e.amountDebited):null;this.amountDebited=null===s?null:s>0?r.Amount.from(s,n)??r.Amount.from(0,n):null,this.balance=r.Amount.from(e.balance,n)??r.Amount.from(0,n)}parseAmountValue(e){if("number"==typeof e)return e;if("string"==typeof e&&""!==e.trim()){const t=parseFloat(e);return isNaN(t)?0:t}return 0}isCredit(){return"CR"===this.debitOrCredit}isDebit(){return"DR"===this.debitOrCredit}getTransactionAmount(){return this.amountCredited||this.amountDebited}getTransactionValue(){const e=this.getTransactionAmount();return e?e.numericValue:0}static from(e,t="TZS"){try{return!1===Jt.statementEntry.safeParse(e).success?void console.error("Missing required StatementEntry fields:",e):new qt(e,t)}catch(e){return void console.error("Error creating StatementEntry:",e)}}static createMany(e,t="TZS"){const r=[];for(const n of e){const e=qt.from(n,t);if(!e)return;r.push(e)}return r}toJSON(){return{accountNo:this.accountNo,debitOrCredit:this.debitOrCredit,tranRefNo:this.tranRefNo,cbaRefNo:this.cbaRefNo,narration:this.narration,txnDate:this.txnDate?.toISOString(),valueDate:this.valueDate?.toISOString(),amountCredited:this.amountCredited?.toJSON()??null,amountDebited:this.amountDebited?.toJSON()??null,balance:this.balance.toJSON(),currency:this.currency}}static fromJSON(e){try{if(!r.AmountFactory.getInstance().isAmountJSON(e.balance))return void console.error("Invalid balance AmountJson structure:",e.balance);if(e.amountCredited&&!r.AmountFactory.getInstance().isAmountJSON(e.amountCredited))return void console.error("Invalid amountCredited AmountJson structure:",e.amountCredited);if(e.amountDebited&&!r.AmountFactory.getInstance().isAmountJSON(e.amountDebited))return void console.error("Invalid amountDebited AmountJson structure:",e.amountDebited);const t=r.Amount.fromJSON(e.balance);if(!t)return void console.error("Failed to reconstruct balance Amount from JSON:",e.balance);let n=0;if(e.amountCredited){const t=r.Amount.fromJSON(e.amountCredited);if(!t)return void console.error("Failed to reconstruct amountCredited Amount from JSON:",e.amountCredited);n=t.numericValue}let a=0;if(e.amountDebited){const t=r.Amount.fromJSON(e.amountDebited);if(!t)return void console.error("Failed to reconstruct amountDebited Amount from JSON:",e.amountDebited);a=t.numericValue}const s={accountNo:e.accountNo,debitOrCredit:e.debitOrCredit,tranRefNo:e.tranRefNo,cbaRefNo:e.cbaRefNo,narration:e.narration,txnDate:e.txnDate?e.txnDate:null,valueDate:e.valueDate?e.valueDate:null,amountCredited:n,amountDebited:a,balance:t.numericValue};return new qt(s,e.currency)}catch(e){return void console.error("Error creating StatementEntry from JSON:",e)}}static createManyFromJson(e){const t=[];for(const r of e){const e=qt.fromJSON(r);if(!e)return;t.push(e)}return t}static getTotalCredits(e){const t=e.length>0?e[0].currency:"TZS",n=e.reduce((e,t)=>t.isCredit()&&t.amountCredited?e+t.amountCredited.numericValue:e,0);return r.Amount.from(n,t)??r.Amount.from(0,t)}static getTotalDebits(e){const t=e.length>0?e[0].currency:"TZS",n=e.reduce((e,t)=>t.isDebit()&&t.amountDebited?e+t.amountDebited.numericValue:e,0);return r.Amount.from(n,t)??r.Amount.from(0,t)}static getNetChange(e){const t=e.length>0?e[0].currency:"TZS",n=qt.getTotalCredits(e).numericValue,a=qt.getTotalDebits(e).numericValue;return r.Amount.from(n-a,t)??r.Amount.from(0,t)}}class Ht{yesterday;today;thisMonth;lastMonth;currency;constructor(e,t="TZS"){this.currency=t,this.yesterday=r.Amount.from(e.yesterday,t)??r.Amount.from(0,t),this.today=r.Amount.from(e.today,t)??r.Amount.from(0,t),this.thisMonth=r.Amount.from(e.thisMonth,t)??r.Amount.from(0,t),this.lastMonth=r.Amount.from(e.lastMonth,t)??r.Amount.from(0,t)}getMonthlyGrowthRate(){return 0===this.lastMonth.numericValue?this.thisMonth.numericValue>0?100:0:(this.thisMonth.numericValue-this.lastMonth.numericValue)/this.lastMonth.numericValue*100}getRecentTotal(){return r.Amount.from(this.today.numericValue+this.yesterday.numericValue,this.currency)}static from(e,t="TZS"){return new Ht(e,t)}toJSON(){return{yesterday:this.yesterday.toJSON(),today:this.today.toJSON(),thisMonth:this.thisMonth.toJSON(),lastMonth:this.lastMonth.toJSON(),currency:this.currency}}static fromJSON(e){try{if(!(r.AmountFactory.getInstance().isAmountJSON(e.yesterday)&&r.AmountFactory.getInstance().isAmountJSON(e.today)&&r.AmountFactory.getInstance().isAmountJSON(e.thisMonth)&&r.AmountFactory.getInstance().isAmountJSON(e.lastMonth)))return void console.error("Invalid AmountJson structure in TransactionSummary JSON:",e);const t=r.Amount.fromJSON(e.yesterday),n=r.Amount.fromJSON(e.today),a=r.Amount.fromJSON(e.thisMonth),s=r.Amount.fromJSON(e.lastMonth);if(!(t&&n&&a&&s))return void console.error("Failed to reconstruct Amount instances from JSON:",e);const i={yesterday:t.numericValue,today:n.numericValue,thisMonth:a.numericValue,lastMonth:s.numericValue};return new Ht(i,e.currency)}catch(e){return void console.error("Error creating TransactionSummary from JSON:",e)}}}class Wt{accountName;accountNo;accountNumber;availableBalance;currentBalance;actualBalance;accountStatus;type;currencyCode;countryCode;currency;constructor(e){let t="TZS";e.currencyCode&&r.CurrencyHelpers.isCode(e.currencyCode)&&(t=e.currencyCode),this.accountName=e.accountName,this.accountNo=e.accountNo,this.accountNumber=e.accountNo,this.currency=t,this.currencyCode=t,this.countryCode=e.countryCode,this.availableBalance=r.Amount.from(e.availableBalance,t)??r.Amount.from(0,t),this.currentBalance=r.Amount.from(e.currentBalance,t)??r.Amount.from(0,t),this.actualBalance=this.currentBalance,this.accountStatus=e.accountStatus,this.type=e.type}hasSufficientBalance(e){return this.availableBalance.numericValue>=e}static from(e){return new Wt(e)}toJSON(){return{accountName:this.accountName,accountNo:this.accountNo,accountNumber:this.accountNumber,availableBalance:this.availableBalance.toJSON(),currentBalance:this.currentBalance.toJSON(),actualBalance:this.actualBalance.toJSON(),accountStatus:this.accountStatus,type:this.type,currencyCode:this.currencyCode,countryCode:this.countryCode,currency:this.currency}}static fromJSON(e){try{if(!r.AmountFactory.getInstance().isAmountJSON(e.availableBalance)||!r.AmountFactory.getInstance().isAmountJSON(e.actualBalance))return void console.error("Invalid AmountJson structure in WalletInfo JSON:",e);const t=r.Amount.fromJSON(e.availableBalance),n=e.currentBalance??e.actualBalance;if(!r.AmountFactory.getInstance().isAmountJSON(n))return void console.error("Invalid currentBalance AmountJson structure in WalletInfo JSON:",e);const a=r.Amount.fromJSON(n);if(!t||!a)return void console.error("Failed to reconstruct Amount instances from JSON:",e);const s=e.accountNo||e.accountNumber;if(!s)return void console.error("Missing account number in WalletInfo JSON:",e);const i={accountName:e.accountName,accountNo:s,availableBalance:t.numericValue,currentBalance:a.numericValue,accountStatus:e.accountStatus||"UNKNOWN",type:e.type,currencyCode:e.currencyCode||e.currency,countryCode:e.countryCode};return new Wt(i)}catch(e){return void console.error("Error creating WalletInfo from JSON:",e)}}static createManyFromJson(e){const t=[];for(const r of e){const e=Wt.fromJSON(r);if(!e)return;t.push(e)}return t}}var Gt,Kt;exports.FilterOperator=void 0,(Gt=exports.FilterOperator||(exports.FilterOperator={})).EQUALS="eq",Gt.NOT_EQUALS="neq",Gt.LESS_THAN="lt",Gt.LESS_THAN_OR_EQUAL="lte",Gt.GREATER_THAN="gt",Gt.GREATER_THAN_OR_EQUAL="gte",Gt.LIKE="like",Gt.LIKE_LOWER="likeLower",Gt.IS_NULL="isNull",Gt.IS_NOT_NULL="isNotNull",Gt.IN="in",exports.SortDirection=void 0,(Kt=exports.SortDirection||(exports.SortDirection={})).ASC="asc",Kt.DESC="desc";const Qt=Symbol("query-builder-type");class Xt{options={filters:[],sort:[],includes:[],groupBy:[],join:[],count:"*",page:1,limit:8};constructor(e={}){this.options={filters:e.filters||[],sort:e.sort||[],includes:e.includes||[],groupBy:e.groupBy||[],join:e.join||[],page:e.page,limit:e.limit}}[Qt]="query-builder";static is(e){return null!==e&&"object"==typeof e&&Qt in e&&"query-builder"===e[Qt]}addFilter(e){return this.options.filters=[...this.options.filters||[],e],this}where(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.EQUALS,value:t})}whereNot(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.NOT_EQUALS,value:t})}whereLike(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE,value:t})}whereLikeLower(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:t})}whereContains(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:`%${t}%`})}whereStartsWith(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:`${t}%`})}whereEndsWith(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LIKE_LOWER,value:`%${t}`})}whereIn(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.IN,value:t})}whereNull(e){return this.addFilter({field:e,operator:exports.FilterOperator.IS_NULL})}whereNotNull(e){return this.addFilter({field:e,operator:exports.FilterOperator.IS_NOT_NULL})}whereGreaterThan(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.GREATER_THAN,value:t})}whereGreaterThanOrEqual(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.GREATER_THAN_OR_EQUAL,value:t})}whereLessThan(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LESS_THAN,value:t})}whereLessThanOrEqual(e,t){return this.addFilter({field:e,operator:exports.FilterOperator.LESS_THAN_OR_EQUAL,value:t})}whereBetween(e,t,r){return this.whereGreaterThanOrEqual(e,t).whereLessThanOrEqual(e,r)}whereDateBetween(e,t){return e&&this.whereGreaterThanOrEqual("createdAt",e),t&&this.whereLessThanOrEqual("createdAt",t),this}addSort(e){return this.options.sort=[...this.options.sort||[],e],this}orderBy(e,t=exports.SortDirection.ASC){return this.addSort({field:e,direction:t})}orderByAsc(e){return this.orderBy(e,exports.SortDirection.ASC)}orderByDesc(e){return this.orderBy(e,exports.SortDirection.DESC)}paginate(e,t){return this.options.page=e,this.options.limit=t,this}with(e){const t=Array.isArray(e)?e:[e];return this.options.includes=[...this.options.includes||[],...t],this}join(e){const t=Array.isArray(e)?e:[e];return this.options.join=[...this.options.join||[],...t],this}groupBy(e){const t=Array.isArray(e)?e:[e];return this.options.groupBy=[...this.options.groupBy||[],...t],this}count(e="*"){return this.options.count=e,this}countAs(e,t){return this.options.count=`${e} as ${t}`,this}build(){const e={};if(void 0!==this.options.page&&void 0!==this.options.limit){const t=(this.options.page-1)*this.options.limit,r=t+this.options.limit-1;e.rangeStart=t,e.rangeEnd=r}if(this.options.filters&&this.options.filters.length>0)for(const t of this.options.filters)switch(t.operator){case exports.FilterOperator.IS_NULL:e[`${t.field}:isNull`]=1;break;case exports.FilterOperator.IS_NOT_NULL:e[`${t.field}:notNull`]=1;break;case exports.FilterOperator.IN:e[`${t.field}:in`]=Array.isArray(t.value)?t.value.join(","):t.value;break;case exports.FilterOperator.LIKE:e[`${t.field}:like`]=t.value;break;case exports.FilterOperator.LIKE_LOWER:e[`${t.field}:likeLower`]=t.value;break;case exports.FilterOperator.GREATER_THAN_OR_EQUAL:e[`${t.field}:gte`]=t.value;break;case exports.FilterOperator.LESS_THAN_OR_EQUAL:e[`${t.field}:lte`]=t.value;break;default:e[`${t.field}:${t.operator}`]=t.value}if(this.options.sort&&this.options.sort.length>0){const t=[],r=[];for(const e of this.options.sort)e.direction===exports.SortDirection.ASC?t.push(e.field):r.push(e.field);t.length>0&&(e.orderBy=t.join(",")),r.length>0&&(e.orderByDesc=r.join(","))}return this.options.includes&&this.options.includes.length>0&&(1===this.options.includes.length?e.eager=this.options.includes[0]:e.eager=`[${this.options.includes.join(",")}]`),this.options.join&&this.options.join.length>0&&(e.join=this.options.join.join(",")),this.options.groupBy&&this.options.groupBy.length>0&&(e.groupBy=this.options.groupBy.join(",")),this.options.count&&(e.count=this.options.count),e}clone(){return new(0,this.constructor)({...this.options,filters:this.options.filters?[...this.options.filters]:[],sort:this.options.sort?[...this.options.sort]:[],includes:this.options.includes?[...this.options.includes]:[],groupBy:this.options.groupBy?[...this.options.groupBy]:[],join:this.options.join?[...this.options.join]:[]})}static create(e){return new Xt(e)}}const er={AIRTEL:{key:"AIRTEL",networkOperator:"Airtel",serviceName:"Airtel Money"},VODACOM:{key:"VODACOM",networkOperator:"Vodacom",serviceName:"M-Pesa"},TIGO:{key:"TIGO",networkOperator:"Yas",serviceName:"Mixx by Yas"},HALOTEL:{key:"HALOTEL",networkOperator:"Halotel",serviceName:"HaloPesa"},SAFARICOM:{key:"SAFARICOM",networkOperator:"Safaricom",serviceName:"M-Pesa"}},tr={user:t.z.object({token:t.z.string(),identity:t.z.string(),name:t.z.string()}),loginRequest:t.z.object({identity:t.z.string().email(),password:t.z.string()}),updatePassword:t.z.object({currentPassword:t.z.string(),newPassword:t.z.string()})},rr=It().router({login:{method:"POST",path:"/login",body:tr.loginRequest,responses:{201:tr.user,400:Jt.validationError,401:Jt.unauthorizedError,500:Jt.serverError},summary:"User login",description:"Authenticate user with email and password"},updatePassword:{method:"POST",path:"/change-password",body:tr.updatePassword,responses:{201:i.default.object({}),400:Jt.validationError,401:Jt.unauthorizedError,500:Jt.serverError},summary:"Update password",description:"Update user password"}});class nr{identity;name;constructor(e){this.identity=e.identity,this.name=e.name}static from(e){return new nr(e)}static fromJson(e){return nr.from(e)}toJson(){return{identity:this.identity,name:this.name}}get email(){return this.identity}getDisplayName(){return this.name||this.identity}isEmailIdentity(){return/^[^\s@]+@[^\s@]+\.[a-z]{2,}$/i.test(this.identity)}getInitials(){return this.getDisplayName().split(" ").map(e=>e.charAt(0).toUpperCase()).slice(0,2).join("")}equals(e){return this.identity===e.identity&&this.name===e.name}}var ar,sr;exports.COLLECTION_STATUS=void 0,(ar=exports.COLLECTION_STATUS||(exports.COLLECTION_STATUS={})).PAYMENT_ACCEPTED="PAYMENT_ACCEPTED",ar.GENERIC_FAILURE="GENERIC_FAILURE",ar.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",ar.PAYMENT_REJECTED="PAYMENT_REJECTED",ar.PENDING_ACK="PENDING_ACK",ar.PROVIDER_FAILED="PROVIDER_FAILED",exports.COLLECTION_CHANNEL=void 0,(sr=exports.COLLECTION_CHANNEL||(exports.COLLECTION_CHANNEL={})).AIRTEL="TZ-AIRTEL-C2B",sr.TIGO="TZ-TIGO-C2B",sr.HALOTEL="TZ-HALOTEL-C2B",sr.SAFARICOM="KE-SAFARICOM-C2B",sr.VODACOM="TZ-VODACOM-C2B";const ir=t.z.nativeEnum(exports.COLLECTION_STATUS),or=t.z.nativeEnum(exports.COLLECTION_CHANNEL),cr=e=>{const t=Array.isArray(e)?e.flatMap(e=>cr(e)):"string"==typeof e?e.split(","):[];return Array.from(new Set(t.map(e=>e.trim()).filter(e=>e.length>0)))},ur=t.z.union([t.z.string(),t.z.array(t.z.string())]),dr={collection:t.z.object({id:t.z.string().min(1),status:ir,statusMessage:t.z.string(),accountNo:t.z.string().min(1),walletId:t.z.string(),transactionDate:t.z.string().datetime(),narration:t.z.string(),msisdn:t.z.string().min(1),channel:or,amount:t.z.number().min(0),serviceFee:t.z.string().optional(),postedAmount:t.z.string().optional(),reference:t.z.string(),partnerReference:t.z.string().nullable().optional(),payerName:t.z.string().nullable().optional(),payerReference:t.z.string().nullable().optional(),merchantName:t.z.string().nullable().optional(),merchantReference:t.z.string().nullable().optional(),transactionId:t.z.string().nullable().optional(),serviceFeeTransactionId:t.z.string().nullable().optional(),requestId:t.z.string().nullable().optional(),completedAt:t.z.string().datetime().nullable().optional(),createdAt:t.z.string().datetime(),updatedAt:t.z.string().datetime(),notes:t.z.string().optional(),currencyCode:t.z.string().default("TZS")}),collectionFilters:t.z.object({page:t.z.number().int().positive().default(1),limit:t.z.number().int().positive().max(1e4).default(20),sortBy:t.z.string().default("createdAt"),sortOrder:t.z.enum(["asc","desc"]).default("desc"),startDate:t.z.string().datetime().optional(),endDate:t.z.string().datetime().optional(),msisdn:t.z.string().optional(),id:t.z.string().optional(),idIn:t.z.array(t.z.string()).optional(),reference:t.z.string().optional(),referenceIn:t.z.array(t.z.string()).optional(),accountNo:t.z.string().optional(),walletId:t.z.string().optional(),partnerReference:t.z.string().optional(),channel:or.optional(),channelIn:t.z.array(or).optional(),status:ir.optional(),statusIn:t.z.array(ir).optional(),minAmount:t.z.number().min(0).optional(),maxAmount:t.z.number().min(0).optional(),search:t.z.string().optional()}),collectionURLQueryParams:t.z.object({page:t.z.string().transform(e=>parseInt(e)||1).optional(),limit:t.z.string().transform(e=>parseInt(e)||20).optional(),sortBy:t.z.string().default("createdAt"),sortOrder:t.z.enum(["asc","desc"]).default("desc"),startDate:t.z.string().optional(),endDate:t.z.string().optional(),msisdn:t.z.string().optional(),id:t.z.string().optional(),idIn:ur.transform(cr).optional(),reference:t.z.string().optional(),referenceIn:ur.transform(cr).optional(),accountNo:t.z.string().optional(),walletId:t.z.string().optional(),partnerReference:t.z.string().optional(),channel:t.z.string().refine(e=>Object.values(exports.COLLECTION_CHANNEL).includes(e)).transform(e=>e).optional(),channelIn:ur.transform(cr).pipe(t.z.array(or)).optional(),status:t.z.string().refine(e=>Object.values(exports.COLLECTION_STATUS).includes(e)).transform(e=>e).optional(),statusIn:ur.transform(cr).pipe(t.z.array(ir)).optional(),minAmount:t.z.string().transform(e=>parseFloat(e)).optional(),maxAmount:t.z.string().transform(e=>parseFloat(e)).optional(),search:t.z.string().optional()}),paymentStatus:ir,paymentChannel:or},lr=It().router({getCollections:{method:"GET",path:"/",query:dr.collectionURLQueryParams,responses:{200:t.z.object({results:t.z.array(dr.collection),total:t.z.number()}),401:Jt.unauthorizedError,403:Jt.forbiddenError,500:Jt.serverError},summary:"List collections",description:"Retrieve a paginated list of collections with optional filtering"},getCollection:{method:"GET",path:"/:id",pathParams:t.z.object({id:t.z.string()}),responses:{200:dr.collection,401:Jt.unauthorizedError,403:Jt.forbiddenError,404:Jt.notFoundError,500:Jt.serverError},summary:"Get collection details",description:"Retrieve detailed information about a specific collection"},getSummary:{method:"GET",path:"/summary",responses:{200:Jt.transactionSummary,401:Jt.unauthorizedError,403:Jt.forbiddenError,500:Jt.serverError},summary:"Get collections summary",description:"Retrieve collection summary statistics for different time periods"}}),hr={[exports.COLLECTION_STATUS.PAYMENT_ACCEPTED]:{label:"Payment Accepted",description:"The payment was successfully accepted",category:"success",color:"success",userFriendlyMessage:"Payment received successfully"},[exports.COLLECTION_STATUS.PENDING_ACK]:{label:"Pending Acknowledgment",description:"The payment is pending acknowledgment",category:"pending",color:"warning",userFriendlyMessage:"Payment is being processed"},[exports.COLLECTION_STATUS.PAYMENT_REJECTED]:{label:"Payment Rejected",description:"The payment was rejected and could not be processed",category:"failed",color:"error",userFriendlyMessage:"Payment was rejected. Please try again"},[exports.COLLECTION_STATUS.GENERIC_FAILURE]:{label:"Payment Failed",description:"A general error occurred during payment processing",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to an unexpected error"},[exports.COLLECTION_STATUS.INSUFFICIENT_FUNDS]:{label:"Insufficient Funds",description:"The payer has insufficient funds to complete the payment",category:"failed",color:"error",userFriendlyMessage:"Insufficient funds to complete the payment"},[exports.COLLECTION_STATUS.PROVIDER_FAILED]:{label:"Provider Failed",description:"An error occurred on the telecom provider's side, and the payment request was not successfully processed",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to an issue with the provider"}},mr={[exports.COLLECTION_CHANNEL.AIRTEL]:er.AIRTEL,[exports.COLLECTION_CHANNEL.TIGO]:er.TIGO,[exports.COLLECTION_CHANNEL.HALOTEL]:er.HALOTEL,[exports.COLLECTION_CHANNEL.VODACOM]:er.VODACOM,[exports.COLLECTION_CHANNEL.SAFARICOM]:er.SAFARICOM};class pr{id;status;statusMessage;accountNo;walletId;transactionDate;narration;msisdn;channel;amount;serviceFee;postedAmount;reference;partnerReference;payerName;payerReference;merchantName;merchantReference;transactionId;serviceFeeTransactionId;requestId;completedAt;createdAt;updatedAt;notes;currencyCode;_originalData;constructor(e){this._originalData={...e};let t="TZS";r.CurrencyHelpers.isCode(e.currencyCode)&&(t=e.currencyCode),this.id=e.id,this.status=e.status,this.statusMessage=e.statusMessage,this.accountNo=e.accountNo,this.walletId=e.walletId,this.transactionDate=new Date(e.transactionDate),this.narration=e.narration,this.msisdn=e.msisdn,this.channel=e.channel,this.amount=r.Amount.from(e.amount,t)??r.Amount.from(0,t),this.serviceFee=e.serviceFee?r.Amount.from(parseFloat(e.serviceFee),t)??r.Amount.from(0,t):void 0,this.postedAmount=e.postedAmount?r.Amount.from(parseFloat(e.postedAmount),t)??r.Amount.from(0,t):void 0,this.reference=e.reference,this.partnerReference=e.partnerReference,this.payerName=e.payerName,this.payerReference=e.payerReference,this.merchantName=e.merchantName,this.merchantReference=e.merchantReference,this.transactionId=e.transactionId,this.serviceFeeTransactionId=e.serviceFeeTransactionId,this.requestId=e.requestId,this.completedAt=e.completedAt?new Date(e.completedAt):null,this.createdAt=new Date(e.createdAt),this.updatedAt=new Date(e.updatedAt),this.notes=e.notes,this.currencyCode=e.currencyCode}getOriginalData(){return this._originalData}getOriginalField(e){return this._originalData[e]}getOriginalFieldUnsafe(e){return this._originalData[e]}isPending(){return this.status===exports.COLLECTION_STATUS.PENDING_ACK}isSuccessful(){return this.status===exports.COLLECTION_STATUS.PAYMENT_ACCEPTED}isFailed(){return Object.entries(hr).filter(([e,t])=>"failed"===t.category).map(([e])=>e).includes(this.status)}getStatusInfo(){return hr[this.status]}getChannelInfo(){return mr[this.channel]}getProviderName(){return this.getChannelInfo().networkOperator}getServiceName(){return this.getChannelInfo().serviceName}isMobileCollection(){return e=this.channel,Object.values(exports.COLLECTION_CHANNEL).includes(e);var e}static from(e){try{return e?.id&&e?.msisdn&&void 0!==e?.amount?new pr(e):void console.error("Missing required Collection fields:",e)}catch(e){return void console.error("Error creating Collection:",e)}}static createMany(e){const t=[];for(const r of e){const e=pr.from(r);e&&t.push(e)}return t}static fromJSON(e){try{if(!e?.id||!e?.msisdn||!e?.amount)return void console.error("Missing required Collection JSON fields:",e);if(!r.AmountFactory.getInstance().isAmountJSON(e.amount))return void console.error("Invalid amount AmountJson structure:",e.amount);if(e.serviceFee&&!r.AmountFactory.getInstance().isAmountJSON(e.serviceFee))return void console.error("Invalid serviceFee AmountJson structure:",e.serviceFee);if(e.postedAmount&&!r.AmountFactory.getInstance().isAmountJSON(e.postedAmount))return void console.error("Invalid postedAmount AmountJson structure:",e.postedAmount);const t=r.Amount.fromJSON(e.amount);if(!t)return void console.error("Failed to reconstruct Amount from JSON:",e.amount);let n,a;if(e.serviceFee){const t=r.Amount.fromJSON(e.serviceFee);if(!t)return void console.error("Failed to reconstruct serviceFee Amount from JSON:",e.serviceFee);n=t.numericValue.toString()}if(e.postedAmount){const t=r.Amount.fromJSON(e.postedAmount);if(!t)return void console.error("Failed to reconstruct postedAmount Amount from JSON:",e.postedAmount);a=t.numericValue.toString()}const s={id:e.id,status:e.status,statusMessage:e.statusMessage,accountNo:e.accountNo,walletId:e.walletId,transactionDate:e.transactionDate,narration:e.narration,msisdn:e.msisdn,channel:e.channel,amount:t.numericValue,serviceFee:n,postedAmount:a,reference:e.reference,partnerReference:e.partnerReference,payerName:e.payerName,payerReference:e.payerReference,merchantName:e.merchantName,merchantReference:e.merchantReference,transactionId:e.transactionId,serviceFeeTransactionId:e.serviceFeeTransactionId,requestId:e.requestId,completedAt:e.completedAt,createdAt:e.createdAt,updatedAt:e.updatedAt,notes:e.notes,currencyCode:e.currencyCode};return new pr(s)}catch(e){return void console.error("Error creating Collection from JSON:",e)}}static createManyFromJson(e){const t=[];for(const r of e){const e=pr.fromJSON(r);e&&t.push(e)}return t}toJSON(){return{id:this.id,status:this.status,statusMessage:this.statusMessage,accountNo:this.accountNo,walletId:this.walletId,transactionDate:this.transactionDate.toISOString(),narration:this.narration,msisdn:this.msisdn,channel:this.channel,amount:this.amount.toJSON(),serviceFee:this.serviceFee?.toJSON(),postedAmount:this.postedAmount?.toJSON(),reference:this.reference,partnerReference:this.partnerReference,payerName:this.payerName,payerReference:this.payerReference,merchantName:this.merchantName,merchantReference:this.merchantReference,transactionId:this.transactionId,serviceFeeTransactionId:this.serviceFeeTransactionId,requestId:this.requestId,completedAt:this.completedAt?.toISOString()??null,createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt.toISOString(),notes:this.notes,currencyCode:this.currencyCode}}}const fr=["id","reference","channel","status"];class yr extends Xt{static create(){return new yr}static fromFilters(e){return(new yr).applyFilters(e)}static fromUrlParams(e){try{const t=dr.collectionURLQueryParams.parse(yr.normalizeUrlParams(e)),r=dr.collectionFilters.parse(t);return yr.fromFilters(r)}catch(e){throw new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){return yr.fromUrlParams(yr.searchParamsToRecord(e))}static fromRequest(e){const{searchParams:t}=new URL(e.url);return yr.fromSearchParams(t)}static from(e){try{return null==e?new yr:Xt.is(e)?new yr(e.options):e instanceof URLSearchParams?yr.fromSearchParams(e):yr.isUrlParamsRecord(e)?yr.fromUrlParams(e):yr.fromFilters(e)}catch(e){throw new Error("Invalid input! Could not create a CollectionQuery instance.")}}static isUrlParamsRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!(e instanceof URLSearchParams)&&Object.values(e).every(e=>"string"==typeof e||Array.isArray(e)&&e.every(e=>"string"==typeof e))}static searchParamsToRecord(e){const t={};return e.forEach((e,r)=>{const n=t[r];void 0===n?t[r]=e:Array.isArray(n)?t[r]=[...n,e]:t[r]=[n,e]}),t}static normalizeUrlParams(e){const t={...e};for(const e of fr){const r=e,n=`${e}In`,a=`${e}:in`,s=`${e}[]`,i=`${e}In[]`,o=t[r],c=cr([t[n],t[a],t[s],t[i],Array.isArray(o)?o:void 0]);c.length>0&&(t[n]=c),Array.isArray(o)&&delete t[r],delete t[a],delete t[s],delete t[i]}return t}whereStatus(e){return this.where("status",e)}whereStatusIn(e){return this.whereInValues("status",e)}whereChannel(e){return this.where("channel",e)}whereChannelIn(e){return this.whereInValues("channel",e)}whereIdIn(e){return this.whereInValues("id",e)}whereReferenceIn(e){return this.whereInValues("reference",e)}wherePending(){return this.whereStatus(exports.COLLECTION_STATUS.PENDING_ACK)}whereSuccessful(){return this.whereStatus(exports.COLLECTION_STATUS.PAYMENT_ACCEPTED)}whereFailed(){return this.whereIn("status",[exports.COLLECTION_STATUS.PAYMENT_REJECTED,exports.COLLECTION_STATUS.GENERIC_FAILURE,exports.COLLECTION_STATUS.INSUFFICIENT_FUNDS,exports.COLLECTION_STATUS.PROVIDER_FAILED])}whereAmountBetween(e,t){return this.whereBetween("amount",e,t)}whereSender(e){return this.whereContains("msisdn",e)}whereAccount(e){return this.whereContains("accountNo",e)}whereWalletId(e){return this.whereContains("walletId",e)}whereReference(e){return this.whereContains("reference",e)}wherePartnerReference(e){return this.whereContains("partnerReference",e)}whereSearch(e){return this.where("search",e)}applyFilters(e){return(e.page||e.limit)&&this.paginate(e.page||1,e.limit||20),e.sortBy&&e.sortOrder&&("asc"===e.sortOrder?this.orderByAsc(e.sortBy):this.orderByDesc(e.sortBy)),(e.startDate||e.endDate)&&this.whereDateBetween(e.startDate,e.endDate),e.statusIn?.length?this.whereStatusIn(e.statusIn):e.status&&this.whereStatus(e.status),e.channelIn?.length?this.whereChannelIn(e.channelIn):e.channel&&this.whereChannel(e.channel),e.msisdn&&this.whereSender(e.msisdn),e.accountNo&&this.whereAccount(e.accountNo),e.walletId&&this.whereWalletId(e.walletId),e.referenceIn?.length?this.whereReferenceIn(e.referenceIn):e.reference&&this.whereReference(e.reference),e.partnerReference&&this.wherePartnerReference(e.partnerReference),e.idIn?.length?this.whereIdIn(e.idIn):e.id&&this.where("id",e.id),void 0===e.minAmount&&void 0===e.maxAmount||(void 0!==e.minAmount&&void 0!==e.maxAmount?this.whereAmountBetween(e.minAmount,e.maxAmount):void 0!==e.minAmount?this.whereGreaterThanOrEqual("amount",e.minAmount):void 0!==e.maxAmount&&this.whereLessThanOrEqual("amount",e.maxAmount)),e.search&&this.whereSearch(e.search),this}toFilters(){const e=this.extractFilterValues();return{page:this.options.page||1,limit:this.options.limit||20,sortBy:this.extractSortField()||"createdAt",sortOrder:this.extractSortOrder()||"desc",startDate:e.startDate,endDate:e.endDate,msisdn:e.msisdn,id:e.id,idIn:e.idIn,reference:e.reference,referenceIn:e.referenceIn,accountNo:e.accountNo,walletId:e.walletId,partnerReference:e.partnerReference,channel:this.isValidChannel(e.channel)?e.channel:void 0,channelIn:this.getValidChannels(e.channelIn),status:this.isValidStatus(e.status)?e.status:void 0,statusIn:this.getValidStatuses(e.statusIn),minAmount:e.minAmount,maxAmount:e.maxAmount,search:e.search}}toUrlParams(){const e=this.toFilters(),t={};return Object.entries(e).forEach(([e,r])=>{if(null!=r)if(Array.isArray(r))r.length>0&&(t[e]=r.join(","));else{const n=String(r);t[e]="startDate"===e||"endDate"===e?function(e){const t=new Date(e);return Number.isNaN(t.getTime())?e:new Date(t.getTime()+108e5).toISOString()}(n):n}}),t}toSearchParams(){return new URLSearchParams(this.toUrlParams())}toQueryString(){return this.toSearchParams().toString()}withPagination(e,t){const r=this.clone();return r.paginate(e,t||r.options.limit||20),r}withSorting(e,t="desc"){const r=this.clone();return"asc"===t?r.orderByAsc(e):r.orderByDesc(e),r}withDateRange(e,t){const r=this.clone();return r.whereDateBetween(e,t),r}withStatus(e){const t=this.clone();return e&&t.whereStatus(e),t}withChannel(e){const t=this.clone();return e&&t.whereChannel(e),t}resetPage(){return this.withPagination(1)}hasFilters(){const e=this.toFilters();return!!(e.startDate||e.endDate||e.msisdn||e.id||e.idIn?.length||e.reference||e.referenceIn?.length||e.accountNo||e.walletId||e.partnerReference||e.channel||e.channelIn?.length||e.status||e.statusIn?.length||e.minAmount||e.maxAmount||e.search)}getActiveFilters(){const e=[],t=this.toFilters();return t.statusIn?.length?e.push(`Status: ${t.statusIn.join(", ")}`):t.status&&e.push(`Status: ${t.status}`),t.channelIn?.length?e.push(`Channel: ${t.channelIn.join(", ")}`):t.channel&&e.push(`Channel: ${t.channel}`),t.startDate&&t.endDate?e.push(`Date: ${t.startDate} to ${t.endDate}`):t.startDate?e.push(`From: ${t.startDate}`):t.endDate&&e.push(`Until: ${t.endDate}`),t.minAmount&&t.maxAmount?e.push(`Amount: ${t.minAmount} - ${t.maxAmount}`):t.minAmount?e.push(`Min Amount: ${t.minAmount}`):t.maxAmount&&e.push(`Max Amount: ${t.maxAmount}`),t.search&&e.push(`Search: "${t.search}"`),t.msisdn&&e.push(`Phone: ${t.msisdn}`),t.accountNo&&e.push(`Account: ${t.accountNo}`),t.walletId&&e.push(`Wallet ID: ${t.walletId}`),t.referenceIn?.length?e.push(`Reference: ${t.referenceIn.join(", ")}`):t.reference&&e.push(`Reference: ${t.reference}`),t.idIn?.length&&e.push(`ID: ${t.idIn.join(", ")}`),e}extractFilterValues(){const e={};if(!this.options.filters)return e;for(const t of this.options.filters){if("in"===t.operator){const r=cr(t.value);r.length>0&&(e[`${t.field}In`]=r);continue}switch(t.field){case"createdAt":"gte"===t.operator?e.startDate=t.value:"lte"===t.operator&&(e.endDate=t.value);break;case"amount":"gte"===t.operator?e.minAmount=t.value:"lte"===t.operator&&(e.maxAmount=t.value);break;case"msisdn":case"reference":case"accountNo":case"walletId":case"partnerReference":"likeLower"===t.operator&&"string"==typeof t.value?e[t.field]=t.value.replace(/%/g,""):"eq"===t.operator&&(e[t.field]=t.value);break;default:"eq"===t.operator&&(e[t.field]=t.value)}}return e}whereInValues(e,t){const r=cr(t);return 0===r.length?this:this.whereIn(e,r)}getValidStatuses(e){const t=cr(e).filter(e=>this.isValidStatus(e));return t.length>0?t:void 0}getValidChannels(e){const t=cr(e).filter(e=>this.isValidChannel(e));return t.length>0?t:void 0}extractSortField(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].field}extractSortOrder(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].direction}isValidChannel(e){return Object.values(exports.COLLECTION_CHANNEL).includes(e)}isValidStatus(e){return Object.values(exports.COLLECTION_STATUS).includes(e)}}var gr,vr;exports.PAYOUT_STATUS=void 0,(gr=exports.PAYOUT_STATUS||(exports.PAYOUT_STATUS={})).PAYMENT_ACCEPTED="PAYMENT_ACCEPTED",gr.GENERIC_FAILURE="GENERIC_FAILURE",gr.WALLET_DEBITED="WALLET_DEBITED",gr.PAYMENT_REJECTED="PAYMENT_REJECTED",gr.PENDING="PENDING",gr.AMOUNT_EXCEED_MAXIMUM="AMOUNT_EXCEED_MAXIMUM",gr.PENDING_ACK="PENDING_ACK",gr.REVERSED="REVERSED",gr.INVALID_SERVICE="INVALID_SERVICE",gr.INVALID_NUMBER="INVALID_NUMBER",gr.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",gr.THIRDPARTY_FAILED="THIRDPARTY_FAILED",gr.PROVIDER_FAILED="PROVIDER_FAILED",exports.MOBILE_PAYOUT_CHANNEL=void 0,(vr=exports.MOBILE_PAYOUT_CHANNEL||(exports.MOBILE_PAYOUT_CHANNEL={})).AIRTEL="TZ-AIRTEL-B2C",vr.VODACOM="TZ-VODACOM-B2C",vr.TIGO="TZ-TIGO-B2C",vr.HALOTEL="TZ-HALOTEL-B2C",vr.SAFARICOM="TZ-SAFARICOM-B2C",exports.BANK_PAYOUT_CHANNEL=void 0,(exports.BANK_PAYOUT_CHANNEL||(exports.BANK_PAYOUT_CHANNEL={})).BANK="TZ-BANK-B2C";const _r=t.z.nativeEnum(exports.PAYOUT_STATUS),Ar=t.z.nativeEnum(exports.MOBILE_PAYOUT_CHANNEL),Nr=t.z.nativeEnum(exports.BANK_PAYOUT_CHANNEL),Ir=t.z.union([Ar,Nr]),Tr=e=>{const t=Array.isArray(e)?e.flatMap(e=>Tr(e)):"string"==typeof e?e.split(","):[];return Array.from(new Set(t.map(e=>e.trim()).filter(e=>e.length>0)))},wr=t.z.union([t.z.string(),t.z.array(t.z.string())]),br={payout:t.z.object({id:t.z.string().min(1),statusCode:t.z.string(),statusCodeText:_r,statusDescription:t.z.string(),countryCode:t.z.string(),serviceCode:Ir,amount:t.z.number().min(0),serviceFee:t.z.string().optional(),postedAmount:t.z.string().optional(),walletId:t.z.string().optional(),msisdn:t.z.string().min(1),narration:t.z.string(),currencyCode:t.z.string(),recipientNames:t.z.string().optional(),transactionRef:t.z.string(),transactionDate:t.z.string().datetime(),externalId:t.z.string().nullable().optional(),cbaReferenceNo:t.z.string().optional(),beepTransactionId:t.z.string().optional(),receiptNumber:t.z.string().optional(),createdAt:t.z.string().datetime(),reversedTransactionId:t.z.string().nullable().optional(),transactionId:t.z.string(),serviceFeeTransactionId:t.z.string().optional(),isReconciled:t.z.number().optional(),requestId:t.z.string().optional(),notes:t.z.string().optional(),updatedAt:t.z.string().datetime().optional()}),payoutFilters:t.z.object({page:t.z.number().int().positive().default(1),limit:t.z.number().int().positive().max(5e4).default(20),sortBy:t.z.string().default("createdAt"),sortOrder:t.z.enum(["asc","desc"]).default("desc"),startDate:t.z.string().datetime().optional(),endDate:t.z.string().datetime().optional(),msisdn:t.z.string().optional(),accountNo:t.z.string().optional(),walletId:t.z.string().optional(),id:t.z.string().optional(),idIn:t.z.array(t.z.string()).optional(),ref:t.z.string().optional(),refIn:t.z.array(t.z.string()).optional(),channelRef:t.z.string().optional(),channelRefIn:t.z.array(t.z.string()).optional(),channel:Ir.optional(),channelIn:t.z.array(Ir).optional(),status:_r.optional(),statusIn:t.z.array(_r).optional(),minAmount:t.z.number().min(0).optional(),maxAmount:t.z.number().min(0).optional(),search:t.z.string().optional()}),payoutURLQueryParams:t.z.object({page:t.z.string().transform(e=>parseInt(e)||1).optional(),limit:t.z.string().transform(e=>parseInt(e)||20).optional(),sortBy:t.z.string().default("createdAt"),sortOrder:t.z.enum(["asc","desc"]).default("desc"),startDate:t.z.string().optional(),endDate:t.z.string().optional(),msisdn:t.z.string().optional(),accountNo:t.z.string().optional(),walletId:t.z.string().optional(),id:t.z.string().optional(),idIn:wr.transform(Tr).optional(),ref:t.z.string().optional(),refIn:wr.transform(Tr).optional(),channelRef:t.z.string().optional(),channelRefIn:wr.transform(Tr).optional(),channel:t.z.string().refine(e=>Object.values(exports.MOBILE_PAYOUT_CHANNEL).includes(e)||e===exports.BANK_PAYOUT_CHANNEL.BANK).transform(e=>e).optional(),channelIn:wr.transform(Tr).pipe(t.z.array(Ir)).optional(),status:t.z.string().refine(e=>Object.values(exports.PAYOUT_STATUS).includes(e)).transform(e=>e).optional(),statusIn:wr.transform(Tr).pipe(t.z.array(_r)).optional(),minAmount:t.z.string().transform(e=>parseFloat(e)).optional(),maxAmount:t.z.string().transform(e=>parseFloat(e)).optional(),search:t.z.string().optional()}),payoutStatus:_r,payoutChannel:Ir,mobileChannel:Ar,bankChannel:Nr,walletSummary:t.z.object({balance:t.z.number(),currency:t.z.string(),lastUpdated:t.z.string().datetime()}),transactionSummary:t.z.object({yesterday:t.z.number(),today:t.z.number(),thisMonth:t.z.number(),lastMonth:t.z.number()}),pagination:t.z.object({page:t.z.number(),limit:t.z.number(),total:t.z.number(),totalPages:t.z.number(),hasNext:t.z.boolean(),hasPrev:t.z.boolean()})},Er=It().router({getPayouts:{method:"GET",path:"",query:br.payoutURLQueryParams,responses:{200:t.z.object({results:t.z.array(br.payout),total:t.z.number()}),401:Jt.unauthorizedError,403:Jt.forbiddenError,500:Jt.serverError},summary:"List payouts",description:"Retrieve a paginated list of payouts with optional filtering"},getPayout:{method:"GET",path:"/:id",pathParams:t.z.object({id:t.z.string()}),responses:{200:br.payout,401:Jt.unauthorizedError,403:Jt.forbiddenError,404:Jt.notFoundError,500:Jt.serverError},summary:"Get payout details",description:"Retrieve detailed information about a specific payout"},getPayoutSummary:{method:"GET",path:"/summary",responses:{200:Jt.transactionSummary,401:Jt.unauthorizedError,403:Jt.forbiddenError,500:Jt.serverError},summary:"Get payout summary",description:"Retrieve payout statistics including yesterday, today, this month, and last month totals"}}),Sr={[exports.PAYOUT_STATUS.PAYMENT_ACCEPTED]:{label:"Payment Accepted",description:"The payment was successfully accepted",category:"success",color:"success",userFriendlyMessage:"Payment completed successfully"},[exports.PAYOUT_STATUS.PENDING_ACK]:{label:"Pending Acknowledgment",description:"The payment is pending acknowledgment",category:"pending",color:"warning",userFriendlyMessage:"Payment is being processed"},[exports.PAYOUT_STATUS.PENDING]:{label:"Pending",description:"Payment is being processed",category:"pending",color:"warning",userFriendlyMessage:"Payment is in progress"},[exports.PAYOUT_STATUS.PAYMENT_REJECTED]:{label:"Payment Rejected",description:"The payment was rejected and could not be processed",category:"failed",color:"error",userFriendlyMessage:"Payment was rejected. Check payment details and try again"},[exports.PAYOUT_STATUS.GENERIC_FAILURE]:{label:"Payment Failed",description:"A general error occurred",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to an unexpected error"},[exports.PAYOUT_STATUS.INSUFFICIENT_BALANCE]:{label:"Insufficient Balance",description:"Insufficient funds are available to process the payment",category:"failed",color:"error",userFriendlyMessage:"Insufficient funds to complete the payment"},[exports.PAYOUT_STATUS.THIRDPARTY_FAILED]:{label:"Service Provider Error",description:"There was an error with the third-party service provider",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to service provider issue"},[exports.PAYOUT_STATUS.PROVIDER_FAILED]:{label:"Service Provider Error",description:"There was an error with the third-party service provider",category:"failed",color:"error",userFriendlyMessage:"Payment failed due to service provider issue"},[exports.PAYOUT_STATUS.AMOUNT_EXCEED_MAXIMUM]:{label:"Amount Exceeds Limit",description:"Payment amount exceeds the maximum allowed limit",category:"failed",color:"error",userFriendlyMessage:"Payment amount exceeds the allowed limit"},[exports.PAYOUT_STATUS.WALLET_DEBITED]:{label:"Wallet Debited",description:"Wallet has been debited but payment is not yet complete",category:"failed",color:"error",userFriendlyMessage:"Payment incomplete - wallet debited but recipient may not have received funds"},[exports.PAYOUT_STATUS.REVERSED]:{label:"Payment Reversed",description:"Payment has been reversed and funds returned",category:"failed",color:"error",userFriendlyMessage:"Payment was reversed and funds have been returned"},[exports.PAYOUT_STATUS.INVALID_SERVICE]:{label:"Invalid Service",description:"The requested payment service is not valid or available",category:"failed",color:"error",userFriendlyMessage:"Selected payment service is not available"},[exports.PAYOUT_STATUS.INVALID_NUMBER]:{label:"Invalid Number",description:"The number used is either barred or invalid",category:"failed",color:"error",userFriendlyMessage:"Recipient’s number is invalid, inactive, or temporarily blocked."}},Cr={[exports.MOBILE_PAYOUT_CHANNEL.AIRTEL]:er.AIRTEL,[exports.MOBILE_PAYOUT_CHANNEL.VODACOM]:er.VODACOM,[exports.MOBILE_PAYOUT_CHANNEL.TIGO]:er.TIGO,[exports.MOBILE_PAYOUT_CHANNEL.HALOTEL]:er.HALOTEL,[exports.MOBILE_PAYOUT_CHANNEL.SAFARICOM]:er.SAFARICOM};function Or(e){return Object.values(exports.MOBILE_PAYOUT_CHANNEL).includes(e)}function xr(e){return e===exports.BANK_PAYOUT_CHANNEL.BANK}class Rr{id;serviceCode;msisdn;amount;transactionDate;statusDescription;statusCodeText;transactionId;transactionRef;recipientNames;narration;serviceFee;notes;swiftCode;createdAt;updatedAt;statusCode;countryCode;postedAmount;walletId;currencyCode;externalId;cbaReferenceNo;beepTransactionId;receiptNumber;reversedTransactionId;serviceFeeTransactionId;isReconciled;requestId;_originalData;constructor(e){this._originalData={...e};let t="TZS";r.CurrencyHelpers.isCode(e.currencyCode)&&(t=e.currencyCode),this.id=e.id,this.serviceCode=e.serviceCode,this.msisdn=e.msisdn,this.amount=r.Amount.from(e.amount,t)??r.Amount.from(0,t),this.transactionDate=new Date(e.transactionDate),this.statusDescription=e.statusDescription,this.statusCodeText=e.statusCodeText,this.transactionId=e.transactionId,this.transactionRef=e.transactionRef,this.recipientNames=e.recipientNames,this.narration=e.narration,this.serviceFee=void 0===e.serviceFee?void 0:r.Amount.from(e.serviceFee,t)??r.Amount.from(0,t),this.notes=e.notes,this.swiftCode=e.swiftCode,this.createdAt=new Date(e.createdAt),this.updatedAt=e.updatedAt?new Date(e.updatedAt):void 0,this.statusCode=e.statusCode,this.countryCode=e.countryCode,this.postedAmount=e.postedAmount?r.Amount.from(parseFloat(e.postedAmount),t):void 0,this.walletId=e.walletId,this.currencyCode=e.currencyCode,this.externalId=e.externalId,this.cbaReferenceNo=e.cbaReferenceNo,this.beepTransactionId=e.beepTransactionId,this.receiptNumber=e.receiptNumber,this.reversedTransactionId=e.reversedTransactionId,this.serviceFeeTransactionId=e.serviceFeeTransactionId,this.isReconciled=e.isReconciled,this.requestId=e.requestId}getOriginalData(){return this._originalData}getOriginalField(e){return this._originalData[e]}getOriginalFieldUnsafe(e){return this._originalData[e]}isPending(){return[exports.PAYOUT_STATUS.PENDING,exports.PAYOUT_STATUS.PENDING_ACK].includes(this.statusCodeText)}isSuccessful(){return this.statusCodeText===exports.PAYOUT_STATUS.PAYMENT_ACCEPTED}isFailed(){return Object.entries(Sr).filter(([e,t])=>"failed"===t.category).map(([e])=>e).includes(this.statusCodeText)}getStatusInfo(){return Sr[this.statusCodeText]}getChannelInfo(){if(Or(this.serviceCode))return Cr[this.serviceCode];if(xr(this.serviceCode)){const e=this.msisdn.split(":")[0];if(e&&r.BankHelpers.validateSwiftCode(e)){if(r.BankHelpers.getCountryFromSwiftCode(e))try{return r.BankRegistry.getInstance().detectBank(e)}catch(t){console.warn(`Failed to create Bank instance for SWIFT code ${e}:`,t)}}if(this.swiftCode&&r.BankHelpers.getCountryFromSwiftCode(this.swiftCode)){if(r.BankHelpers.getCountryFromSwiftCode(this.swiftCode))try{return r.BankRegistry.getInstance().detectBank(this.swiftCode)}catch(e){console.warn(`Failed to create Bank instance for SWIFT code ${this.swiftCode}:`,e)}}}}getAccountNumber(){try{if(Or(this.serviceCode))return this.msisdn;if(xr(this.serviceCode)){return this.msisdn.split(":")[1]||this.msisdn}}catch(e){console.warn("failed to get the account number from payout msisdn: ",this.msisdn)}return this.msisdn}getProviderName(){const e=this.getChannelInfo();return Or(this.serviceCode)&&e?e.networkOperator:r.Bank.is(e)?e.shortName:"Bank Transfer"}static from(e){try{return e?.id&&e?.msisdn&&void 0!==e?.amount?new Rr(e):void console.error("Missing required Payout fields:",e)}catch(e){return void console.error("Error creating Payout:",e)}}static createMany(e){const t=[];for(const r of e){const e=Rr.from(r);e&&t.push(e)}return t}static fromJSON(e){try{if(!e?.id||!e?.msisdn||!e?.amount)return void console.error("Missing required Payout JSON fields:",e);if(!r.AmountFactory.getInstance().isAmountJSON(e.amount))return void console.error("Invalid amount AmountJson structure:",e.amount);if(e.serviceFee&&!r.AmountFactory.getInstance().isAmountJSON(e.serviceFee))return void console.error("Invalid serviceFee AmountJson structure:",e.serviceFee);if(e.postedAmount&&!r.AmountFactory.getInstance().isAmountJSON(e.postedAmount))return void console.error("Invalid postedAmount AmountJson structure:",e.postedAmount);const t=r.Amount.fromJSON(e.amount);if(!t)return void console.error("Failed to reconstruct Amount from JSON:",e.amount);let n,a;if(e.serviceFee){const t=r.Amount.fromJSON(e.serviceFee);if(!t)return void console.error("Failed to reconstruct serviceFee Amount from JSON:",e.serviceFee);n=t.numericValue}if(e.postedAmount){const t=r.Amount.fromJSON(e.postedAmount);if(!t)return void console.error("Failed to reconstruct postedAmount Amount from JSON:",e.postedAmount);a=t.numericValue.toString()}const s={id:e.id,serviceCode:e.serviceCode,msisdn:e.msisdn,amount:t.numericValue,transactionDate:e.transactionDate,statusDescription:e.statusDescription,statusCodeText:e.statusCodeText,transactionId:e.transactionId,transactionRef:e.transactionRef,recipientNames:e.recipientNames,narration:e.narration,serviceFee:n,notes:e.notes,swiftCode:e.swiftCode,createdAt:e.createdAt,updatedAt:e.updatedAt,statusCode:e.statusCode,countryCode:e.countryCode,postedAmount:a,walletId:e.walletId,currencyCode:e.currencyCode,externalId:e.externalId,cbaReferenceNo:e.cbaReferenceNo,beepTransactionId:e.beepTransactionId,receiptNumber:e.receiptNumber,reversedTransactionId:e.reversedTransactionId,serviceFeeTransactionId:e.serviceFeeTransactionId,isReconciled:e.isReconciled,requestId:e.requestId};return new Rr(s)}catch(e){return void console.error("Error creating Payout from JSON:",e)}}static createManyFromJson(e){const t=[];for(const r of e){const e=Rr.fromJSON(r);e&&t.push(e)}return t}toJSON(){return{id:this.id,serviceCode:this.serviceCode,msisdn:this.msisdn,amount:this.amount.toJSON(),transactionDate:this.transactionDate.toISOString(),statusDescription:this.statusDescription,statusCodeText:this.statusCodeText,transactionId:this.transactionId,transactionRef:this.transactionRef,recipientNames:this.recipientNames,narration:this.narration,serviceFee:this.serviceFee?.toJSON(),notes:this.notes,swiftCode:this.swiftCode,createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt?.toISOString(),statusCode:this.statusCode,countryCode:this.countryCode,postedAmount:this.postedAmount?.toJSON(),walletId:this.walletId,currencyCode:this.currencyCode,externalId:this.externalId,cbaReferenceNo:this.cbaReferenceNo,beepTransactionId:this.beepTransactionId,receiptNumber:this.receiptNumber,reversedTransactionId:this.reversedTransactionId,serviceFeeTransactionId:this.serviceFeeTransactionId,isReconciled:this.isReconciled,requestId:this.requestId}}}const Dr=["status","channel","id","ref","channelRef"],Pr=Object.fromEntries(Object.entries({status:"statusCodeText",channel:"serviceCode",id:"id",ref:"transactionRef",channelRef:"channelReference"}).map(([e,t])=>[t,e]));class Lr extends Xt{static create(){return new Lr}static fromFilters(e){return(new Lr).applyFilters(e)}static fromUrlParams(e){try{const t=br.payoutURLQueryParams.parse(Lr.normalizeUrlParams(e)),r=br.payoutFilters.parse(t);return Lr.fromFilters(r)}catch(e){throw new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){return Lr.fromUrlParams(Lr.searchParamsToRecord(e))}static fromRequest(e){const{searchParams:t}=new URL(e.url);return Lr.fromSearchParams(t)}static from(e){return null==e?new Lr:Xt.is(e)?new Lr(e.options):e instanceof URLSearchParams?Lr.fromSearchParams(e):Lr.isUrlParamsRecord(e)?Lr.fromUrlParams(e):Lr.fromFilters(e)}static isUrlParamsRecord(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!(e instanceof URLSearchParams)&&Object.values(e).every(e=>"string"==typeof e||Array.isArray(e)&&e.every(e=>"string"==typeof e))}static searchParamsToRecord(e){const t={};return e.forEach((e,r)=>{const n=t[r];void 0===n?t[r]=e:Array.isArray(n)?t[r]=[...n,e]:t[r]=[n,e]}),t}static normalizeUrlParams(e){const t={...e};for(const e of Dr){const r=e,n=`${e}In`,a=`${e}:in`,s=`${e}[]`,i=`${e}In[]`,o=t[r],c=Tr([t[n],t[a],t[s],t[i],Array.isArray(o)?o:void 0]);c.length>0&&(t[n]=c),Array.isArray(o)&&delete t[r],delete t[a],delete t[s],delete t[i]}return t}whereStatus(e){return this.where("statusCodeText",e)}whereStatusIn(e){return this.whereInValues("statusCodeText",e)}whereChannel(e){return this.where("serviceCode",e)}whereChannelIn(e){return this.whereInValues("serviceCode",e)}whereIdIn(e){return this.whereInValues("id",e)}whereRefIn(e){return this.whereInValues("transactionRef",e)}whereChannelRef(e){return this.whereContains("channelReference",e)}whereChannelRefIn(e){return this.whereInValues("channelReference",e)}wherePending(){return this.whereIn("statusCodeText",[exports.PAYOUT_STATUS.PENDING,exports.PAYOUT_STATUS.PENDING_ACK])}whereSuccessful(){return this.whereStatus(exports.PAYOUT_STATUS.PAYMENT_ACCEPTED)}whereFailed(){return this.whereIn("statusCodeText",[exports.PAYOUT_STATUS.PAYMENT_REJECTED,exports.PAYOUT_STATUS.GENERIC_FAILURE,exports.PAYOUT_STATUS.AMOUNT_EXCEED_MAXIMUM,exports.PAYOUT_STATUS.INVALID_SERVICE,exports.PAYOUT_STATUS.INSUFFICIENT_BALANCE,exports.PAYOUT_STATUS.THIRDPARTY_FAILED,exports.PAYOUT_STATUS.WALLET_DEBITED,exports.PAYOUT_STATUS.REVERSED])}whereAmountBetween(e,t){return this.whereBetween("amount",e,t)}whereRecipient(e){return this.whereContains("msisdn",e)}whereAccount(e){return this.whereContains("accountNo",e)}whereWalletId(e){return this.whereContains("walletId",e)}whereReference(e){return this.whereContains("transactionRef",e)}whereMobile(){return this.whereIn("serviceCode",Object.values(exports.MOBILE_PAYOUT_CHANNEL))}whereBank(){return this.whereChannel(exports.BANK_PAYOUT_CHANNEL.BANK)}whereSearch(e){return this.where("search",e)}applyFilters(e){return(e.page||e.limit)&&this.paginate(e.page||1,e.limit||20),e.sortBy&&e.sortOrder&&("asc"===e.sortOrder?this.orderByAsc(e.sortBy):this.orderByDesc(e.sortBy)),(e.startDate||e.endDate)&&this.whereDateBetween(e.startDate,e.endDate),e.statusIn?.length?this.whereStatusIn(e.statusIn):e.status&&this.whereStatus(e.status),e.channelIn?.length?this.whereChannelIn(e.channelIn):e.channel&&this.whereChannel(e.channel),e.msisdn&&this.whereRecipient(e.msisdn),e.accountNo&&this.whereAccount(e.accountNo),e.walletId&&this.whereWalletId(e.walletId),e.refIn?.length?this.whereRefIn(e.refIn):e.ref&&this.whereReference(e.ref),e.channelRefIn?.length?this.whereChannelRefIn(e.channelRefIn):e.channelRef&&this.whereChannelRef(e.channelRef),e.idIn?.length?this.whereIdIn(e.idIn):e.id&&this.where("id",e.id),void 0===e.minAmount&&void 0===e.maxAmount||(void 0!==e.minAmount&&void 0!==e.maxAmount?this.whereAmountBetween(e.minAmount,e.maxAmount):void 0!==e.minAmount?this.whereGreaterThanOrEqual("amount",e.minAmount):void 0!==e.maxAmount&&this.whereLessThanOrEqual("amount",e.maxAmount)),e.search&&this.whereSearch(e.search),this}toFilters(){const e=this.extractFilterValues();return{page:this.options.page||1,limit:this.options.limit||20,sortBy:this.extractSortField()||"createdAt",sortOrder:this.extractSortOrder()||"desc",startDate:e.startDate,endDate:e.endDate,msisdn:e.msisdn,accountNo:e.accountNo,walletId:e.walletId,id:e.id,idIn:e.idIn,ref:e.transactionRef,refIn:e.refIn,channelRef:e.channelReference,channelRefIn:e.channelRefIn,channel:this.isValidChannel(e.serviceCode)?e.serviceCode:void 0,channelIn:this.getValidChannels(e.channelIn),status:this.isValidStatus(e.statusCodeText)?e.statusCodeText:void 0,statusIn:this.getValidStatuses(e.statusIn),minAmount:e.minAmount,maxAmount:e.maxAmount,search:e.search}}toUrlParams(){const e=this.toFilters(),t={};return Object.entries(e).forEach(([e,r])=>{if(null!=r)if(Array.isArray(r))r.length>0&&(t[e]=r.join(","));else{const n=String(r);t[e]="startDate"===e||"endDate"===e?function(e){const t=new Date(e);return Number.isNaN(t.getTime())?e:new Date(t.getTime()+108e5).toISOString()}(n):n}}),t}toSearchParams(){return new URLSearchParams(this.toUrlParams())}toQueryString(){return this.toSearchParams().toString()}withPagination(e,t){const r=this.clone();return r.paginate(e,t||r.options.limit||20),r}withSorting(e,t="desc"){const r=this.clone();return"asc"===t?r.orderByAsc(e):r.orderByDesc(e),r}withDateRange(e,t){const r=this.clone();return r.whereDateBetween(e,t),r}withStatus(e){const t=this.clone();return e&&t.whereStatus(e),t}withChannel(e){const t=this.clone();return e&&t.whereChannel(e),t}resetPage(){return this.withPagination(1)}hasFilters(){const e=this.toFilters();return!!(e.startDate||e.endDate||e.msisdn||e.accountNo||e.walletId||e.id||e.idIn?.length||e.ref||e.refIn?.length||e.channelRef||e.channelRefIn?.length||e.channel||e.channelIn?.length||e.status||e.statusIn?.length||e.minAmount||e.maxAmount||e.search)}getActiveFilters(){const e=[],t=this.toFilters();return t.statusIn?.length?e.push(`Status: ${t.statusIn.join(", ")}`):t.status&&e.push(`Status: ${t.status}`),t.channelIn?.length?e.push(`Channel: ${t.channelIn.join(", ")}`):t.channel&&e.push(`Channel: ${t.channel}`),t.startDate&&t.endDate?e.push(`Date: ${t.startDate} to ${t.endDate}`):t.startDate?e.push(`From: ${t.startDate}`):t.endDate&&e.push(`Until: ${t.endDate}`),t.minAmount&&t.maxAmount?e.push(`Amount: ${t.minAmount} - ${t.maxAmount}`):t.minAmount?e.push(`Min Amount: ${t.minAmount}`):t.maxAmount&&e.push(`Max Amount: ${t.maxAmount}`),t.search&&e.push(`Search: "${t.search}"`),t.msisdn&&e.push(`Recipient: ${t.msisdn}`),t.accountNo&&e.push(`Account: ${t.accountNo}`),t.walletId&&e.push(`Wallet ID: ${t.walletId}`),t.refIn?.length?e.push(`Reference: ${t.refIn.join(", ")}`):t.ref&&e.push(`Reference: ${t.ref}`),t.channelRefIn?.length?e.push(`Channel Ref: ${t.channelRefIn.join(", ")}`):t.channelRef&&e.push(`Channel Ref: ${t.channelRef}`),t.idIn?.length&&e.push(`ID: ${t.idIn.join(", ")}`),e}extractFilterValues(){const e={};if(!this.options.filters)return e;for(const t of this.options.filters){if("in"===t.operator){const r=Tr(t.value);if(0===r.length)continue;e[`${Pr[t.field]??t.field}In`]=r;continue}switch(t.field){case"createdAt":"gte"===t.operator?e.startDate=t.value:"lte"===t.operator&&(e.endDate=t.value);break;case"amount":"gte"===t.operator?e.minAmount=t.value:"lte"===t.operator&&(e.maxAmount=t.value);break;case"msisdn":case"accountNo":case"walletId":case"transactionRef":case"channelReference":"likeLower"===t.operator&&"string"==typeof t.value?e[t.field]=t.value.replace(/%/g,""):"eq"===t.operator&&(e[t.field]=t.value);break;default:"eq"===t.operator&&(e[t.field]=t.value)}}return e}whereInValues(e,t){const r=Tr(t);return 0===r.length?this:this.whereIn(e,r)}getValidStatuses(e){const t=Tr(e).filter(e=>this.isValidStatus(e));return t.length>0?t:void 0}getValidChannels(e){const t=Tr(e).filter(e=>this.isValidChannel(e));return t.length>0?t:void 0}extractSortField(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].field}extractSortOrder(){if(this.options.sort&&0!==this.options.sort.length)return this.options.sort[0].direction}isValidChannel(e){return Object.values(exports.MOBILE_PAYOUT_CHANNEL).includes(e)||e===exports.BANK_PAYOUT_CHANNEL.BANK}isValidStatus(e){return Object.values(exports.PAYOUT_STATUS).includes(e)}}const kr={localTransferRequest:t.z.object({amount:t.z.number().int().positive(),from:t.z.string().min(1),to:t.z.string().min(1),description:t.z.string().min(1)}),localTransferResponse:t.z.object({transactionId:t.z.string(),from:t.z.string(),to:t.z.string(),transactionDate:t.z.string(),narration:t.z.string(),amount:t.z.number(),transactionRef:t.z.string()})},Fr=It().router({localTransfer:{method:"POST",path:"/local-transfer",body:kr.localTransferRequest,responses:{201:kr.localTransferResponse,400:Jt.validationError,401:Jt.unauthorizedError,404:Jt.notFoundError,500:Jt.serverError},summary:"Local transfer",description:"Transfer funds locally between wallets."}});var zr;exports.WALLET_TYPE=void 0,(zr=exports.WALLET_TYPE||(exports.WALLET_TYPE={})).VENDOR="Vendor",zr.DEFAULT_DISBURSEMENT="DEFAULT DISBURSEMENT",zr.DEFAULT_COLLECTION="DEFAULT COLLECTION",zr.COLLECTION="COLLECTION",zr.DISBURSEMENT="DISBURSEMENT";const Ur=t.z.nativeEnum(exports.WALLET_TYPE),Mr=t.z.object({id:t.z.string().min(1),accountNo:t.z.string().min(1),accountName:t.z.string().min(1),shadowAccountNo:t.z.string().nullish(),externalId:t.z.string().nullish(),reference:t.z.string().nullish(),type:t.z.string().min(1),vendorId:t.z.string().nullish(),balance:t.z.number(),minBalance:t.z.union([t.z.number(),t.z.string()]),approvalLimit:t.z.union([t.z.number(),t.z.string()]),currency:t.z.string().min(1),countryCode:t.z.string().min(1),createdAt:t.z.string().min(1),updatedAt:t.z.string().min(1)}),jr=t.z.object({availableBalance:t.z.number(),currentBalance:t.z.number(),accountStatus:t.z.string().min(1),accountNo:t.z.string().min(1),accountName:t.z.string().min(1)}),Zr={wallet:Mr,walletType:Ur,walletPathParams:t.z.object({accountNo:t.z.string().min(1)}),walletBalance:jr,walletStatementQuery:t.z.object({startDate:t.z.string().regex(/^\d{4}-\d{2}-\d{2}$/),endDate:t.z.string().regex(/^\d{4}-\d{2}-\d{2}$/)})},Br=It().router({listWallets:{method:"GET",path:"",responses:{200:t.z.array(Zr.wallet),401:Jt.unauthorizedError,500:Jt.serverError},summary:"List wallets",description:"Retrieve all wallets linked to the account across supported currencies."},getWalletInfo:{method:"GET",path:"/:accountNo",pathParams:t.z.object({accountNo:t.z.string().min(1)}),responses:{200:Zr.wallet,401:Jt.unauthorizedError,500:Jt.serverError},summary:"Get wallet info",description:"Retrieve wallet metadata including balance, currency, and type for a specific wallet."},getWalletBalance:{method:"GET",path:"/:accountNo/balance",pathParams:Zr.walletPathParams,responses:{200:Zr.walletBalance,401:Jt.unauthorizedError,404:Jt.notFoundError,500:Jt.serverError},summary:"Get wallet balance",description:"Retrieve the current and available balance for a specific wallet account number."},getWalletStatement:{method:"GET",path:"/:accountNo/statement",pathParams:Zr.walletPathParams,query:Zr.walletStatementQuery,responses:{200:t.z.array(Jt.statementEntry),400:Jt.validationError,401:Jt.unauthorizedError,404:Jt.notFoundError,500:Jt.serverError},summary:"Get wallet statement",description:"Retrieve statement entries for a specific wallet within a date range."}});class $r{id;accountNo;accountName;shadowAccountNo;externalId;reference;type;vendorId;balance;minBalance;approvalLimit;currency;countryCode;createdAt;updatedAt;_originalData;constructor(e){this._originalData={...e};let t="TZS";r.CurrencyHelpers.isCode(e.currency)?t=e.currency:"KSH"===e.currency&&(t="KES"),this.id=e.id,this.accountNo=e.accountNo,this.accountName=e.accountName,this.shadowAccountNo=e.shadowAccountNo,this.externalId=e.externalId,this.reference=e.reference,this.type=e.type,this.vendorId=e.vendorId,this.balance=r.Amount.from(e.balance,t)??r.Amount.from(0,t),this.minBalance=r.Amount.from(this.parseAmountValue(e.minBalance),t)??r.Amount.from(0,t),this.approvalLimit=r.Amount.from(this.parseAmountValue(e.approvalLimit),t)??r.Amount.from(0,t),this.currency=t,this.countryCode=e.countryCode,this.createdAt=new Date(e.createdAt),this.updatedAt=new Date(e.updatedAt)}getOriginalData(){return this._originalData}parseAmountValue(e){if("number"==typeof e)return e;const t=parseFloat(e);return Number.isNaN(t)?0:t}isCollectionWallet(){return this.type.includes("COLLECTION")}isDisbursementWallet(){return this.type.includes("DISBURSEMENT")}isDefaultWallet(){return this.type.startsWith("DEFAULT")}static from(e){return new $r(e)}static createMany(e){const t=[];try{for(const r of e)t.push($r.from(r));return t}catch(e){return void console.error("Error creating Wallets:",e)}}toJSON(){return{id:this.id,accountNo:this.accountNo,accountName:this.accountName,shadowAccountNo:this.shadowAccountNo,externalId:this.externalId,reference:this.reference,type:this.type,vendorId:this.vendorId,balance:this.balance.toJSON(),minBalance:this.minBalance.toJSON(),approvalLimit:this.approvalLimit.toJSON(),currency:this.currency,countryCode:this.countryCode,createdAt:this.createdAt.toISOString(),updatedAt:this.updatedAt.toISOString()}}static fromJSON(e){try{if(!r.AmountFactory.getInstance().isAmountJSON(e.balance))return void console.error("Invalid balance AmountJson structure in Wallet JSON:",e);if(!r.AmountFactory.getInstance().isAmountJSON(e.minBalance)||!r.AmountFactory.getInstance().isAmountJSON(e.approvalLimit))return void console.error("Invalid wallet threshold AmountJson structure in Wallet JSON:",e);const t=r.Amount.fromJSON(e.balance),n=r.Amount.fromJSON(e.minBalance),a=r.Amount.fromJSON(e.approvalLimit);return t&&n&&a?new $r({id:e.id,accountNo:e.accountNo,accountName:e.accountName,shadowAccountNo:e.shadowAccountNo,externalId:e.externalId,reference:e.reference,type:e.type,vendorId:e.vendorId,balance:t.numericValue,minBalance:n.numericValue,approvalLimit:a.numericValue,currency:e.currency,countryCode:e.countryCode,createdAt:e.createdAt,updatedAt:e.updatedAt}):void console.error("Failed to reconstruct balance Amount from JSON:",e)}catch(e){return void console.error("Error creating Wallet from JSON:",e)}}}exports.APIError=Pt,exports.AuthDTOSchemas=tr,exports.AuthRepository=class extends Yt{constructor(e){super("auth",rr,e)}async login(e){const t={identity:e.email,password:e.password},r=await this.client.login({body:t}),n=this.handleResponse(r,201),a=nr.from(n);if(!a)throw new Error("Invalid user data received from server");return{user:a,token:n.token}}async updatePassword(e){const t=await this.client.updatePassword({body:e});if(201!==t.status){if(400===t.status)throw new Error("Validation error");if(401===t.status)throw new Error("Unauthorized");throw new Error("Failed to update password")}return!0}},exports.BaseRepository=Yt,exports.COLLECTION_STATUS_INFO=hr,exports.Collection=pr,exports.CollectionDTOSchemas=dr,exports.CollectionQuery=yr,exports.CollectionRepository=class extends Yt{constructor(e){super("collection",lr,e)}async getCollections(e){try{const t=yr.from(e),r=t.build(),n=await this.client.getCollections({query:r}),a=this.handleResponse(n,200),s=t.toFilters(),i={page:s.page,limit:s.limit,total:a.total,totalPages:a.total>0?Math.ceil(a.total/s.limit):0,hasNext:s.page*s.limit<a.total,hasPrev:s.page>1},o=pr.createMany(a.results);if(!o)throw new Error("Invalid collection data received from server");return{collections:o,pagination:i}}catch(e){throw new Error(`Failed to fetch collections: ${e instanceof Error?e.message:"Unknown error"}`)}}async getCollectionsFromRequest(e){const t=yr.fromRequest(e);return this.getCollections(t)}async getCollection(e){const t=await this.client.getCollection({params:{id:e}}),r=this.handleResponse(t,200),n=pr.from(r);if(!n)throw new Error("Invalid collection data received from server");return n}async getCollectionStats(){const e=await this.client.getSummary(),t=this.handleResponse(e,200),r=Ht.from(t);if(!r)throw new Error("Invalid summary data received from server");return r}},exports.CommonSchemas=Jt,exports.MobileChannels=er,exports.PAYOUT_STATUS_INFO=Sr,exports.Payout=Rr,exports.PayoutDTOSchemas=br,exports.PayoutQuery=Lr,exports.PayoutRepository=class extends Yt{constructor(e){super("payout",Er,e)}async getPayouts(e){try{const t=Lr.from(e),r=t.build(),n=await this.client.getPayouts({query:r}),a=this.handleResponse(n,200),s=t.toFilters(),i={page:s.page,limit:s.limit,total:a.total,totalPages:a.total>0?Math.ceil(a.total/s.limit):0,hasNext:s.page*s.limit<a.total,hasPrev:s.page>1},o=Rr.createMany(a.results);if(!o)throw new Error("Invalid payout data received from server");return{payouts:o,pagination:i}}catch(e){throw new Error(`Failed to fetch payouts: ${e instanceof Error?e.message:"Unknown error"}`)}}async getPayoutsFromRequest(e){const t=Lr.fromRequest(e);return this.getPayouts(t)}async getPayout(e){const t=await this.client.getPayout({params:{id:e}}),r=this.handleResponse(t,200),n=Rr.from(r);if(!n)throw new Error("Invalid payout data received from server");return n}async getPayoutStats(){const e=await this.client.getPayoutSummary(),t=this.handleResponse(e,200),r=Ht.from(t);if(!r)throw new Error("Invalid summary data received from server");return r}},exports.QUERY_BUILDER_TYPE=Qt,exports.QueryBuilder=Xt,exports.StatementEntry=qt,exports.TransactionDTOSchemas=kr,exports.TransactionRepository=class extends Yt{constructor(e){super("transaction",Fr,e)}async localTransfer(e){const t=await this.client.localTransfer({body:e});return this.handleResponse(t,201)}},exports.TransactionSummary=Ht,exports.User=nr,exports.Wallet=$r,exports.WalletDTOSchemas=Zr,exports.WalletInfo=Wt,exports.WalletRepository=class extends Yt{constructor(e){super("wallet",Br,e)}async listWallets(){const e=await this.client.listWallets(),t=this.handleResponse(e,200),r=$r.createMany(t);if(!r)throw new Error("Invalid wallet data received from server");return r}async getWalletInfo(e){const t=await this.client.getWalletInfo({params:{accountNo:e}}),r=this.handleResponse(t,200);return $r.from(r)}async getWalletBalance(e){const t=await this.client.getWalletBalance({params:{accountNo:e}}),r=this.handleResponse(t,200);return Wt.from(r)}async getWalletStatement(e){const t=await this.client.getWalletStatement({params:{accountNo:e.accountNo},query:{startDate:this.formatStatementDate(e.startDate),endDate:this.formatStatementDate(e.endDate)}}),r=this.handleResponse(t,200),n=qt.createMany(r);if(!n)throw new Error("Invalid statement entry data received from server");return n}formatStatementDate(e){if(e instanceof Date){if(Number.isNaN(e.getTime()))throw new Error("Invalid statement date provided.");return e.toISOString().slice(0,10)}if(/^\d{4}-\d{2}-\d{2}$/.test(e))return e;const t=new Date(e);if(Number.isNaN(t.getTime()))throw new Error(`Invalid statement date: ${e}`);return t.toISOString().slice(0,10)}},exports.authContract=rr,exports.collectionContract=lr,exports.collectionToStringArray=cr,exports.payoutContract=Er,exports.payoutToStringArray=Tr,exports.statementEntrySchema=Vt,exports.transactionContract=Fr,exports.walletContract=Br;
2
2
  //# sourceMappingURL=index.cjs.js.map