@catena/cli 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,14 +0,0 @@
1
- import{C as e,T as t,_ as n,a as r,c as i,d as a,f as o,h as s,l as c,m as l,o as u,s as d,t as f,u as p,w as m,y as h}from"./dist-w03V0QPF.mjs";import{t as g}from"./hmac-CXnNqvhW.mjs";import{A as _,C as v,D as y,E as ee,M as te,O as ne,S as re,T as b,_ as x,a as ie,b as S,c as ae,d as oe,f as C,g as se,h as ce,i as le,j as ue,k as de,l as fe,m as pe,n as me,o as he,p as ge,r as _e,s as ve,t as ye,u as be,v as xe,w,x as Se,y as Ce}from"./index.mjs";import{defineCommand as we}from"citty";import*as T from"valibot";const Te=`2.56.3`;let Ee={getDocsUrl:({docsBaseUrl:e,docsPath:t=``,docsSlug:n})=>t?`${e??`https://viem.sh`}${t}${n?`#${n}`:``}`:void 0,version:`viem@${Te}`};var De=class e extends Error{constructor(t,n={}){let r=n.cause instanceof e?n.cause.details:n.cause?.message?n.cause.message:n.details,i=n.cause instanceof e&&n.cause.docsPath||n.docsPath,a=Ee.getDocsUrl?.({...n,docsPath:i}),o=[t||`An error occurred.`,``,...n.metaMessages?[...n.metaMessages,``]:[],...a?[`Docs: ${a}`]:[],...r?[`Details: ${r}`]:[],...Ee.version?[`Version: ${Ee.version}`]:[]].join(`
2
- `);super(o,n.cause?{cause:n.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`BaseError`}),this.details=r,this.docsPath=i,this.metaMessages=n.metaMessages,this.name=n.name??this.name,this.shortMessage=t,this.version=Te}walk(e){return Oe(this,e)}};function Oe(e,t){return t?.(e)?e:e&&typeof e==`object`&&`cause`in e&&e.cause!==void 0?Oe(e.cause,t):t?null:e}function ke(e,{strict:t=!0}={}){return!e||typeof e!=`string`?!1:t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith(`0x`)}function Ae(e){return ke(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}var je=class extends De{constructor({size:e,targetSize:t,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:`SizeExceedsPaddingSizeError`})}};function Me(e,{dir:t,size:n=32}={}){return typeof e==`string`?Ne(e,{dir:t,size:n}):Pe(e,{dir:t,size:n})}function Ne(e,{dir:t,size:n=32}={}){if(n===null)return e;let r=e.replace(`0x`,``);if(r.length>n*2)throw new je({size:Math.ceil(r.length/2),targetSize:n,type:`hex`});return`0x${r[t===`right`?`padEnd`:`padStart`](n*2,`0`)}`}function Pe(e,{dir:t,size:n=32}={}){if(n===null)return e;if(e.length>n)throw new je({size:e.length,targetSize:n,type:`bytes`});let r=new Uint8Array(n);for(let i=0;i<n;i++){let a=t===`right`;r[a?i:n-i-1]=e[a?i:e.length-i-1]}return r}var Fe=class extends De{constructor({max:e,min:t,signed:n,size:r,value:i}){super(`Number "${i}" is not in safe ${r?`${r*8}-bit ${n?`signed`:`unsigned`} `:``}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:`IntegerOutOfRangeError`})}},Ie=class extends De{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:`SizeOverflowError`})}};function Le(e,{size:t}){if(Ae(e)>t)throw new Ie({givenSize:Ae(e),maxSize:t})}const Re=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function ze(e,t={}){return typeof e==`number`||typeof e==`bigint`?He(e,t):typeof e==`string`?We(e,t):typeof e==`boolean`?Be(e,t):Ve(e,t)}function Be(e,t={}){let n=`0x${Number(e)}`;return typeof t.size==`number`?(Le(n,{size:t.size}),Me(n,{size:t.size})):n}function Ve(e,t={}){let n=``;for(let t=0;t<e.length;t++)n+=Re[e[t]];let r=`0x${n}`;return typeof t.size==`number`?(Le(r,{size:t.size}),Me(r,{dir:`right`,size:t.size})):r}function He(e,t={}){let{signed:n,size:r}=t,i=BigInt(e),a;r?a=n?(1n<<BigInt(r)*8n-1n)-1n:2n**(BigInt(r)*8n)-1n:typeof e==`number`&&(a=BigInt(2**53-1));let o=typeof a==`bigint`&&n?-a-1n:0;if(a&&i>a||i<o){let t=typeof e==`bigint`?`n`:``;throw new Fe({max:a?`${a}${t}`:void 0,min:`${o}${t}`,signed:n,size:r,value:`${e}${t}`})}let s=`0x${(n&&i<0?(1n<<BigInt(r*8))+BigInt(i):i).toString(16)}`;return r?Me(s,{size:r}):s}const Ue=new TextEncoder;function We(e,t={}){return Ve(Ue.encode(e),t)}const Ge=new TextEncoder;function Ke(e,t={}){return typeof e==`number`||typeof e==`bigint`?Xe(e,t):typeof e==`boolean`?qe(e,t):ke(e)?Ye(e,t):Ze(e,t)}function qe(e,t={}){let n=new Uint8Array(1);return n[0]=Number(e),typeof t.size==`number`?(Le(n,{size:t.size}),Me(n,{size:t.size})):n}const E={zero:48,nine:57,A:65,F:70,a:97,f:102};function Je(e){if(e>=E.zero&&e<=E.nine)return e-E.zero;if(e>=E.A&&e<=E.F)return e-(E.A-10);if(e>=E.a&&e<=E.f)return e-(E.a-10)}function Ye(e,t={}){let n=e;t.size&&(Le(n,{size:t.size}),n=Me(n,{dir:`right`,size:t.size}));let r=n.slice(2);r.length%2&&(r=`0${r}`);let i=r.length/2,a=new Uint8Array(i);for(let e=0,t=0;e<i;e++){let n=Je(r.charCodeAt(t++)),i=Je(r.charCodeAt(t++));if(n===void 0||i===void 0)throw new De(`Invalid byte sequence ("${r[t-2]}${r[t-1]}" in "${r}").`);a[e]=n*16+i}return a}function Xe(e,t){return Ye(He(e,t))}function Ze(e,t={}){let n=Ge.encode(e);return typeof t.size==`number`?(Le(n,{size:t.size}),Me(n,{dir:`right`,size:t.size})):n}const Qe=BigInt(0),$e=BigInt(1),et=BigInt(2),tt=BigInt(7),nt=BigInt(256),rt=BigInt(113),it=[],at=[],ot=[];for(let e=0,t=$e,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],it.push(2*(5*r+n)),at.push((e+1)*(e+2)/2%64);let i=Qe;for(let e=0;e<7;e++)t=(t<<$e^(t>>tt)*rt)%nt,t&et&&(i^=$e<<($e<<BigInt(e))-$e);ot.push(i)}const st=c(ot,!0),ct=st[0],lt=st[1],ut=(e,t,n)=>n>32?r(e,t,n):d(e,t,n),dt=(e,t,n)=>n>32?u(e,t,n):i(e,t,n);function ft(e,t=24){let r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let t=0;t<10;t++)r[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){let n=(t+8)%10,i=(t+2)%10,a=r[i],o=r[i+1],s=ut(a,o,1)^r[n],c=dt(a,o,1)^r[n+1];for(let n=0;n<50;n+=10)e[t+n]^=s,e[t+n+1]^=c}let t=e[2],i=e[3];for(let n=0;n<24;n++){let r=at[n],a=ut(t,i,r),o=dt(t,i,r),s=it[n];t=e[s],i=e[s+1],e[s]=a,e[s+1]=o}for(let t=0;t<50;t+=10){for(let n=0;n<10;n++)r[n]=e[t+n];for(let n=0;n<10;n++)e[t+n]^=~r[(n+2)%10]&r[(n+4)%10]}e[0]^=ct[n],e[1]^=lt[n]}n(r)}var pt=class r extends p{constructor(e,n,r,i=!1,a=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=i,this.rounds=a,l(r),!(0<e&&e<200))throw Error(`only keccak-f1600 function is supported`);this.state=new Uint8Array(200),this.state32=t(this.state)}clone(){return this._cloneInto()}keccak(){e(this.state32),ft(this.state32,this.rounds),e(this.state32),this.posOut=0,this.pos=0}update(e){o(this),e=m(e),a(e);let{blockLen:t,state:n}=this,r=e.length;for(let i=0;i<r;){let a=Math.min(t-this.pos,r-i);for(let t=0;t<a;t++)n[this.pos++]^=e[i++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:t,pos:n,blockLen:r}=this;e[n]^=t,t&128&&n===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){o(this,!1),a(e),this.finish();let t=this.state,{blockLen:n}=this;for(let r=0,i=e.length;r<i;){this.posOut>=n&&this.keccak();let a=Math.min(n-this.posOut,i-r);e.set(t.subarray(this.posOut,this.posOut+a),r),this.posOut+=a,r+=a}return e}xofInto(e){if(!this.enableXOF)throw Error(`XOF is not possible for this instance`);return this.writeInto(e)}xof(e){return l(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(s(e,this),this.finished)throw Error(`digest() was already called`);return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,n(this.state)}_cloneInto(e){let{blockLen:t,suffix:n,outputLen:i,rounds:a,enableXOF:o}=this;return e||=new r(t,n,i,o,a),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=a,e.suffix=n,e.outputLen=i,e.enableXOF=o,e.destroyed=this.destroyed,e}};const mt=((e,t,n)=>h(()=>new pt(t,e,n)))(1,136,32);function ht(e,t){let n=t||`hex`,r=mt(ke(e,{strict:!1})?Ke(e):e);return n===`bytes`?r:ze(r)}var gt=class extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){let t=super.get(e);return super.has(e)&&(super.delete(e),super.set(e,t)),t}set(e,t){if(super.has(e)&&super.delete(e),super.set(e,t),this.maxSize&&this.size>this.maxSize){let e=super.keys().next().value;e!==void 0&&super.delete(e)}return this}};const _t=/^0x[a-fA-F0-9]{40}$/,vt=new gt(8192);function yt(e,t){let{strict:n=!0}=t??{},r=`${e}.${n}`;if(vt.has(r))return vt.get(r);let i=_t.test(e)?e.toLowerCase()===e||!n||xt(e)===e:!1;return vt.set(r,i),i}const bt=new gt(8192);function xt(e,t){if(bt.has(`${e}.${t}`))return bt.get(`${e}.${t}`);let n=t?`${t}${e.toLowerCase()}`:e.substring(2).toLowerCase(),r=ht(Ze(n),`bytes`),i=(t?n.substring(`${t}0x`.length):n).split(``);for(let e=0;e<40;e+=2)r[e>>1]>>4>=8&&i[e]&&(i[e]=i[e].toUpperCase()),(r[e>>1]&15)>=8&&i[e+1]&&(i[e+1]=i[e+1].toUpperCase());let a=`0x${i.join(``)}`;return bt.set(`${e}.${t}`,a),a}function St(){return`0.1.1`}var D=class e extends Error{static setStaticOptions(t){e.prototype.docsOrigin=t.docsOrigin,e.prototype.showVersion=t.showVersion,e.prototype.version=t.version}constructor(t,n={}){let r=(()=>{if(n.cause instanceof e){if(n.cause.details)return n.cause.details;if(n.cause.shortMessage)return n.cause.shortMessage}return n.cause&&`details`in n.cause&&typeof n.cause.details==`string`?n.cause.details:n.cause?.message?n.cause.message:n.details})(),i=n.cause instanceof e&&n.cause.docsPath||n.docsPath,a=n.docsOrigin??e.prototype.docsOrigin,o=`${a}${i??``}`,s=!!(n.version??e.prototype.showVersion),c=n.version??e.prototype.version,l=[t||`An error occurred.`,...n.metaMessages?[``,...n.metaMessages]:[],...r||i||s?[``,r?`Details: ${r}`:void 0,i?`See: ${o}`:void 0,s?`Version: ${c}`:void 0]:[]].filter(e=>typeof e==`string`).join(`
3
- `);super(l,n.cause?{cause:n.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsOrigin",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"showVersion",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`BaseError`}),this.cause=n.cause,this.details=r,this.docs=o,this.docsOrigin=a,this.docsPath=i,this.shortMessage=t,this.showVersion=s,this.version=c}walk(e){return Ct(this,e)}};Object.defineProperty(D,"defaultStaticOptions",{enumerable:!0,configurable:!0,writable:!0,value:{docsOrigin:`https://oxlib.sh`,showVersion:!1,version:`ox@${St()}`}}),D.setStaticOptions(D.defaultStaticOptions);function Ct(e,t){return t?.(e)?e:e&&typeof e==`object`&&`cause`in e&&e.cause?Ct(e.cause,t):t?null:e}function wt(e,t){if(Wt(e)>t)throw new qt({givenSize:Wt(e),maxSize:t})}const O={zero:48,nine:57,A:65,F:70,a:97,f:102};function Tt(e){if(e>=O.zero&&e<=O.nine)return e-O.zero;if(e>=O.A&&e<=O.F)return e-(O.A-10);if(e>=O.a&&e<=O.f)return e-(O.a-10)}function Et(e,t={}){let{dir:n,size:r=32}=t;if(r===0)return e;if(e.length>r)throw new Jt({size:e.length,targetSize:r,type:`Bytes`});let i=new Uint8Array(r);for(let t=0;t<r;t++){let a=n===`right`;i[a?t:r-t-1]=e[a?t:e.length-t-1]}return i}function Dt(e,t={}){let{dir:n=`left`}=t,r=e,i=0;for(let e=0;e<r.length-1&&r[n===`left`?e:r.length-e-1].toString()===`0`;e++)i++;return r=n===`left`?r.slice(i):r.slice(0,r.length-i),r}function Ot(e,t){if(Pt(e)>t)throw new Ft({givenSize:Pt(e),maxSize:t})}function kt(e,t={}){let{dir:n,size:r=32}=t;if(r===0)return e;let i=e.replace(`0x`,``);if(i.length>r*2)throw new It({size:Math.ceil(i.length/2),targetSize:r,type:`Hex`});return`0x${i[n===`right`?`padEnd`:`padStart`](r*2,`0`)}`}function At(e){if(e===null||typeof e==`boolean`||typeof e==`string`)return JSON.stringify(e);if(typeof e==`number`){if(!Number.isFinite(e))throw TypeError(`Cannot canonicalize non-finite number`);return Object.is(e,-0)?`0`:JSON.stringify(e)}if(typeof e==`bigint`)throw TypeError(`Cannot canonicalize bigint`);if(Array.isArray(e))return`[${e.map(e=>At(e)).join(`,`)}]`;if(typeof e==`object`)return`{${Object.keys(e).sort().reduce((t,n)=>{let r=e[n];return r!==void 0&&t.push(`${JSON.stringify(n)}:${At(r)}`),t},[]).join(`,`)}}`}const jt=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function Mt(e,t={}){let n=``;for(let t=0;t<e.length;t++)n+=jt[e[t]];let r=`0x${n}`;return typeof t.size==`number`?(Ot(r,t.size),Nt(r,t.size)):r}function Nt(e,t){return kt(e,{dir:`right`,size:t})}function Pt(e){return Math.ceil((e.length-2)/2)}var Ft=class extends D{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed \`${t}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`Hex.SizeOverflowError`})}},It=class extends D{constructor({size:e,targetSize:t,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${t}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`Hex.SizeExceedsPaddingSizeError`})}};const Lt=new TextDecoder,Rt=new TextEncoder;function zt(e){return e instanceof Uint8Array?e:typeof e==`string`?Vt(e):Bt(e)}function Bt(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function Vt(e,t={}){let{size:n}=t,r=e;n&&(Ot(e,n),r=Nt(e,n));let i=r.slice(2);i.length%2&&(i=`0${i}`);let a=i.length/2,o=new Uint8Array(a);for(let e=0,t=0;e<a;e++){let n=Tt(i.charCodeAt(t++)),r=Tt(i.charCodeAt(t++));if(n===void 0||r===void 0)throw new D(`Invalid byte sequence ("${i[t-2]}${i[t-1]}" in "${i}").`);o[e]=n<<4|r}return o}function Ht(e,t={}){let{size:n}=t,r=Rt.encode(e);return typeof n==`number`?(wt(r,n),Ut(r,n)):r}function Ut(e,t){return Et(e,{dir:`right`,size:t})}function Wt(e){return e.length}function Gt(e,t={}){let{size:n}=t,r=e;return n!==void 0&&(wt(r,n),r=Kt(r)),Lt.decode(r)}function Kt(e){return Dt(e,{dir:`right`})}var qt=class extends D{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed \`${t}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`Bytes.SizeOverflowError`})}},Jt=class extends D{constructor({size:e,targetSize:t,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${t}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`Bytes.SizeExceedsPaddingSizeError`})}};function Yt(e,t,n={}){let{as:r=typeof t==`string`?`Hex`:`Bytes`}=n,i=g(f,zt(e),zt(t));return r===`Bytes`?i:Mt(i)}const Xt=new TextEncoder,Zt=new TextDecoder,Qt=Object.fromEntries(Array.from(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`).map((e,t)=>[t,e.charCodeAt(0)])),$t={...Object.fromEntries(Array.from(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`).map((e,t)=>[e.charCodeAt(0),t])),61:0,45:62,95:63};function en(e,t={}){let{pad:n=!0,url:r=!1}=t,i=new Uint8Array(Math.ceil(e.length/3)*4);for(let t=0,n=0;n<e.length;t+=4,n+=3){let r=(e[n]<<16)+(e[n+1]<<8)+(e[n+2]|0);i[t]=Qt[r>>18],i[t+1]=Qt[r>>12&63],i[t+2]=Qt[r>>6&63],i[t+3]=Qt[r&63]}let a=e.length%3,o=Math.floor(e.length/3)*4+(a&&a+1),s=Zt.decode(new Uint8Array(i.buffer,0,o));return n&&a===1&&(s+=`==`),n&&a===2&&(s+=`=`),r&&(s=s.replaceAll(`+`,`-`).replaceAll(`/`,`_`)),s}function tn(e,t={}){return en(Ht(e),t)}function nn(e){let t=e.replace(/=+$/,``),n=t.length,r=new Uint8Array(n+3);Xt.encodeInto(t+`===`,r);for(let e=0,n=0;e<t.length;e+=4,n+=3){let t=($t[r[e]]<<18)+($t[r[e+1]]<<12)+($t[r[e+2]]<<6)+$t[r[e+3]];r[n]=t>>16,r[n+1]=t>>8&255,r[n+2]=t&255}let i=(n>>2)*3+(n%4&&n%4-1);return new Uint8Array(r.buffer,0,i)}function rn(e){return Gt(nn(e))}const k={acceptPayment:`Accept-Payment`,authorization:`Authorization`,paymentAuthorization:`Payment-Authorization`,paymentReceipt:`Payment-Receipt`,paymentSession:`Payment-Session`,paymentSessionSnapshot:`Payment-Session-Snapshot`,wwwAuthenticate:`WWW-Authenticate`},an={payment:`Payment`};function on(e){let t=rn(e);return JSON.parse(t)}function A(e){return tn(At(e),{pad:!1,url:!0})}function sn(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function cn(e,t){return typeof t==`bigint`?t.toString():t}function ln(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function un(e){return e==null}function dn(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function fn(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}const pn=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function mn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function hn(e){if(mn(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return mn(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}const gn=new Set([`string`,`number`,`symbol`]);function _n(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function vn(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function j(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function yn(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout===`optional`)}function bn(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function xn(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function M(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function Sn(e){return typeof e==`string`?e:e?.message}function Cn(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function N(e,t,n){var r;let i=e.inst?._zod?.traits;i?.has(`$ZodType`)&&(i.has(`$ZodCheck`)?(r=e).schema??(r.schema=e.inst):e.schema=e.inst);let a=e.schema===e.inst?void 0:e.schema?._zod.def?.error,o=e.message?e.message:Sn(e.inst?._zod.def?.error?.(e))??Sn(a?.(e))??Sn(t?.error?.(e))??Sn(n.customError?.(e))??Sn(n.localeError?.(e))??`Invalid input`,{inst:s,schema:c,continue:l,input:u,...d}=e;return d.path??=[],d.message=o,t?.reportInput&&(d.input=u),d}const wn=/[\uD800-\uDBFF]/;function Tn(e){let t=e.length;if(!wn.test(e))return t;let n=t;for(let r=0;r<t-1;r++)(e.charCodeAt(r)&64512)==55296&&(e.charCodeAt(r+1)&64512)==56320&&(n--,r++);return n}function En(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function Dn(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}function On(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);r.get?Object.defineProperty(e,n,{...r,enumerable:!1}):jn(e,n,r.value)}}function kn(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function An(e,t,n){return kn(e,t,n,!1)}function jn(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:kn(this,t,n.bind(this))},set(e){kn(this,t,e)}})}function Mn(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}let Nn,P=!1;const Pn={configurable:!0,get(){P=!0}};function F(e,t,n){let r=Object.getPrototypeOf(e._zod);if(t in r&&Nn!==e._zod){Nn=void 0;return}Nn=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,Pn);let e=P;P=!1;try{let r=n(this);return P?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r}),P||=e,r}catch(n){throw delete this[t],P||=e,n}},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})}function Fn(e,t,n,r){let i=Mn(e,t);i&&Object.defineProperty(i,t,{configurable:!0,get(){let e={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,e),e.value=n(this),Object.defineProperty(this,t,e),e.value},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:e})}})}var In;const Ln={value:void 0,enumerable:!1};let Rn=`captureStackTrace`in Error?Error:null;function zn(e){let t=Rn;if(t){let n=t.stackTraceLimit;if(typeof n==`number`){try{t.stackTraceLimit=0}catch{return Rn=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function I(e,t,n,r){let i={};function a(e){this.def=e,this.constr=d,this.traits=new Set}a.prototype=i;let o=n,s=o&&new WeakSet;function c(n,r){if(!n._zod){Ln.value=new a(r);try{Object.defineProperty(n,"_zod",Ln)}finally{Ln.value=void 0}}if(n._zod.traits.has(e))return;if(n._zod.traits.add(e),t(n,r),s){let e=Object.getPrototypeOf(n),t=n._zod.constr.prototype,r=e;for(;r&&r!==t;)r=Object.getPrototypeOf(r);let i=r??e;s.has(i)||(s.add(i),On(i,o))}let i=d.prototype;for(let e in i)Object.prototype.hasOwnProperty.call(i,e)&&(e in n||(n[e]=i[e].bind(n)))}let l=r?.Parent??Object;class u extends l{}Object.defineProperty(u,"name",{value:e});function d(e){let t=r?.Parent?zn(u):this;c(t,e);let n=t._zod.deferred;if(n){for(let e of n)e();t._zod.deferred=void 0}let i=globalThis.__zod_globalConfig?.postProcessor;return i&&i(t),t}return Object.defineProperty(d,"init",{value:c}),Object.defineProperty(d,Symbol.hasInstance,{value:t=>r?.Parent&&t instanceof r.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(d,"name",{value:e}),d}var Bn=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}};(In=globalThis).__zod_globalConfig??(In.__zod_globalConfig={});const Vn=globalThis.__zod_globalConfig;function L(e){return e&&Object.assign(Vn,e),Vn}function Hn(){let e=this._zod;return e.message??=JSON.stringify(e.def,cn,2),e.message}function Un(e){this._zod.message=e}const Wn={get:Hn,set:Un,enumerable:!0,configurable:!0},Gn={value:void 0,enumerable:!1},Kn={value:void 0,enumerable:!1},qn=new WeakSet([Object.prototype,Error.prototype]),Jn=(e,t)=>{e.name=`$ZodError`,Gn.value=e._zod,Object.defineProperty(e,"_zod",Gn),Kn.value=t,Object.defineProperty(e,"issues",Kn),Gn.value=void 0,Kn.value=void 0,Object.defineProperty(e,"message",Wn);let n=Object.getPrototypeOf(e);qn.has(n)||(qn.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let e=()=>this.message;return Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0})}}))},Yn=I(`$ZodError`,Jn),Xn=I(`$ZodError`,Jn,void 0,{Parent:Error}),Zn=(e=>{let t=(n,r,i,a)=>{let o=i?{...i,async:!1}:{async:!1},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Bn;if(s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>N(e,o,L())));throw pn(n,a?.callee??t),n}return s.value};return t})(Xn),Qn=(e=>{let t=async(n,r,i,a)=>{let o=i?{...i,async:!0}:{async:!0},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>N(e,o,L())));throw pn(n,a?.callee??t),n}return s.value};return t})(Xn),$n=(e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Bn;return a.issues.length?{success:!1,error:new(e??Yn)(a.issues.map(e=>N(e,i,L())))}:{success:!0,data:a.value}})(Xn),er=(e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>N(e,i,L())))}:{success:!0,data:a.value}})(Xn),tr=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},nr=/^-?\d+(?:\.\d+)?$/,rr=/^(?:true|false)$/i,ir=I(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),ar=e=>{let t=e.value;return!un(t)&&t.length!==void 0},or=I(`$ZodCheckMinLength`,(e,t)=>{var n;ir.init(e,t),(n=e._zod.def).when??(n.when=ar),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>=t.minimum&&i<t.minimum*2?Tn(r):i)>=t.minimum)return;let a=En(r);n.issues.push({origin:a,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),sr=I(`$ZodCheckStringFormat`,(e,t)=>{var n,r;ir.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),cr=I(`$ZodCheckRegex`,(e,t)=>{sr.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),lr={major:4,minor:5,patch:4},R=I(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=lr;let r=e._zod.def.checks,i=e._zod.traits.has(`$ZodCheck`)?[e,...r??[]]:r?.length?[...r]:[];for(let t of i)for(let n of t._zod.onattach)n(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(t,n,r)=>{if(t.memo)return t;let i=bn(t),a;for(let o of n){if(o._zod.def.when){if(xn(t)||!o._zod.def.when(t))continue}else if(i)continue;let n=t.issues.length,s=o._zod.check(t);if(s instanceof Promise&&r?.async===!1)throw new Bn;if(a||s instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await s,t.issues.length!==n&&(Cn(t.issues,n,e),i||=bn(t,n))});else{if(t.issues.length===n)continue;Cn(t.issues,n,e),i||=bn(t,n)}}return a?a.then(()=>t):t},n=(n,r,a)=>{if(bn(n))return n.aborted=!0,n;let o=t(r,i,a);if(o instanceof Promise){if(a.async===!1)throw new Bn;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(r,a)=>{if(a.skipChecks)return e._zod.parse(r,a);if(a.direction===`backward`){let t=e._zod.parse({value:r.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,r,a)):n(t,r,a)}let o=e._zod.parse(r,a);if(o instanceof Promise){if(a.async===!1)throw new Bn;return o.then(e=>t(e,i,a))}return t(o,i,a)}}},{get"~standard"(){return An(this,`~standard`,dr(this))},set"~standard"(e){kn(this,`~standard`,e)}}),ur=e=>e.success?{value:e.data}:{issues:e.error?.issues};function dr(e){return{validate:t=>{try{return ur($n(e,t))}catch{return er(e,t).then(ur)}},vendor:`zod`,version:1}}const fr=I(`$ZodString`,(e,t)=>{R.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??tr(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),pr=I(`$ZodNumber`,(e,t)=>{R.init(e,t),e._zod.pattern=e._zod.bag.pattern??nr,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:String(i):void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),mr=I(`$ZodBoolean`,(e,t)=>{R.init(e,t),e._zod.pattern=rr,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),hr=I(`$ZodUnknown`,(e,t)=>{R.init(e,t),e._zod.parse=e=>e}),gr=I(`$ZodNever`,(e,t)=>{R.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function _r(e,t,n){e.issues.length&&t.issues.push(...M(n,e.issues)),t.value[n]=e.value}const vr=I(`$ZodArray`,(e,t)=>{R.init(e,t);let n=Vn.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({expected:`array`,code:`invalid_type`,input:a,inst:e}),r;r.value=n?n.alloc(e,r,Array(a.length),i):Array(a.length);let o=[];for(let e=0;e<a.length;e++){let n=a[e],s=t.element._zod.run({value:n,issues:[]},i);s instanceof Promise?o.push(s.then(t=>_r(t,r,e))):_r(s,r,e)}return o.length?Promise.all(o).then(()=>r):r}});function yr(e,t,n,r,i,a){let o=n in r,s=a===`optional`;if(o||!s||i!==`optional`){if(e.issues.length){if(i!==void 0&&s&&!o)return;t.issues.push(...M(n,e.issues))}if(!o&&i===void 0){e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]});return}e.value===void 0?o&&(t.value[n]=void 0):t.value[n]=e.value}}const br=[];function xr(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:br,i=r.length?[...t,...r]:t;for(let t of i)if(!e.shape?.[t]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${String(t)}": expected a Zod schema`);let a=yn(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(a)}}function Sr(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optin,d=c.optout;for(let i in t){if(s.has(i))continue;if(i===`__proto__`){l===`never`&&o.push(i);continue}if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>yr(e,n,i,t,u,d))):yr(a,n,i,t,u,d)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a,continue:!0}),e.length?Promise.all(e).then(()=>n):n}const Cr=new WeakMap,wr=I(`$ZodObject`,(e,t)=>{if(R.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Cr.set(t,e),Object.defineProperty(t,"shape",{get:()=>{let n={...e};return Object.defineProperty(t,"shape",{value:n}),Cr.set(t,n),n}})}let n=ln(()=>xr(t));F(e,`propValues`,e=>{let t=e.def.shape,n={};for(let e in t){let r=t[e]._zod;if(r.values){Object.prototype.hasOwnProperty.call(n,e)||fn(n,e,new Set);for(let t of r.values)n[e].add(t);r.optin!==void 0&&n[e].add(void 0)}}return n});let r=mn,i=t.catchall,a,o=Vn.memoizer;o?.attach(e),e._zod.parse=(t,s)=>{a??=n.value;let c=t.value;if(!r(c))return t.issues.push({expected:`object`,code:`invalid_type`,input:c,inst:e}),t;t.value=o?o.alloc(e,t,{},s):{};let l=[],u=a.shape;for(let e of a.allKeys){if(e===`__proto__`)continue;let n=u[e],r=n._zod.optin,i=n._zod.optout,a=n._zod.run({value:c[e],issues:[]},s);a instanceof Promise?l.push(a.then(n=>yr(n,t,e,c,r,i))):yr(a,t,e,c,r,i)}return i?Sr(l,c,t,s,n.value,e):l.length?Promise.all(l).then(()=>t):t}});function Tr(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!bn(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>N(e,r,L())))}),t)}const Er=I(`$ZodUnion`,(e,t)=>{R.init(e,t),F(e,`optin`,e=>e.def.options.some(e=>e._zod.optin===`defaulted`)?`defaulted`:e.def.options.some(e=>e._zod.optin!==void 0)?`optional`:void 0),F(e,`optout`,e=>e.def.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),F(e,`values`,e=>{if(e.def.options.every(e=>e._zod.values))return new Set(e.def.options.flatMap(e=>Array.from(e._zod.values)))}),F(e,`pattern`,e=>{if(e.def.options.every(e=>e._zod.pattern)){let t=e.def.options.map(e=>e._zod.pattern);return RegExp(`^(${t.map(e=>dn(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>Tr(t,r,e,i)):Tr(o,r,e,i)}}),Dr=I(`$ZodRecord`,(e,t)=>{R.init(e,t);let n=Vn.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!hn(a))return r.issues.push({expected:`record`,code:`invalid_type`,input:a,inst:e}),r;let o=[],s=t.keyType._zod.values;if(s&&!t.partial){r.value=n?n.alloc(e,r,{},i):{};let c=new Set;for(let n of s)if(typeof n==`string`||typeof n==`number`||typeof n==`symbol`){if(c.add(typeof n==`number`?n.toString():n),n===`__proto__`)continue;let s=t.keyType._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){r.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>N(e,i,L())),input:n,path:[n],inst:e});continue}let l=s.value;if(l===`__proto__`)continue;let u=t.valueType._zod.run({value:a[n],issues:[]},i);u instanceof Promise?o.push(u.then(e=>{e.issues.length&&r.issues.push(...M(n,e.issues)),r.value[l]=e.value})):(u.issues.length&&r.issues.push(...M(n,u.issues)),r.value[l]=u.value)}let l;for(let e in a)if(!c.has(e)){if(t.mode===`loose`){if(e===`__proto__`)continue;r.value[e]=a[e]}else l??=[],l.push(e)}l&&l.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:l,continue:!0})}else{r.value=n?n.alloc(e,r,{},i):{};let c;for(let n of Reflect.ownKeys(a)){if(n===`__proto__`||!Object.prototype.propertyIsEnumerable.call(a,n))continue;let l=t.keyType._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof n==`string`&&nr.test(n)&&l.issues.length){let e=t.keyType._zod.run({value:Number(n),issues:[]},i);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(l=e)}if(l.issues.length){t.mode===`loose`?r.value[n]=a[n]:s?(c??=[],c.push(n)):r.issues.push({code:`invalid_key`,origin:`record`,issues:l.issues.map(e=>N(e,i,L())),input:n,path:[n],inst:e});continue}let u=l.value;if(u===`__proto__`)continue;let d=t.valueType._zod.run({value:a[n],issues:[]},i);d instanceof Promise?o.push(d.then(e=>{e.issues.length&&r.issues.push(...M(n,e.issues)),r.value[u]=e.value})):(d.issues.length&&r.issues.push(...M(n,d.issues)),r.value[u]=d.value)}c&&c.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:c,continue:!0})}return o.length?Promise.all(o).then(()=>r):r}}),Or=I(`$ZodEnum`,(e,t)=>{R.init(e,t);let n=sn(t.entries),r=new Set(n);e._zod.values=r;let i=n.filter(e=>gn.has(typeof e));e._zod.pattern=RegExp(i.length?`^(${i.map(e=>_n(e.toString())).join(`|`)})$`:`^[^\\s\\S]$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),kr=I(`$ZodLiteral`,(e,t)=>{R.init(e,t);let n=new Set(t.values);e._zod.values=n,e._zod.pattern=RegExp(t.values.length?`^(${t.values.map(e=>typeof e==`string`?_n(e):e?_n(e.toString()):String(e)).join(`|`)})$`:`^[^\\s\\S]$`),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}});function Ar(e,t){return e.value=t.issues.length?void 0:t.value,e}const jr=I(`$ZodOptional`,(e,t)=>{R.init(e,t),F(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),e._zod.optout=`optional`,F(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t,void 0]):void 0}),F(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${dn(t.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(e.value===void 0){if(t.innerType._zod.optin!==`defaulted`)return e;let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(t=>Ar(e,t)):Ar(e,r)}return t.innerType._zod.run(e,n)}}),Mr=I(`$ZodCustom`,(e,t)=>{ir.init(e,t),R.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Nr(t,n,r,e));Nr(i,n,r,e)}});function Nr(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(Dn(e))}}function Pr(e,t){return new e({type:`string`,...j(t)})}function Fr(e,t){return new e({type:`number`,checks:[],...j(t)})}function Ir(e,t){return new e({type:`boolean`,...j(t)})}function Lr(e){return new e({type:`unknown`})}function Rr(e,t){return new e({type:`never`,...j(t)})}function zr(e,t){return new or({check:`min_length`,...j(t),minimum:e})}function z(e,t){return new cr({check:`string_format`,format:`regex`,...j(t),pattern:e})}function Br(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...j(n)})}const B=I(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);R.init(e,t),e.def=t,e.type=t.type},{get with(){return this.check},set with(e){kn(this,`with`,e)},parse(e,t){return Zn(this,e,t,{callee:this.parse})},parseAsync(e,t){return Qn(this,e,t,{callee:this.parseAsync})},safeParse(e,t){return $n(this,e,t)},safeParseAsync(e,t){return er(this,e,t)},check(...e){let t=this.def;return this.clone({...t,checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0})},clone(e,t){return vn(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},apply(e,...t){return t.length===0?e(this):e(this,...t)}}),Vr=I(`ZodMiniString`,(e,t)=>{fr.init(e,t),B.init(e,t)});function V(e){return Pr(Vr,e)}const Hr=I(`ZodMiniNumber`,(e,t)=>{pr.init(e,t),B.init(e,t)});function Ur(e){return Fr(Hr,e)}const Wr=I(`ZodMiniBoolean`,(e,t)=>{mr.init(e,t),B.init(e,t)});function Gr(e){return Ir(Wr,e)}const Kr=I(`ZodMiniUnknown`,(e,t)=>{hr.init(e,t),B.init(e,t)});function H(){return Lr(Kr)}const qr=I(`ZodMiniNever`,(e,t)=>{gr.init(e,t),B.init(e,t)});function Jr(e){return Rr(qr,e)}const Yr=I(`ZodMiniArray`,(e,t)=>{vr.init(e,t),B.init(e,t)});function Xr(e,t){return new Yr({type:`array`,element:e,...j(t)})}const Zr=I(`ZodMiniObject`,(e,t)=>{wr.init(e,t),B.init(e,t),Fn(e,`shape`,e=>e._zod.def.shape,!1)});function U(e,t){let n={type:`object`,shape:e??{},...j(t)};return new Zr(n)}function Qr(e,t){return new Zr({type:`object`,shape:e,catchall:H(),...j(t)})}const $r=I(`ZodMiniUnion`,(e,t)=>{Er.init(e,t),B.init(e,t)});function ei(e,t){return new $r({type:`union`,options:e,...j(t)})}const ti=I(`ZodMiniRecord`,(e,t)=>{Dr.init(e,t),B.init(e,t)});function W(e,t,n){return!t||!t._zod?new ti({type:`record`,keyType:V(),valueType:e,...j(t)}):new ti({type:`record`,keyType:e,valueType:t,...j(n)})}const ni=I(`ZodMiniEnum`,(e,t)=>{Or.init(e,t),B.init(e,t),e.options=Object.values(t.entries)});function ri(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new ni({type:`enum`,entries:n,...j(t)})}const ii=I(`ZodMiniLiteral`,(e,t)=>{kr.init(e,t),B.init(e,t)});function G(e,t){return new ii({type:`literal`,values:Array.isArray(e)?e:[e],...j(t)})}const ai=I(`ZodMiniOptional`,(e,t)=>{jr.init(e,t),B.init(e,t)});function K(e){return new ai({type:`optional`,innerType:e})}const oi=I(`ZodMiniCustom`,(e,t)=>{Mr.init(e,t),B.init(e,t)});function si(e,t={}){return Br(oi,e,t)}function ci(){return V().check(z(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/,`Invalid ISO 8601 datetime`))}function li(e){return e instanceof Date?Number.isFinite(e.getTime())?e.toISOString():`Invalid Date`:e}function ui(){return V().check(z(/^0x[0-9a-fA-F]{40}$/,`Invalid address`))}function di(){return V().check(z(/^0x[0-9a-fA-F]{64}$/,`Invalid hash`))}function fi(){return V().check(z(/^0x[0-9a-fA-F]+$/,`Invalid signature`))}const pi=U({description:K(V()),digest:K(V().check(z(/^sha-256=/,`Invalid digest format`))),expires:K(ci()),header:K(V().check(z(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,`Invalid HTTP header name`))),id:V().check(zr(1)),intent:V(),method:V(),meta:K(W(V(),V())),opaque:K(V()),realm:V(),request:W(V(),H())});function mi(e,t){let{description:n,digest:r,meta:i,method:a,header:o,intent:s,realm:c,request:l,secretKey:u}=e,d=Oi(o)?void 0:o,f=e.expires?li(e.expires):void 0,p=e.opaque??(i===void 0?void 0:A(i)),m=u?ki({...e,expires:f,...i!==void 0&&{meta:i},opaque:p},{secretKey:u}):e.id;return pi.parse({id:m,realm:c,method:a,intent:s,request:l,...n&&{description:n},...r&&{digest:r},...f&&{expires:f},...d!==void 0&&{header:d},...i!==void 0&&{meta:i},...p!==void 0&&{opaque:p}})}function hi(e){let t=[q(`id`,e.id),q(`realm`,e.realm),q(`method`,e.method),q(`intent`,e.intent),q(`request`,A(e.request))];e.description!==void 0&&t.push(q(`description`,e.description)),e.digest!==void 0&&t.push(q(`digest`,e.digest)),e.expires!==void 0&&t.push(q(`expires`,e.expires));let n=e.header;return n!==void 0&&!Oi(n)&&t.push(q(`header`,n)),e.opaque===void 0?e.meta!==void 0&&t.push(q(`opaque`,A(e.meta))):t.push(q(`opaque`,e.opaque)),`${an.payment} ${t.join(`, `)}`}function q(e,t){if(/[\r\n]/.test(t))throw Error(`Invalid quoted-string value.`);return`${e}="${t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/[\u0100-\uffff]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}"`}function gi(e,t){let n=_i(e);if(!n)throw Error(`Missing Payment scheme.`);let{request:r,opaque:i,...a}=vi(n);if(!r)throw Error(`Missing request parameter.`);if(r.length>16384)throw Error(`Request parameter too large.`);if(a.method&&!/^[a-z][a-z0-9:_-]*$/.test(a.method))throw Error(`Invalid method: "${a.method}". Must be lowercase per spec.`);return mi({...a,request:on(r),...i&&{opaque:i}},t)}function _i(e){let t=an.payment,[n]=Si(e,t);if(n===void 0)return null;let r=n+t.length;for(;r<e.length&&/\s/.test(e[r]??``);)r++;return e.slice(r)}function vi(e){let t=Object.create(null),n=0;for(;n<e.length;){for(;n<e.length&&/[\s,]/.test(e[n]??``);)n++;if(n>=e.length)break;let r=n;for(;n<e.length&&/[A-Za-z0-9_-]/.test(e[n]??``);)n++;let i=e.slice(r,n).toLowerCase();if(!i)throw Error(`Malformed auth-param.`);for(;n<e.length&&/\s/.test(e[n]??``);)n++;if(e[n]!==`=`)break;for(n++;n<e.length&&/\s/.test(e[n]??``);)n++;let[a,o]=yi(e,n);if(n=o,i in t)throw Error(`Duplicate parameter: ${i}`);t[i]=a}return t}function yi(e,t){if(e[t]===`"`)return bi(e,t+1);let n=t;for(;n<e.length&&e[n]!==`,`;)n++;return[e.slice(t,n).trim(),n]}function bi(e,t){let n=t,r=!1,i=t,a;for(;n<e.length;){let o=e[n];if(n++,r){a??=[];let t=o===`u`?e.slice(n,n+4):void 0;t&&/^[0-9A-Fa-f]{4}$/.test(t)?(a.push(String.fromCharCode(Number.parseInt(t,16))),n+=4):a.push(o),i=n,r=!1;continue}if(o===`\\`){a??=[],a.push(e.slice(i,n-1)),i=n,r=!0;continue}if(o===`"`)return[a?[...a,e.slice(i,n-1)].join(``):e.slice(t,n-1),n]}throw Error(`Unterminated quoted-string.`)}function xi(e,t,n){if(e.slice(t,t+n.length).toLowerCase()!==n.toLowerCase())return!1;let r=e[t+n.length];return!!(r&&/\s/.test(r))}function Si(e,t){let n=[],r=!1,i=!1;for(let a=0;a<e.length;a++){let o=e[a];if(r){i?i=!1:o===`\\`?i=!0:o===`"`&&(r=!1);continue}if(o===`"`){r=!0;continue}if(!xi(e,a,t))continue;let s=a-1;for(;s>=0&&/\s/.test(e[s]??``);)s--;s>=0&&e[s]!==`,`||n.push(a)}return n}function Ci(e,t){if(e.status!==402)throw Error(`Response status is not 402.`);return wi(e.headers,t)}function wi(e,t){let n=e.get(k.wwwAuthenticate);if(!n)throw Error(`Missing ${k.wwwAuthenticate} header.`);return Ti(n,t)}function Ti(e,t){let n=Si(e,an.payment);if(n.length===0)throw Error(`No Payment schemes found.`);return n.map((r,i)=>{let a=i+1<n.length?n[i+1]:e.length;return gi(e.slice(r,a).replace(/,\s*$/,``),t)})}function Ei(e){let t=[e.realm,e.method,e.intent,A(e.request),e.expires??``,e.digest??``],n=e.header;return n!==void 0&&!Oi(n)&&t.push(n),t.push(e.opaque??(e.meta?A(e.meta):``)),t.join(`|`)}function Di(e){return e.header??k.authorization}function Oi(e){return e?.toLowerCase()===k.authorization.toLowerCase()}function ki(e,t){let n=Ei(e);return en(Yt(Ht(t.secretKey),Ht(n),{as:`Bytes`}),{url:!0,pad:!1})}var Ai=class extends Error{name=`MissingPaymentSchemeError`;constructor(){super(`Missing Payment scheme.`)}},ji=class extends Error{name=`InvalidCredentialEncodingError`;constructor(){super(`Invalid base64url or JSON.`)}};function Mi(e){let t=e.match(RegExp(`^${an.payment}\\s+(.+)$`,`i`));if(!t?.[1])throw new Ai;try{let e=rn(t[1]),n=JSON.parse(e),{opaque:r,request:i,meta:a,...o}=n.challenge,{meta:s,opaque:c}=Ni(r);return{challenge:pi.parse({...o,...s!==void 0&&{meta:s},...c!==void 0&&{opaque:c},request:on(i)}),payload:n.payload,...n.source&&{source:n.source}}}catch{throw new ji}}function Ni(e){if(e===void 0)return{};if(typeof e==`string`)return{opaque:e};if(!Pi(e))throw Error(`Invalid opaque.`);return{meta:e,opaque:A(e)}}function Pi(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:Object.values(e).every(e=>typeof e==`string`)}var Fi=class extends Error{details;status=402;hint;constructor(e,t={}){super(e),this.details=t.details}toProblemDetails(e){return{type:this.type,title:this.title,status:this.status,detail:this.message,...this.details&&Object.keys(this.details).length>0&&{details:this.details},...this.hint&&{hint:this.hint},...e&&{challengeId:e}}}},Ii=class extends Fi{name=`InvalidChallengeError`;title=`Invalid Challenge`;status=402;type=`https://paymentauth.org/problems/invalid-challenge`;constructor(e={}){let{id:t,reason:n}=e,r=t?` "${t}"`:``,i=n?`: ${n}`:``;super(`Challenge${r} is invalid${i}.`)}},Li=class extends Fi{name=`PaymentExpiredError`;title=`Payment Expired`;type=`https://paymentauth.org/problems/payment-expired`;constructor(e={}){let{expires:t}=e;super(t?`Payment expired at ${t}.`:`Payment has expired.`)}};function Ri(e,t){if(!e)throw new Ii({...t&&{id:t},reason:`missing required expires field`});if(Number.isNaN(new Date(e).getTime()))throw new Ii({...t&&{id:t},reason:`malformed expires timestamp`});if(new Date(e)<new Date)throw new Li({expires:e})}function zi(e){return e}function Bi(e,t){let{canHandleChallenge:n,context:r,createCredential:i}=t;return{...e,canHandleChallenge:n,context:r,createCredential:i}}const Vi=Qr({method:V(),reference:V(),externalId:K(V()),subscriptionId:K(V()),status:G(`success`),timestamp:ci()});function Hi(e){let t=rn(e);return Ui(JSON.parse(t))}function Ui(e){return Vi.parse(e)}function Wi(e){let t=e.headers.get(k.paymentReceipt);if(!t)throw Error(`Missing ${k.paymentReceipt} header.`);return Hi(t)}function Gi(e){return{encode(t){return tn(JSON.stringify(e.parse(t)))},decode(t){try{return e.parse(JSON.parse(rn(t)))}catch{throw new Ki}}}}var Ki=class extends Error{name=`InvalidJsonHeaderError`;constructor(){super(`Invalid base64 JSON header.`)}};const qi=[`exact`],Ji=`PAYMENT-REQUIRED`,Yi=`PAYMENT-SIGNATURE`,Xi=V().check(zr(1)),Zi=Ur().check(si(e=>e>0,`Must be positive`)),J=V().check(z(/^\d+$/,`Invalid atomic amount`)),Qi=ui(),$i=V().check(z(RegExp(`^eip155:\\d+$`),`Invalid EVM CAIP-2 network`)),ea=U({description:K(V()),iconUrl:K(V()),mimeType:K(V()),serviceName:K(V()),tags:K(Xr(V())),url:Xi}),ta=U({amount:J,asset:Xi,extra:K(W(V(),H())),maxTimeoutSeconds:Zi,network:$i,payTo:Xi,scheme:ri(qi)}),na=W(V(),U({info:W(V(),H()),schema:W(V(),H())})),ra=U({accepts:Xr(ta).check(zr(1)),error:K(V()),extensions:K(na),resource:ea,x402Version:G(2)}),ia=ei([U({authorization:U({from:Qi,nonce:di(),to:Qi,validAfter:J,validBefore:J,value:J}),signature:fi()}),U({permit2Authorization:U({deadline:J,from:Qi,nonce:J,permitted:U({amount:J,token:Qi}),spender:Qi,witness:U({to:Qi,validAfter:J})}),signature:fi()})]),aa=U({accepted:ta,extensions:K(na),payload:ia,resource:K(ea),x402Version:G(2)}),oa=U({amount:K(J),errorMessage:K(V()),errorReason:K(V()),extensions:K(na),extra:K(W(V(),H())),network:Xi,payer:K(V()),success:Gr(),transaction:V()}),sa=Gi(ra),ca=Gi(aa),la=Gi(oa);sa.encode,sa.decode;function ua(e){try{let t=JSON.parse(rn(e));return da(t)}catch{throw new Ki}}ca.encode,ca.decode,la.encode,la.decode;const da=e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new Ki;let t=e;if(t.x402Version!==2||!Array.isArray(t.accepts))throw new Ki;let n=ea.parse(t.resource),r=t.extensions===void 0?void 0:na.safeParse(t.extensions).data;return{accepts:t.accepts,...r?{extensions:r}:{},resource:n,x402Version:2}},fa=Symbol.for(`mppx.x402.challenge`);function pa(e){return Object.defineProperty(e,fa,{value:!0}),e}function ma(e){return!!e?.[fa]}function ha(e){let t={};for(let n of e){let e=t[n.name]??={};e[n.intent]=ba(n)}return t}function ga(e,t){let n=ha(e),r=Da(e,n,t),i=e.map((e,t)=>({intent:e.intent,method:e.name,q:r[ba(e)]??1,index:t}));return{definition:r,entries:i,header:va(i),keys:n}}function _a(e){let t=e.split(/\s*,\s*/).map(e=>e.trim()).filter(Boolean);if(t.length===0)throw Error(`Accept-Payment header is empty.`);return t.map((e,t)=>Ta(e,t))}function va(e){return e.map(({method:e,intent:t,q:n})=>{let r=`${e}/${t}`;return n===1?r:`${r};q=${ja(n)}`}).join(`, `)}function ya(e,t,n){let r=new Map;for(let e of t){let t=ba(e),n=r.get(t);n?n.push(e):r.set(t,[e])}return e.flatMap((e,t)=>{let i=r.get(ba(e));if(!i)return[];let a=xa(e,n);return!a||a.q<=0?[]:i.filter(t=>t.canHandleChallenge?.({challenge:e})??!0).map(n=>({challenge:e,index:t,match:a,method:n}))}).sort((e,t)=>wa(e.challenge)-wa(t.challenge)||t.match.q-e.match.q||e.index-t.index).map(e=>{let{match:t,...n}=e;return n})}function ba(e){let t=e.method??e.name;if(!t)throw Error(`Missing payment method name.`);return`${t}/${e.intent}`}function xa(e,t){let n;for(let r of t){if(!Sa(e,r))continue;let t={...r,specificity:Ca(r)};(!n||t.specificity>n.specificity||t.specificity===n.specificity&&t.q>n.q||t.specificity===n.specificity&&t.q===n.q&&t.index<n.index)&&(n=t)}return n}function Sa(e,t){return(t.method===`*`||t.method===e.method)&&(t.intent===`*`||t.intent===e.intent)}function Ca(e){return Number(e.method!==`*`)+Number(e.intent!==`*`)}function wa(e){return+!!ma(e)}function Ta(e,t){let n=/^(?<method>[^/;\s]+|\*)\s*\/\s*(?<intent>[^/;\s]+|\*)(?<params>(?:\s*;\s*.+)?)$/u.exec(e),r=n?.groups?.method,i=n?.groups?.intent;if(!r||!i)throw Error(`Invalid Accept-Payment entry: ${e}`);Ma(r,`method`),Ma(i,`intent`);let a=1;for(let t of Ea(n.groups?.params)){if(!t)continue;let n=/^(?<name>[A-Za-z0-9_-]+)\s*=\s*(?<value>\S+)$/u.exec(t),r=n?.groups?.name,i=n?.groups?.value;if(!r||!i)throw Error(`Invalid Accept-Payment parameter: ${t}`);r===`q`&&(a=ka(i,`Accept-Payment entry "${e}"`))}return{intent:i,method:r,q:a,index:t}}function Ea(e){return e?e.split(/\s*;\s*/).filter(Boolean):[]}function Da(e,t,n){if(!n)return{};let r=typeof n==`function`?n(t):n,i=new Set(e.map(e=>ba(e))),a={};for(let[e,t]of Object.entries(r??{})){if(!i.has(e))throw Error(`Unknown payment preference "${e}". Available: ${[...i].join(`, `)}`);a[e]=Oa(t,`payment preference "${e}"`)}return a}function Oa(e,t){if(typeof e!=`number`||Number.isNaN(e)||!Number.isFinite(e))throw Error(`Invalid q-value for ${t}. Expected a finite number.`);return Aa(e,t)}function ka(e,t){if(!/^0(?:\.\d{0,3})?$|^1(?:\.0{0,3})?$/.test(e))throw Error(`Invalid q-value for ${t}. Expected an HTTP qvalue.`);return Aa(Number(e),t)}function Aa(e,t){if(e<0||e>1)throw Error(`Invalid q-value for ${t}. Expected a value between 0 and 1.`);let n=Math.round(e*1e3);if(Math.abs(e*1e3-n)>1e-9)throw Error(`Invalid q-value for ${t}. Expected at most 3 decimal places.`);return n/1e3}function ja(e){return e.toFixed(3).replace(/\.0+$/,``).replace(/(\.\d*?)0+$/,`$1`)}function Ma(e,t){if(e!==`*`&&!/^[a-z0-9-]+$/.test(e))throw Error(`Invalid Accept-Payment ${t}: ${e}`)}var Na=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function Pa(e){}function Fa(e){if(typeof e==`function`)throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=Pa,onError:n=Pa,onRetry:r=Pa,onComment:i,maxBufferSize:a}=e,o=[],s=0,c=!0,l,u=``,d=0,f,p=!1;function m(e){if(p)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,e.charCodeAt(0)===239&&e.charCodeAt(1)===187&&e.charCodeAt(2)===191&&(e=e.slice(3))),o.length===0){let t=g(e);t!==``&&(o.push(t),s=t.length),h();return}if(e.indexOf(`
4
- `)===-1&&e.indexOf(`\r`)===-1){o.push(e),s+=e.length,h();return}o.push(e);let t=o.join(``);o.length=0,s=0;let n=g(t);n!==``&&(o.push(n),s=n.length),h()}function h(){a!==void 0&&(s+u.length<=a||(p=!0,o.length=0,s=0,l=void 0,u=``,d=0,f=void 0,n(new Na(`Buffered data exceeded max buffer size of ${a} characters`,{type:`max-buffer-size-exceeded`}))))}function g(e){let n=0;if(e.indexOf(`\r`)===-1){let r=e.indexOf(`
5
- `,n);for(;r!==-1;){if(n===r){d>0&&t({id:l,event:f,data:u}),l=void 0,u=``,d=0,f=void 0,n=r+1,r=e.indexOf(`
6
- `,n);continue}let i=e.charCodeAt(n);if(Ia(e,n,i)){let i=e.charCodeAt(n+5)===32?n+6:n+5,a=e.slice(i,r);if(d===0&&e.charCodeAt(r+1)===10){t({id:l,event:f,data:a}),l=void 0,u=``,f=void 0,n=r+2,r=e.indexOf(`
7
- `,n);continue}u=d===0?a:`${u}
8
- ${a}`,d++}else La(e,n,i)?f=e.slice(e.charCodeAt(n+6)===32?n+7:n+6,r)||void 0:_(e,n,r);n=r+1,r=e.indexOf(`
9
- `,n)}return e.slice(n)}for(;n<e.length;){let t=e.indexOf(`\r`,n),r=e.indexOf(`
10
- `,n),i=-1;if(t!==-1&&r!==-1?i=t<r?t:r:t===-1?r!==-1&&(i=r):i=t===e.length-1?-1:t,i===-1)break;_(e,n,i),n=i+1,e.charCodeAt(n-1)===13&&e.charCodeAt(n)===10&&n++}return e.slice(n)}function _(e,t,n){if(t===n){y();return}let r=e.charCodeAt(t);if(Ia(e,t,r)){let r=e.charCodeAt(t+5)===32?t+6:t+5,i=e.slice(r,n);u=d===0?i:`${u}
11
- ${i}`,d++;return}if(La(e,t,r)){f=e.slice(e.charCodeAt(t+6)===32?t+7:t+6,n)||void 0;return}if(r===105&&e.charCodeAt(t+1)===100&&e.charCodeAt(t+2)===58){let r=e.slice(e.charCodeAt(t+3)===32?t+4:t+3,n);r.includes(`\0`)||(l=r);return}if(r===58){if(i){let r=e.slice(t,n);i(r.slice(e.charCodeAt(t+1)===32?2:1))}return}let a=e.slice(t,n),o=a.indexOf(`:`);if(o===-1){v(a,``,a);return}let s=a.slice(0,o),c=a.charCodeAt(o+1)===32?2:1;v(s,a.slice(o+c),a)}function v(e,t,i){switch(e){case`event`:f=t||void 0;break;case`data`:u=d===0?t:`${u}
12
- ${t}`,d++;break;case`id`:t.includes(`\0`)||(l=t);break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new Na(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new Na(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}))}}function y(){d>0&&t({id:l,event:f,data:u}),l=void 0,u=``,d=0,f=void 0}function ee(e={}){if(e.consume&&o.length>0){let e=o.join(``);_(e,0,e.length)}c=!0,l=void 0,u=``,d=0,f=void 0,o.length=0,s=0,p=!1}return{feed:m,reset:ee}}function Ia(e,t,n){return n===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function La(e,t,n){return n===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}const Ra=[k.authorization,Ji,`PAYMENT-RESPONSE`,Yi];function za(e,t,n){let r=new Headers(e.headers);for(let e of Ra)(e!==k.authorization||r.get(e)?.startsWith(`Payment `))&&r.delete(e);return r.set(t,n),{...e,headers:r}}function Ba(e){if(typeof e==`string`)try{let t=JSON.parse(e),n=t?.id;return t?.jsonrpc!==`2.0`||typeof t?.method!=`string`?void 0:typeof n==`string`||typeof n==`number`?n:void 0}catch{return}}const Va=new WeakMap;function Ha(e){let t=Ba(e?.body);if(t===void 0)return;let n=new Headers(e?.headers);if(n.has(`mcp-method`))return t;let r=n.get(`accept`)?.toLowerCase()??``;return r.includes(`application/json`)&&r.includes(`text/event-stream`)?t:void 0}function Ua(e){if(!e||typeof e!=`object`)return;let t=e,n=t.id;if(t.jsonrpc!==`2.0`||n!==void 0&&typeof n!=`string`&&typeof n!=`number`)return;let r=`error`in t;if(r!==`result`in t)return r?Number.isInteger(t.error?.code)&&typeof t.error?.message==`string`?e:void 0:n!==void 0&&typeof t.result==`object`?e:void 0}function Wa(e){if(!e||typeof e!=`object`)return;let t=e?.challenges;if(!Array.isArray(t)||t.length===0)return;let n=[];for(let e of t){let t=pi.safeParse(e);if(!t.success)return;n.push(t.data)}let{httpStatus:r,problem:i}=e;return{challenges:n,...typeof r==`number`?{httpStatus:r}:{},...i===void 0?{}:{problem:i}}}function Ga(e){if(e)return`error`in e?e.error?.code!==-32042&&e.error?.code!==-32043?void 0:Wa(e.error.data):Wa(e.result?._meta?.[`org.paymentauth/payment-required`])}function Ka(e,t){return!e||e.id!==t?[]:Ga(e)?.challenges??[]}async function qa(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=!1,i,a=Fa({onEvent(e){if(!r&&e.data&&(r=!0,!(e.event&&e.event!==`message`)))try{i=Ua(JSON.parse(e.data))}catch{}}});try{for(;;){if(r)return i;let{done:e,value:o}=await t.read();if(e)return a.feed(n.decode()),a.reset({consume:!0}),i;a.feed(n.decode(o,{stream:!0}))}}finally{t.cancel().catch(()=>{})}}function Ja(e){let t=Va.get(e);if(t)return t;let n=(async()=>{let t=e.headers.get(`content-type`)?.toLowerCase()??``;if(t.includes(`application/json`))return e.clone().json().then(Ua).catch(()=>void 0);if(t.includes(`text/event-stream`))return qa(e)})();return Va.set(e,n),n}function Ya(){return{getChallenges(e,t){let n=Ha(t);return e.status===402||n===void 0?[]:Ja(e).then(e=>Ka(e,n))},setCredential(e,t){let n=JSON.parse(e.body),r=Mi(t);return{...e,body:JSON.stringify({...n,params:{...n.params,_meta:{...n.params?._meta,"org.paymentauth/credential":r}}})}}}}function Xa(){return{getChallenges(e){return e.status!==402||!e.headers.has(k.wwwAuthenticate)?[]:Ci(e)},setCredential(e,t,n){return za(e,n?.challenge?Di(n.challenge):k.authorization,t)}}}function Za(){return{getChallenges(e){if(e.status!==402)return[];let t=e.headers.get(Ji);if(!t)return[];let n=ua(t);if(e.url&&n.resource.url!==e.url)throw Error(`x402 payment-required resource does not match response URL.`);return n.accepts.flatMap((e,t)=>{let r=ta.safeParse(e);if(!r.success)return[];let i=r.data;return pa(mi({id:`x402:${t}`,intent:`charge`,method:`evm`,realm:new URL(n.resource.url).host,request:{...i,...n.extensions?{extensions:n.extensions}:{},resource:n.resource}}))})},setCredential(e,t){return za(e,Yi,t)}}}function Qa(e){return e}function $a(){let e=[Xa(),Za(),Ya()],t=new WeakMap,n=(e,n)=>{for(let r of n)t.set(r,e);return n},r=(t,r)=>{let i=(a,o)=>{for(let s=a;s<e.length;s++){let a=e[s],c=a.getChallenges(t,r);if(c instanceof Promise)return c.then(e=>i(s+1,[...o,...n(a,e)]));o.push(...n(a,c))}return o};return i(0,[])};return Qa({name:`http`,isPaymentRequired(e,t){if(e.status===402)return!0;let n=r(e,t);return n instanceof Promise?n.then(e=>e.length>0):n.length>0},getChallenges(e,t){return r(e,t)},setCredential(n,r,i){let a=i?.challenge?t.get(i.challenge):void 0,o=e[0];if(!a&&!o)throw Error(`No protocol to attach the credential.`);return(a??o).setCredential(n,r,i)}})}const eo=new WeakMap;function to(e){return eo.has(e)}function no(e,t){return Promise.resolve(eo.get(e)?.(t))}const ro=new WeakMap,io=new WeakMap;function ao(e,t,n){ro.has(e)&&io.set(t,n)}function oo(e,t){return Promise.resolve(ro.get(e)?.(t)??t.response)}const so=Symbol.for(`mppx.fetch.wrapper`);let co;const lo=new WeakMap;async function Y(e,t){let n=e?.attempt.settle;if(!n)return t.status!==`pending`;e.attempt.settle=void 0;let r=await n(t);return r||(e.attempt.settle=n),r}function uo(e){let{acceptPayment:t,acceptPaymentPolicy:n=`always`,fetch:r=globalThis.fetch,maxPaymentRetries:i=3,methods:a,onChallenge:o,orderChallenges:s,transport:c=$a()}=e,l=e.eventDispatcher??po(),u=t??ga(a),d=No(r),f=async(e,t,r)=>{let p=Mo(e,t?.headers),m=p.has(k.acceptPayment),h=Ro(p,u),g=Ao(e,t,p),_=ko(e,t,p,h.header,m,n),v=await d(Po(_.input),_.init),y=jo(_.init,await g);if(!await c.isPaymentRequired(v,y))return v;let ee=t?.context,{context:te,orderChallenges:ne,...re}=y??{},b,x,ie,S;try{for(let n=0;n<i;n++){x=await c.getChallenges(v,y);let i=(await zo(ya(x,a,h.entries),ne??s))[0];if(!i){if(await Y(S,{challenges:x,response:v,status:`rejected`}),n>0)return v;throw Error(`No method found for challenges: ${x.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${a.map(e=>`${e.name}.${e.intent}`).join(`, `)}`)}let u=i.challenge;b=u,ie=i.method,b.expires&&Ri(b.expires,b.id);let p=Wo(v,_.input,_.input),m=S,g=hi(u),te=m?.method===i.method&&m?.key===g,ae=!1;if(m){let e=await Y(m,{challenges:x,response:v,status:te?`pending`:`rejected`});ae=te&&!e}S=ae?m:void 0;let oe=vo(async e=>{if(e===void 0&&ae&&m)return m.promise;ae&&m&&(await Y(m,{status:`rejected`}),S=void 0);let t=e??ee;if(!to(i.method))return Lo(u,i.method,t);let n={prepare:()=>no(i.method,{challenge:u,context:t,fetch:d,input:p})},r=n.prepare().then(()=>Lo(u,i.method,t,n));return S={attempt:n,key:e===void 0?g:void 0,method:i.method,promise:r},r}),C=await l.emit(`challenge.received`,yo({challenge:u,challenges:x,createCredential:oe,init:t,input:e,method:i.method,response:v}))??(o?await o(b,{createCredential:oe}):void 0)??await oe(),se=S;se&&await se.promise.catch(()=>void 0)!==C&&(await Y(se,{status:`rejected`}),S=void 0),Io(C),await l.emit(`credential.created`,bo({challenge:u,credential:C,init:t,input:e,method:i.method,response:v})),v=await d(p,c.setCredential({...re,headers:_.headers},C,{challenge:u}));let ce=await c.isPaymentRequired(v,y);if(ce||(await Y(se,{response:v,status:v.ok?`accepted`:`rejected`}),S=void 0),v.ok&&mo(l,`payment.response`)&&await l.emit(`payment.response`,xo({challenge:u,credential:C,init:t,input:e,method:i.method,response:v})),!ce)return v.ok?oo(i.method,{challenge:u,credential:C,fetch:d,headers:_.headers,input:p,...r?{refetch:()=>f(Po(_.input),t,!1)}:{},response:v,signal:Fo(e,t)}):v}x=void 0;try{x=await c.getChallenges(v,y)}catch{}return await Y(S,{challenges:x,response:v,status:`rejected`}),v}catch(n){throw await Y(S,{challenges:x,response:v,status:`rejected`}),await l.emit(`payment.failed`,So({challenge:b,challenges:x,error:n,init:t,input:e,method:ie,response:v})),n}},p=(e,t)=>f(e,t,!0);return p[so]=d,p}function fo(e){let t=Object.getOwnPropertyDescriptor(globalThis,`fetch`);if(!t||!t.writable&&!t.set)throw Error(`globalThis.fetch is not writable`);co||=globalThis.fetch,globalThis.fetch=uo({...e,acceptPaymentPolicy:e.acceptPaymentPolicy??(Ho()?`same-origin`:`always`),fetch:globalThis.fetch})}function po(){let e={"*":new Set,"challenge.received":new Set,"credential.created":new Set,"payment.failed":new Set,"payment.response":new Set},t={async emit(t,n){switch(t){case`challenge.received`:{let r;for(let t of e[`challenge.received`]){let e=await ho(t,n);if(typeof e==`string`&&e.length>0){r=e;break}}return await _o(e[`*`],t,n),r}case`credential.created`:await go(e[`credential.created`],n),await _o(e[`*`],t,n);return;case`payment.failed`:await go(e[`payment.failed`],n),await _o(e[`*`],t,n);return;case`payment.response`:await go(e[`payment.response`],n),await _o(e[`*`],t,n);return}},on:(t,n)=>{switch(t){case`*`:case`challenge.received`:case`credential.created`:case`payment.failed`:case`payment.response`:return e[t].add(n),()=>e[t].delete(n);default:throw Error(`Unknown client event "${String(t)}".`)}}};return lo.set(t,t=>e[t].size>0||e[`*`].size>0),t}function mo(e,t){return lo.get(e)?.(t)??!0}async function ho(e,t){try{return await e(t)}catch{return}}async function go(e,t){for(let n of e)try{await n(t)}catch{}}async function _o(e,t,n){await go(e,Object.freeze({name:t,payload:n}))}function vo(e){let t;return n=>(t??=e(n),t)}function yo(e){return Object.freeze({challenge:X(e.challenge),challenges:e.challenges.map(e=>X(e)),createCredential:e.createCredential,init:Co(e.init),input:wo(e.input),method:To(e.method),response:Eo(e.response)})}function bo(e){return Object.freeze({challenge:X(e.challenge),credential:e.credential,init:Co(e.init),input:wo(e.input),method:To(e.method),...e.response===void 0?{}:{response:Eo(e.response)}})}function xo(e){return Object.freeze({challenge:X(e.challenge),credential:e.credential,init:Co(e.init),input:wo(e.input),method:To(e.method),response:Eo(e.response)})}function So(e){return Object.freeze({...e.challenge?{challenge:X(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>X(e))}:{},error:e.error,init:Co(e.init),input:wo(e.input),...e.method?{method:To(e.method)}:{},...e.response===void 0?{}:{response:Eo(e.response)}})}function Co(e){if(e)return Oo({...e,...e.headers?{headers:new Headers(e.headers)}:{}})}function wo(e){if(e instanceof Request)try{return e.clone()}catch{return e}return e instanceof URL?new URL(e):e}function To(e){return Oo(Object.assign({},e))}function Eo(e){return e instanceof Response?e.clone():X(e)}function X(e){try{return Do(structuredClone(e))}catch{return Oo(e)}}function Do(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))Do(t);return e}function Oo(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function ko(e,t,n,r,i,a){let o=!!r&&!i&&Bo(e,a);if(!o)return{headers:n,init:t,input:e};let s=new Headers(e instanceof Request?e.headers:void 0);return n.forEach((e,t)=>{s.set(t,e)}),s.set(k.acceptPayment,r),t?(t.headers=s,{headers:s,init:t,input:e}):{headers:s,init:o?{headers:s}:void 0,input:e}}function Ao(e,t,n){if(e instanceof Request&&t?.body===void 0&&e.body&&!e.bodyUsed){if(!n.has(`mcp-method`)){let e=n.get(`accept`)?.toLowerCase()??``;if(!e.includes(`application/json`)||!e.includes(`text/event-stream`))return}try{return e.clone().text().catch(()=>void 0)}catch{return}}}function jo(e,t){return t===void 0?e:{...e,body:t}}function Mo(e,t){return t?new Headers(t):new Headers(e instanceof Request?e.headers:void 0)}function No(e){let t=e;for(;t[so];)t=t[so];return t}function Po(e){if(!(e instanceof Request)||!e.body||e.bodyUsed)return e;try{return e.clone()}catch{return e}}function Fo(e,t){return t?.signal??(e instanceof Request?e.signal:void 0)}function Io(e){if(!e.trim())throw Error(`Credential header value must be non-empty`);if(e.includes(`\r`)||e.includes(`
13
- `))throw Error(`Credential header value contains illegal newline characters`)}async function Lo(e,t,n,r){let i=t.context&&n!==void 0?t.context.parse(n):void 0,a=i===void 0?{challenge:e}:{challenge:e,context:i};return r&&ao(t,a,r),t.createCredential(a)}function Ro(e,t){let n=e.get(k.acceptPayment);if(!n)return t;try{return{...t,entries:_a(n),header:n}}catch{return t}}async function zo(e,t){return t?t(e):e}function Bo(e,t){if(t===`always`)return!0;if(t===`never`)return!1;let n=Uo(e);return t===`same-origin`?!Ho()||n.origin===globalThis.location.origin:t.origins.some(e=>Vo(n,e))}function Vo(e,t){if(t.startsWith(`*.`)){let n=t.slice(1);return e.hostname.endsWith(n)||e.hostname===t.slice(2)}return e.origin===new URL(t).origin}function Ho(){return globalThis.location!==void 0}function Uo(e){return e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e,Ho()?globalThis.location.href:void 0)}function Wo(e,t,n){if(!e.url)return t;let r=new URL(e.url),i=Uo(n);if(r.origin!==i.origin)throw Error(`Refusing to send payment credential across redirect from ${i.origin} to ${r.origin}`);return e.url}function Go(){let e=new Uint8Array(64);return crypto.getRandomValues(e),Object.freeze({created:Math.floor(Date.now()/1e3),nonce:en(e,{pad:!1,url:!0})})}function Ko(...e){return{protocol:`composed`,async sign(t,n=Go()){for(let r of e)t=await r.sign(t,n);return t}}}function qo(e,t){return async(n,r)=>e(await t.sign(new Request(n,r)))}function Jo(e){let{attestation:t,maxPaymentRetries:n,onChallenge:r,orderChallenges:i,polyfill:a=!0,acceptPaymentPolicy:o=a&&globalThis.location!==void 0?`same-origin`:`always`,transport:s=$a()}=e,c=e.fetch??globalThis.fetch,l=t?Yo(c,t):c,u=e.methods.flat(),d=ga(u,e.paymentPreferences),f=po(),p=r,m={acceptPayment:d,acceptPaymentPolicy:o,...(e.fetch||t)&&{fetch:l},eventDispatcher:f,...n!==void 0&&{maxPaymentRetries:n},...p&&{onChallenge:p},...i&&{orderChallenges:i},methods:u,transport:s},h=uo(m);a&&fo(m);function g(e){return f.on(`challenge.received`,e)}function _(e){return f.on(`credential.created`,e)}function v(e){return f.on(`payment.failed`,e)}function y(e){return f.on(`payment.response`,e)}async function ee(e,t){let n=ts(e),r=await s.getChallenges(e,t?.request),a=Object.freeze(r.map(e=>Z(e))),o=is(d.entries,t?.acceptPayment),c,l;try{let e=(await as(ya(r,u,o),t?.orderChallenges??i))[0];if(!e)throw Error(`No method found for challenges: ${r.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${u.map(e=>`${e.name}.${e.intent}`).join(`, `)}`);let d=e.challenge;c=a[e.index],l=e.method,c.expires&&Ri(c.expires,c.id);let p=c,m=l,h=Xo(async e=>{try{p.expires&&Ri(p.expires,p.id);let t=Xo(t=>os(p,m,t??e)),i=await f.emit(`challenge.received`,Zo({challenge:p,challenges:r,createCredential:t,method:m,response:n}))??await t();return Io(i),await f.emit(`credential.created`,Qo({challenge:p,credential:i,method:m,response:n})),i}catch(e){throw await f.emit(`payment.failed`,$o({challenge:p,challenges:r,error:e,method:m,response:n})),e}});return Object.freeze({challenge:p,challenges:a,createCredential:h,method:es(m),setCredential(e,t){return Io(t),s.setCredential(e,t,{challenge:d})}})}catch(e){throw await f.emit(`payment.failed`,$o({challenge:c,challenges:r,error:e,method:l,response:n})),e}}return{fetch:h,rawFetch:c,methods:u,transport:s,on:f.on,onChallengeReceived:g,onCredentialCreated:_,onPaymentFailed:v,onPaymentResponse:y,preparePayment:ee,async createCredential(e,t,n){return(await ee(e,n)).createCredential(t)}}}function Yo(e,t){let n=Object.values(t);if(n.length===0)throw TypeError(`Mppx client attestation must configure at least one signer.`);return qo(e,Ko(...n))}function Xo(e){let t;return n=>(t??=e(n),t)}function Zo(e){return Object.freeze({challenge:Z(e.challenge),challenges:e.challenges.map(e=>Z(e)),createCredential:e.createCredential,method:es(e.method),response:ts(e.response)})}function Qo(e){return Object.freeze({challenge:Z(e.challenge),credential:e.credential,method:es(e.method),response:ts(e.response)})}function $o(e){return Object.freeze({...e.challenge?{challenge:Z(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>Z(e))}:{},error:e.error,...e.method?{method:es(e.method)}:{},response:ts(e.response)})}function es(e){return rs(Object.assign({},e))}function ts(e){if(e instanceof Response)try{return e.clone()}catch{return new Response(null,{headers:e.headers,status:e.status,statusText:e.statusText})}return Z(e)}function Z(e){try{let t=structuredClone(e);if(e&&t&&typeof e==`object`&&typeof t==`object`)for(let n of Object.getOwnPropertySymbols(e)){let r=Object.getOwnPropertyDescriptor(e,n);r&&Object.defineProperty(t,n,r)}return ns(t)}catch{return rs(e)}}function ns(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))ns(t);return e}function rs(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function is(e,t){return t?typeof t==`string`?_a(t):t:e}async function as(e,t){return t?t(e):e}async function os(e,t,n){let r=t.context&&n!==void 0?t.context.parse(n):void 0;return t.createCredential(r===void 0?{challenge:e}:{challenge:e,context:r})}const ss=2048;var Q=class extends Error{name=`MppResourceUrlError`};function cs(e){if(e.length>ss)throw new Q(`MPP resource URL is too long`);if(Array.from(e).some(e=>{let t=e.charCodeAt(0);return e===`\\`||t<=32||t===127}))throw new Q(`MPP resource URL is invalid`);let t=e.match(/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)([^?#]*)(\?[^#]*)?(?:#.*)?$/);if(!t)throw new Q(`MPP resource URL must be absolute`);let n;try{n=new URL(e)}catch{throw new Q(`MPP resource URL is invalid`)}if(n.username||n.password)throw new Q(`MPP resource URL must not contain credentials`);let r=n.protocol.toLowerCase();if(r!==`https:`&&!(r===`http:`&&ls(n.hostname)))throw new Q(`MPP resource URL must use HTTPS or loopback HTTP`);let i=t[3]||`/`,a=t[4]||``,o=`${r}//${n.hostname.toLowerCase()}${n.port?`:${n.port}`:``}${i}${a}`;if(o.length>ss)throw new Q(`MPP resource URL is too long`);return o}function ls(e){let t=e.toLowerCase();if(t===`localhost`||t===`[::1]`)return!0;let n=t.split(`.`);return n.length===4&&n[0]===`127`&&n.every(e=>/^\d{1,3}$/.test(e)&&Number(e)<=255)}const us=/^[A-Za-z0-9_-]+$/,ds=/^0x[0-9a-fA-F]{40}$/,fs=/^(?:0|[1-9]\d*)$/,ps=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/,ms=/^sha-256=:([A-Za-z0-9+/]{43}=):$/,hs=/^sha-256=([A-Za-z0-9+/]{43}=)$/,gs=new Set([`mpp_challenge_not_payable`,`mpp_network_mismatch`,`mpp_counterparty_rail_not_found`]),_s=`mpp_counterparty_rail_not_found`,vs=`mpp_network_mismatch`,ys=U({type:G(`authorization`),from:V(),to:V(),value:V(),validAfter:V(),validBefore:V(),nonce:V(),signature:V()}),bs={amount:V(),currency:V(),description:K(V()),externalId:K(V()),recipient:V()},xs=U({...bs,methodDetails:U({chainId:Ur(),credentialTypes:Xr(G(`authorization`)),decimals:G(6),permit2Address:K(V()),splits:K(Jr())})}),Ss=U({...bs,methodDetails:U({type:G(`evm`),evm:U({chainId:Ur(),credentialTypes:K(Xr(G(`authorization`))),decimals:G(6),permit2Address:K(V()),splits:K(Jr())})})}),Cs=zi({name:`evm`,intent:`charge`,schema:{credential:{payload:ys},request:xs}}),ws=zi({name:`usdc`,intent:`charge`,schema:{credential:{payload:ys},request:Ss}});var Ts=class extends Error{intentId;status;reasons;expiresAt;constructor(e,t){super(e),this.name=`MppPaymentError`,this.intentId=t.intentId,this.status=t.status,this.reasons=t.reasons,this.expiresAt=t.expiresAt}},$=class extends Error{intentId;reasons;constructor(e,t={}){super(e,t.cause===void 0?void 0:{cause:t.cause}),this.name=`MppFetchPaymentError`,this.intentId=t.intentId,this.reasons=t.reasons??[]}},Es=class extends ${accountId;requiredNetworks;constructor(e,t,n){super(`Account ${e} cannot pay on the MPP challenge's required network${t.length===1?``:`s`}: ${t.map(ce).join(`, `)}`,{reasons:n}),this.name=`MppNetworkMismatchError`,this.accountId=e,this.requiredNetworks=t}},Ds=class extends ${recipient;network;requiredRail;constructor(e,t,n,r){super(`No saved Catena counterparty rail can pay ${e} on ${t}`,{reasons:n}),this.name=`MppCounterpartyNotFoundError`,this.recipient=e,this.network=t,this.requiredRail=r}},Os=class extends ${expiresAt;constructor(e,t,n){super(`The MPP payment is awaiting human approval (intent ${e}); retry the request after approval`,{intentId:e,reasons:t}),this.name=`MppApprovalPendingError`,this.expiresAt=n}},ks=class extends ${status;constructor(e,t,n){super(`Catena ${t} the MPP payment (intent ${e})`,{intentId:e,reasons:n}),this.name=`MppPaymentDeclinedError`,this.status=t}},As=class extends ${method;atomicAmount;network;recipient;resourceUrl;constructor(e,t,n,r){super(`The MPP payment could not be confirmed (intent ${e}); reconcile it with getIntent("${e}") before paying again`,{intentId:e,cause:r}),this.name=`MppSubmitInterruptedError`,this.method=t.method,this.atomicAmount=t.atomicAmount,this.network=t.network,this.recipient=t.recipient,this.resourceUrl=n}},js=class extends ${receipt;constructor(e,t){super(`The MPP payment completed (intent ${e.intentId}) but the post-payment continuation failed; inspect getIntent("${e.intentId}") before retrying manually`,{intentId:e.intentId,cause:t}),this.name=`MppRetryFailedError`,this.receipt=e}};function Ms(e){let t=async({challenge:t})=>(await Us(e,Hs(t,e.maxAtomicAmount))).credential;return[Bi(Cs,{canHandleChallenge:({challenge:t})=>Ws(`evm`,t,e.maxAtomicAmount)!==void 0,createCredential:t}),Bi(ws,{canHandleChallenge:({challenge:t})=>Ws(`usdc`,t,e.maxAtomicAmount)!==void 0,createCredential:t})]}const Ns=Object.assign(e=>Ms(e),{charge:Ms});function Ps(e,t){let n=(t.baseFetch??globalThis.fetch).bind(globalThis),r={client:e,accountId:t.accountId,...t.maxAtomicAmount!==void 0&&{maxAtomicAmount:t.maxAtomicAmount}},i=Jo({methods:Ns(r),fetch:n,polyfill:!1});return async(a,o)=>{let s=await n(a,o);if(s.status!==402||!s.headers.has(`WWW-Authenticate`))return s;let c;try{c=await i.transport.getChallenges(s,o)}catch{return s}if(c.length===0)return s;if(!x(a,o))throw new $(`The request body cannot be replayed after MPP payment; buffer it as a string, URLSearchParams, Blob, ArrayBuffer, or typed array`);let l=Rs(a,s),{payment:u,prepared:d}=await Fs(i,s,c,o,r,l),f={intentId:u.intentId,...u.terms,resourceUrl:l};await Bs(f,async()=>{await t.onPayment?.(f)});let p=se(a,o),m=d.setCredential({...o,headers:p},u.credential),h=await Bs(f,()=>n(a,m));if(h.status===402)throw new js(f,Error(`The paid MPP retry still requires payment`));return Vs(e,f.intentId,h),h}}async function Fs(e,t,n,r,i,a){let o,s=[];for(let c=0;c<5;c+=1){let l={missing:!1},u;try{u=await e.preparePayment(t,{request:r,orderChallenges:e=>{o??=e.slice(0,5).map(e=>e.index);let t=o[c],n=e.find(e=>e.index===t);return l.missing=n===void 0,n===void 0?[]:[n]}})}catch(e){let t=o??[];if(t.length===0)throw n.some(e=>Gs(e,i.maxAtomicAmount))?new $(`Every supported charge in the MPP challenge costs more than the caller's maximum amount`,{cause:e}):new $(`The MPP challenge offers no Catena-supported native USDC charge`,{cause:e});if(l.missing&&s.length>0){if(c+1<t.length)continue;break}throw new $(`The selected MPP challenge could not be prepared`,{cause:e})}let d=Hs(u.challenge,i.maxAtomicAmount);try{return{payment:await Us(i,d,a),prepared:u}}catch(e){if(e instanceof _&&e.code!==void 0&&gs.has(e.code))s.push({error:e,terms:d.terms});else throw Is(e,d.terms,a)}if(c+1>=(o?.length??0))break}throw Ls(i.accountId,s)}function Is(e,t,n){if(e instanceof ue&&e.outcome===`unknown`)return new As(e.intentId,t,n,e);if(!(e instanceof Ts))return e;switch(e.status){case`pending`:return new Os(e.intentId,e.reasons,e.expiresAt);case`blocked`:case`failed`:return new ks(e.intentId,e.status,e.reasons);case`processing`:case`completed`:return new $(e.message,{intentId:e.intentId,reasons:e.reasons,cause:e})}return Ce(e.status)}function Ls(e,t){let n=t.filter(e=>e.error.code===_s),r=t.filter(e=>e.error.code===vs),i=t.filter(e=>e.error.code!==_s&&e.error.code!==vs),a=[...new Set([...n,...r,...i].map(e=>e.error.message))],o=n.find(e=>e.error.status===404);return o?new Ds(o.terms.recipient,o.terms.network,a,xe(o.error.details,o.terms.recipient)):r.length>0&&n.length===0?new Es(e,[...new Set(r.map(e=>e.terms.network))],a):new $(`No supported candidate in the MPP challenge is payable from this account`,{reasons:a})}function Rs(e,t){let n;try{n=typeof e==`string`?zs(e):e instanceof URL?e:new URL(e.url)}catch(e){throw new $(`The MPP resource request URL must be absolute`,{cause:e})}let r;try{r=new URL(t.url||n.href)}catch(e){throw new $(`The final MPP resource URL is invalid`,{cause:e})}if(r.origin!==n.origin)throw new $(`Refusing to pay after a cross-origin redirect from ${n.origin} to ${r.origin}`);try{return cs(t.url||n.href)}catch(e){throw new $(`The final MPP resource URL cannot be bound to a payment intent`,{cause:e})}}function zs(e){try{return new URL(e)}catch{return new URL(e,globalThis.location.href)}}async function Bs(e,t){try{return await t()}catch(t){throw new js(e,t)}}function Vs(e,t,n){try{let r=Wi(n);if(!ge.test(r.reference))return;pe(e,t,r.reference)}catch{return}}function Hs(e,t){let n=e.method;if(n!==`evm`&&n!==`usdc`)throw Error(`Unsupported Catena MPP challenge ${e.method}/${e.intent}`);let r=Ws(n,e,t);if(r===void 0)throw Error(`Catena MPP charge challenge failed validation`);return{challenge:{id:e.id,realm:e.realm,method:n,intent:`charge`,request:r.request,...e.description!==void 0&&{description:e.description},...e.digest!==void 0&&{digest:e.digest},expires:r.expires,...r.header!==void 0&&{header:r.header},...e.opaque!==void 0&&{opaque:e.opaque}},terms:r.terms}}async function Us(e,t,n){let r=await e.client.submitIntent({action:{type:`mpp`,accountId:e.accountId,challenge:t.challenge,...n!==void 0&&{resource:{url:n}}}});return{...t,credential:rc(r,t.challenge),intentId:r.id}}function Ws(e,t,n){if(t.method!==e||t.intent!==`charge`)return;let r=Qs(t);if(r===void 0)return;let i=e===`evm`?Js(t.request,n):Ys(t.request,n);return i===void 0?void 0:{...r,terms:i}}function Gs(e,t){if(t===void 0||e.method!==`evm`&&e.method!==`usdc`)return!1;let n=Ws(e.method,e,void 0);return n!==void 0&&BigInt(n.terms.atomicAmount)>t}function Ks(e,t){return tc(e.amount)&&(t===void 0||BigInt(e.amount)<=t)&&nc(e.currency)&&nc(e.recipient)&&(e.description===void 0||qs(e.description,1024))&&(e.externalId===void 0||qs(e.externalId,256))}function qs(e,t){if(e.length>t)return!1;for(let t of e){let e=t.codePointAt(0);if(e!==void 0&&e>=55296&&e<=57343)return!1}return!0}function Js(e,t){let n=xs.safeParse(e);if(!n.success||!Ks(n.data,t))return;let{amount:r,methodDetails:i,recipient:a}=n.data,o=Zs(i.chainId);return Xs(i)&&i.credentialTypes.length===1&&o!==void 0?{method:`evm`,atomicAmount:r,network:o,recipient:a}:void 0}function Ys(e,t){let n=Ss.safeParse(e);if(!n.success||!Ks(n.data,t))return;let{amount:r,methodDetails:i,recipient:a}=n.data,o=i.evm,s=Zs(o.chainId);return Xs(o)&&(o.credentialTypes===void 0||o.credentialTypes.length===1)&&s!==void 0?{method:`usdc`,atomicAmount:r,network:s,recipient:a}:void 0}function Xs(e){return Number.isSafeInteger(e.chainId)&&e.chainId>=1&&(e.permit2Address===void 0||nc(e.permit2Address))}function Zs(e){return Number.isSafeInteger(e)&&e>=1?`eip155:${e}`:void 0}function Qs(e){if(!$s(e))return;let t=Date.parse(e.expires),n=t-Date.now();if(!Number.isFinite(t)||n<5e3||n>36e5)return;let r=A(e.request),i=new TextEncoder().encode(JSON.stringify({...e,request:r})).byteLength;return r.length>0&&r.length<=16384&&i<=32768?{request:r,expires:e.expires,header:e.header}:void 0}function $s(e){return!(e.id.length<1||e.id.length>256||e.realm.length<1||e.realm.length>256||e.expires===void 0||!ps.test(e.expires)||e.description!==void 0&&e.description.length>1024||e.header!==void 0&&e.header!==`Payment-Authorization`||e.opaque!==void 0&&(e.opaque.length>8192||!us.test(e.opaque))||e.digest!==void 0&&!ec(e.digest))}function ec(e){if(e.length>128)return!1;let t=ms.exec(e)??hs.exec(e);if(!t)return!1;try{let e=atob(t[1]);return e.length===32&&btoa(e)===t[1]}catch{return!1}}function tc(e){return e.length<=78&&fs.test(e)&&BigInt(e)>0n}function nc(e){return ds.test(e)&&yt(e)}function rc(e,t){switch(e.status){case`completed`:{let n=te(e.data,`mpp`);if(n===void 0)throw oc(`Catena MPP payment ${e.id} completed without an MPP credential`,e);if(!ic(n,t))throw oc(`Catena MPP payment ${e.id} completed with a credential that does not match the selected challenge; reconcile with client.getIntent("${e.id}") before another payment attempt`,e);return n}case`pending`:throw oc(`Catena MPP payment ${e.id} is pending${sc(e.reasons)}`,e);case`processing`:throw oc(`Catena MPP payment ${e.id} is processing; if it was approved, re-run the paid request so a fresh challenge can consume the grant (polling never advances an approved payment); otherwise poll client.getIntent("${e.id}"), because an executing payment completes on its own`,e);case`blocked`:throw oc(`Catena MPP payment ${e.id} was blocked${sc(e.reasons)}`,e);case`failed`:throw oc(`Catena MPP payment ${e.id} failed${sc(e.reasons)}`,e)}return Ce(e.status)}function ic(e,t){if(e.trim().length===0||e.includes(`\r`)||e.includes(`
14
- `))return!1;let n;try{n=Mi(e)}catch{return!1}let r=n.challenge;if(r.id!==t.id||r.realm!==t.realm||r.method!==t.method||r.intent!==t.intent||r.description!==t.description||r.digest!==t.digest||r.expires!==t.expires||r.header!==t.header||r.opaque!==t.opaque||A(r.request)!==t.request)return!1;let i=ys.safeParse(n.payload),a=t.method===`evm`?xs.safeParse(r.request):Ss.safeParse(r.request);if(!i.success||!a.success)return!1;let o=a.data.recipient;return nc(i.data.from)&&nc(i.data.to)&&i.data.to.toLowerCase()===o.toLowerCase()&&i.data.value===a.data.amount&&ac(i.data.validAfter)&&ac(i.data.validBefore)&&BigInt(i.data.validBefore)>BigInt(i.data.validAfter)&&/^0x[0-9a-fA-F]{64}$/.test(i.data.nonce)&&/^0x[0-9a-fA-F]{130}$/.test(i.data.signature)}function ac(e){return e.length<=78&&fs.test(e)}function oc(e,t){return new Ts(e,{intentId:t.id,status:t.status,reasons:t.reasons,expiresAt:t.expiresAt})}function sc(e){return e.length>0?`: ${e.join(`; `)}`:``}function cc(e){return{intentId:e.intentId,method:e.method,amountAtomicUsdc:e.atomicAmount,recipient:e.recipient,network:e.network}}const lc=/(?:^|,)\s*Payment(?![!#$%&'*+\-.^_`|~0-9A-Za-z])/i;function uc(e,t){he(e,`payment-authorization`)&&ne(`--header cannot set Payment-Authorization; the payment loop attaches it after paying`),e.some(e=>e.name.toLowerCase()===`authorization`&&lc.test(e.value))&&ne(`--header cannot provide the Payment authentication scheme in Authorization; the payment loop attaches it after paying`),_e(e,t)}const dc=b({url:w({description:`The paywalled URL to fetch (an MPP endpoint)`,required:!0,schema:T.pipe(T.string(),T.url())}),account:w({description:`Source wallet account id the payment draws from`,required:!0,schema:Se}),maxAmount:w({description:`Refuse challenges above this USD amount (decimal string, e.g. 0.25). Policy limits still apply server-side.`,schema:T.pipe(T.string(),T.regex(/^\d+(\.\d{1,6})?$/))}),method:re({description:`HTTP method for the request`,choices:[`GET`,`POST`]}),data:w({description:`Request body. Use @path to read a file or @- for stdin. Implies POST and a JSON content type unless overridden.`}),contentType:w({description:`Content-Type header for the request body (default application/json when --data is set)`}),output:w({description:`Write the full response body to this file (must be a regular file; written for any HTTP status — check .status). Without it .body is capped at 4000 characters; longer or non-UTF-8 bodies are saved to a file (path reported in .bodyPath)`}),header:v({description:`Request header as "Name: Value" (repeatable, like curl -H); sent on both requests, except caller Authorization is replaced on the paid retry when MPP uses that field for its credential`,schema:ae}),profile:y,json:ee}),fc=we({meta:{name:`mpp`,description:`Fetch a URL, paying its MPP challenge via USDC`},args:dc.args,async run({args:e,rawArgs:t}){let n=dc.parse(e,t),r=n.method??(n.data===void 0?`GET`:`POST`);n.data!==void 0&&r!==`POST`&&ne(`--data cannot be sent with --method ${r}; a body requires POST`),n.contentType!==void 0&&n.data===void 0&&ne(`--content-type has no effect without --data`),uc(n.header,n.contentType);let i=n.output===void 0?void 0:me(n.output),a=n.data===void 0?void 0:oe(n.data),o=le(n.header,n.contentType,a);await S(n)(async e=>{let t,s=Ps(e,{accountId:n.account,...n.maxAmount!==void 0&&{maxAtomicAmount:C(n.maxAmount)},onPayment:e=>{t=e}}),c;try{c=await s(n.url,{method:r,...a!==void 0&&{body:a},...o!==void 0&&{headers:o}})}catch(e){if(e instanceof As&&e.intentId!==void 0)throw Error(be(e.intentId,n.profile),{cause:e});if(e instanceof js)return{status:null,paid:!0,retryFailed:!0,payment:cc(e.receipt),error:e.message};if(e instanceof Es){let t=e.requiredNetworks.map(e=>ve(e)??e);return{status:null,paid:!1,retryFailed:!1,networkMismatch:{account:e.accountId,requiredNetworks:t,requiredNetworkIds:[...e.requiredNetworks]},error:`${e.message}. Re-run with --account set to a wallet account on ${t.join(` or `)} (your account ids are in \`catena accounts list${fe(n.profile)}\`).`}}if(e instanceof Ds){let t=e.requiredRail?.network??ve(e.network)??e.network,r=ie(e.recipient,t,void 0,n.profile);return{status:null,paid:!1,retryFailed:!1,counterpartyNotFound:{recipient:e.recipient,network:t,networkId:e.network,...e.requiredRail!==void 0&&{requiredRail:e.requiredRail},createCommand:r,nameIsPlaceholder:!0},error:`${e.message}. Add it, then re-run:\n ${r}\n(counterparty creation may require approval per your policy)`}}if(e instanceof Os)return{status:null,paid:!1,retryFailed:!1,approvalPending:{intentId:e.intentId,expiresAt:e.expiresAt,reasons:[...e.reasons]},error:e.message};throw e}let l={status:c.status,paid:t!==void 0,retryFailed:!1,...t!==void 0&&{payment:cc(t)}},u;try{u=Buffer.from(await c.arrayBuffer())}catch(e){let r=t===void 0?``:`; the payment completed — inspect it with \`catena intents get ${t.intentId}${fe(n.profile)}\` before any manual retry`;return{...l,error:`failed to read the response body: ${de(e)}${r}`}}return{...l,...ye(u,t?.intentId,i)}},{exitCode:e=>+(`error`in e)})}});export{fc as mppCommand};