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