@temboplus/tembo-dashboard 0.3.0-rc.1 → 0.3.0-rc.3

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}),A=e=>({status:"valid",value:e}),_=e=>"aborted"===e.status,T=e=>"dirty"===e.status,E=e=>"valid"===e.status,N=e=>"undefined"!=typeof Promise&&e instanceof Promise;var b;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:null==e?void 0:e.message}(b||(b={}));class S{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 I=(e,t)=>{if(E(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 w(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(N(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 I(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(N(n)?n:Promise.resolve(n));return I(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 Ae.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({...w(this._def),schema:this,typeName:Oe.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new _e({...w(this._def),innerType:this,defaultValue:t,typeName:Oe.ZodDefault})}brand(){return new be({typeName:Oe.ZodBranded,type:this,...w(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Te({...w(this._def),innerType:this,catchValue:t,typeName:Oe.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Se.create(this,e)}readonly(){return Ie.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}))$/,z=/^(([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})))$/,F=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||!z.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,...b.errToObj(r)}),this.nonempty=e=>this.min(1,b.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){F(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",...b.errToObj(e)})}url(e){return this._addCheck({kind:"url",...b.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...b.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...b.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...b.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...b.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...b.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...b.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,...b.errToObj(null==e?void 0:e.message)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...b.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:null==t?void 0:t.position,...b.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...b.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...b.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...b.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...b.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...b.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,...w(e)})};class B 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,b.toString(t))}gt(e,t){return this.setLimit("min",e,!1,b.toString(t))}lte(e,t){return this.setLimit("max",e,!0,b.toString(t))}lt(e,t){return this.setLimit("max",e,!1,b.toString(t))}setLimit(e,t,r,n){return new B({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:b.toString(n)}]})}_addCheck(e){return new B({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:b.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:b.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:b.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:b.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:b.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:b.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:b.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:b.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:b.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)}}B.create=e=>new B({checks:[],typeName:Oe.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...w(e)});class Z 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,b.toString(t))}gt(e,t){return this.setLimit("min",e,!1,b.toString(t))}lte(e,t){return this.setLimit("max",e,!0,b.toString(t))}lt(e,t){return this.setLimit("max",e,!1,b.toString(t))}setLimit(e,t,r,n){return new Z({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:b.toString(n)}]})}_addCheck(e){return new Z({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:b.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:b.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:b.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:b.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:b.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}}Z.create=e=>{var t;return new Z({checks:[],typeName:Oe.ZodBigInt,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...w(e)})};class V 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 A(e.data)}}V.create=e=>new V({typeName:Oe.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...w(e)});class $ 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 $({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:b.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:b.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}}$.create=e=>new $({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:Oe.ZodDate,...w(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 A(e.data)}}J.create=e=>new J({typeName:Oe.ZodSymbol,...w(e)});class q 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 A(e.data)}}q.create=e=>new q({typeName:Oe.ZodUndefined,...w(e)});class Y 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 A(e.data)}}Y.create=e=>new Y({typeName:Oe.ZodNull,...w(e)});class H extends C{constructor(){super(...arguments),this._any=!0}_parse(e){return A(e.data)}}H.create=e=>new H({typeName:Oe.ZodAny,...w(e)});class W extends C{constructor(){super(...arguments),this._unknown=!0}_parse(e){return A(e.data)}}W.create=e=>new W({typeName:Oe.ZodUnknown,...w(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,...w(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 A(e.data)}}K.create=e=>new K({typeName:Oe.ZodVoid,...w(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 S(t,e,t.path,r)))).then(e=>y.mergeArray(r,e));const a=[...t.data].map((e,r)=>n.type._parseSync(new S(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:b.toString(t)}})}max(e,t){return new Q({...this._def,maxLength:{value:e,message:b.toString(t)}})}length(e,t){return new Q({...this._def,exactLength:{value:e,message:b.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 Ae?Ae.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,...w(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 S(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 S(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 b.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=b.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,...w(t)}),ee.strictCreate=(e,t)=>new ee({shape:()=>e,unknownKeys:"strict",catchall:G.create(),typeName:Oe.ZodObject,...w(t)}),ee.lazycreate=(e,t)=>new ee({shape:e,unknownKeys:"strip",catchall:G.create(),typeName:Oe.ZodObject,...w(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,...w(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 _e?re(e._def.innerType):e instanceof q?[void 0]:e instanceof Y?[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,...w(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(_(e)||_(n))return g;const a=ae(e.value,n.value);return a.valid?((T(e)||T(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,...w(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 S(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,...w(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 S(r,e,r.path,e)),value:s._parse(new S(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,...w(r)}:{keyType:M.create(),valueType:e,typeName:Oe.ZodRecord,...w(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 S(r,e,r.path,[s,"key"])),value:a._parse(new S(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,...w(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 S(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:b.toString(t)}})}max(e,t){return new ue({...this._def,maxSize:{value:e,message:b.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,...w(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 A(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 A(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,...w(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,...w(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,...w(t)})}he.create=(e,t)=>new he({value:e,typeName:Oe.ZodLiteral,...w(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 A(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 A(e.data)}get enum(){return this._def.values}}fe.create=(e,t)=>new fe({values:e,typeName:Oe.ZodNativeEnum,...w(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 A(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,...w(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(!E(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=>E(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,...w(r)}),ge.createWithPreprocess=(e,t,r)=>new ge({schema:t,effect:{type:"preprocess",transform:e},typeName:Oe.ZodEffects,...w(r)});class ve extends C{_parse(e){return this._getType(e)===o.undefined?A(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ve.create=(e,t)=>new ve({innerType:e,typeName:Oe.ZodOptional,...w(t)});class Ae extends C{_parse(e){return this._getType(e)===o.null?A(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ae.create=(e,t)=>new Ae({innerType:e,typeName:Oe.ZodNullable,...w(t)});class _e 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}}_e.create=(e,t)=>new _e({innerType:e,typeName:Oe.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...w(t)});class Te 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 N(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}}Te.create=(e,t)=>new Te({innerType:e,typeName:Oe.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...w(t)});class Ee 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}}}Ee.create=e=>new Ee({typeName:Oe.ZodNaN,...w(e)});const Ne=Symbol("zod_brand");class be 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 Se 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 Se({in:e,out:t,typeName:Oe.ZodPipeline})}}class Ie extends C{_parse(e){const t=this._def.innerType._parse(e);return E(t)&&(t.value=Object.freeze(t.value)),t}}Ie.create=(e,t)=>new Ie({innerType:e,typeName:Oe.ZodReadonly,...w(t)});const we=(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=B.create,De=Ee.create,Pe=Z.create,Le=V.create,ke=$.create,ze=J.create,Fe=q.create,Ue=Y.create,Me=H.create,je=W.create,Be=G.create,Ze=K.create,Ve=Q.create,$e=ee.create,Je=ee.strictCreate,qe=te.create,Ye=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=Ae.create,ct=ge.createWithPreprocess,ut=Se.create,dt={string:e=>M.create({...e,coerce:!0}),number:e=>B.create({...e,coerce:!0}),boolean:e=>V.create({...e,coerce:!0}),bigint:e=>Z.create({...e,coerce:!0}),date:e=>$.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:A,isAborted:_,isDirty:T,isValid:E,isAsync:N,get util(){return a},get objectUtil(){return s},ZodParsedType:o,getParsedType:c,ZodType:C,ZodString:M,ZodNumber:B,ZodBigInt:Z,ZodBoolean:V,ZodDate:$,ZodSymbol:J,ZodUndefined:q,ZodNull:Y,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:Ae,ZodDefault:_e,ZodCatch:Te,ZodNaN:Ee,BRAND:Ne,ZodBranded:be,ZodPipeline:Se,ZodReadonly:Ie,custom:we,Schema:C,ZodSchema:C,late:Ce,get ZodFirstPartyTypeKind(){return Oe},coerce:dt,any:Me,array:Ve,bigint:Pe,boolean:Le,date:ke,discriminatedUnion:Ye,effect:st,enum:rt,function:Xe,instanceof:(e,t={message:`Input not instance of ${e.name}`})=>we(t=>t instanceof e,t),intersection:He,lazy:et,literal:tt,map:Ke,nan:De,nativeEnum:nt,never:Be,null:Ue,nullable:ot,number:Re,object:$e,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:ze,transformer:st,tuple:We,undefined:Fe,union:qe,unknown:je,void:Ze,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"),At=e=>"method"in e&&"path"in e,_t=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>{var n,a,s;return At(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,_t(r,t)]})),Tt=Symbol("ContractPlainType"),Et=()=>({router:(e,t)=>_t(e,t),query:e=>e,mutation:e=>e,responses:e=>e,response:()=>Tt,body:()=>Tt,type:()=>Tt,otherResponse:({contentType:e,body:t})=>({contentType:e,body:t}),noBody:()=>vt}),Nt=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("&"):"",bt=e=>e?Object.keys(e).flatMap(t=>St(t,e[t])).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",St=(e,t)=>Array.isArray(t)?t.flatMap((t,r)=>St(`${e}[${r}]`,t)):t instanceof Date?[[`${e}`,t.toISOString()]]:null===t?[[`${e}`,""]]:void 0===t?[]:"object"==typeof t?Object.keys(t).flatMap(r=>St(`${e}[${r}]`,t[r])):[[`${e}`,`${t}`]];class It extends Error{constructor(e,t){super(`Server returned unexpected response. Expected one of: ${t.join(",")} got: ${e.status}`),this.response=e}}const wt=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?Nt(e):bt(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||wt,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 It(s,r)}},Dt=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>At(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)}),zt=Lt.extend({statusCode:i.default.literal(401)}),Ft=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()}),Bt=i.default.object({balance:i.default.number(),availableBalance:i.default.number(),accountNumber:i.default.string(),accountName:i.default.string()}),Zt=i.default.object({yesterday:i.default.number(),today:i.default.number(),thisMonth:i.default.number(),lastMonth:i.default.number()});const Vt=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"}`)}}),$t=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:Vt,valueDate:Vt,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(Number.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(Number.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:zt,forbiddenError:Ft,notFoundError:Ut,serverError:Mt,pagination:jt,transactionSummary:Zt,walletSummary:Bt,statementEntry:$t};class qt{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 Yt{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 Number.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 Jt.statementEntry.safeParse(e).success?new Yt(e,t):void console.error("Missing required StatementEntry fields:",e)}catch(e){return void console.error("Error creating StatementEntry:",e)}}static createMany(e,t="TZS"){const r=[];for(const n of e){const e=Yt.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 Yt(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=Yt.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=Yt.getTotalCredits(e).numericValue,a=Yt.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"}};var tr;exports.USER_ROLE=void 0,(tr=exports.USER_ROLE||(exports.USER_ROLE={})).READ_ONLY="ReadOnly",tr.ADMIN="Admin",tr.INITIATOR="Initiator",tr.APPROVER="Approver";const rr=t.z.enum(exports.USER_ROLE),nr={user:t.z.object({token:t.z.string(),identity:t.z.string(),name:t.z.string(),role:rr}),userRole:rr,loginRequest:t.z.object({identity:t.z.email(),password:t.z.string()}),updatePassword:t.z.object({currentPassword:t.z.string(),newPassword:t.z.string()})},ar=Et().router({login:{method:"POST",path:"/login",body:nr.loginRequest,responses:{201:nr.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:nr.updatePassword,responses:{201:i.default.object({}),400:Jt.validationError,401:Jt.unauthorizedError,500:Jt.serverError},summary:"Update password",description:"Update user password"}});class sr{identity;name;role;constructor(e){this.identity=e.identity,this.name=e.name,this.role=e.role}static from(e){return new sr(e)}static fromJson(e){return sr.from(e)}toJson(){return{identity:this.identity,name:this.name,role:this.role}}get email(){return this.identity}getDisplayName(){return this.name||this.identity}hasRole(e){return this.role===e}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&&this.role===e.role}}var ir,or;exports.COLLECTION_STATUS=void 0,(ir=exports.COLLECTION_STATUS||(exports.COLLECTION_STATUS={})).PAYMENT_ACCEPTED="PAYMENT_ACCEPTED",ir.GENERIC_FAILURE="GENERIC_FAILURE",ir.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",ir.PAYMENT_REJECTED="PAYMENT_REJECTED",ir.PENDING_ACK="PENDING_ACK",ir.PROVIDER_FAILED="PROVIDER_FAILED",exports.COLLECTION_CHANNEL=void 0,(or=exports.COLLECTION_CHANNEL||(exports.COLLECTION_CHANNEL={})).AIRTEL="TZ-AIRTEL-C2B",or.TIGO="TZ-TIGO-C2B",or.HALOTEL="TZ-HALOTEL-C2B",or.SAFARICOM="KE-SAFARICOM-C2B",or.VODACOM="TZ-VODACOM-C2B";const cr=t.z.enum(exports.COLLECTION_STATUS),ur=t.z.enum(exports.COLLECTION_CHANNEL),dr=e=>{const t=Array.isArray(e)?e.flatMap(e=>dr(e)):"string"==typeof e?e.split(","):[];return Array.from(new Set(t.map(e=>e.trim()).filter(e=>e.length>0)))},lr=t.z.union([t.z.string(),t.z.array(t.z.string())]),hr={collection:t.z.object({id:t.z.string().min(1),status:cr,statusMessage:t.z.string(),accountNo:t.z.string().min(1),walletId:t.z.string(),transactionDate:t.z.iso.datetime(),narration:t.z.string(),msisdn:t.z.string().min(1),channel:ur,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.iso.datetime().nullable().optional(),createdAt:t.z.iso.datetime(),updatedAt:t.z.iso.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(5e4).default(20),sortBy:t.z.string().default("createdAt"),sortOrder:t.z.enum(["asc","desc"]).default("desc"),startDate:t.z.iso.datetime().optional(),endDate:t.z.iso.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:ur.optional(),channelIn:t.z.array(ur).optional(),status:cr.optional(),statusIn:t.z.array(cr).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:lr.transform(dr).optional(),reference:t.z.string().optional(),referenceIn:lr.transform(dr).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:lr.transform(dr).pipe(t.z.array(ur)).optional(),status:t.z.string().refine(e=>Object.values(exports.COLLECTION_STATUS).includes(e)).transform(e=>e).optional(),statusIn:lr.transform(dr).pipe(t.z.array(cr)).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:cr,paymentChannel:ur},mr=Et().router({getCollections:{method:"GET",path:"/",query:hr.collectionURLQueryParams,responses:{200:t.z.object({results:t.z.array(hr.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:hr.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"}}),pr={[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"}},fr={[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 yr{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(pr).filter(([e,t])=>"failed"===t.category).map(([e])=>e).includes(this.status)}getStatusInfo(){return pr[this.status]}getChannelInfo(){return fr[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{const t=e;return t?.id&&t?.msisdn&&void 0!==t?.amount?new yr(t):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=yr.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 yr(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=yr.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 gr=["id","reference","channel","status"];class vr extends Xt{static create(){return new vr}static fromFilters(e){return(new vr).applyFilters(e)}static fromUrlParams(e){try{const t=hr.collectionURLQueryParams.parse(vr.normalizeUrlParams(e)),r=hr.collectionFilters.parse(t);return vr.fromFilters(r)}catch(e){throw console.log(e),new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){return vr.fromUrlParams(vr.searchParamsToRecord(e))}static fromRequest(e){const{searchParams:t}=new URL(e.url);return vr.fromSearchParams(t)}static from(e){try{return null==e?new vr:Xt.is(e)?new vr(e.options):e instanceof URLSearchParams?vr.fromSearchParams(e):vr.isUrlParamsRecord(e)?vr.fromUrlParams(e):vr.fromFilters(e)}catch(e){throw console.log(e),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 gr){const r=e,n=`${e}In`,a=`${e}:in`,s=`${e}[]`,i=`${e}In[]`,o=t[r],c=dr([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=dr(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=dr(t);return 0===r.length?this:this.whereIn(e,r)}getValidStatuses(e){const t=dr(e).filter(e=>this.isValidStatus(e));return t.length>0?t:void 0}getValidChannels(e){const t=dr(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).some(t=>t===e)}isValidStatus(e){return Object.values(exports.COLLECTION_STATUS).some(t=>t===e)}}var Ar,_r;exports.PAYOUT_STATUS=void 0,(Ar=exports.PAYOUT_STATUS||(exports.PAYOUT_STATUS={})).PAYMENT_ACCEPTED="PAYMENT_ACCEPTED",Ar.GENERIC_FAILURE="GENERIC_FAILURE",Ar.WALLET_DEBITED="WALLET_DEBITED",Ar.PAYMENT_REJECTED="PAYMENT_REJECTED",Ar.PENDING="PENDING",Ar.AMOUNT_EXCEED_MAXIMUM="AMOUNT_EXCEED_MAXIMUM",Ar.PENDING_ACK="PENDING_ACK",Ar.REVERSED="REVERSED",Ar.INVALID_SERVICE="INVALID_SERVICE",Ar.INVALID_NUMBER="INVALID_NUMBER",Ar.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",Ar.THIRDPARTY_FAILED="THIRDPARTY_FAILED",Ar.PROVIDER_FAILED="PROVIDER_FAILED",exports.MOBILE_PAYOUT_CHANNEL=void 0,(_r=exports.MOBILE_PAYOUT_CHANNEL||(exports.MOBILE_PAYOUT_CHANNEL={})).AIRTEL="TZ-AIRTEL-B2C",_r.VODACOM="TZ-VODACOM-B2C",_r.TIGO="TZ-TIGO-B2C",_r.HALOTEL="TZ-HALOTEL-B2C",_r.SAFARICOM="TZ-SAFARICOM-B2C",exports.BANK_PAYOUT_CHANNEL=void 0,(exports.BANK_PAYOUT_CHANNEL||(exports.BANK_PAYOUT_CHANNEL={})).BANK="TZ-BANK-B2C";const Tr=t.z.enum(exports.PAYOUT_STATUS),Er=t.z.enum(exports.MOBILE_PAYOUT_CHANNEL),Nr=t.z.enum(exports.BANK_PAYOUT_CHANNEL),br=t.z.union([Er,Nr]),Sr=e=>{const t=Array.isArray(e)?e.flatMap(e=>Sr(e)):"string"==typeof e?e.split(","):[];return Array.from(new Set(t.map(e=>e.trim()).filter(e=>e.length>0)))},Ir=t.z.union([t.z.string(),t.z.array(t.z.string())]),wr={payout:t.z.object({id:t.z.string().min(1),statusCode:t.z.string(),statusCodeText:Tr,statusDescription:t.z.string(),countryCode:t.z.string(),serviceCode:br,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.iso.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.iso.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.iso.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.iso.datetime().optional(),endDate:t.z.iso.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:br.optional(),channelIn:t.z.array(br).optional(),status:Tr.optional(),statusIn:t.z.array(Tr).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:Ir.transform(Sr).optional(),ref:t.z.string().optional(),refIn:Ir.transform(Sr).optional(),channelRef:t.z.string().optional(),channelRefIn:Ir.transform(Sr).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:Ir.transform(Sr).pipe(t.z.array(br)).optional(),status:t.z.string().refine(e=>Object.values(exports.PAYOUT_STATUS).includes(e)).transform(e=>e).optional(),statusIn:Ir.transform(Sr).pipe(t.z.array(Tr)).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:Tr,payoutChannel:br,mobileChannel:Er,bankChannel:Nr,walletSummary:t.z.object({balance:t.z.number(),currency:t.z.string(),lastUpdated:t.z.iso.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()})},Cr=Et().router({getPayouts:{method:"GET",path:"",query:wr.payoutURLQueryParams,responses:{200:t.z.object({results:t.z.array(wr.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:wr.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"}}),Or={[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."}},xr={[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 Rr(e){return Object.values(exports.MOBILE_PAYOUT_CHANNEL).includes(e)}function Dr(e){return e===exports.BANK_PAYOUT_CHANNEL.BANK}class Pr{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(Or).filter(([e,t])=>"failed"===t.category).map(([e])=>e).includes(this.statusCodeText)}getStatusInfo(){return Or[this.statusCodeText]}getChannelInfo(){if(Rr(this.serviceCode))return xr[this.serviceCode];if(Dr(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(Rr(this.serviceCode))return this.msisdn;if(Dr(this.serviceCode)){return this.msisdn.split(":")[1]||this.msisdn}}catch{console.warn("failed to get the account number from payout msisdn: ",this.msisdn)}return this.msisdn}getProviderName(){const e=this.getChannelInfo();return Rr(this.serviceCode)&&e?e.networkOperator:r.Bank.is(e)?e.shortName:"Bank Transfer"}static from(e){try{const t=e;return t?.id&&t?.msisdn&&void 0!==t?.amount?new Pr(t):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=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 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 Pr(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=Pr.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 Lr=["status","channel","id","ref","channelRef"],kr=Object.fromEntries(Object.entries({status:"statusCodeText",channel:"serviceCode",id:"id",ref:"transactionRef",channelRef:"channelReference"}).map(([e,t])=>[t,e]));class zr extends Xt{static create(){return new zr}static fromFilters(e){return(new zr).applyFilters(e)}static fromUrlParams(e){try{const t=wr.payoutURLQueryParams.parse(zr.normalizeUrlParams(e)),r=wr.payoutFilters.parse(t);return zr.fromFilters(r)}catch{throw new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){return zr.fromUrlParams(zr.searchParamsToRecord(e))}static fromRequest(e){const{searchParams:t}=new URL(e.url);return zr.fromSearchParams(t)}static from(e){return null==e?new zr:Xt.is(e)?new zr(e.options):e instanceof URLSearchParams?zr.fromSearchParams(e):zr.isUrlParamsRecord(e)?zr.fromUrlParams(e):zr.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 Lr){const r=e,n=`${e}In`,a=`${e}:in`,s=`${e}[]`,i=`${e}In[]`,o=t[r],c=Sr([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=Sr(t.value);if(0===r.length)continue;e[`${kr[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=Sr(t);return 0===r.length?this:this.whereIn(e,r)}getValidStatuses(e){const t=Sr(e).filter(e=>this.isValidStatus(e));return t.length>0?t:void 0}getValidChannels(e){const t=Sr(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).some(t=>t===e)||e===exports.BANK_PAYOUT_CHANNEL.BANK}isValidStatus(e){return Object.values(exports.PAYOUT_STATUS).some(t=>t===e)}}var Fr,Ur,Mr,jr;exports.SETTLEMENT_STATUS=void 0,(Fr=exports.SETTLEMENT_STATUS||(exports.SETTLEMENT_STATUS={})).PENDING="PENDING",Fr.APPROVED="APPROVED",Fr.REJECTED="REJECTED",exports.SETTLEMENT_ACTION=void 0,(Ur=exports.SETTLEMENT_ACTION||(exports.SETTLEMENT_ACTION={})).APPROVED="APPROVED",Ur.REJECTED="REJECTED",exports.CREATE_SETTLEMENT_STATUS=void 0,(Mr=exports.CREATE_SETTLEMENT_STATUS||(exports.CREATE_SETTLEMENT_STATUS={})).SUCCESS="SUCCESS",Mr.WALLET_NOT_FOUND="WALLET_NOT_FOUND",Mr.INITIATOR_NOT_AUTHORIZED="INITIATOR_NOT_AUTHORIZED",Mr.MISSING_BANK_DETAILS="MISSING_BANK_DETAILS",Mr.UNSUPPORTED_BANK_CODE="UNSUPPORTED_BANK_CODE",Mr.FAILED="FAILED",exports.ACTION_SETTLEMENT_STATUS=void 0,(jr=exports.ACTION_SETTLEMENT_STATUS||(exports.ACTION_SETTLEMENT_STATUS={})).SUCCESS="SUCCESS",jr.SETTLEMENT_NOT_FOUND="SETTLEMENT_NOT_FOUND",jr.ACTIONER_NOT_AUTHORIZED="ACTIONER_NOT_AUTHORIZED",jr.SELF_ACTION_NOT_ALLOWED="SELF_ACTION_NOT_ALLOWED",jr.INVALID_STATE="INVALID_STATE",jr.FAILED="FAILED";const Br=t.z.enum(exports.SETTLEMENT_STATUS),Zr=t.z.enum(exports.SETTLEMENT_ACTION),Vr=t.z.enum(exports.CREATE_SETTLEMENT_STATUS),$r=t.z.enum(exports.ACTION_SETTLEMENT_STATUS),Jr=t.z.object({id:t.z.string().min(1),date:t.z.string(),initiatedAt:t.z.string().nullish(),initiatedById:t.z.string().nullish(),actionedAt:t.z.string().nullish(),actionedById:t.z.string().nullish(),vendorId:t.z.string(),walletId:t.z.string(),accountNo:t.z.string(),status:Br,statusCode:t.z.string().nullish(),description:t.z.string(),bankAccountNo:t.z.string().nullish(),bankAccountName:t.z.string().nullish(),bankCode:t.z.string().nullish(),amount:t.z.number(),payoutId:t.z.string().nullish(),transactionId:t.z.string().nullish(),createdAt:t.z.string(),updatedAt:t.z.string()}),qr=t.z.object({status:Br.optional(),accountNo:t.z.string().optional(),walletId:t.z.string().optional()}).catchall(t.z.union([t.z.string(),t.z.number()])),Yr=t.z.object({accountNo:t.z.string().min(1,"Account number is required"),description:t.z.string().min(1,"Description is required"),amount:t.z.number().refine(e=>0!==e,"Amount must not be 0")}),Hr=t.z.object({status:Vr,data:Jr.optional()}),Wr=t.z.object({status:Zr}),Gr=t.z.object({status:$r,data:Jr.optional()}),Kr={settlement:Jr,settlementStatus:Br,settlementAction:Zr,settlementFilters:qr,createSettlementRequest:Yr,createSettlementStatus:Vr,createSettlementResponse:Hr,actionSettlementRequest:Wr,actionSettlementStatus:$r,actionSettlementResponse:Gr},Qr=Et().router({getSettlements:{method:"GET",path:"",query:Kr.settlementFilters,responses:{200:t.z.array(Kr.settlement),401:Jt.unauthorizedError,403:Jt.forbiddenError,500:Jt.serverError},summary:"List settlements",description:"Retrieve settlements belonging to your vendor, with optional filtering and sorting via query params"},getSettlement:{method:"GET",path:"/:id",pathParams:t.z.object({id:t.z.string()}),responses:{200:Kr.settlement,401:Jt.unauthorizedError,403:Jt.forbiddenError,404:Jt.notFoundError,500:Jt.serverError},summary:"Get settlement details",description:"Retrieve detailed information about a specific settlement"},createSettlement:{method:"POST",path:"",body:Kr.createSettlementRequest,responses:{201:Kr.createSettlementResponse,400:Jt.validationError,401:Jt.unauthorizedError,403:Jt.forbiddenError,500:Jt.serverError},summary:"Create settlement",description:"Create a new settlement request initiated by the authenticated user. Expected failures (e.g. WALLET_NOT_FOUND) are reported via the body `status` field, not HTTP errors"},actionSettlement:{method:"POST",path:"/:id/action",pathParams:t.z.object({id:t.z.string()}),body:Kr.actionSettlementRequest,responses:{201:Kr.actionSettlementResponse,400:Jt.validationError,401:Jt.unauthorizedError,403:Jt.forbiddenError,500:Jt.serverError},summary:"Action settlement",description:"Approve or reject a PENDING settlement as the authenticated user. Expected failures (e.g. INVALID_STATE) are reported via the body `status` field, not HTTP errors"}}),Xr={[exports.SETTLEMENT_STATUS.PENDING]:{label:"Pending",description:"The settlement is awaiting approval",category:"pending",color:"warning",userFriendlyMessage:"Settlement is awaiting approval"},[exports.SETTLEMENT_STATUS.APPROVED]:{label:"Approved",description:"The settlement has been approved",category:"success",color:"success",userFriendlyMessage:"Settlement was approved"},[exports.SETTLEMENT_STATUS.REJECTED]:{label:"Rejected",description:"The settlement has been rejected",category:"failed",color:"error",userFriendlyMessage:"Settlement was rejected"}};function en(e){if(!e)return;const t=new Date(e);return Number.isNaN(t.getTime())?void 0:t}class tn{id;date;initiatedAt;initiatedById;actionedAt;actionedById;vendorId;walletId;accountNo;status;statusCode;description;bankAccountNo;bankAccountName;bankCode;amount;payoutId;transactionId;createdAt;updatedAt;_originalData;constructor(e){this._originalData={...e},this.id=e.id,this.date=new Date(e.date),this.initiatedAt=en(e.initiatedAt),this.initiatedById=e.initiatedById,this.actionedAt=en(e.actionedAt),this.actionedById=e.actionedById,this.vendorId=e.vendorId,this.walletId=e.walletId,this.accountNo=e.accountNo,this.status=e.status,this.statusCode=e.statusCode,this.description=e.description,this.bankAccountNo=e.bankAccountNo,this.bankAccountName=e.bankAccountName,this.bankCode=e.bankCode,this.amount=r.Amount.from(e.amount,"TZS")??r.Amount.from(0,"TZS"),this.payoutId=e.payoutId,this.transactionId=e.transactionId,this.createdAt=new Date(e.createdAt),this.updatedAt=new Date(e.updatedAt)}getOriginalData(){return this._originalData}isPending(){return this.status===exports.SETTLEMENT_STATUS.PENDING}isApproved(){return this.status===exports.SETTLEMENT_STATUS.APPROVED}isRejected(){return this.status===exports.SETTLEMENT_STATUS.REJECTED}canBeActioned(){return this.isPending()}getStatusInfo(){return Xr[this.status]}static from(e){try{const t=e;return t?.id&&t?.accountNo&&void 0!==t?.amount?new tn(t):void console.error("Missing required Settlement fields:",e)}catch(e){return void console.error("Error creating Settlement:",e)}}static createMany(e){const t=[];for(const r of e){const e=tn.from(r);e&&t.push(e)}return t}static fromJSON(e){return tn.from(e)}toJSON(){return{...this._originalData}}}const rn={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()})},nn=Et().router({localTransfer:{method:"POST",path:"/local-transfer",body:rn.localTransferRequest,responses:{201:rn.localTransferResponse,400:Jt.validationError,401:Jt.unauthorizedError,404:Jt.notFoundError,500:Jt.serverError},summary:"Local transfer",description:"Transfer funds locally between wallets."}});const an={vendor:t.z.object({businessName:t.z.string(),tradeName:t.z.string(),enableCollections:t.z.number(),enablePayouts:t.z.number(),enableRemittance:t.z.number(),bankAccountNo:t.z.string().nullish(),bankAccountName:t.z.string().nullish(),bankCode:t.z.string().nullish(),enableAutoSettlement:t.z.number(),disablePaymentApproval:t.z.number()})},sn=Et().router({getMe:{method:"GET",path:"/me",responses:{200:an.vendor,401:Jt.unauthorizedError,403:Jt.forbiddenError,500:Jt.serverError},summary:"Get vendor profile",description:"Retrieve the vendor profile of the authenticated user, including feature flags and bank details"}});class on{businessName;tradeName;enableCollections;enablePayouts;enableRemittance;bankAccountNo;bankAccountName;bankCode;enableAutoSettlement;disablePaymentApproval;constructor(e){this.businessName=e.businessName,this.tradeName=e.tradeName,this.enableCollections=e.enableCollections,this.enablePayouts=e.enablePayouts,this.enableRemittance=e.enableRemittance,this.bankAccountNo=e.bankAccountNo,this.bankAccountName=e.bankAccountName,this.bankCode=e.bankCode,this.enableAutoSettlement=e.enableAutoSettlement,this.disablePaymentApproval=e.disablePaymentApproval}isCollectionsEnabled(){return 1===this.enableCollections}isPayoutsEnabled(){return 1===this.enablePayouts}isRemittanceEnabled(){return 1===this.enableRemittance}isAutoSettlementEnabled(){return 1===this.enableAutoSettlement}requiresPaymentApproval(){return 1!==this.disablePaymentApproval}hasBankDetails(){return Boolean(this.bankAccountNo&&this.bankCode)}getDisplayName(){return this.tradeName||this.businessName}static from(e){try{const t=e;return t?.businessName?new on(t):void console.error("Missing required Vendor fields:",e)}catch(e){return void console.error("Error creating Vendor:",e)}}static fromJson(e){return new on(e)}toJson(){return{businessName:this.businessName,tradeName:this.tradeName,enableCollections:this.enableCollections,enablePayouts:this.enablePayouts,enableRemittance:this.enableRemittance,bankAccountNo:this.bankAccountNo,bankAccountName:this.bankAccountName,bankCode:this.bankCode,enableAutoSettlement:this.enableAutoSettlement,disablePaymentApproval:this.disablePaymentApproval}}}var cn;exports.WALLET_TYPE=void 0,(cn=exports.WALLET_TYPE||(exports.WALLET_TYPE={})).COLLECTION="COLLECTION",cn.DISBURSEMENT="DISBURSEMENT";const un=t.z.enum(exports.WALLET_TYPE),dn=t.z.enum(["Vendor","DEFAULT DISBURSEMENT","DEFAULT COLLECTION","COLLECTION","DISBURSEMENT"]).transform(e=>"DEFAULT COLLECTION"===e||"COLLECTION"===e?exports.WALLET_TYPE.COLLECTION:exports.WALLET_TYPE.DISBURSEMENT),ln=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:dn,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)}),hn=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)}),mn={wallet:ln,walletType:un,walletPathParams:t.z.object({accountNo:t.z.string().min(1)}),walletBalance:hn,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}$/)})},pn=Et().router({listWallets:{method:"GET",path:"",responses:{200:t.z.array(mn.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:mn.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:mn.walletPathParams,responses:{200:mn.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:mn.walletPathParams,query:mn.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 fn{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===exports.WALLET_TYPE.COLLECTION}isDisbursementWallet(){return this.type===exports.WALLET_TYPE.DISBURSEMENT}isDefaultWallet(){return!1}static from(e){return new fn(e)}static createMany(e){const t=[];try{for(const r of e)t.push(fn.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 fn({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=nr,exports.AuthRepository=class extends qt{constructor(e){super("auth",ar,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=sr.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=qt,exports.COLLECTION_STATUS_INFO=pr,exports.Collection=yr,exports.CollectionDTOSchemas=hr,exports.CollectionQuery=vr,exports.CollectionRepository=class extends qt{constructor(e){super("collection",mr,e)}async getCollections(e){try{const t=vr.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=yr.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=vr.fromRequest(e);return this.getCollections(t)}async getCollection(e){const t=await this.client.getCollection({params:{id:e}}),r=this.handleResponse(t,200),n=yr.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=Or,exports.Payout=Pr,exports.PayoutDTOSchemas=wr,exports.PayoutQuery=zr,exports.PayoutRepository=class extends qt{constructor(e){super("payout",Cr,e)}async getPayouts(e){try{const t=zr.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=Pr.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=zr.fromRequest(e);return this.getPayouts(t)}async getPayout(e){const t=await this.client.getPayout({params:{id:e}}),r=this.handleResponse(t,200),n=Pr.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.SETTLEMENT_STATUS_INFO=Xr,exports.Settlement=tn,exports.SettlementDTOSchemas=Kr,exports.SettlementRepository=class extends qt{constructor(e){super("settlement",Qr,e)}async getSettlements(e){const t=await this.client.getSettlements({query:e??{}}),r=this.handleResponse(t,200);return tn.createMany(r)}async getSettlement(e){const t=await this.client.getSettlement({params:{id:e}}),r=this.handleResponse(t,200),n=tn.from(r);if(!n)throw new Error("Invalid settlement data received from server");return n}async createSettlement(e){const t=await this.client.createSettlement({body:e}),r=this.handleResponse(t,201);return{status:r.status,settlement:r.data?tn.from(r.data):void 0}}async actionSettlement(e,t){const r=await this.client.actionSettlement({params:{id:e},body:{status:t}}),n=this.handleResponse(r,201);return{status:n.status,settlement:n.data?tn.from(n.data):void 0}}async approveSettlement(e){return this.actionSettlement(e,exports.SETTLEMENT_ACTION.APPROVED)}async rejectSettlement(e){return this.actionSettlement(e,exports.SETTLEMENT_ACTION.REJECTED)}},exports.StatementEntry=Yt,exports.TransactionDTOSchemas=rn,exports.TransactionRepository=class extends qt{constructor(e){super("transaction",nn,e)}async localTransfer(e){const t=await this.client.localTransfer({body:e});return this.handleResponse(t,201)}},exports.TransactionSummary=Ht,exports.User=sr,exports.Vendor=on,exports.VendorDTOSchemas=an,exports.VendorRepository=class extends qt{constructor(e){super("vendor",sn,e)}async getMe(){const e=await this.client.getMe(),t=this.handleResponse(e,200),r=on.from(t);if(!r)throw new Error("Invalid vendor data received from server");return r}},exports.Wallet=fn,exports.WalletDTOSchemas=mn,exports.WalletInfo=Wt,exports.WalletRepository=class extends qt{constructor(e){super("wallet",pn,e)}async listWallets(){const e=await this.client.listWallets(),t=this.handleResponse(e,200),r=fn.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 fn.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=Yt.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=ar,exports.collectionContract=mr,exports.collectionToStringArray=dr,exports.payoutContract=Cr,exports.payoutToStringArray=Sr,exports.settlementContract=Qr,exports.statementEntrySchema=$t,exports.transactionContract=nn,exports.vendorContract=sn,exports.walletContract=pn;
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}),A=e=>({status:"valid",value:e}),_=e=>"aborted"===e.status,T=e=>"dirty"===e.status,N=e=>"valid"===e.status,E=e=>"undefined"!=typeof Promise&&e instanceof Promise;var S;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:null==e?void 0:e.message}(S||(S={}));class I{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 b=(e,t)=>{if(N(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 w(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 O{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(E(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 b(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(E(n)?n:Promise.resolve(n));return b(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:Ce.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return ve.create(this,this._def)}nullable(){return Ae.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({...w(this._def),schema:this,typeName:Ce.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new _e({...w(this._def),innerType:this,defaultValue:t,typeName:Ce.ZodDefault})}brand(){return new Se({typeName:Ce.ZodBranded,type:this,...w(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Te({...w(this._def),innerType:this,catchValue:t,typeName:Ce.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Ie.create(this,e)}readonly(){return be.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const C=/^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}))$/,z=/^(([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})))$/,F=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||!z.test(e))}class M extends O{constructor(){super(...arguments),this._regex=(e,t,r)=>this.refinement(t=>e.test(t),{validation:t,code:u.invalid_string,...S.errToObj(r)}),this.nonempty=e=>this.min(1,S.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)C.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){F(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",...S.errToObj(e)})}url(e){return this._addCheck({kind:"url",...S.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...S.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...S.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...S.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...S.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...S.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...S.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,...S.errToObj(null==e?void 0:e.message)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...S.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:null==t?void 0:t.position,...S.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...S.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...S.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...S.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...S.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...S.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:Ce.ZodString,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...w(e)})};class B extends O{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,S.toString(t))}gt(e,t){return this.setLimit("min",e,!1,S.toString(t))}lte(e,t){return this.setLimit("max",e,!0,S.toString(t))}lt(e,t){return this.setLimit("max",e,!1,S.toString(t))}setLimit(e,t,r,n){return new B({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:S.toString(n)}]})}_addCheck(e){return new B({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:S.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:S.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:S.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:S.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:S.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:S.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:S.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:S.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:S.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)}}B.create=e=>new B({checks:[],typeName:Ce.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...w(e)});class Z extends O{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,S.toString(t))}gt(e,t){return this.setLimit("min",e,!1,S.toString(t))}lte(e,t){return this.setLimit("max",e,!0,S.toString(t))}lt(e,t){return this.setLimit("max",e,!1,S.toString(t))}setLimit(e,t,r,n){return new Z({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:S.toString(n)}]})}_addCheck(e){return new Z({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:S.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:S.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:S.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:S.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:S.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}}Z.create=e=>{var t;return new Z({checks:[],typeName:Ce.ZodBigInt,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...w(e)})};class V extends O{_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 A(e.data)}}V.create=e=>new V({typeName:Ce.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...w(e)});class $ extends O{_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 $({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:S.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:S.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}}$.create=e=>new $({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:Ce.ZodDate,...w(e)});class J extends O{_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 A(e.data)}}J.create=e=>new J({typeName:Ce.ZodSymbol,...w(e)});class q extends O{_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 A(e.data)}}q.create=e=>new q({typeName:Ce.ZodUndefined,...w(e)});class Y extends O{_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 A(e.data)}}Y.create=e=>new Y({typeName:Ce.ZodNull,...w(e)});class W extends O{constructor(){super(...arguments),this._any=!0}_parse(e){return A(e.data)}}W.create=e=>new W({typeName:Ce.ZodAny,...w(e)});class H extends O{constructor(){super(...arguments),this._unknown=!0}_parse(e){return A(e.data)}}H.create=e=>new H({typeName:Ce.ZodUnknown,...w(e)});class G extends O{_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:Ce.ZodNever,...w(e)});class K extends O{_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 A(e.data)}}K.create=e=>new K({typeName:Ce.ZodVoid,...w(e)});class Q extends O{_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 I(t,e,t.path,r)))).then(e=>y.mergeArray(r,e));const a=[...t.data].map((e,r)=>n.type._parseSync(new I(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:S.toString(t)}})}max(e,t){return new Q({...this._def,maxLength:{value:e,message:S.toString(t)}})}length(e,t){return new Q({...this._def,exactLength:{value:e,message:S.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 Ae?Ae.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:Ce.ZodArray,...w(t)});class ee extends O{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 I(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 I(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 S.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=S.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:Ce.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:Ce.ZodObject,...w(t)}),ee.strictCreate=(e,t)=>new ee({shape:()=>e,unknownKeys:"strict",catchall:G.create(),typeName:Ce.ZodObject,...w(t)}),ee.lazycreate=(e,t)=>new ee({shape:e,unknownKeys:"strip",catchall:G.create(),typeName:Ce.ZodObject,...w(t)});class te extends O{_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:Ce.ZodUnion,...w(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 _e?re(e._def.innerType):e instanceof q?[void 0]:e instanceof Y?[null]:null;class ne extends O{_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:Ce.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...w(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 O{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=(e,n)=>{if(_(e)||_(n))return g;const a=ae(e.value,n.value);return a.valid?((T(e)||T(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:Ce.ZodIntersection,...w(r)});class ie extends O{_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 I(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:Ce.ZodTuple,rest:null,...w(t)})};class oe extends O{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 I(r,e,r.path,e)),value:s._parse(new I(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 O?{keyType:e,valueType:t,typeName:Ce.ZodRecord,...w(r)}:{keyType:M.create(),valueType:e,typeName:Ce.ZodRecord,...w(t)})}}class ce extends O{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 I(r,e,r.path,[s,"key"])),value:a._parse(new I(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:Ce.ZodMap,...w(r)});class ue extends O{_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 I(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:S.toString(t)}})}max(e,t){return new ue({...this._def,maxSize:{value:e,message:S.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:Ce.ZodSet,...w(t)});class de extends O{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 A(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 A(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(H.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(H.create()),returns:t||H.create(),typeName:Ce.ZodFunction,...w(r)})}}class le extends O{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:Ce.ZodLazy,...w(t)});class he extends O{_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:Ce.ZodEnum,...w(t)})}he.create=(e,t)=>new he({value:e,typeName:Ce.ZodLiteral,...w(t)});class pe extends O{_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 A(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 O{_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 A(e.data)}get enum(){return this._def.values}}fe.create=(e,t)=>new fe({values:e,typeName:Ce.ZodNativeEnum,...w(t)});class ye extends O{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 A(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}ye.create=(e,t)=>new ye({type:e,typeName:Ce.ZodPromise,...w(t)});class ge extends O{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Ce.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(!N(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=>N(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:Ce.ZodEffects,effect:t,...w(r)}),ge.createWithPreprocess=(e,t,r)=>new ge({schema:t,effect:{type:"preprocess",transform:e},typeName:Ce.ZodEffects,...w(r)});class ve extends O{_parse(e){return this._getType(e)===o.undefined?A(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ve.create=(e,t)=>new ve({innerType:e,typeName:Ce.ZodOptional,...w(t)});class Ae extends O{_parse(e){return this._getType(e)===o.null?A(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ae.create=(e,t)=>new Ae({innerType:e,typeName:Ce.ZodNullable,...w(t)});class _e extends O{_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}}_e.create=(e,t)=>new _e({innerType:e,typeName:Ce.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...w(t)});class Te extends O{_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 E(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}}Te.create=(e,t)=>new Te({innerType:e,typeName:Ce.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...w(t)});class Ne extends O{_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}}}Ne.create=e=>new Ne({typeName:Ce.ZodNaN,...w(e)});const Ee=Symbol("zod_brand");class Se extends O{_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 Ie extends O{_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 Ie({in:e,out:t,typeName:Ce.ZodPipeline})}}class be extends O{_parse(e){const t=this._def.innerType._parse(e);return N(t)&&(t.value=Object.freeze(t.value)),t}}be.create=(e,t)=>new be({innerType:e,typeName:Ce.ZodReadonly,...w(t)});const we=(e,t={},r)=>e?W.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})}}):W.create(),Oe={object:ee.lazycreate};var Ce;!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"}(Ce||(Ce={}));const xe=M.create,Re=B.create,De=Ne.create,Pe=Z.create,Le=V.create,ke=$.create,ze=J.create,Fe=q.create,Ue=Y.create,Me=W.create,je=H.create,Be=G.create,Ze=K.create,Ve=Q.create,$e=ee.create,Je=ee.strictCreate,qe=te.create,Ye=ne.create,We=se.create,He=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=Ae.create,ct=ge.createWithPreprocess,ut=Ie.create,dt={string:e=>M.create({...e,coerce:!0}),number:e=>B.create({...e,coerce:!0}),boolean:e=>V.create({...e,coerce:!0}),bigint:e=>Z.create({...e,coerce:!0}),date:e=>$.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:A,isAborted:_,isDirty:T,isValid:N,isAsync:E,get util(){return a},get objectUtil(){return s},ZodParsedType:o,getParsedType:c,ZodType:O,ZodString:M,ZodNumber:B,ZodBigInt:Z,ZodBoolean:V,ZodDate:$,ZodSymbol:J,ZodUndefined:q,ZodNull:Y,ZodAny:W,ZodUnknown:H,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:Ae,ZodDefault:_e,ZodCatch:Te,ZodNaN:Ne,BRAND:Ee,ZodBranded:Se,ZodPipeline:Ie,ZodReadonly:be,custom:we,Schema:O,ZodSchema:O,late:Oe,get ZodFirstPartyTypeKind(){return Ce},coerce:dt,any:Me,array:Ve,bigint:Pe,boolean:Le,date:ke,discriminatedUnion:Ye,effect:st,enum:rt,function:Xe,instanceof:(e,t={message:`Input not instance of ${e.name}`})=>we(t=>t instanceof e,t),intersection:We,lazy:et,literal:tt,map:Ke,nan:De,nativeEnum:nt,never:Be,null:Ue,nullable:ot,number:Re,object:$e,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:ze,transformer:st,tuple:He,undefined:Fe,union:qe,unknown:je,void:Ze,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"),At=e=>"method"in e&&"path"in e,_t=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>{var n,a,s;return At(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,_t(r,t)]})),Tt=Symbol("ContractPlainType"),Nt=()=>({router:(e,t)=>_t(e,t),query:e=>e,mutation:e=>e,responses:e=>e,response:()=>Tt,body:()=>Tt,type:()=>Tt,otherResponse:({contentType:e,body:t})=>({contentType:e,body:t}),noBody:()=>vt}),Et=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("&"):"",St=e=>e?Object.keys(e).flatMap(t=>It(t,e[t])).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",It=(e,t)=>Array.isArray(t)?t.flatMap((t,r)=>It(`${e}[${r}]`,t)):t instanceof Date?[[`${e}`,t.toISOString()]]:null===t?[[`${e}`,""]]:void 0===t?[]:"object"==typeof t?Object.keys(t).flatMap(r=>It(`${e}[${r}]`,t[r])):[[`${e}`,`${t}`]];class bt extends Error{constructor(e,t){super(`Server returned unexpected response. Expected one of: ${t.join(",")} got: ${e.status}`),this.response=e}}const wt=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}},Ot=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},Ct=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?Et(e):St(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||wt,d=r.baseHeaders&&Object.fromEntries(Object.entries(r.baseHeaders).map(([t,r])=>"function"==typeof r?[t,r(e)]:[t,r])),l={...d&&Ct(d),...Ct(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:Ot(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 bt(s,r)}},Dt=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,r])=>At(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)}),zt=Lt.extend({statusCode:i.default.literal(401)}),Ft=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()}),Bt=i.default.object({balance:i.default.number(),availableBalance:i.default.number(),accountNumber:i.default.string(),accountName:i.default.string()}),Zt=i.default.object({yesterday:i.default.number(),today:i.default.number(),thisMonth:i.default.number(),lastMonth:i.default.number()});const Vt=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"}`)}}),$t=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:Vt,valueDate:Vt,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(Number.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(Number.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:zt,forbiddenError:Ft,notFoundError:Ut,serverError:Mt,pagination:jt,transactionSummary:Zt,walletSummary:Bt,statementEntry:$t};class qt{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 Yt{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 Number.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 Jt.statementEntry.safeParse(e).success?new Yt(e,t):void console.error("Missing required StatementEntry fields:",e)}catch(e){return void console.error("Error creating StatementEntry:",e)}}static createMany(e,t="TZS"){const r=[];for(const n of e){const e=Yt.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 Yt(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=Yt.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=Yt.getTotalCredits(e).numericValue,a=Yt.getTotalDebits(e).numericValue;return r.Amount.from(n-a,t)??r.Amount.from(0,t)}}class Wt{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 Wt(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 Wt(i,e.currency)}catch(e){return void console.error("Error creating TransactionSummary from JSON:",e)}}}class Ht{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 Ht(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 Ht(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=Ht.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"}};var tr;exports.USER_ROLE=void 0,(tr=exports.USER_ROLE||(exports.USER_ROLE={})).READ_ONLY="ReadOnly",tr.ADMIN="Admin",tr.INITIATOR="Initiator",tr.APPROVER="Approver";const rr=t.z.enum(exports.USER_ROLE),nr={user:t.z.object({token:t.z.string(),identity:t.z.string(),name:t.z.string(),role:rr}),userRole:rr,loginRequest:t.z.object({identity:t.z.email(),password:t.z.string()}),updatePassword:t.z.object({currentPassword:t.z.string(),newPassword:t.z.string()})},ar=Nt().router({login:{method:"POST",path:"/login",body:nr.loginRequest,responses:{201:nr.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:nr.updatePassword,responses:{201:i.default.object({}),400:Jt.validationError,401:Jt.unauthorizedError,500:Jt.serverError},summary:"Update password",description:"Update user password"}});class sr{identity;name;role;constructor(e){this.identity=e.identity,this.name=e.name,this.role=e.role}static from(e){return new sr(e)}static fromJSON(e){return sr.from(e)}toJSON(){return{identity:this.identity,name:this.name,role:this.role}}get email(){return this.identity}getDisplayName(){return this.name||this.identity}hasRole(e){return this.role===e}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&&this.role===e.role}}var ir,or;exports.COLLECTION_STATUS=void 0,(ir=exports.COLLECTION_STATUS||(exports.COLLECTION_STATUS={})).PAYMENT_ACCEPTED="PAYMENT_ACCEPTED",ir.GENERIC_FAILURE="GENERIC_FAILURE",ir.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",ir.PAYMENT_REJECTED="PAYMENT_REJECTED",ir.PENDING_ACK="PENDING_ACK",ir.PROVIDER_FAILED="PROVIDER_FAILED",exports.COLLECTION_CHANNEL=void 0,(or=exports.COLLECTION_CHANNEL||(exports.COLLECTION_CHANNEL={})).AIRTEL="TZ-AIRTEL-C2B",or.TIGO="TZ-TIGO-C2B",or.HALOTEL="TZ-HALOTEL-C2B",or.SAFARICOM="KE-SAFARICOM-C2B",or.VODACOM="TZ-VODACOM-C2B";const cr=t.z.enum(exports.COLLECTION_STATUS),ur=t.z.enum(exports.COLLECTION_CHANNEL),dr=e=>{const t=Array.isArray(e)?e.flatMap(e=>dr(e)):"string"==typeof e?e.split(","):[];return Array.from(new Set(t.map(e=>e.trim()).filter(e=>e.length>0)))},lr=t.z.union([t.z.string(),t.z.array(t.z.string())]),hr={collection:t.z.object({id:t.z.string().min(1),status:cr,statusMessage:t.z.string(),accountNo:t.z.string().min(1),walletId:t.z.string(),transactionDate:t.z.iso.datetime(),narration:t.z.string(),msisdn:t.z.string().min(1),channel:ur,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.iso.datetime().nullable().optional(),createdAt:t.z.iso.datetime(),updatedAt:t.z.iso.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(5e4).default(20),sortBy:t.z.string().default("createdAt"),sortOrder:t.z.enum(["asc","desc"]).default("desc"),startDate:t.z.iso.datetime().optional(),endDate:t.z.iso.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:ur.optional(),channelIn:t.z.array(ur).optional(),status:cr.optional(),statusIn:t.z.array(cr).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:lr.transform(dr).optional(),reference:t.z.string().optional(),referenceIn:lr.transform(dr).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:lr.transform(dr).pipe(t.z.array(ur)).optional(),status:t.z.string().refine(e=>Object.values(exports.COLLECTION_STATUS).includes(e)).transform(e=>e).optional(),statusIn:lr.transform(dr).pipe(t.z.array(cr)).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:cr,paymentChannel:ur},mr=Nt().router({getCollections:{method:"GET",path:"/",query:hr.collectionURLQueryParams,responses:{200:t.z.object({results:t.z.array(hr.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:hr.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"}}),pr={[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"}},fr={[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 yr{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(pr).filter(([e,t])=>"failed"===t.category).map(([e])=>e).includes(this.status)}getStatusInfo(){return pr[this.status]}getChannelInfo(){return fr[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{const t=e;return t?.id&&t?.msisdn&&void 0!==t?.amount?new yr(t):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=yr.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 yr(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=yr.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 gr=["id","reference","channel","status"];class vr extends Xt{static create(){return new vr}static fromFilters(e){return(new vr).applyFilters(e)}static fromUrlParams(e){try{const t=hr.collectionURLQueryParams.parse(vr.normalizeUrlParams(e)),r=hr.collectionFilters.parse(t);return vr.fromFilters(r)}catch(e){throw console.log(e),new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){return vr.fromUrlParams(vr.searchParamsToRecord(e))}static fromRequest(e){const{searchParams:t}=new URL(e.url);return vr.fromSearchParams(t)}static from(e){try{return null==e?new vr:Xt.is(e)?new vr(e.options):e instanceof URLSearchParams?vr.fromSearchParams(e):vr.isUrlParamsRecord(e)?vr.fromUrlParams(e):vr.fromFilters(e)}catch(e){throw console.log(e),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 gr){const r=e,n=`${e}In`,a=`${e}:in`,s=`${e}[]`,i=`${e}In[]`,o=t[r],c=dr([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=dr(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=dr(t);return 0===r.length?this:this.whereIn(e,r)}getValidStatuses(e){const t=dr(e).filter(e=>this.isValidStatus(e));return t.length>0?t:void 0}getValidChannels(e){const t=dr(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).some(t=>t===e)}isValidStatus(e){return Object.values(exports.COLLECTION_STATUS).some(t=>t===e)}}var Ar,_r;exports.PAYOUT_STATUS=void 0,(Ar=exports.PAYOUT_STATUS||(exports.PAYOUT_STATUS={})).PAYMENT_ACCEPTED="PAYMENT_ACCEPTED",Ar.GENERIC_FAILURE="GENERIC_FAILURE",Ar.WALLET_DEBITED="WALLET_DEBITED",Ar.PAYMENT_REJECTED="PAYMENT_REJECTED",Ar.PENDING="PENDING",Ar.AMOUNT_EXCEED_MAXIMUM="AMOUNT_EXCEED_MAXIMUM",Ar.PENDING_ACK="PENDING_ACK",Ar.REVERSED="REVERSED",Ar.INVALID_SERVICE="INVALID_SERVICE",Ar.INVALID_NUMBER="INVALID_NUMBER",Ar.INSUFFICIENT_BALANCE="INSUFFICIENT_BALANCE",Ar.THIRDPARTY_FAILED="THIRDPARTY_FAILED",Ar.PROVIDER_FAILED="PROVIDER_FAILED",exports.MOBILE_PAYOUT_CHANNEL=void 0,(_r=exports.MOBILE_PAYOUT_CHANNEL||(exports.MOBILE_PAYOUT_CHANNEL={})).AIRTEL="TZ-AIRTEL-B2C",_r.VODACOM="TZ-VODACOM-B2C",_r.TIGO="TZ-TIGO-B2C",_r.HALOTEL="TZ-HALOTEL-B2C",_r.SAFARICOM="TZ-SAFARICOM-B2C",exports.BANK_PAYOUT_CHANNEL=void 0,(exports.BANK_PAYOUT_CHANNEL||(exports.BANK_PAYOUT_CHANNEL={})).BANK="TZ-BANK-B2C";const Tr=t.z.enum(exports.PAYOUT_STATUS),Nr=t.z.enum(exports.MOBILE_PAYOUT_CHANNEL),Er=t.z.enum(exports.BANK_PAYOUT_CHANNEL),Sr=t.z.union([Nr,Er]),Ir=e=>{const t=Array.isArray(e)?e.flatMap(e=>Ir(e)):"string"==typeof e?e.split(","):[];return Array.from(new Set(t.map(e=>e.trim()).filter(e=>e.length>0)))},br=t.z.union([t.z.string(),t.z.array(t.z.string())]),wr={payout:t.z.object({id:t.z.string().min(1),statusCode:t.z.string(),statusCodeText:Tr,statusDescription:t.z.string(),countryCode:t.z.string(),serviceCode:Sr,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.iso.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.iso.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.iso.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.iso.datetime().optional(),endDate:t.z.iso.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:Sr.optional(),channelIn:t.z.array(Sr).optional(),status:Tr.optional(),statusIn:t.z.array(Tr).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:br.transform(Ir).optional(),ref:t.z.string().optional(),refIn:br.transform(Ir).optional(),channelRef:t.z.string().optional(),channelRefIn:br.transform(Ir).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:br.transform(Ir).pipe(t.z.array(Sr)).optional(),status:t.z.string().refine(e=>Object.values(exports.PAYOUT_STATUS).includes(e)).transform(e=>e).optional(),statusIn:br.transform(Ir).pipe(t.z.array(Tr)).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:Tr,payoutChannel:Sr,mobileChannel:Nr,bankChannel:Er,walletSummary:t.z.object({balance:t.z.number(),currency:t.z.string(),lastUpdated:t.z.iso.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()})},Or=Nt().router({getPayouts:{method:"GET",path:"",query:wr.payoutURLQueryParams,responses:{200:t.z.object({results:t.z.array(wr.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:wr.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."}},xr={[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 Rr(e){return Object.values(exports.MOBILE_PAYOUT_CHANNEL).includes(e)}function Dr(e){return e===exports.BANK_PAYOUT_CHANNEL.BANK}class Pr{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(Rr(this.serviceCode))return xr[this.serviceCode];if(Dr(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(Rr(this.serviceCode))return this.msisdn;if(Dr(this.serviceCode)){return this.msisdn.split(":")[1]||this.msisdn}}catch{console.warn("failed to get the account number from payout msisdn: ",this.msisdn)}return this.msisdn}getProviderName(){const e=this.getChannelInfo();return Rr(this.serviceCode)&&e?e.networkOperator:r.Bank.is(e)?e.shortName:"Bank Transfer"}static from(e){try{const t=e;return t?.id&&t?.msisdn&&void 0!==t?.amount?new Pr(t):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=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 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 Pr(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=Pr.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 Lr=["status","channel","id","ref","channelRef"],kr=Object.fromEntries(Object.entries({status:"statusCodeText",channel:"serviceCode",id:"id",ref:"transactionRef",channelRef:"channelReference"}).map(([e,t])=>[t,e]));class zr extends Xt{static create(){return new zr}static fromFilters(e){return(new zr).applyFilters(e)}static fromUrlParams(e){try{const t=wr.payoutURLQueryParams.parse(zr.normalizeUrlParams(e)),r=wr.payoutFilters.parse(t);return zr.fromFilters(r)}catch{throw new Error("Invalid URL parameters. Please check your query string values.")}}static fromSearchParams(e){return zr.fromUrlParams(zr.searchParamsToRecord(e))}static fromRequest(e){const{searchParams:t}=new URL(e.url);return zr.fromSearchParams(t)}static from(e){return null==e?new zr:Xt.is(e)?new zr(e.options):e instanceof URLSearchParams?zr.fromSearchParams(e):zr.isUrlParamsRecord(e)?zr.fromUrlParams(e):zr.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 Lr){const r=e,n=`${e}In`,a=`${e}:in`,s=`${e}[]`,i=`${e}In[]`,o=t[r],c=Ir([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=Ir(t.value);if(0===r.length)continue;e[`${kr[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=Ir(t);return 0===r.length?this:this.whereIn(e,r)}getValidStatuses(e){const t=Ir(e).filter(e=>this.isValidStatus(e));return t.length>0?t:void 0}getValidChannels(e){const t=Ir(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).some(t=>t===e)||e===exports.BANK_PAYOUT_CHANNEL.BANK}isValidStatus(e){return Object.values(exports.PAYOUT_STATUS).some(t=>t===e)}}var Fr,Ur,Mr,jr;exports.SETTLEMENT_STATUS=void 0,(Fr=exports.SETTLEMENT_STATUS||(exports.SETTLEMENT_STATUS={})).PENDING="PENDING",Fr.APPROVED="APPROVED",Fr.REJECTED="REJECTED",exports.SETTLEMENT_ACTION=void 0,(Ur=exports.SETTLEMENT_ACTION||(exports.SETTLEMENT_ACTION={})).APPROVED="APPROVED",Ur.REJECTED="REJECTED",exports.CREATE_SETTLEMENT_STATUS=void 0,(Mr=exports.CREATE_SETTLEMENT_STATUS||(exports.CREATE_SETTLEMENT_STATUS={})).SUCCESS="SUCCESS",Mr.WALLET_NOT_FOUND="WALLET_NOT_FOUND",Mr.INITIATOR_NOT_AUTHORIZED="INITIATOR_NOT_AUTHORIZED",Mr.MISSING_BANK_DETAILS="MISSING_BANK_DETAILS",Mr.UNSUPPORTED_BANK_CODE="UNSUPPORTED_BANK_CODE",Mr.FAILED="FAILED",exports.ACTION_SETTLEMENT_STATUS=void 0,(jr=exports.ACTION_SETTLEMENT_STATUS||(exports.ACTION_SETTLEMENT_STATUS={})).SUCCESS="SUCCESS",jr.SETTLEMENT_NOT_FOUND="SETTLEMENT_NOT_FOUND",jr.ACTIONER_NOT_AUTHORIZED="ACTIONER_NOT_AUTHORIZED",jr.SELF_ACTION_NOT_ALLOWED="SELF_ACTION_NOT_ALLOWED",jr.INVALID_STATE="INVALID_STATE",jr.FAILED="FAILED";const Br=t.z.enum(exports.SETTLEMENT_STATUS),Zr=t.z.enum(exports.SETTLEMENT_ACTION),Vr=t.z.enum(exports.CREATE_SETTLEMENT_STATUS),$r=t.z.enum(exports.ACTION_SETTLEMENT_STATUS),Jr=t.z.object({id:t.z.string().min(1),date:t.z.string(),initiatedAt:t.z.string().nullish(),initiatedById:t.z.string().nullish(),actionedAt:t.z.string().nullish(),actionedById:t.z.string().nullish(),vendorId:t.z.string(),walletId:t.z.string(),accountNo:t.z.string(),status:Br,statusCode:t.z.string().nullish(),description:t.z.string(),bankAccountNo:t.z.string().nullish(),bankAccountName:t.z.string().nullish(),bankCode:t.z.string().nullish(),amount:t.z.number(),payoutId:t.z.string().nullish(),transactionId:t.z.string().nullish(),createdAt:t.z.string(),updatedAt:t.z.string()}),qr=t.z.object({status:Br.optional(),accountNo:t.z.string().optional(),walletId:t.z.string().optional()}).catchall(t.z.union([t.z.string(),t.z.number()])),Yr=t.z.object({accountNo:t.z.string().min(1,"Account number is required"),description:t.z.string().min(1,"Description is required"),amount:t.z.number().refine(e=>0!==e,"Amount must not be 0")}),Wr=t.z.object({status:Vr,data:Jr.optional()}),Hr=t.z.object({status:Zr}),Gr=t.z.object({status:$r,data:Jr.optional()}),Kr={settlement:Jr,settlementStatus:Br,settlementAction:Zr,settlementFilters:qr,createSettlementRequest:Yr,createSettlementStatus:Vr,createSettlementResponse:Wr,actionSettlementRequest:Hr,actionSettlementStatus:$r,actionSettlementResponse:Gr},Qr=Nt().router({getSettlements:{method:"GET",path:"",query:Kr.settlementFilters,responses:{200:t.z.array(Kr.settlement),401:Jt.unauthorizedError,403:Jt.forbiddenError,500:Jt.serverError},summary:"List settlements",description:"Retrieve settlements belonging to your vendor, with optional filtering and sorting via query params"},getSettlement:{method:"GET",path:"/:id",pathParams:t.z.object({id:t.z.string()}),responses:{200:Kr.settlement,401:Jt.unauthorizedError,403:Jt.forbiddenError,404:Jt.notFoundError,500:Jt.serverError},summary:"Get settlement details",description:"Retrieve detailed information about a specific settlement"},createSettlement:{method:"POST",path:"",body:Kr.createSettlementRequest,responses:{201:Kr.createSettlementResponse,400:Jt.validationError,401:Jt.unauthorizedError,403:Jt.forbiddenError,500:Jt.serverError},summary:"Create settlement",description:"Create a new settlement request initiated by the authenticated user. Expected failures (e.g. WALLET_NOT_FOUND) are reported via the body `status` field, not HTTP errors"},actionSettlement:{method:"POST",path:"/:id/action",pathParams:t.z.object({id:t.z.string()}),body:Kr.actionSettlementRequest,responses:{201:Kr.actionSettlementResponse,400:Jt.validationError,401:Jt.unauthorizedError,403:Jt.forbiddenError,500:Jt.serverError},summary:"Action settlement",description:"Approve or reject a PENDING settlement as the authenticated user. Expected failures (e.g. INVALID_STATE) are reported via the body `status` field, not HTTP errors"}}),Xr={[exports.SETTLEMENT_STATUS.PENDING]:{label:"Pending",description:"The settlement is awaiting approval",category:"pending",color:"warning",userFriendlyMessage:"Settlement is awaiting approval"},[exports.SETTLEMENT_STATUS.APPROVED]:{label:"Approved",description:"The settlement has been approved",category:"success",color:"success",userFriendlyMessage:"Settlement was approved"},[exports.SETTLEMENT_STATUS.REJECTED]:{label:"Rejected",description:"The settlement has been rejected",category:"failed",color:"error",userFriendlyMessage:"Settlement was rejected"}};function en(e){if(!e)return;const t=new Date(e);return Number.isNaN(t.getTime())?void 0:t}class tn{id;date;initiatedAt;initiatedById;actionedAt;actionedById;vendorId;walletId;accountNo;status;statusCode;description;bankAccountNo;bankAccountName;bankCode;amount;payoutId;transactionId;createdAt;updatedAt;_originalData;constructor(e){this._originalData={...e},this.id=e.id,this.date=new Date(e.date),this.initiatedAt=en(e.initiatedAt),this.initiatedById=e.initiatedById,this.actionedAt=en(e.actionedAt),this.actionedById=e.actionedById,this.vendorId=e.vendorId,this.walletId=e.walletId,this.accountNo=e.accountNo,this.status=e.status,this.statusCode=e.statusCode,this.description=e.description,this.bankAccountNo=e.bankAccountNo,this.bankAccountName=e.bankAccountName,this.bankCode=e.bankCode,this.amount=r.Amount.from(e.amount,"TZS")??r.Amount.from(0,"TZS"),this.payoutId=e.payoutId,this.transactionId=e.transactionId,this.createdAt=new Date(e.createdAt),this.updatedAt=new Date(e.updatedAt)}getOriginalData(){return this._originalData}isPending(){return this.status===exports.SETTLEMENT_STATUS.PENDING}isApproved(){return this.status===exports.SETTLEMENT_STATUS.APPROVED}isRejected(){return this.status===exports.SETTLEMENT_STATUS.REJECTED}canBeActioned(){return this.isPending()}getStatusInfo(){return Xr[this.status]}static from(e){try{const t=e;return t?.id&&t?.accountNo&&void 0!==t?.amount?new tn(t):void console.error("Missing required Settlement fields:",e)}catch(e){return void console.error("Error creating Settlement:",e)}}static createMany(e){const t=[];for(const r of e){const e=tn.from(r);e&&t.push(e)}return t}static fromJSON(e){return tn.from(e)}toJSON(){return{...this._originalData}}}const rn={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()})},nn=Nt().router({localTransfer:{method:"POST",path:"/local-transfer",body:rn.localTransferRequest,responses:{201:rn.localTransferResponse,400:Jt.validationError,401:Jt.unauthorizedError,404:Jt.notFoundError,500:Jt.serverError},summary:"Local transfer",description:"Transfer funds locally between wallets."}});const an={vendor:t.z.object({businessName:t.z.string(),tradeName:t.z.string(),enableCollections:t.z.number(),enablePayouts:t.z.number(),enableRemittance:t.z.number(),bankAccountNo:t.z.string().nullish(),bankAccountName:t.z.string().nullish(),bankCode:t.z.string().nullish(),enableAutoSettlement:t.z.number(),disablePaymentApproval:t.z.number()})},sn=Nt().router({getMe:{method:"GET",path:"/me",responses:{200:an.vendor,401:Jt.unauthorizedError,403:Jt.forbiddenError,500:Jt.serverError},summary:"Get vendor profile",description:"Retrieve the vendor profile of the authenticated user, including feature flags and bank details"}});class on{businessName;tradeName;canCollect;canPayout;canRemit;automatedSettlements;disabledPaymentApproval;settlementAccount;constructor(e){this.businessName=e.businessName,this.tradeName=e.tradeName,this.canCollect=e.canCollect,this.canPayout=e.canPayout,this.canRemit=e.canRemit,this.automatedSettlements=e.automatedSettlements,this.disabledPaymentApproval=e.disabledPaymentApproval,this.settlementAccount=e.settlementAccount}hasSettlementAccount(){return null!==this.settlementAccount}getDisplayName(){return this.tradeName||this.businessName}static from(e){try{const t=e;if(!t?.businessName)return void console.error("Missing required Vendor fields:",e);const n=t,a=n.bankCode?r.Bank.fromBIC(n.bankCode):void 0,s=a&&n.bankAccountName&&n.bankAccountNo?{accountName:n.bankAccountName,accountNo:n.bankAccountNo,bank:a}:null;return new on({businessName:n.businessName,tradeName:n.tradeName,canCollect:1===n.enableCollections,canPayout:1===n.enablePayouts,canRemit:1===n.enableRemittance,automatedSettlements:1===n.enableAutoSettlement,disabledPaymentApproval:1===n.disablePaymentApproval,settlementAccount:s})}catch(e){return void console.error("Error creating Vendor:",e)}}static fromJSON(e){let t=null;if(e.settlementAccount){const n=r.Bank.fromJSON(e.settlementAccount.bank);n&&(t={accountName:e.settlementAccount.accountName,accountNo:e.settlementAccount.accountNo,bank:n})}return new on({...e,settlementAccount:t})}toJSON(){return{businessName:this.businessName,tradeName:this.tradeName,canCollect:this.canCollect,canPayout:this.canPayout,canRemit:this.canRemit,automatedSettlements:this.automatedSettlements,disabledPaymentApproval:this.disabledPaymentApproval,settlementAccount:this.settlementAccount?{accountName:this.settlementAccount.accountName,accountNo:this.settlementAccount.accountNo,bank:this.settlementAccount.bank.toJSON()}:null}}}var cn;function un(e){switch(e){case"DEFAULT COLLECTION":case exports.WALLET_TYPE.COLLECTION:return exports.WALLET_TYPE.COLLECTION;case"Vendor":case"DEFAULT DISBURSEMENT":case exports.WALLET_TYPE.DISBURSEMENT:return exports.WALLET_TYPE.DISBURSEMENT;default:throw new TypeError(`Unsupported wallet type: ${String(e)}`)}}exports.WALLET_TYPE=void 0,(cn=exports.WALLET_TYPE||(exports.WALLET_TYPE={})).COLLECTION="COLLECTION",cn.DISBURSEMENT="DISBURSEMENT";const dn=t.z.enum(exports.WALLET_TYPE),ln=t.z.enum(["Vendor","DEFAULT DISBURSEMENT","DEFAULT COLLECTION","COLLECTION","DISBURSEMENT"]).transform(un),hn=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:ln,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)}),mn=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)}),pn={wallet:hn,walletType:dn,walletPathParams:t.z.object({accountNo:t.z.string().min(1)}),walletBalance:mn,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}$/)})},fn=Nt().router({listWallets:{method:"GET",path:"",responses:{200:t.z.array(pn.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:pn.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:pn.walletPathParams,responses:{200:pn.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:pn.walletPathParams,query:pn.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 yn{id;accountNo;accountName;shadowAccountNo;externalId;reference;type;vendorId;balance;minBalance;approvalLimit;currency;countryCode;createdAt;updatedAt;_originalData;constructor(e){const t=un(e.type);this._originalData={...e,type:t};let n="TZS";r.CurrencyHelpers.isCode(e.currency)?n=e.currency:"KSH"===e.currency&&(n="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=t,this.vendorId=e.vendorId,this.balance=r.Amount.from(e.balance,n)??r.Amount.from(0,n),this.minBalance=r.Amount.from(this.parseAmountValue(e.minBalance),n)??r.Amount.from(0,n),this.approvalLimit=r.Amount.from(this.parseAmountValue(e.approvalLimit),n)??r.Amount.from(0,n),this.currency=n,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===exports.WALLET_TYPE.COLLECTION}isDisbursementWallet(){return this.type===exports.WALLET_TYPE.DISBURSEMENT}isDefaultWallet(){return!1}static from(e){return new yn(e)}static createMany(e){const t=[];for(const r of e)try{t.push(yn.from(r))}catch(e){console.warn("Skipping unsupported wallet:",e)}return t}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 yn({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=nr,exports.AuthRepository=class extends qt{constructor(e){super("auth",ar,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=sr.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=qt,exports.COLLECTION_STATUS_INFO=pr,exports.Collection=yr,exports.CollectionDTOSchemas=hr,exports.CollectionQuery=vr,exports.CollectionRepository=class extends qt{constructor(e){super("collection",mr,e)}async getCollections(e){try{const t=vr.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=yr.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=vr.fromRequest(e);return this.getCollections(t)}async getCollection(e){const t=await this.client.getCollection({params:{id:e}}),r=this.handleResponse(t,200),n=yr.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=Wt.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=Pr,exports.PayoutDTOSchemas=wr,exports.PayoutQuery=zr,exports.PayoutRepository=class extends qt{constructor(e){super("payout",Or,e)}async getPayouts(e){try{const t=zr.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=Pr.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=zr.fromRequest(e);return this.getPayouts(t)}async getPayout(e){const t=await this.client.getPayout({params:{id:e}}),r=this.handleResponse(t,200),n=Pr.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=Wt.from(t);if(!r)throw new Error("Invalid summary data received from server");return r}},exports.QUERY_BUILDER_TYPE=Qt,exports.QueryBuilder=Xt,exports.SETTLEMENT_STATUS_INFO=Xr,exports.Settlement=tn,exports.SettlementDTOSchemas=Kr,exports.SettlementRepository=class extends qt{constructor(e){super("settlement",Qr,e)}async getSettlements(e){const t=await this.client.getSettlements({query:e??{}}),r=this.handleResponse(t,200);return tn.createMany(r)}async getSettlement(e){const t=await this.client.getSettlement({params:{id:e}}),r=this.handleResponse(t,200),n=tn.from(r);if(!n)throw new Error("Invalid settlement data received from server");return n}async createSettlement(e){const t=await this.client.createSettlement({body:e}),r=this.handleResponse(t,201);return{status:r.status,settlement:r.data?tn.from(r.data):void 0}}async actionSettlement(e,t){const r=await this.client.actionSettlement({params:{id:e},body:{status:t}}),n=this.handleResponse(r,201);return{status:n.status,settlement:n.data?tn.from(n.data):void 0}}async approveSettlement(e){return this.actionSettlement(e,exports.SETTLEMENT_ACTION.APPROVED)}async rejectSettlement(e){return this.actionSettlement(e,exports.SETTLEMENT_ACTION.REJECTED)}},exports.StatementEntry=Yt,exports.TransactionDTOSchemas=rn,exports.TransactionRepository=class extends qt{constructor(e){super("transaction",nn,e)}async localTransfer(e){const t=await this.client.localTransfer({body:e});return this.handleResponse(t,201)}},exports.TransactionSummary=Wt,exports.User=sr,exports.Vendor=on,exports.VendorDTOSchemas=an,exports.VendorRepository=class extends qt{constructor(e){super("vendor",sn,e)}async getMe(){const e=await this.client.getMe(),t=this.handleResponse(e,200),r=on.from(t);if(!r)throw new Error("Invalid vendor data received from server");return r}},exports.Wallet=yn,exports.WalletDTOSchemas=pn,exports.WalletInfo=Ht,exports.WalletRepository=class extends qt{constructor(e){super("wallet",fn,e)}async listWallets(){const e=await this.client.listWallets(),t=this.handleResponse(e,200),r=yn.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 yn.from(r)}async getWalletBalance(e){const t=await this.client.getWalletBalance({params:{accountNo:e}}),r=this.handleResponse(t,200);return Ht.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=Yt.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=ar,exports.collectionContract=mr,exports.collectionToStringArray=dr,exports.normalizeWalletType=un,exports.payoutContract=Or,exports.payoutToStringArray=Ir,exports.settlementContract=Qr,exports.statementEntrySchema=$t,exports.transactionContract=nn,exports.vendorContract=sn,exports.walletContract=fn;
2
2
  //# sourceMappingURL=index.cjs.js.map