mppx 0.13.2 → 0.13.4
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/CHANGELOG.md +21 -0
- package/dist/cli/cli.js +3 -3
- package/dist/cli/plugins/index.js +1 -1
- package/dist/cli/validate/helpers.d.ts +1 -0
- package/dist/cli/validate/helpers.js +2 -1
- package/dist/internal/version.d.ts +2 -2
- package/dist/internal/version.js +1 -1
- package/dist/server/Mppx.d.ts +1 -1
- package/dist/server/Mppx.js +6 -3
- package/dist/server/internal/challengeMeta.d.ts +5 -0
- package/dist/server/internal/challengeMeta.js +14 -0
- package/dist/tempo/server/Methods.d.ts +5 -0
- package/dist/tempo/server/Methods.js +5 -1
- package/dist/tempo/server/index.d.ts +1 -1
- package/dist/tempo/server/internal/html.gen.js +1 -1
- package/dist/tempo/session/client/Transports.js +39 -12
- package/dist/tempo/session/precompile/Chain.d.ts +4 -0
- package/dist/tempo/session/precompile/Chain.js +8 -2
- package/dist/tempo/session/server/ChannelStore.d.ts +8 -0
- package/dist/tempo/session/server/ChannelStore.js +17 -0
- package/dist/tempo/session/server/CredentialVerification.d.ts +3 -1
- package/dist/tempo/session/server/CredentialVerification.js +56 -11
- package/dist/tempo/session/server/Session.d.ts +4 -2
- package/dist/tempo/session/server/Session.js +23 -5
- package/dist/tempo/session/server/Settlement.d.ts +40 -1
- package/dist/tempo/session/server/Settlement.js +105 -34
- package/dist/tempo/session/server/index.d.ts +1 -1
- package/dist/x402/server/EvmCharge.js +10 -3
- package/package.json +1 -1
package/dist/cli/cli.js
CHANGED
|
@@ -226,7 +226,7 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
|
|
|
226
226
|
`);switch(t){case`message`:return{type:`message`,data:r};case`payment-need-voucher`:{let e=wE(r);return yE(e)?{type:`payment-need-voucher`,data:e}:null}case`payment-receipt`:{let e=wE(r);return bE(e)?{type:`payment-receipt`,data:e}:null}default:return{type:`message`,data:r}}}function wE(e){try{return JSON.parse(e)}catch{return null}}function TE(e){return JSON.stringify({mpp:`authorization`,authorization:e})}function EE(){return JSON.stringify({mpp:`payment-close-request`})}function DE(e){let t=OE(e);return t?t.mpp===`authorization`&&typeof t.authorization==`string`?{mpp:`authorization`,authorization:t.authorization}:t.mpp===`message`&&typeof t.data==`string`?{mpp:`message`,data:t.data}:t.mpp===`payment-close-request`?{mpp:`payment-close-request`}:t.mpp===`payment-close-ready`&&bE(t.data)?{mpp:`payment-close-ready`,data:t.data}:t.mpp===`payment-error`&&typeof t.status==`number`&&typeof t.message==`string`?{mpp:`payment-error`,status:t.status,message:t.message}:t.mpp===`payment-need-voucher`&&yE(t.data)?{mpp:`payment-need-voucher`,data:t.data}:t.mpp===`payment-receipt`&&bE(t.data)?{mpp:`payment-receipt`,data:t.data}:null:null}function OE(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t?null:t}catch{return null}}var kE,AE,jE,ME=F((()=>{kE=(1n<<96n)-1n,AE=new Set([`open`,`topUp`,`voucher`,`close`]),jE=`0x4d50500000000000000000000000000000000000`}));function NE(e){return BE.encode(e)}function PE(e){return BE.decode(e)}var FE,IE,LE,RE,zE,BE,VE=F((()=>{KC(),Xx(),FE=J.custom(e=>typeof e==`string`&&de(e,{strict:!1})),IE=J.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),LE=J.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]+$/.test(e)),RE=J.object({authorizedSigner:FE,expiringNonceHash:IE,operator:FE,payee:FE,payer:FE,salt:IE,token:FE}),zE=J.object({acceptedCumulative:J.string(),chainId:J.number(),channelId:IE,closeRequestedAt:J.optional(J.string()),deposit:J.string(),descriptor:RE,escrow:FE,highestVoucher:J.optional(J.object({channelId:IE,cumulativeAmount:J.string(),signature:LE})),requiredCumulative:J.string(),settled:J.string(),spent:J.string(),units:J.optional(J.number())}),BE=WC(zE)}));function HE(e){return{status:`active`,...e}}function UE(e,t){switch(t.type){case`challengeReceived`:return e.status===`closing`||e.status===`closed`?JE(e,t):{state:{status:`challenged`,challengeId:t.challengeId},effects:[]};case`challenge`:return e.status!==`idle`&&e.status!==`active`?JE(e,t):t.snapshot?{state:{status:`hydrating`,challengeId:t.challengeId,snapshot:t.snapshot},effects:[{type:`hydrate`,snapshot:t.snapshot}]}:{state:{status:`opening`,challengeId:t.challengeId},effects:[{type:`open`}]};case`hydrated`:return e.status===`hydrating`?{state:KE(e.challengeId,t.snapshot),effects:[]}:JE(e,t);case`activated`:return e.status===`closing`||e.status===`closed`?JE(e,t):{state:oD({challengeId:t.challengeId,entry:t.entry,spent:t.spent,units:t.units??0}),effects:[]};case`opened`:return e.status===`opening`?{state:qE(e.challengeId,t.receipt,t.descriptor,t.deposit),effects:[]}:JE(e,t);case`receiptAccepted`:return e.status===`closing`||e.status===`closed`?JE(e,t):{state:lD(t.receipt,t.entry),effects:[]};case`needVoucher`:return e.status===`active`?GE({challengeId:e.challengeId,descriptor:t.descriptor,event:t.event}):JE(e,t);case`topUpStarted`:return e.status===`voucherNeeded`?{state:{status:`toppingUp`,challengeId:e.challengeId,channelId:e.channelId,descriptor:e.descriptor,deposit:e.deposit},effects:[]}:JE(e,t);case`voucherAccepted`:return e.status!==`voucherNeeded`&&e.status!==`toppingUp`?JE(e,t):{state:qE(e.challengeId,t.receipt,e.descriptor,t.deposit??e.deposit),effects:[]};case`settleStarted`:return e.status===`active`?{state:{status:`settling`,channelId:e.channelId,descriptor:e.descriptor,deposit:e.deposit},effects:[{type:`settle`,channelId:e.channelId}]}:JE(e,t);case`settled`:return e.status===`settling`?{state:qE(t.receipt.challengeId,t.receipt,e.descriptor,t.deposit??e.deposit),effects:[]}:JE(e,t);case`closeRequested`:return e.status===`active`?{state:{status:`closeRequested`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`requestClose`,channelId:e.channelId}]}:JE(e,t);case`withdrawable`:return e.status===`closeRequested`?{state:{status:`withdrawable`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`withdraw`,channelId:e.channelId}]}:JE(e,t);case`closeStarted`:return e.status!==`active`&&e.status!==`withdrawable`&&e.status!==`closeRequested`?JE(e,t):{state:{status:`closing`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`close`,channelId:e.channelId}]};case`closed`:return e.status!==`closing`&&e.status!==`withdrawable`?JE(e,t):{state:{status:`closed`,channelId:e.channelId,descriptor:e.descriptor},effects:[]}}}function WE(e,t){let n=UE(e.state,t);return e.state=n.state,n}function GE(e){let{challengeId:t,descriptor:n,event:r}=e,i=BigInt(r.requiredCumulative),a=BigInt(r.deposit);return i>a?{state:{status:`toppingUp`,challengeId:t,channelId:r.channelId,descriptor:n,deposit:r.deposit},effects:[{type:`topUp`,channelId:r.channelId,amount:(i-a).toString()}]}:{state:{status:`voucherNeeded`,challengeId:t,channelId:r.channelId,descriptor:n,requiredCumulative:r.requiredCumulative,deposit:r.deposit},effects:[{type:`voucher`}]}}function KE(e,t){return HE({challengeId:e,channelId:t.channelId,descriptor:t.descriptor,acceptedCumulative:t.acceptedCumulative,deposit:t.deposit,spent:t.spent,units:t.units??0})}function qE(e,t,n,r){return HE({challengeId:e,channelId:t.channelId,descriptor:n,acceptedCumulative:t.acceptedCumulative,deposit:r,spent:t.spent,units:t.units??0})}function JE(e,t){throw Error(`Invalid session transition: ${e.status} + ${t.type}`)}function YE(e){let{cumulativeAmount:t,maxVoucherCumulative:n}=e;if(n!==null&&!(t<=n))throw Error(`requested voucher amount ${t} exceeds local maxDeposit ${n}`)}function XE(e){let{channel:t,maxVoucherCumulative:n,receipt:r}=e;if(!t||r.channelId!==t.channelId)return;let i=BigInt(r.acceptedCumulative),a=BigInt(r.spent);if(a>i)throw Error(`receipt spent exceeds accepted cumulative voucher amount`);if(i>t.cumulativeAmount)throw Error(`receipt accepted cumulative exceeds local voucher state`);if(a>t.cumulativeAmount)throw Error(`receipt spent exceeds local voucher state`);YE({cumulativeAmount:i,maxVoucherCumulative:n}),YE({cumulativeAmount:a,maxVoucherCumulative:n})}function ZE(e){let{channel:t,maxVoucherCumulative:n,receipt:r,spent:i}=e;if(!r||r.channelId!==t?.channelId)return i;XE({channel:t,maxVoucherCumulative:n,receipt:r});let a=BigInt(r.spent);return i>a?i:a}function QE(e,t){return typeof e==`bigint`?e:N(e,t)}function $E(e){let{contextDepositRaw:t,maxDeposit:n,requestAmount:r,suggestedDepositRaw:i}=e;if(tD(r,n),t!==void 0){let e=BigInt(t);if(e<r)throw Error(`opening deposit ${e} below request amount ${r}`);return e}let a=i===void 0?void 0:BigInt(i),o=a!==void 0&&a>r?a:r;return n===void 0||o<n?o:n}function eD(e){let{deposit:t,maxDeposit:n,requiredCumulative:r,suggestedDeposit:i,topUpAmount:a}=e;if(r<=t)return 0n;YE({cumulativeAmount:r,maxVoucherCumulative:n??null});let o=r-t,s=a??i??o,c=s>o?s:o;if(n==null)return c;let l=n-t;return c<l?c:l}function tD(e,t){YE({cumulativeAmount:e,maxVoucherCumulative:t??null})}function nD(e){let{channel:t,currentSocket:n,lastChallenge:r}=e;if(!t?.opened)return;let i=n?.challenge??r,a=n?.channelId??t.channelId;if(!i)throw Error(`Cannot close session: no challenge available. This usually means close() was called on a SessionManager instance that was recreated after the session was opened. Use the same SessionManager instance that opened the session, or make a request first to receive a fresh 402 challenge.`);if(!a)throw Error(`Cannot close session: no channel ID available. The session may not have been fully opened.`);return{challenge:i,channel:t,channelId:a}}function rD(e){let{cumulativeAmount:t,spent:n}=e;return t>n?t:n}function iD(e){let{cumulativeAmount:t,readySpent:n,spent:r}=e;if(!uE(n))throw Error(`close-ready spent is not a uint96 amount`);if(n<r)throw Error(`close-ready spent is below locally confirmed spend`);if(n>rD({cumulativeAmount:t,spent:r}))throw Error(`close-ready spent exceeds local voucher state`)}function aD(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:i=0n,receipt:a}=e,o=dE(r),s=dE(a.spent);return o===void 0||s===void 0||!uE(i)?!1:!!a.txHash&&a.challengeId===t&&a.channelId===n&&a.acceptedCumulative===r&&s>=i&&s<=o}function oD(e){return HE({challengeId:e.challengeId,channelId:e.entry.channelId,descriptor:e.entry.descriptor,acceptedCumulative:e.entry.cumulativeAmount.toString(),deposit:e.entry.deposit.toString(),spent:e.spent,units:e.units})}function sD(){return{channel:null,lastChallenge:null,lastUrl:null,spent:0n,socketSession:null,state:hD}}function cD(e){let{maxVoucherCumulative:t,receipt:n,runtime:r}=e;r.spent=ZE({channel:r.channel,maxVoucherCumulative:t,receipt:n,spent:r.spent}),n&&r.channel?.channelId===n.channelId&&WE(r,{type:`receiptAccepted`,receipt:n,entry:r.channel})}function lD(e,t){return HE({challengeId:e.challengeId,channelId:e.channelId,descriptor:t.descriptor,acceptedCumulative:e.acceptedCumulative,deposit:t.deposit.toString(),spent:e.spent,units:e.units??0})}function uD(e){let{challengeId:t,channelId:n,closeReadyReceipt:r,cumulativeAmount:i,deliveredChunks:a=0n,socketChallengeId:o,socketChannelId:s,spent:c,tickCost:l=0n}=e;if(c>i)throw Error(`locally confirmed spend exceeds local voucher state`);if(r&&r.challengeId===t&&r.channelId===n){let e=dE(r.spent);if(e===void 0)throw Error(`close-ready spent is not a uint96 amount`);return e>c?e:c}if(o===t&&s===n&&l>0n){let e=a*l,t=c>e?c:e;return t>i?i:t}return i}function dD(e){let{channel:t,channelId:n,challengeId:r,cumulativeAmount:i,spent:a,state:o}=e;if(!(!t||t.channelId!==n)&&(t.cumulativeAmount=i,r))return UE(o,{type:`activated`,challengeId:r,entry:t,spent:a.toString(),units:o.status===`active`?o.units:0}).state}function fD(e){return{channel:e.channel===null?null:{entry:e.channel,cumulativeAmount:e.channel.cumulativeAmount,deposit:e.channel.deposit,opened:e.channel.opened},spent:e.spent,state:e.state}}function pD(e,t){return e.channel?(e.channel.entry.cumulativeAmount=e.channel.cumulativeAmount,e.channel.entry.deposit=e.channel.deposit,e.channel.entry.opened=e.channel.opened,{channel:e.channel.entry,spent:e.spent,state:e.state}):(t&&(t.opened=!1),{channel:null,spent:e.spent,state:e.state})}async function mD(e){let{activeSocket:t,currentSocket:n,target:r}=e,i=n.closeReadyReceipt??await(async()=>(t.send(EE()),e.waitForCloseReady()))(),a=BigInt(i.spent);iD({cumulativeAmount:r.channel.cumulativeAmount,readySpent:a,spent:e.spent});let o=await e.createSessionCredential(r.challenge,{action:`close`,channelId:r.channelId,descriptor:r.channel.descriptor,cumulativeAmountRaw:a.toString()}),s=a.toString();n.expectedCloseAmount=s;try{let i=e.waitForReceipt(e=>aD({challengeId:r.challenge.id,channelId:r.channelId,expectedCloseAmount:s,minimumSpent:a,receipt:e}));t.send(TE(o));let c=await i;return t.close(),n.closeReadyReceipt=null,c}finally{n.expectedCloseAmount=null}}var hD,gD=F((()=>{ME(),VE(),hD={status:`idle`}}));function _D(e){let t=new Map,n=!1,r=[],i=e.readyState,a=(e,n,i)=>{let a=t.get(e);if(a||(a=new Set,t.set(e,a)),a.add({once:typeof i==`object`&&i.once===!0,value:n}),e===`message`&&r){let e=r;r=null;for(let t of e)s(`message`,t)}},o=(e,n)=>{let r=t.get(e);if(r)for(let e of r)e.value===n&&r.delete(e)};function s(e,a){if(a.type===`close`){if(n)return;n=!0,i=eO.CLOSED,r=null}if(a.type===`open`&&(i=eO.OPEN),a.type===`message`&&r){r.push(a);return}switch(a.type){case`close`:l.onclose?.(a);break;case`error`:l.onerror?.(a);break;case`message`:l.onmessage?.(a);break;case`open`:l.onopen?.(a)}let o=t.get(e);if(o)for(let e of Array.from(o))typeof e.value==`function`?e.value(a):e.value.handleEvent(a),e.once&&o.delete(e)}let c=null,l={addEventListener:a,close(t,n){e.close(t,n)},get bufferedAmount(){return e.bufferedAmount},get extensions(){return e.extensions},on(e,t){a(e,t)},onclose:null,onerror:null,get onmessage(){return c},set onmessage(e){if(c=e,e&&r){let e=r;r=null;for(let t of e)s(`message`,t)}},onopen:null,off(e,t){o(e,t)},get protocol(){return e.protocol},get readyState(){return i},removeEventListener:o,send(t){e.send(t)},get url(){return e.url}};return{emit:s,socket:l}}function vD(e){return{acceptedCumulative:BigInt(e.acceptedCumulative),deposit:BigInt(e.deposit),requiredCumulative:BigInt(e.requiredCumulative)}}function yD(e){let{amount:t,assertVoucherWithinLocalLimit:n,channel:r,decimals:i,lastChallenge:a,lastUrl:o}=e;if(!r?.opened)throw Error(`Cannot top up session: no open channel.`);if(!a)throw Error(`Cannot top up session: no challenge available. Make a request first.`);if(!o)throw Error(`Cannot top up session: no URL available. Call fetch(), sse(), or ws() first.`);let s=QE(t,i);if(s<=0n)throw Error(`Top-up amount must be greater than zero.`);return n(r.cumulativeAmount+s),{additionalDeposit:s,challenge:a,channelId:r.channelId,input:o}}function bD(e){let{additionalDeposit:t,channel:n,channelId:r,challengeId:i,currentState:a,knownDeposit:o,receipt:s,spent:c}=e;if(n?.channelId!==r)return;let l=o!==void 0&&o>n.deposit?o:n.deposit,u={...n,deposit:l+t};return s?{channel:u,state:lD(s,u)}:i?{channel:u,state:oD({challengeId:i,entry:u,spent:c.toString(),units:a.status===`active`?a.units:0})}:{channel:u}}async function xD(e){if(e.event.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`channel-mismatch`};let t=vD(e.event);e.assertVoucherWithinLocalLimit(t.requiredCumulative),await e.topUpIfNeeded({challenge:e.challenge,input:e.input,channelId:e.expectedChannelId,deposit:t.deposit,requiredCumulative:t.requiredCumulative,...e.signal?{signal:e.signal}:{}});let n=e.getChannel();if(!n||n.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`missing-channel`};let r=n.cumulativeAmount>t.requiredCumulative?n.cumulativeAmount:fE(t.requiredCumulative);return{status:`ready`,context:{action:`voucher`,channelId:e.expectedChannelId,descriptor:n.descriptor,cumulativeAmountRaw:r.toString()}}}function SD(e){return e.method===Ax.tempo&&e.intent===jx.session}function CD(e){return SD(e)&&Ox(e.request.methodDetails,Mx.sessionProtocol)===Nx.v2}function wD(e){return Ox(e.request.methodDetails,Mx.sessionSnapshot)}function TD(e,t,n){let r=e instanceof Request?e.headers:void 0;return{...t,headers:{...Sw(r),...Sw(t?.headers),[q.authorization]:n}}}function ED(e){try{let t=typeof location>`u`?void 0:location.href,n=e instanceof Request?new URL(e.url):e instanceof URL?new URL(e):new URL(String(e),t);return n.hash=``,n}catch{return e}}function DD(e){let t=new URL(e.toString());return t.protocol===`ws:`&&(t.protocol=`http:`),t.protocol===`wss:`&&(t.protocol=`https:`),t}async function OD(e){let t=await e.text().catch(()=>``);if(!t)return``;if(!e.headers.get(`Content-Type`)?.includes(`application/problem+json`))return t;try{return JSON.parse(t).detail??t}catch{return t}}async function kD(e){let{channel:t,channelId:n}=e;if(!t?.descriptor||t.channelId!==n)throw Error(`Cannot top up session: no local channel descriptor available.`);let r=await AD({challenge:e.challenge,context:{action:`topUp`,channelId:n,descriptor:t.descriptor,additionalDepositRaw:e.additionalDeposit.toString()},createSessionCredential:e.createSessionCredential,fetch:e.fetch,input:e.input,signal:e.signal});if(!r.ok)throw Error(`Top-up POST failed with status ${r.status}`);let i=r.headers.get(q.paymentReceipt);return i?xE(i):void 0}async function AD(e){let t=async t=>e.fetch(ED(e.input),{method:`POST`,...e.signal?{signal:e.signal}:{},headers:{[q.authorization]:await e.createSessionCredential(t,e.context)}}),n=await t(e.challenge);if(n.status!==402)return n;let r=sS(n).find(CD);return r?t(r):n}async function jD(e){let t=MD({channel:e.getChannel(),response:e.response});if(!t)return;let{channel:n,challenge:r,snapshot:i}=t;e.setChallenge(r);let a=BigInt(i.requiredCumulative),o=n.cumulativeAmount;await e.topUpIfNeeded({challenge:r,input:e.input,channelId:i.channelId,deposit:BigInt(i.deposit),requiredCumulative:a,signal:e.init?.signal??(e.input instanceof Request?e.input.signal:void 0)});let s=e.getChannel();if(!s?.descriptor||s.channelId!==i.channelId)return;let c=s.cumulativeAmount>a?s.cumulativeAmount:a,l=()=>e.restoreCumulative(i.channelId,o),u;try{let t=await e.createSessionCredential(r,{action:`voucher`,channelId:i.channelId,descriptor:s.descriptor,cumulativeAmountRaw:c.toString()});u=await e.fetch(e.input,TD(e.input,e.init,t))}catch(e){throw await l(),e}return!u.ok&&!u.headers.get(q.paymentReceipt)&&await l(),u}function MD(e){let t=sS(e.response).find(CD);if(!t)return;let n=wD(t);if(!n)return;let{channel:r}=e;if(!(!r?.descriptor||r.channelId!==n.channelId))return{channel:r,challenge:t,snapshot:n}}async function ND(e){if(!e.lastUrl)throw Error(`Cannot close session: no URL available. This usually means close() was called on a SessionManager instance that was recreated after the session was opened. Use the same SessionManager instance that opened the session, or call fetch()/sse() before close().`);let t=e.target.challenge,n=e.signedCloseAmount,r=async(r,i=!1)=>{t=r,n=(i?e.resolveSignedCloseAmount?.(r):void 0)??e.signedCloseAmount;let a=await e.createSessionCredential(r,{action:`close`,channelId:e.target.channelId,descriptor:e.target.channel.descriptor,cumulativeAmountRaw:n});return e.fetch(e.lastUrl,{method:`POST`,headers:{[q.authorization]:a}})},i=await r(e.target.challenge);if(i.status===402){let t=sS(i).find(CD);t&&(e.setChallenge?.(t),i=await r(t,!0))}if(!i.ok){let e=await OD(i),t=i.headers.get(q.wwwAuthenticate)??``;throw Error(`Close request failed with status ${i.status}${e?`: ${e}`:``}${t?` [${q.wwwAuthenticate}: ${t}]`:``}`)}let a=i.headers.get(q.paymentReceipt);if(!a)return;let o=xE(a);if(!o.txHash||!re.validate(o.txHash,{strict:!0})||re.size(o.txHash)!==32||!aD({challengeId:t.id,channelId:e.target.channelId,expectedCloseAmount:n,minimumSpent:e.getMinimumSpent?.()??0n,receipt:o}))throw Error(`Session close response included a mismatched payment receipt.`);return o}async function PD(e,t,n){let{onReceipt:r,signal:i,...a}=t??{},o=i??(e instanceof Request?e.signal:void 0),s={...a,headers:{...Sw(a.headers),Accept:`text/event-stream`},...o?{signal:o}:{}},c=await n.doFetch(e,s);return!SE(c)&&n.getChannel()?.opened&&(c=await n.doFetch(e,s)),FD(e,c,{onReceipt:r,signal:o},n)}function FD(e,t,n,r){if(!SE(t))throw Error(`SSE response is not an event stream.`);if(!t.body)throw Error(`Response has no body.`);let i=r.getChallenge();return ID({onNeedVoucher:t=>VD({challenge:i,driver:r,input:e,signal:n?.signal},t),onReceipt(e){r.acceptReceipt(e),n?.onReceipt?.(e)},response:t,signal:n?.signal})}async function*ID(e){for await(let t of LD(e))t.data!==void 0&&(yield t.data)}async function*LD(e){if(!e.response.body)throw Error(`Response has no body.`);let t=e.response.body.getReader(),n=new TextDecoder,r=``,i=!1,a=()=>{t.cancel(e.signal?.reason).catch(()=>void 0)};e.signal?.addEventListener(`abort`,a,{once:!0}),e.signal?.aborted&&a();try{for(;!e.signal?.aborted;){let{done:a,value:o}=await t.read();for(a?(i=!0,r+=n.decode()):r+=n.decode(o,{stream:!0});;){let t=RD(r,a);if(!t)break;let n=t.index+t.length,i=r.slice(0,t.index),o=r.slice(0,n);if(r=r.slice(n),!i.trim())continue;let s=CE(i.replace(/\r\n|\r/g,`
|
|
227
227
|
`));if(!s){yield{raw:o};continue}switch(s.type){case`message`:yield{data:s.data,raw:o};break;case`payment-need-voucher`:await e.onNeedVoucher(s.data,e.signal);break;case`payment-receipt`:e.onReceipt(s.data)}}if(a)break}}finally{e.signal?.removeEventListener(`abort`,a),i||await t.cancel().catch(()=>void 0),t.releaseLock()}}function RD(e,t){for(let n=0;n<e.length;n++){let r=zD(e,n,t);if(!r)continue;let i=zD(e,n+r,t);if(i)return{index:n,length:r+i};n+=r-1}}function zD(e,t,n){return e[t]===`
|
|
228
228
|
`?1:e[t]===`\r`?e[t+1]===`
|
|
229
|
-
`?2:t+1===e.length&&!n?0:1:0}function BD(e){let t=new AbortController,n=()=>t.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,n,{once:!0}),e.signal?.aborted&&n();let r=LD({...e,signal:t.signal}),i=new TextEncoder,a=new Headers(e.response.headers);a.delete(`content-length`);let o=()=>e.signal?.removeEventListener(`abort`,n),s=new Response(new ReadableStream({async pull(e){try{let t=await r.next();if(t.done)return o(),e.close();e.enqueue(i.encode(t.value.raw))}catch(e){throw o(),e}},async cancel(){o(),t.abort(),await r.return(void 0)}}),{headers:a,status:e.response.status,statusText:e.response.statusText});for(let t of[`redirected`,`type`,`url`])Object.defineProperty(s,t,{configurable:!0,get:()=>e.response[t]});return s}async function VD(e,t){let n=e.driver.getChannel();if(!n||!e.challenge)return;let r=await xD({assertVoucherWithinLocalLimit:e.driver.assertVoucherWithinLocalLimit,challenge:e.challenge,event:t,expectedChannelId:n.channelId,getChannel:e.driver.getChannel,input:e.input,signal:e.signal,topUpIfNeeded:e.driver.topUpIfNeeded});if(r.status!==`ready`)return;let i=await AD({challenge:e.challenge,context:r.context,createSessionCredential:e.driver.createSessionCredential,fetch:e.driver.fetch,input:e.input,signal:e.signal});if(!i.ok)throw Error(`Voucher POST failed with status ${i.status}`)}async function HD(e){let t=new URL(e.input.toString()),n=DD(t);e.onProbeUrl?.(n);let r=await e.fetch(n,{...e.probeInit,...e.signal?{signal:e.signal}:{}});if(r.status!==402)throw Error(`Expected a 402 payment challenge from ${n}, received ${r.status} instead.`);let i=sS(r).find(CD);if(!i)throw Error(`No payment challenge received from HTTP endpoint for this WebSocket URL. The server may not require payment or did not advertise a challenge.`);return{challenge:i,httpUrl:n,wsUrl:t}}async function UD(e){let t=await HD(e);
|
|
229
|
+
`?2:t+1===e.length&&!n?0:1:0}function BD(e){let t=new AbortController,n=()=>t.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,n,{once:!0}),e.signal?.aborted&&n();let r=LD({...e,signal:t.signal}),i=new TextEncoder,a=new Headers(e.response.headers);a.delete(`content-length`);let o=()=>e.signal?.removeEventListener(`abort`,n),s=new Response(new ReadableStream({async pull(e){try{let t=await r.next();if(t.done)return o(),e.close();e.enqueue(i.encode(t.value.raw))}catch(e){throw o(),e}},async cancel(){o(),t.abort(),await r.return(void 0)}}),{headers:a,status:e.response.status,statusText:e.response.statusText});for(let t of[`redirected`,`type`,`url`])Object.defineProperty(s,t,{configurable:!0,get:()=>e.response[t]});return s}async function VD(e,t){let n=e.driver.getChannel();if(!n||!e.challenge)return;let r=await xD({assertVoucherWithinLocalLimit:e.driver.assertVoucherWithinLocalLimit,challenge:e.challenge,event:t,expectedChannelId:n.channelId,getChannel:e.driver.getChannel,input:e.input,signal:e.signal,topUpIfNeeded:e.driver.topUpIfNeeded});if(r.status!==`ready`)return;let i=await AD({challenge:e.challenge,context:r.context,createSessionCredential:e.driver.createSessionCredential,fetch:e.driver.fetch,input:e.input,signal:e.signal});if(!i.ok)throw Error(`Voucher POST failed with status ${i.status}`)}async function HD(e){let t=new URL(e.input.toString()),n=DD(t);e.onProbeUrl?.(n);let r=await e.fetch(n,{...e.probeInit,...e.signal?{signal:e.signal}:{}});if(r.status!==402)throw Error(`Expected a 402 payment challenge from ${n}, received ${r.status} instead.`);let i=sS(r).find(CD);if(!i)throw Error(`No payment challenge received from HTTP endpoint for this WebSocket URL. The server may not require payment or did not advertise a challenge.`);return{challenge:i,httpUrl:n,wsUrl:t}}async function UD(e){e.signal?.throwIfAborted();let t=await HD(e);e.signal?.throwIfAborted();let n=await e.createSessionCredential(t.challenge,{});return e.signal?.throwIfAborted(),{...t,credential:n}}function WD(e){let{challenge:t,credential:n,socket:r}=e;return{challenge:t,channelId:qS(n).payload.channelId,closeReadyReceipt:null,deliveredChunks:0n,expectedCloseAmount:null,socket:r,tickCost:vE(t)}}function GD(e){let{challengeId:t,channelId:n,receipt:r}=e;return r.challengeId===t&&r.channelId===n}function KD(e){if(!GD(e))return`received mismatched payment-close-ready frame`;let t=dE(e.receipt.spent);if(t===void 0)return`received invalid payment-close-ready spend`;if(t>e.cumulativeAmount)return`received payment-close-ready beyond local voucher state`}function qD(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,receipt:i}=e;if(!GD(e))return`received mismatched payment-receipt frame`;if(r!==null&&i.txHash&&!aD({challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:BigInt(r),receipt:i}))return`received mismatched payment-close receipt frame`}async function JD(e){let{challenge:t,credential:n,options:r,WebSocket:i,wsUrl:a}=e,o=r?.signal;o?.throwIfAborted();let s=new i(a,r?.protocols),c=WD({challenge:t,credential:n,socket:s});e.setSocketSession(c);let l=_D(s),u=t=>{e.rejectReceipt(Error(t)),e.rejectCloseReady(Error(t)),(s.readyState===eO.CONNECTING||s.readyState===eO.OPEN)&&s.close(tO,t)},d=()=>{e.rejectReceipt(Error(`WebSocket payment flow aborted.`)),e.rejectCloseReady(Error(`WebSocket payment flow aborted.`)),s.close()};s.addEventListener(`close`,t=>{o?.removeEventListener(`abort`,d),c.socket=null,c.expectedCloseAmount=null,e.rejectReceipt(Error(`WebSocket closed before the payment flow completed.`)),e.rejectCloseReady(Error(`WebSocket closed before the payment flow completed.`)),l.emit(`close`,{code:t.code??1e3,reason:t.reason??``,type:`close`,wasClean:!0})}),s.addEventListener(`error`,()=>{l.emit(`error`,{type:`error`})}),s.addEventListener(`message`,async t=>{let n=typeof t.data==`string`?t.data:void 0;n&&await XD({driver:e,failSocketFlow:u,managedEmit:l.emit,message:n,rawSocket:s,socketState:c})}),o?.addEventListener(`abort`,d,{once:!0});try{await YD(s,l.emit,a,o),o?.throwIfAborted()}catch(e){throw o?.removeEventListener(`abort`,d),s.close(),e}return s.send(TE(n)),await e.waitForReceipt(),l.socket}function YD(e,t,n,r){return new Promise((i,a)=>{let o=()=>{e.removeEventListener(`open`,s),e.removeEventListener(`error`,c),e.removeEventListener(`close`,c),r?.removeEventListener(`abort`,l)},s=()=>{o(),t(`open`,{type:`open`}),i()},c=()=>{o(),a(Error(`WebSocket connection to ${n} failed to open.`))},l=()=>{o(),a(r?.reason)};e.addEventListener(`open`,s,{once:!0}),e.addEventListener(`error`,c,{once:!0}),e.addEventListener(`close`,c,{once:!0}),r?.addEventListener(`abort`,l,{once:!0}),r?.aborted&&l()})}async function XD(e){let t=DE(e.message);if(!t){e.managedEmit(`message`,{data:e.message,type:`message`});return}switch(t.mpp){case`authorization`:return;case`message`:e.socketState.deliveredChunks+=1n,e.managedEmit(`message`,{data:t.data,type:`message`});return;case`payment-close-ready`:ZD(e,t.data);return;case`payment-error`:e.driver.rejectReceipt(Error(t.message)),e.driver.rejectCloseReady(Error(t.message));return;case`payment-need-voucher`:await QD(e,t.data);return;case`payment-receipt`:$D(e,t.data);return}}function ZD(e,t){let n=e.driver.getChannel()?.cumulativeAmount??0n,r=KD({challengeId:e.driver.challenge.id,channelId:e.socketState.channelId,cumulativeAmount:n,receipt:t});if(r){e.failSocketFlow(r);return}e.driver.acceptReceipt(t),e.driver.options?.onReceipt?.(t),e.driver.settleCloseReady(t),e.managedEmit(`close`,{code:1e3,reason:`stream complete`,type:`close`,wasClean:!0})}async function QD(e,t){try{let n=e.driver.challenge;n.expires&&new Date(n.expires).getTime()<=Date.now()+nO&&(n=await e.driver.refreshChallenge(),e.driver.challenge=n,e.socketState.challenge=n);let r=await xD({assertVoucherWithinLocalLimit:e.driver.assertVoucherWithinLocalLimit,challenge:n,event:t,expectedChannelId:e.socketState.channelId,getChannel:e.driver.getChannel,input:e.driver.httpUrl,signal:e.driver.options?.signal,topUpIfNeeded:e.driver.topUpIfNeeded});if(r.status===`ignored`){e.failSocketFlow(r.reason===`channel-mismatch`?`received mismatched payment-need-voucher frame`:`cannot create voucher: no active channel`);return}let i=await e.driver.createSessionCredential(n,r.context);e.rawSocket.send(TE(i))}catch(t){e.failSocketFlow(t instanceof Error?t.message:`failed to create websocket voucher`)}}function $D(e,t){let n=qD({challengeId:e.driver.challenge.id,channelId:e.socketState.channelId,expectedCloseAmount:e.socketState.expectedCloseAmount,receipt:t});if(n){e.failSocketFlow(n);return}e.driver.acceptReceipt(t),e.driver.options?.onReceipt?.(t),e.driver.settleReceipt(t)}var eO,tO,nO,rO=F((()=>{gS(),oT(),Px(),eC(),ME(),gD(),eO={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3},tO=3008,nO=5e3})),iO,aO,oO,sO,cO,lO=F((()=>{iO={mainnet:4217,testnet:42431},aO={ousd:Se(iO.mainnet).address,usdc:M(we(iO.mainnet).address),pathUsd:Ce(iO.mainnet).address},oO={[iO.mainnet]:aO.usdc,[iO.testnet]:aO.pathUsd},sO=Object.freeze({[iO.mainnet]:Object.freeze({swap:`0xF72E5107c32C655ffA7539a3C8e97B7C3cE16A3F`,token:`0x20c000000000000000000000f37de3740ADec032`}),[iO.testnet]:Object.freeze({swap:`0xd05f8EdFBB54Da0d765C9fE9b2B3f7d2E3a8C466`,token:`0x20c000000000000000000000f37de3740ADec032`})}),iO.mainnet,iO.testnet,cO={[iO.mainnet]:`https://rpc.tempo.xyz`,[iO.testnet]:`https://rpc.moderato.tempo.xyz`}})),uO=Ze({chainName:()=>EO,confirm:()=>xO,decodeMemo:()=>mO,fetchBalanceLines:()=>AO,fetchTokenInfo:()=>kO,fmtBalance:()=>SO,fmtChallengeValue:()=>hO,fmtRequestValue:()=>pO,isAgentEnvironment:()=>vO,isTempoAccount:()=>yO,isTestnet:()=>OO,link:()=>gO,mainnetTokens:()=>FO,networkRpcUrls:()=>MO,parseMethodOpts:()=>_O,pathUsd:()=>NO,pc:()=>X,printRequestHeaders:()=>dO,printResponseHeaders:()=>fO,prompt:()=>bO,resolveChain:()=>TO,resolveFundingNetwork:()=>wO,resolveRpcUrl:()=>CO,testnetTokens:()=>IO,usdc:()=>PO});function dO(e,t,n){let{pathname:r,host:i}=new URL(e);n(`> ${(t.method??`GET`).toUpperCase()} ${r} HTTP/1.1\n`),n(`> Host: ${i}\n`);for(let[e,r]of Object.entries(t.headers??{}))n(`> ${e}: ${r}\n`);n(`>
|
|
230
230
|
`)}function fO(e,t){if(!t.include&&t.verbose<2||t.silent)return;let n=`HTTP/1.1 ${e.status} ${e.statusText}`,r=t.verbose>=2?process.stderr:process.stdout,i=t.verbose>=2?`< `:``;r.write(`${i}${n}\n`);for(let[t,n]of e.headers)r.write(`${i}${t}: ${n}\n`);r.write(t.verbose>=2?`<
|
|
231
231
|
`:`
|
|
232
232
|
`)}function pO(e,t,n){if(jO.has(e)&&typeof t==`string`)return`${t} ${X.dim(`(${SO(BigInt(t),n.tokenSymbol,n.tokenDecimals)})`)}`;if(e===`chainId`&&typeof t==`number`){let e=EO({id:t,name:``});return e?`${t} ${X.dim(`(${e})`)}`:String(t)}return typeof t==`string`&&/^0x[0-9a-fA-F]{40}$/.test(t)?n.explorerUrl?gO(`${n.explorerUrl}/address/${t}`,t):t:typeof t==`string`&&/^https?:\/\//.test(t)?X.link(t,t):String(t)}function mO(e){try{let t=e.replace(/^0x0*/,``);if(!t)return;let n=Uint8Array.from(t.match(/.{1,2}/g).map(e=>Number.parseInt(e,16))),r=new TextDecoder().decode(n);return/^[\x20-\x7e]+$/.test(r)?r:void 0}catch{return}}function hO(e,t){if(e===`realm`&&typeof t==`string`)try{let e=new URL(t.includes(`://`)?t:`https://${t}`);return X.link(e.href,t)}catch{}return String(t)}function gO(e,t){return X.link(e,t)}function _O(e){if(!e)return{};let t=Array.isArray(e)?e:[e],n={};for(let e of t){let t=e.indexOf(`=`);if(t===-1)throw Error(`Invalid method option format: ${e} (expected key=value)`);n[e.slice(0,t)]=e.slice(t+1)}return n}function vO(e=process.env){if(e.CLAUDECODE)return!0;for(let[t,n]of Object.entries(e))if(n&&(t===`CODEX`||t.startsWith(`CODEX_`)))return!0;return!1}function yO(e){return e.startsWith(`tempo:`)}function bO(e){let t=P.createInterface({input:process.stdin,output:process.stderr});return new Promise(n=>{t.on(`close`,()=>n(void 0)),t.question(`${X.bold(`▸ ${e}:`)} `,e=>{t.close(),n(e.trim()||void 0)})})}function xO(e,t=!1){let n=P.createInterface({input:process.stdin,output:process.stderr});return new Promise(r=>{let i=t?`(Y/n)`:`(y/N)`;n.question(`${X.bold(`▸ ${e}`)} ${X.dim(i)} `,e=>{n.close();let i=e.trim().toLowerCase();r(i===``?t:i===`y`)})})}function SO(e,t,n=6,r){let[i,a]=(Number(e)/10**n).toString().split(`.`),o=i.replace(/\B(?=(\d{3})+(?!\d))/g,`_`),s=r?.explorerUrl&&r.token?X.dim(X.link(`${r.explorerUrl}/token/${r.token}`,t,!0)):X.dim(t);return`${a?`${o}.${a}`:o} ${s}`}function CO(e,t={}){return e??(t.network?MO[t.network]:void 0)??(process.env.MPPX_RPC_URL?.trim()||process.env.RPC_URL?.trim()||void 0)}function wO(e={}){if(e.network)return e.network;if(!e.rpcUrl&&!(process.env.MPPX_RPC_URL?.trim()||process.env.RPC_URL?.trim()))return`testnet`}async function TO(e={}){let t=CO(e.rpcUrl,{network:e.network});if(!t)return ve;let{getChainId:n}=await import(`viem/actions`),r=await n(j({transport:ue(t)})),i=Object.values(await import(`viem/tempo/chains`)).filter(e=>typeof e==`object`&&!!e&&`id`in e&&e.id===r),a=i.find(e=>`serializers`in e&&e.serializers)??i[0];if(!a)throw Error(`Unknown chain ID ${r} from RPC ${t}`);return a}function EO(e){return{[ve.id]:`mainnet`,[ye.id]:`testnet`}[e.id]??e.name}function DO(e){return typeof e==`bigint`?e:e.amount}function OO(e){return e.id!==ve.id}async function kO(e,t,n,r={}){let{Actions:i}=await import(`viem/tempo`),[a,o]=await Promise.all([i.token.getBalance(e,{account:n,token:t}).then(DO).catch(()=>0n),i.token.getMetadata(e,{token:t}).catch(e=>{if(r.requireDecimals)throw e;return{symbol:t}})]),s={"0x20c0000000000000000000000000000000000000":`PathUSD`,"0x20C000000000000000000000b9537d11c60E8b50":`USDC`}[t]??o.symbol,c=`decimals`in o&&typeof o.decimals==`number`?o.decimals:6;if(r.requireDecimals&&!(`decimals`in o&&typeof o.decimals==`number`))throw Error(`Token decimals are unavailable.`);return{balance:a,symbol:s,decimals:c,token:t}}async function AO(e,t){if(t?.chain){let n=j({chain:t.chain,transport:ue(t.rpcUrl)}),r=t.chain.blockExplorers?.default?.url,i=X.dim(`(${EO(t.chain)})`);return OO(t.chain)?(await Promise.all(IO.map(t=>kO(n,t,e)))).filter(e=>e.balance>0n).map(e=>`${SO(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token})} ${i}`):(await Promise.all(FO.map(t=>kO(n,t,e)))).map(e=>`${SO(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token})} ${i}`)}let n=j({chain:ve,transport:ue(CO())}),r=ve.blockExplorers?.default?.url,i=(await Promise.all(FO.map(t=>kO(n,t,e)))).map(e=>SO(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token}));if(t?.includeTestnet!==!1){let t=j({chain:ye,transport:ue()}),n=ye.blockExplorers?.default?.url,r=await Promise.all(IO.map(n=>kO(t,n,e)));for(let e of r)e.balance>0n&&i.push(`${SO(e.balance,e.symbol,e.decimals,{explorerUrl:n,token:e.token})} ${X.dim(`(testnet)`)}`)}return i}var X,jO,MO,NO,PO,FO,IO,LO=F((()=>{lO(),X=(()=>{let e=process||{},t=e.argv||[],n=e.env||{},r=!(n.NO_COLOR||t.includes(`--no-color`))&&(!!n.FORCE_COLOR||t.includes(`--color`)||(e.stdout||{}).isTTY&&n.TERM!==`dumb`||!!n.CI),i=(e,t,n,r)=>{let i=``,a=0,o=r;do i+=e.substring(a,o)+n,a=o+t.length,o=e.indexOf(t,a);while(~o);return i+e.substring(a)},a=r?(e,t,n=e)=>r=>{let a=`${r}`,o=a.indexOf(t,e.length);return~o?e+i(a,t,n,o)+t:e+a+t}:()=>String;return{isColorSupported:r,reset:a(`\x1B[0m`,`\x1B[0m`),bold:a(`\x1B[1m`,`\x1B[22m`,`\x1B[22m\x1B[1m`),dim:a(`\x1B[2m`,`\x1B[22m`,`\x1B[22m\x1B[2m`),italic:a(`\x1B[3m`,`\x1B[23m`),underline:a(`\x1B[4m`,`\x1B[24m`),inverse:a(`\x1B[7m`,`\x1B[27m`),hidden:a(`\x1B[8m`,`\x1B[28m`),strikethrough:a(`\x1B[9m`,`\x1B[29m`),black:a(`\x1B[30m`,`\x1B[39m`),red:a(`\x1B[31m`,`\x1B[39m`),green:a(`\x1B[32m`,`\x1B[39m`),yellow:a(`\x1B[33m`,`\x1B[39m`),blue:a(`\x1B[34m`,`\x1B[39m`),magenta:a(`\x1B[35m`,`\x1B[39m`),cyan:a(`\x1B[36m`,`\x1B[39m`),white:a(`\x1B[37m`,`\x1B[39m`),gray:a(`\x1B[90m`,`\x1B[39m`),bgBlack:a(`\x1B[40m`,`\x1B[49m`),bgRed:a(`\x1B[41m`,`\x1B[49m`),bgGreen:a(`\x1B[42m`,`\x1B[49m`),bgYellow:a(`\x1B[43m`,`\x1B[49m`),bgBlue:a(`\x1B[44m`,`\x1B[49m`),bgMagenta:a(`\x1B[45m`,`\x1B[49m`),bgCyan:a(`\x1B[46m`,`\x1B[49m`),bgWhite:a(`\x1B[47m`,`\x1B[49m`),blackBright:a(`\x1B[90m`,`\x1B[39m`),redBright:a(`\x1B[91m`,`\x1B[39m`),greenBright:a(`\x1B[92m`,`\x1B[39m`),yellowBright:a(`\x1B[93m`,`\x1B[39m`),blueBright:a(`\x1B[94m`,`\x1B[39m`),magentaBright:a(`\x1B[95m`,`\x1B[39m`),cyanBright:a(`\x1B[96m`,`\x1B[39m`),whiteBright:a(`\x1B[97m`,`\x1B[39m`),bgBlackBright:a(`\x1B[100m`,`\x1B[49m`),bgRedBright:a(`\x1B[101m`,`\x1B[49m`),bgGreenBright:a(`\x1B[102m`,`\x1B[49m`),bgYellowBright:a(`\x1B[103m`,`\x1B[49m`),bgBlueBright:a(`\x1B[104m`,`\x1B[49m`),bgMagentaBright:a(`\x1B[105m`,`\x1B[49m`),bgCyanBright:a(`\x1B[106m`,`\x1B[49m`),bgWhiteBright:a(`\x1B[107m`,`\x1B[49m`),link(e,t,n){return r?`\x1b]8;;${e}\x07${n?t:X.underline(t)}\x1b]8;;\x07`:t}}})(),jO=new Set([`amount`,`suggestedDeposit`,`minVoucherDelta`]),MO={mainnet:cO[iO.mainnet],testnet:cO[iO.testnet]},NO=`0x20c0000000000000000000000000000000000000`,PO=`0x20C000000000000000000000b9537d11c60E8b50`,FO=[NO,PO],IO=[`0x20c0000000000000000000000000000000000000`,`0x20c0000000000000000000000000000000000001`,`0x20c0000000000000000000000000000000000002`,`0x20c0000000000000000000000000000000000003`]}));function RO(){let e=Number.parseInt(process.env.MPPX_KEYCHAIN_COMMAND_TIMEOUT_MS??``,10);return Number.isFinite(e)&&e>0?e:XO}function zO(e,t){return`code`in e&&e.code===`ENOENT`&&e.message.includes(t)}function BO(e){return new I({code:`KEYCHAIN_UNAVAILABLE`,message:`Linux keyring requires secret-tool. Install libsecret-tools.`,hint:`On Debian/Ubuntu, run: sudo apt install libsecret-tools gnome-keyring dbus-x11`,exitCode:69,cause:e})}function VO(e){if(e&&zO(e,`secret-tool`))throw BO(e)}function HO(e,t){return new Promise(n=>{m.execFile(e,t,{timeout:RO()},(e,t,r)=>{n({stdout:t.trim(),stderr:r.trim(),error:e})})})}function UO(){let e=c.join(process.env.XDG_CONFIG_HOME||c.join(b.homedir(),`.config`),`mppx`,`default`);return{get(){try{return t.readFileSync(e,`utf-8`).trim()||`main`}catch{return`main`}},set(n){t.mkdirSync(c.dirname(e),{recursive:!0}),t.writeFileSync(e,n,`utf-8`)},clear(){try{t.unlinkSync(e)}catch{}}}}function WO(e){return e||(process.env.MPPX_ACCOUNT?.trim()?process.env.MPPX_ACCOUNT:UO().get())}function GO(e=`main`){let t=YO;return{async list(){let e=b.platform();if(e===`darwin`){let{stdout:e,error:n}=await HO(`security`,[`dump-keychain`]);if(n)return[];let r=[],i=e.split(`keychain:`);for(let e of i){let n=e.match(/"svce"<blob>="([^"]*)"/),i=e.match(/"acct"<blob>="([^"]*)"/);n?.[1]===t&&i?.[1]&&r.push(i[1])}return r}if(e===`linux`){let{stdout:e,stderr:n,error:r}=await HO(`secret-tool`,[`search`,`--all`,`--unlock`,`service`,t]);if(VO(r),r)return[];let i=`${e}\n${n}`,a=[],o=i.matchAll(/\baccount = (.+)/g);for(let e of o)e[1]&&a.push(e[1]);return a}throw Error(`Unsupported platform: ${e}`)},async get(){let n=b.platform();if(n===`darwin`){let{stdout:n,error:r}=await HO(`security`,[`find-generic-password`,`-s`,t,`-a`,e,`-w`]);return r?void 0:n}if(n===`linux`){let{stdout:n,error:r}=await HO(`secret-tool`,[`lookup`,`service`,t,`account`,e]);return VO(r),r?void 0:n||void 0}throw Error(`Unsupported platform: ${n}`)},async set(n){let r=b.platform();if(r===`darwin`){await HO(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);let{error:r}=await HO(`security`,[`add-generic-password`,`-s`,t,`-a`,e,`-w`,n]);if(r)throw r;return}if(r===`linux`){let r=m.execFile(`secret-tool`,[`store`,`--label`,`${t} ${e}`,`service`,t,`account`,e]),i=setTimeout(()=>r.kill(),RO());return r.stdin?.write(n),r.stdin?.end(),new Promise((e,t)=>{r.on(`close`,n=>{clearTimeout(i),n===0?e():t(Error(`secret-tool exited with code ${n}`))}),r.on(`error`,e=>{clearTimeout(i),t(zO(e,`secret-tool`)?BO(e):e)})})}throw Error(`Unsupported platform: ${r}`)},async delete(){let n=b.platform();if(n===`darwin`){await HO(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);return}if(n===`linux`){let{error:n}=await HO(`secret-tool`,[`clear`,`service`,t,`account`,e]);VO(n);return}throw Error(`Unsupported platform: ${n}`)}}}async function KO(e){let{privateKeyToAccount:t}=await import(`viem/accounts`),n=process.env.MPPX_PRIVATE_KEY?.trim();if(n)return{account:t(n),source:`environment`};let r=WO(e),i=await GO(r).get();if(i)return{account:t(i),accountName:r,source:`keychain`};throw Error(`Account "${r}" not found.`)}async function qO(e){let t=WO(e);if(!process.env.MPPX_PRIVATE_KEY?.trim()&&yO(t))throw new I({code:`UNSUPPORTED_ACCOUNT`,message:`Persistent sessions require an mppx account or MPPX_PRIVATE_KEY.`,exitCode:2});return KO(e).catch(e=>{throw new I({code:`ACCOUNT_NOT_FOUND`,message:e instanceof Error?e.message:`No account found.`,exitCode:69,...e instanceof Error&&{cause:e}})})}async function JO(e){return(await KO(e)).account}var YO,XO,ZO=F((()=>{LO(),YO=`mppx`,XO=1e4}));rO(),ZO();const QO=[[`ANTIGRAVITY_CLI_ALIAS`,`antigravity`],[`CLAUDECODE`,`claude_code`],[`CLINE_ACTIVE`,`cline`],[`CODEX_SANDBOX`,`codex_cli`],[`CODEX_THREAD_ID`,`codex_cli`],[`CODEX_SANDBOX_NETWORK_DISABLED`,`codex_cli`],[`CODEX_CI`,`codex_cli`],[`CURSOR_AGENT`,`cursor`],[`GEMINI_CLI`,`gemini_cli`],[`OPENCODE`,`open_code`],[`OPENCLAW_SHELL`,`openclaw`],[`CLAUDE_CODE_ENTRYPOINT`,`claude_code`],[`CODEX_INTERNAL_ORIGINATOR_OVERRIDE`,`codex_cli`]];function $O(e=process.env){return QO.find(([t])=>e[t])?.[1]}const ek=Symbol(`mppx.x402.asset`);function tk(e){return{[ek]:!0,address:e.address,decimals:e.decimals,network:e.network,transfer:e.transfer}}function nk(e,t){let n=e(t.chainId);return tk({address:n.address,decimals:n.decimals,network:fk(t.chainId),transfer:mk(t.transfer,n)})}const rk={USDC:tk({address:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,decimals:6,network:`eip155:8453`,transfer:{name:`USD Coin`,type:`eip3009`,version:`2`}})},ik={USDC:tk({address:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,decimals:6,network:`eip155:84532`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})},ak={USDC:tk({address:`0xcebA9300f2b948710d2653dD7B07f33A8B32118C`,decimals:6,network:`eip155:42220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}}),USDT:tk({address:`0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e`,decimals:6,network:`eip155:42220`,transfer:{name:`Tether USD`,type:`eip3009`,version:`1`}})},ok={USDC:tk({address:`0x01C5C0122039549AD1493B8220cABEdD739BC44E`,decimals:6,network:`eip155:11142220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})};function sk(e){return typeof e!=`object`||!e?!1:e[ek]===!0}function ck(e){return typeof e==`function`&&typeof e.addresses==`object`&&typeof e.decimals==`number`}function lk(e){return typeof e==`string`}function uk(e,t){if(sk(e))return e.network===t?{address:e.address,decimals:e.decimals,transfer:e.transfer}:void 0;if(ck(e)){let n=e.addresses[pk(t)];return n?{address:n,decimals:e.decimals,name:e.name}:void 0}return{address:e}}function dk(e,t,n){let r=uk(e,n);return r?M(r.address)===M(t):!1}function fk(e){return`eip155:${e}`}function pk(e){return Number(e.slice(7))}function mk(e,t){if(e.type!==`eip3009`)return e;if(e.name)return{...e,name:e.name};if(!t.name)throw Error(`EIP-3009 token assets require a token name.`);return{...e,name:t.name}}var hk=Ze({base:()=>rk,baseSepolia:()=>ik,celo:()=>ak,celoSepolia:()=>ok,define:()=>tk,fromToken:()=>nk,isAsset:()=>sk,isRawAddress:()=>lk,isToken:()=>ck,matches:()=>dk,resolve:()=>uk,toChainId:()=>pk,toNetwork:()=>fk}),gk=Ze({base:()=>_k,baseSepolia:()=>vk,celo:()=>yk,celoSepolia:()=>bk});const _k=8453,vk=84532,yk=42220,bk=11142220;Rx();function xk(e){let t=[Lx(e.accepted),Lx(e.resource),Lx(e.extensions)].join(`|`);return ne.sha256(te.fromString(t),{as:`Hex`})}ew(),DC();async function Sk(e){let t=e.context?.account??e.config.account;if(!t?.signTypedData)throw Error(`x402 exact requires a typed-data signer.`);let n=e.challenge.request,r=iC(n);if(Ek(e.config,r),!n.resource)throw Error(`x402 exact EIP-3009 requires resource information.`);let i=n.extensions?.mppx?Ok(n.extensions):n.extensions,a=r.extra?.assetTransferMethod??`eip3009`;if(a!==`eip3009`)throw Error(`x402 exact ${String(a)} signing is not implemented yet.`);let o=r.extra?.name,s=r.extra?.version;if(typeof o!=`string`||typeof s!=`string`)throw Error(`x402 exact EIP-3009 requires token name and version.`);let c=Math.floor(Date.now()/1e3),l={from:M(t.address),nonce:i?.mppx?xk({accepted:r,extensions:i,resource:n.resource}):Ak(),to:M(r.payTo),validAfter:(c-600).toString(),validBefore:(c+r.maxTimeoutSeconds).toString(),value:r.amount},u=await t.signTypedData({domain:{chainId:Tk(r.network),name:o,verifyingContract:M(r.asset),version:s},message:{...l,value:BigInt(l.value),validAfter:BigInt(l.validAfter),validBefore:BigInt(l.validBefore)},primaryType:`TransferWithAuthorization`,types:wk});return QC({accepted:r,...i?{extensions:i}:{},payload:{authorization:l,signature:u},...n.resource?{resource:n.resource}:{},x402Version:2})}function Ck(e){let t=e.challenge.request,n;try{n=iC(t),Ek(e.config,n)}catch{return!1}if(!t.resource||(n.extra?.assetTransferMethod??`eip3009`)!==`eip3009`)return!1;let r=n.extra?.name,i=n.extra?.version;return typeof r==`string`&&typeof i==`string`}const wk={TransferWithAuthorization:[{name:`from`,type:`address`},{name:`to`,type:`address`},{name:`value`,type:`uint256`},{name:`validAfter`,type:`uint256`},{name:`validBefore`,type:`uint256`},{name:`nonce`,type:`bytes32`}]};function Tk(e){return Number(e.slice(sC.length))}function Ek(e,t){let n=Tk(t.network);if(e.networks&&!e.networks.includes(n))throw Error(`x402 exact chain ID is not allowed: ${n}.`);let r=e.currencies??e.assets;if(r?.some(e=>lk(e))&&!e.networks?.length)throw Error(`x402 exact raw currency allowlists require networks.`);if(r){let e=M(t.asset);if(!r.some(n=>dk(n,e,t.network)))throw Error(`x402 exact currency is not allowed: ${e}.`)}if(e.maxAtomicAmount!==void 0&&BigInt(t.amount)>BigInt(e.maxAtomicAmount))throw Error(`x402 exact amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0){let n=Dk(e,t);if(n===void 0)throw Error(`x402 exact maxAmount requires currency decimals.`);if(BigInt(t.amount)>N(e.maxAmount,n))throw Error(`x402 exact amount exceeds maxAmount.`)}}function Dk(e,t){let n=e.currencies??e.assets,r=M(t.asset),i=n?.find(e=>dk(e,r,t.network)),a=i?uk(i,t.network):void 0;return a?.decimals===void 0?e.decimals:a.decimals}function Ok(e){let t=e.mppx;return t?{...e,mppx:{...t,info:{...t.info,nonce:kk()}}}:e}function kk(){return jk().slice(2)}function Ak(){return jk()}function jk(){let e=globalThis.crypto;if(!e?.getRandomValues)throw Error(`x402 exact requires crypto randomness.`);let t=e.getRandomValues(new Uint8Array(32));return`0x${Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}`}Xx();const Mk=[`authorization`],Nk=J.string().check(J.regex(/^\d+$/,`Invalid atomic amount`));J.object({name:J.string().check(J.minLength(1)),version:J.string().check(J.minLength(1))});const Pk=J.object({chainId:J.number(),credentialTypes:J.optional(J.array(J.enum(Mk)).check(J.minLength(1))),decimals:J.optional(J.number()),permit2Address:J.optional(Gx()),splits:J.optional(J.array(J.object({amount:Nk,recipient:Gx()})))});J.object({amount:Nk,currency:Gx(),description:J.optional(J.string()),externalId:J.optional(J.string()),methodDetails:Pk,recipient:Gx()});const Fk=J.object({amount:Bx(),chainId:J.number(),currency:Gx(),credentialTypes:J.optional(J.array(J.enum(Mk)).check(J.minLength(1))),decimals:J.number(),description:J.optional(J.string()),externalId:J.optional(J.string()),permit2Address:J.optional(Gx()),recipient:Gx(),splits:J.optional(J.array(J.object({amount:Nk,recipient:Gx()})))}),Ik=J.object({from:Gx(),nonce:Kx(),signature:Jx(),to:Gx(),type:J.literal(`authorization`),validAfter:Nk,validBefore:Nk,value:Nk}),Lk={TransferWithAuthorization:[{name:`from`,type:`address`},{name:`to`,type:`address`},{name:`value`,type:`uint256`},{name:`validAfter`,type:`uint256`},{name:`validBefore`,type:`uint256`},{name:`nonce`,type:`bytes32`}]};function Rk(e){return{chainId:e.chainId,name:e.authorization.name,verifyingContract:e.currency,version:e.authorization.version}}function zk(e){return ne.keccak256(te.fromString(JSON.stringify([e.id,e.realm])),{as:`Hex`})}function Bk(e){return`eip155:${e}`}function Vk(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}qT(),Xx();const Hk=GT({name:`evm`,intent:`charge`,schema:{credential:{payload:Ik},request:J.pipe(Fk,J.transform(({amount:e,chainId:t,credentialTypes:n=[`authorization`],currency:r,decimals:i,permit2Address:a,recipient:o,splits:s,...c})=>({...c,amount:N(e,i).toString(),currency:M(r),methodDetails:{chainId:t,credentialTypes:n,decimals:i,...a?{permit2Address:M(a)}:{},...s?{splits:s}:{}},recipient:M(o)})))}});eC(),qT(),ES(),Xx();function Uk(e){return KT(Hk,{canHandleChallenge({challenge:t}){return!Wk(t)||Ck({challenge:t,config:e})},context:J.object({account:J.optional(J.custom())}),async createCredential({challenge:t,context:n}){if(Wk(t))return Sk({challenge:t,config:e,context:n});let r=n?.account??e.account;if(!r?.signTypedData)throw Error(`EVM authorization requires a typed-data signer.`);let i=t.request;if(Gk(e,i),!i.methodDetails.credentialTypes?.includes(`authorization`))throw Error(`EVM authorization is not accepted by this challenge.`);if(i.methodDetails.splits?.length)throw Error(`EVM authorization does not support payment splits.`);let a=Kk(e,i),o=t.expires?Math.floor(new Date(t.expires).getTime()/1e3).toString():(Math.floor(Date.now()/1e3)+300).toString();return ZS(XS({challenge:t,payload:{from:M(r.address),nonce:zk(t),signature:await r.signTypedData({domain:Rk({authorization:a,chainId:i.methodDetails.chainId,currency:i.currency}),message:{from:M(r.address),nonce:zk(t),to:M(i.recipient),validAfter:0n,validBefore:BigInt(o),value:BigInt(i.amount)},primaryType:`TransferWithAuthorization`,types:Lk}),to:M(i.recipient),type:`authorization`,validAfter:`0`,validBefore:o,value:i.amount},source:Vk({address:M(r.address),chainId:i.methodDetails.chainId})}))}})}function Wk(e){return wS(e)&&e.request.scheme===`exact`&&typeof e.request.network==`string`}function Gk(e,t){let n=t.methodDetails.chainId,r=Bk(n);if(e.networks&&!e.networks.includes(n))throw Error(`EVM chain ID is not allowed: ${n}.`);let i=e.currencies??e.assets;if(i?.some(e=>lk(e))&&!e.networks?.length)throw Error(`EVM raw currency allowlists require networks.`);if(i){let e=M(t.currency);if(!i.some(t=>dk(t,e,r)))throw Error(`EVM currency is not allowed: ${e}.`)}if(e.maxAtomicAmount!==void 0&&BigInt(t.amount)>BigInt(e.maxAtomicAmount))throw Error(`EVM charge amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0){let n=qk(e,t);if(n===void 0)throw Error(`EVM charge maxAmount requires currency decimals.`);if(BigInt(t.amount)>N(e.maxAmount,n))throw Error(`EVM charge amount exceeds maxAmount.`)}}function Kk(e,t){let n=e.currencies??e.assets,r=M(t.currency),i=Bk(t.methodDetails.chainId),a=n?.find(e=>dk(e,r,i)),o=a?uk(a,i):void 0;if(o?.transfer?.type===`eip3009`)return{name:o.transfer.name,version:o.transfer.version};if(e.authorization)return e.authorization;throw Error(`EVM authorization requires token name and version.`)}function qk(e,t){let n=e.currencies??e.assets,r=M(t.currency),i=Bk(t.methodDetails.chainId),a=n?.find(e=>dk(e,r,i)),o=a?uk(a,i):void 0;return o?.decimals===void 0?e.decimals:o.decimals}function Jk(e){return[Jk.charge(e)]}(function(e){e.charge=Uk,e.assets=hk,e.chains=gk})(Jk||={});function Yk(e){return e}var Xk=F((()=>{}));ES(),Xk();function Zk(){return Yk({method:`evm`,supports:e=>e.method===`evm`&&!wS(e),async setup({challenge:e}){let t=e.request,n=t.methodDetails,r=n?.chainId,i=r?Qk(r):void 0,a=t.currency,o=await JO(),s=[...Object.values(rk),...Object.values(ik),...Object.values(ak),...Object.values(ok)],c=a??``;if(i&&a)try{let e=j({chain:i,transport:ue()}),t=await De(e,{address:a,abi:se,functionName:`symbol`});t&&(c=t)}catch{}return{tokenSymbol:c,tokenDecimals:n?.decimals??6,explorerUrl:i?.blockExplorers?.default?.url,methods:[...Jk({account:o,currencies:s})]}}})}function Qk(e){return Object.values(Be).find(t=>t.id===e)}function $k(e,t){if(!Number.isInteger(t)||t<0)throw RangeError(`Decimals must be a non-negative integer.`);if(!/^-?(?:\d+(?:\.\d*)?|\.\d+)$/.test(e))throw TypeError(`Value \`${e}\` is not a valid decimal number.`);let n=e.startsWith(`-`),[r=`0`,i=``]=(n?e.slice(1):e).split(`.`),a=i.slice(0,t).padEnd(t,`0`),o=BigInt(`${r||`0`}${a}`);return i.length>t&&i[t]>=`5`&&(o+=1n),n?-o:o}Xx();const eA=J.object({customer:J.optional(J.string().check(J.minLength(1))),hooks:J.optional(J.object({inputs:J.object({tax:J.object({calculation:J.string().check(J.minLength(1))})})})),metadata:J.optional(J.record(J.string(),J.string())),receipt_email:J.optional(J.string().check(J.minLength(1)))}),tA=J.custom(e=>typeof e==`function`),nA=J.union([eA,tA]);qT(),Xx();const rA=GT({name:`stripe`,intent:`charge`,schema:{credential:{payload:J.object({externalId:J.optional(J.string()),spt:J.string()})},request:J.pipe(J.object({amount:Bx(),currency:J.string(),decimals:J.number(),description:J.optional(J.string()),externalId:J.optional(J.string()),metadata:J.optional(J.record(J.string(),J.string())),networkId:J.string(),paymentIntentOptions:J.optional(nA),paymentMethodTypes:J.array(J.string()).check(J.minLength(1)),recipient:J.optional(J.string())}),J.transform(({amount:e,decimals:t,metadata:n,networkId:r,paymentIntentOptions:i,paymentMethodTypes:a,...o})=>({...o,amount:$k(e,t).toString(),methodDetails:{networkId:r,paymentMethodTypes:a,...n!==void 0&&{metadata:n}}})))}});eC(),qT(),Xx();function iA(e){let{client:t,createToken:n,externalId:r,paymentMethod:i}=e;return KT(rA,{context:J.object({paymentMethod:J.optional(J.string())}),async createCredential({challenge:e,context:a}){let o=a?.paymentMethod??i;if(!o)throw Error(`paymentMethod is required (pass via context or parameters)`);let s=e.request.amount,c=e.request.currency,l=typeof e.request.externalId==`string`?e.request.externalId:void 0,u=e.request.methodDetails?.networkId;if(!u)throw Error(`networkId is required in challenge.methodDetails`);let d=e.request.methodDetails?.metadata;if(d?.externalId)throw Error(`methodDetails.metadata.externalId is reserved; use credential externalId instead`);let f=e.expires?Math.floor(new Date(e.expires).getTime()/1e3):Math.floor(Date.now()/1e3)+3600,p=await n({amount:s,challenge:e,client:t,currency:c,expiresAt:f,metadata:d,networkId:u,paymentMethod:o}),m=l??r;return ZS({challenge:e,payload:{spt:p,...m===void 0?{}:{externalId:m}}})}})}function aA(e){return[iA(e)]}(function(e){e.charge=iA})(aA||={}),Dx(),LO(),Xk();function oA(){return Yk({method:`stripe`,supports(e){return e.method===`stripe`&&e.intent===`charge`},async setup({challenge:e,methodOpts:t}){let n=e.request,r=n.currency,i=cA(p.object({paymentMethod:p.string(),secretKey:p.string().optional()}),t,[`paymentMethod`,`secretKey`]),a=i.secretKey??process.env.MPPX_STRIPE_SECRET_KEY;if(!a)throw new I({code:`MISSING_ENV`,message:`MPPX_STRIPE_SECRET_KEY environment variable is required for Stripe payments.`,exitCode:2});return{tokenSymbol:r?.toUpperCase()??``,tokenDecimals:n.decimals??2,methods:[aA.charge({paymentMethod:i.paymentMethod,createToken:async({paymentMethod:e,amount:t,currency:n,networkId:r,expiresAt:i,metadata:o})=>{let s=new URLSearchParams({payment_method:e,"usage_limits[currency]":n,"usage_limits[max_amount]":t,"usage_limits[expires_at]":i.toString()}),c=sA(a),l=process.env.MPPX_STRIPE_SPT_URL?process.env.MPPX_STRIPE_SPT_URL:c?`https://api.stripe.com/v1/test_helpers/shared_payment/granted_tokens`:`https://api.stripe.com/v1/shared_payment/issued_tokens`;if(r){let e=c?`seller_details[network_id]`:`seller_details[network_business_profile]`;s.set(e,r)}if(o)for(let[e,t]of Object.entries(o))s.set(`metadata[${e}]`,t);let u={Authorization:`Basic ${btoa(`${a}:`)}`,"Content-Type":`application/x-www-form-urlencoded`,"Stripe-Version":`2026-07-29.preview`},d=await globalThis.fetch(l,{method:`POST`,headers:u,body:s});if(!d.ok){let a=await d.json();if(c&&(o||r)&&a.error.message.includes(`Received unknown parameter`)){let r=new URLSearchParams({payment_method:e,"usage_limits[currency]":n,"usage_limits[max_amount]":t,"usage_limits[expires_at]":i.toString()});if(d=await globalThis.fetch(l,{method:`POST`,headers:u,body:r}),!d.ok){let e=await d.json();throw new I({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${e.error.message}`,exitCode:77})}}else throw new I({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${a.error.message}`,exitCode:77})}let{id:f}=await d.json();return f}})]}},formatReceiptField(e,t){if(e===`reference`&&typeof t==`string`&&t.startsWith(`pi_`)){let e=process.env.MPPX_STRIPE_SECRET_KEY,n=`https://dashboard.stripe.com${e!==void 0&&sA(e)?`/test`:``}/payments/${t}`;return X.link(n,t,!0)}}})}function sA(e){return e.startsWith(`sk_test_`)||e.startsWith(`rk_test_`)}function cA(e,t,n){if(t&&typeof t==`object`&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!n.includes(e));if(e.length)throw Error(`Unsupported CLI method option(s): ${e.join(`, `)}`)}let r=e.safeParse(t??{});if(r.success)return r.data;let i=r.error.issues.map(e=>`${e.path.length?e.path.join(`.`):`options`}: ${e.message}`).join(`, `);throw Error(`Invalid CLI options (${i})`)}function lA(e={}){let{account:t}=e;return(e,{account:n}={})=>{let r=n??t;if(!r){if(!e.account)throw Error("No `account` provided. Pass `account` to parameters or context.");return e.account}return ge(r)}}var uA=F((()=>{}));function dA(e){return Object.fromEntries(Object.entries(e.headers??{}).filter(([e])=>e.toLowerCase()!==`content-type`))}var fA=F((()=>{}));function pA(e,t={}){return ue(e.url,{fetchFn:e.fetch,fetchOptions:{headers:dA(e)},...t})}function mA(e){let{chain:t,getClient:n,remoteFeePayer:r,rpcUrl:i}=e;return n?!t?.serializers&&!r?n:async e=>{let i=await n(e),a=i;if(r&&i.transport.key!==`feePayer`){let e=i.request.bind(i),t=ze(ae({request:t=>e(t)},{retryCount:0}),pA(r,{retryCount:i.transport.retryCount}))({account:i.account,chain:i.chain,pollingInterval:i.pollingInterval,retryCount:0}),n=ie({...t.config,retryCount:0},t.value);a=Object.assign({},i,{request:n.request,transport:{...n.config,...n.value}})}return!t?.serializers||a.chain?.serializers?.transaction?a:Object.assign({},a,{chain:{...t,...e.chainId===void 0?{}:{id:e.chainId},...a.chain,formatters:a.chain?.formatters??t.formatters,prepareTransactionRequest:a.chain?.prepareTransactionRequest??t.prepareTransactionRequest,serializers:a.chain?.serializers?.transaction?a.chain.serializers:t.serializers}})}:({chainId:e})=>{if(!i)throw Error("No `rpcUrl` provided.");let n=e||Number(Object.keys(i)[0]),a=i[n];if(!a)throw Error(`No \`rpcUrl\` configured for \`chainId\` (${n}).`);let o=r?ze(ue(a),pA(r)):ue(a);return j({chain:_A[n]??{...t,id:n},transport:o})}}function hA(e,t){if(t!==void 0&&e.chain?.id!==void 0&&e.chain.id!==t)throw Error(`Chain ID mismatch: expected ${t}, got ${e.chain.id}.`)}function gA(e,t){if(e!==void 0&&(t===void 0||!e.includes(t)))throw Error(`Chain ID not allowed: ${t??`unknown`}.`)}var _A,vA=F((()=>{fA(),_A={[ve.id]:ve,[ye.id]:ye}}));function yA(e){let t=ne.keccak256(te.fromString(e),{as:`Hex`});return re.toBytes(re.slice(t,0,10))}function bA(e){let{serverId:t,clientId:n,challengeId:r}=e,i=new Uint8Array(32);return i.set(re.toBytes(SA),0),i[4]=CA,i.set(yA(t),5),n&&i.set(yA(n),15),i.set(xA(r),25),re.fromBytes(i)}function xA(e){let t=ne.keccak256(te.fromString(e),{as:`Hex`});return re.toBytes(re.slice(t,0,7))}var SA,CA,wA=F((()=>{SA=re.slice(ne.keccak256(te.fromString(`mpp`),{as:`Hex`}),0,4),CA=1}));function TA(e,t){return Ge.resolve(e).toLowerCase()===Ge.resolve(t).toLowerCase()}var EA=F((()=>{}));async function DA(e,t){let{account:n,amountOut:r,tokenOut:i,tokenIn:a,slippage:o}=t,s=a.filter(e=>!TA(e,i)),c=await Promise.allSettled([De(e,Fe.token.getBalance.call(e,{account:n,token:i})),...s.map(t=>De(e,Fe.token.getBalance.call(e,{account:n,token:t})))]),l=c[0];if(!(l.status===`fulfilled`&&l.value>=r)){for(let t=0;t<s.length;t++){let n=c[t+1];if(n.status!==`fulfilled`)continue;let a=n.value;if(a<=0n)continue;let l=s[t];try{let t=await Fe.dex.getBuyQuote(e,{tokenIn:l,tokenOut:i,amountOut:r});if(a>=t){let n=t+t*BigInt(Math.round(o*100))/kA;return[Fe.token.approve.call(e,{amount:n,spender:Ie.stablecoinDex,token:l}),Fe.dex.buy.call({tokenIn:l,tokenOut:i,amountOut:r,maxAmountIn:n})]}}catch{}}throw new jA({currency:i})}}function OA(e,t){return e?e===!0?{tokenIn:t,slippage:1}:{tokenIn:e.tokenIn?[...e.tokenIn,...t.filter(t=>!e.tokenIn.some(e=>TA(e,t)))]:t,slippage:e.slippage??1}:!1}var kA,AA,jA,MA=F((()=>{EA(),lO(),kA=10000n,AA=[aO.pathUsd,aO.usdc],jA=class extends Error{name=`InsufficientFundsError`;constructor({currency:e}){super(`Insufficient funds: no balance in ${e} and no viable swap route from fallback currencies.`)}}}));function NA(e){let t=BigInt(e.amount),n=e.methodDetails?.splits??[],r=n.reduce((e,t)=>e+BigInt(t.amount),0n);if(r>=t)throw Error(`Invalid charge request: split total must be less than total amount.`);let i=t-r;if(i<=0n)throw Error(`Invalid charge request: primary transfer amount must be positive.`);return[{amount:i.toString(),memo:e.methodDetails?.memo,recipient:e.recipient},...n.map(e=>({amount:e.amount,memo:e.memo,recipient:e.recipient}))]}var PA=F((()=>{}));function FA(e,t,n){t&&(n&&!n.some(e=>TA(e,t))||e.some(e=>TA(e,t))||e.push(t))}async function IA(e,t,n){try{return(await Fe.token.getBalance(e,{account:t,token:n})).amount>0n}catch{return!1}}function LA(e){let t=e.chain?.feeToken;if(t)return Le.toAddress(t);let n=e.chain?.id;return n?oO[n]:void 0}function RA(e){let t=[];return FA(t,aO.pathUsd),FA(t,oO[e]),t}async function zA(e){let{account:t,allowedTokens:n,candidateTokens:r,client:i,prioritizeCandidates:a}=e,o=[];if(a)for(let e of r??[])FA(o,e,n);if(FA(o,await Fe.fee.getUserToken(i,{account:t}).then(e=>e?.address).catch(()=>void 0),n),FA(o,LA(i),n),!a)for(let e of r??[])FA(o,e,n);for(let e of o)if(await IA(i,t,e))return e;return o[0]}var BA=F((()=>{EA(),lO()}));function VA(e){if(e!==void 0)return sO[e]}function HA(e){let t=VA(e.chainId);return!!t&&de(e.currency,{strict:!1})&&fe(e.currency,t.token)}function UA(e){let t=VA(e.chainId),n=e.transfers.length===1?e.transfers[0]:void 0;if(!t||!n?.memo)return;let r=BigInt(n.amount),i=n.memo;return{calls:[{data:oe({abi:Ne.tip20,functionName:`approve`,args:[t.swap,r]}),to:t.token},{data:oe({abi:GA,functionName:`swapTo`,args:[t.token,r,e.currency,n.recipient,i]}),to:t.swap}],settlementSender:t.swap,transfers:[{amount:r,memo:i,recipient:n.recipient}]}}async function WA(e,t){let n=UA(t);if(n)try{return await De(e,Fe.token.getBalance.call(e,{account:t.account,token:n.calls[0].to}))<n.transfers[0].amount?void 0:(await Te(e,{account:t.account,calls:n.calls}),n)}catch{return}}var GA,KA=F((()=>{lO(),GA=pe([`function swapTo(address inputToken,uint256 amount,address targetToken,address recipient,bytes32 memo)`])}));function qA(e){return{name:`MPP`,version:`3`,chainId:e}}function JA(e){let{account:t,challengeId:n,realm:r}=e;return{account:t,challengeId:n,realm:r}}function YA(e){let{account:t,chainId:n,challengeId:r,realm:i}=e;return{domain:qA(n),types:QA,primaryType:ZA,message:JA({account:t,challengeId:r,realm:i})}}function XA(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}var ZA,QA,$A=F((()=>{ZA=`Proof`,QA={Proof:[{name:`account`,type:`address`},{name:`challengeId`,type:`string`},{name:`realm`,type:`string`}]}}));function ej(e={}){let{clientId:t}=e,n=mA({chain:ve,getClient:e.getClient,rpcUrl:cO}),r=lA({account:e.account});return KT(oE,{context:tj,async createCredential({challenge:i,context:a}){let o=i.request.methodDetails?.chainId;if(e.expectedChainId!==void 0&&o!==void 0&&o!==e.expectedChainId)throw Error(`Chain ID mismatch: expected ${e.expectedChainId}, got ${o}.`);(o!==void 0||e.allowedChainIds?.length===0)&&gA(e.allowedChainIds,o);let s=o??e.expectedChainId??(e.allowedChainIds?.length===1?e.allowedChainIds[0]:void 0),c=await n({chainId:s});hA(c,s);let l=s??c.chain?.id;if(gA(e.allowedChainIds,l),l===void 0)throw Error("No `chainId` provided. Pass a chain ID in the challenge or client.");let{request:u}=i,{amount:d,methodDetails:f}=u,p=f?.supportedModes??[`pull`,`push`],m=r(c,a),h=async t=>await e.resolveAccount?.({account:m,chainId:l,operation:t})??m;if(e.expectedRecipients){let t=new Set(e.expectedRecipients.map(e=>e.toLowerCase()));if(!u.recipient||!t.has(u.recipient.toLowerCase()))throw Error(`Unexpected primary recipient: ${u.recipient}`);let n=f?.splits;if(n){for(let e of n)if(!t.has(e.recipient.toLowerCase()))throw Error(`Unexpected split recipient: ${e.recipient}`)}}if(BigInt(d)===0n){let e=await h({kind:`signPaymentProof`});return ZS({challenge:i,payload:{signature:await je(c,{account:e,...YA({account:e.address,chainId:l,challengeId:i.id,realm:i.realm})}),type:`proof`},source:XA({address:e.address,chainId:l})})}let g=u.currency,_=HA({chainId:l,currency:g}),v=bA({challengeId:i.id,clientId:t,serverId:i.realm}),y=NA({amount:d,methodDetails:{...f,memo:v},recipient:u.recipient}),b=y.map(e=>Fe.token.transfer.call(c,{amount:BigInt(e.amount),...e.memo&&{memo:e.memo},to:e.recipient,token:g})),x=OA(a?.autoSwap??e.autoSwap,AA),S=f?.machineTokenEnabled===!0?UA({chainId:l,currency:g,transfers:y}):void 0,C=m,w;if(S){let e=await(async()=>{try{return await h({calls:S.calls,kind:`executeCalls`})}catch{return}})();e&&(w=await WA(c,{account:e.address,chainId:l,currency:g,transfers:y}),w&&(C=e))}let T;w||(C=await h({kind:`executeCalls`,...x?{}:{calls:b}}),T=x?await DA(c,{account:C.address,amountOut:BigInt(d),tokenOut:g,tokenIn:x.tokenIn,slippage:x.slippage}):void 0);let ee=w?.calls??[...T??[],...b],E=RA(l),D=w||_?await zA({account:C.address,allowedTokens:E,candidateTokens:E,client:c,prioritizeCandidates:!0}):void 0,O=(()=>{let t=a?.mode??e.mode;if(t){if(!p.includes(t))throw Error(`Challenge does not support ${t} mode.`);return t}let n=C.type===`json-rpc`?`push`:`pull`;return p.includes(n)?n:p[0]})(),k=(()=>{let e=Math.floor(Date.now()/1e3)+25;if(!i.expires)return e;let t=Math.floor(new Date(i.expires).getTime()/1e3);return Math.min(e,t)})();if(O===`push`){let{receipts:e}=C.type===`local`?{receipts:[await ke(c,{account:C,calls:ee,...D?{feeToken:D}:{},nonceKey:`expiring`,validBefore:k})]}:await Oe(c,{account:C,...D?{capabilities:{feeToken:D}}:{},calls:ee,experimental_fallback:ee.length===1,forceAtomic:ee.length>1}),t=e?.[0]?.transactionHash;if(!t)throw Error(`No transaction receipt returned.`);return ZS({challenge:i,payload:{hash:t,type:`hash`},source:XA({address:C.address,chainId:l})})}let te=await Ee(c,{account:C,calls:ee,...D?{feeToken:D}:{},nonceKey:`expiring`,validBefore:k});if(te.gas=(te.gas??0n)+5000n,f?.feePayer){let e=te;delete e.feePayerSignature,delete e.feeToken,e.feePayer=!0}return ZS({challenge:i,payload:{signature:await Ae(c,te),type:`transaction`},source:XA({address:C.address,chainId:l})})}})}var tj,nj=F((()=>{eC(),qT(),uA(),vA(),Xx(),wA(),MA(),PA(),lO(),BA(),KA(),$A(),lE(),tj=J.object({account:J.optional(J.custom()),autoSwap:J.optional(J.custom()),mode:J.optional(J.enum(XT))})}));function rj(e){return BigInt(e.authorizedSigner)===0n?e.payer:e.authorizedSigner}function ij(e){let t=O.encode(O.from([`address payer`,`address payee`,`address operator`,`address token`,`bytes32 salt`,`address authorizedSigner`,`bytes32 expiringNonceHash`,`address escrow`,`uint256 chainId`]),[e.payer,e.payee,e.operator,e.token,e.salt,e.authorizedSigner,e.expiringNonceHash,e.escrow??`0x4d50500000000000000000000000000000000000`,BigInt(e.chainId)]);return ne.keccak256(t)}function aj(e){return Ke.encodeForSigning(e)}function oj(e){let{feePayer:t,transaction:n}=e;return t?{...n,feePayerSignature:null}:n}function sj(e,t){return ne.keccak256(re.concat(aj(e),t.sender))}var cj=F((()=>{ME()})),lj,uj,dj,fj,pj=F((()=>{lj=[{name:`payer`,type:`address`},{name:`payee`,type:`address`},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`salt`,type:`bytes32`},{name:`authorizedSigner`,type:`address`},{name:`expiringNonceHash`,type:`bytes32`}],uj=[{name:`settled`,type:`uint96`},{name:`deposit`,type:`uint96`},{name:`closeRequestedAt`,type:`uint32`}],dj={name:`descriptor`,type:`tuple`,components:lj},fj=[{type:`function`,name:`CLOSE_GRACE_PERIOD`,stateMutability:`view`,inputs:[],outputs:[{type:`uint64`}]},{type:`function`,name:`VOUCHER_TYPEHASH`,stateMutability:`view`,inputs:[],outputs:[{type:`bytes32`}]},{type:`function`,name:`open`,stateMutability:`nonpayable`,inputs:[{name:`payee`,type:`address`},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`deposit`,type:`uint96`},{name:`salt`,type:`bytes32`},{name:`authorizedSigner`,type:`address`}],outputs:[{name:`channelId`,type:`bytes32`}]},{type:`function`,name:`settle`,stateMutability:`nonpayable`,inputs:[dj,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`topUp`,stateMutability:`nonpayable`,inputs:[dj,{name:`additionalDeposit`,type:`uint96`}],outputs:[]},{type:`function`,name:`close`,stateMutability:`nonpayable`,inputs:[dj,{name:`cumulativeAmount`,type:`uint96`},{name:`captureAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`requestClose`,stateMutability:`nonpayable`,inputs:[dj],outputs:[]},{type:`function`,name:`withdraw`,stateMutability:`nonpayable`,inputs:[dj],outputs:[]},{type:`function`,name:`getChannel`,stateMutability:`view`,inputs:[dj],outputs:[{type:`tuple`,components:[{name:`descriptor`,type:`tuple`,components:lj},{name:`state`,type:`tuple`,components:uj}]}]},{type:`function`,name:`getChannelState`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`}],outputs:[{type:`tuple`,components:uj}]},{type:`function`,name:`getChannelStatesBatch`,stateMutability:`view`,inputs:[{name:`channelIds`,type:`bytes32[]`}],outputs:[{type:`tuple[]`,components:uj}]},{type:`function`,name:`computeChannelId`,stateMutability:`view`,inputs:[{name:`payer`,type:`address`},{name:`payee`,type:`address`},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`salt`,type:`bytes32`},{name:`authorizedSigner`,type:`address`},{name:`expiringNonceHash`,type:`bytes32`}],outputs:[{type:`bytes32`}]},{type:`function`,name:`getVoucherDigest`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}],outputs:[{type:`bytes32`}]},{type:`function`,name:`domainSeparator`,stateMutability:`view`,inputs:[],outputs:[{type:`bytes32`}]},{type:`event`,name:`ChannelOpened`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`authorizedSigner`,type:`address`},{name:`salt`,type:`bytes32`},{name:`expiringNonceHash`,type:`bytes32`},{name:`deposit`,type:`uint96`}]},{type:`event`,name:`Settled`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`cumulativeAmount`,type:`uint96`},{name:`deltaPaid`,type:`uint96`},{name:`newSettled`,type:`uint96`}]},{type:`event`,name:`TopUp`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`additionalDeposit`,type:`uint96`},{name:`newDeposit`,type:`uint96`}]},{type:`event`,name:`CloseRequested`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`closeGraceEnd`,type:`uint256`}]},{type:`event`,name:`ChannelClosed`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`settledToPayee`,type:`uint96`},{name:`refundedToPayer`,type:`uint96`}]},{type:`event`,name:`CloseRequestCancelled`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0}]}]}));function mj(e,t){return{name:Sj,version:Cj,chainId:t,verifyingContract:e}}function hj(e,t){return He.getVoucherSignPayload({chainId:e,channelId:t.channelId,cumulativeAmount:t.cumulativeAmount})}function gj(e,t,n){return e.toLowerCase()===He.address.toLowerCase()?hj(t,n):le({domain:mj(e,t),types:wj,primaryType:`Voucher`,message:{channelId:n.channelId,cumulativeAmount:n.cumulativeAmount}})}function _j(e){return e===`secp256k1`||e===`p256`||e===`webAuthn`}function vj(e,t){return Pe.signVoucher(e,{chainId:t.chainId,channel:t.channelId,cumulativeAmount:t.cumulativeAmount})}async function yj(e,t,n,r,i){let a=await(async()=>{if(r.toLowerCase()===He.address.toLowerCase())try{return await vj(t,{chainId:i,channelId:n.channelId,cumulativeAmount:n.cumulativeAmount})}catch{}return je(e,{account:t,domain:mj(r,i),types:wj,primaryType:`Voucher`,message:n})})(),o=We.from(a);if(!_j(o.type))throw Error(`TIP-1034 vouchers require a TIP-1020 primitive signature; received "${o.type}".`);return We.serialize(o)}async function bj(e,t,n,r,i){let a=await je(e,{account:t,domain:mj(r,i),types:Tj,primaryType:`CloseAuthorization`,message:n}),o=We.from(a);if(!_j(o.type))throw Error(`TIP-1034 close authorizations require a TIP-1020 primitive signature; received "${o.type}".`);return We.serialize(o)}function xj(e,t,n,r){try{let i=We.from(n.signature);if(!_j(i.type)||We.serialize(i).toLowerCase()!==n.signature.toLowerCase())return!1;let a=gj(e,t,n),o=We.extractAddress({payload:a,signature:i});return We.verify(i,{address:o,payload:a})&&TA(o,r)}catch{return!1}}var Sj,Cj,wj,Tj,Ej=F((()=>{EA(),Sj=`TIP20 Channel Reserve`,Cj=`1`,wj={Voucher:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]},Tj={CloseAuthorization:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]}}));function Dj(e){return typeof e==`object`&&!!e}function Oj(e){return typeof e==`string`&&de(e,{strict:!1})?e:void 0}function kj(e){return Oj(e.accessKeyAddress)}function Aj(){let e=BigInt(Math.floor(Date.now()/1e3))-60n;return e<=0n?0:Number(BigInt(re.random(8))%e)}function jj(e){return kj(e)??e.address}async function Mj(e,t){let{account:n,calls:r,feePayer:i,feeToken:a,validAfter:o}=t;return Ee(e,{account:n,calls:r,nonceKey:`expiring`,...i?{feePayer:!0}:{},feeToken:a,...o===void 0?{}:{validAfter:o}})}async function Nj(e,t){return await Ae(e,t)}function Pj(e,t,n=!1){let r=e.request.methodDetails,i=Dj(r)?Oj(r.escrowContract)??Oj(r.escrow):void 0,a=t??`0x4d50500000000000000000000000000000000000`;if(i&&!Ij(i,a)&&(!n||t!==void 0))throw Error(`Tempo session escrow ${i} does not match client escrow ${a}.`);return i&&!Ij(i,a)?i:a}function Fj(e,t,n,r){return ZS({challenge:e,payload:t,source:`did:pkh:eip155:${n}:${r.address}`})}function Ij(e,t){return e.toLowerCase()===t.toLowerCase()}async function Lj(e,t,n,r,i,a=jE){let o=ij({...n,chainId:i,escrow:a}),s=fE(r),c=await yj(e,t,{channelId:o,cumulativeAmount:s},a,i);return{action:`voucher`,channelId:o,descriptor:n,cumulativeAmount:s.toString(),signature:c}}async function Rj(e,t,n,r,i,a=jE){let o=await Lj(e,t,n,r,i,a),s=await bj(e,t,{channelId:o.channelId,cumulativeAmount:fE(BigInt(o.cumulativeAmount))},a,i);return{action:`close`,channelId:o.channelId,descriptor:n,cumulativeAmount:o.cumulativeAmount,signature:o.signature,closeSignature:s}}async function zj(e,t,n){let r=jj(t),i=n.escrow??`0x4d50500000000000000000000000000000000000`,a=n.operator??`0x0000000000000000000000000000000000000000`,o=re.random(32),s=fE(n.deposit),c=fE(n.initialAmount),l=oe({abi:fj,functionName:`open`,args:[n.payee,a,n.token,s,o,r]}),u=await Nj(e,await Mj(e,{account:t,calls:[...n.prefixCalls??[],{to:i,data:l}],feePayer:n.feePayer,feeToken:n.feeToken??n.token})),d=Re.deserialize(u),f={authorizedSigner:r,expiringNonceHash:sj(oj({...n.feePayer?{feePayer:!0}:{},transaction:d}),{sender:t.address}),operator:a,payee:n.payee,payer:t.address,salt:o,token:n.token},p=ij({...f,chainId:n.chainId,escrow:i});return{action:`open`,type:`transaction`,channelId:p,transaction:u,signature:await yj(e,t,{channelId:p,cumulativeAmount:c},i,n.chainId),descriptor:f,cumulativeAmount:c.toString(),authorizedSigner:f.authorizedSigner}}async function Bj(e,t,n,r,i,a,o=jE,s=[],c=n.token){let l=ij({...n,chainId:i,escrow:o}),u=fE(r);return{action:`topUp`,type:`transaction`,channelId:l,transaction:await Nj(e,await Mj(e,{account:t,calls:[...s,{to:o,data:oe({abi:fj,functionName:`topUp`,args:[n,u]})}],feePayer:a,feeToken:c,validAfter:Aj()})),descriptor:n,additionalDeposit:u.toString()}}var Vj=F((()=>{eC(),cj(),pj(),ME(),Ej()}));function Hj(e){let{payee:t,token:n,escrow:r,chainId:i}=e;return`${t.toLowerCase()}:${n.toLowerCase()}:${r.toLowerCase()}:${i}`}function Uj(e){return Hj({payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId})}function Wj(){let e=new Map;return{get:t=>e.get(t),set(t){e.set(Uj(t),t)},delete(t){e.delete(t)}}}function Gj(e){return{...e,cumulativeAmount:e.cumulativeAmount.toString(),deposit:e.deposit.toString()}}function Kj(e){return{...e,cumulativeAmount:BigInt(e.cumulativeAmount),deposit:BigInt(e.deposit)}}var qj=F((()=>{}));function Jj(e){if(e<0n||e>Zj)throw new Y({reason:`amount exceeds uint96 range`})}async function Yj(e,t,n=jE,r){return Xj(await De(e,{address:n,abi:fj,functionName:`getChannelState`,args:[t],...r===void 0?{}:{blockNumber:r}}))}function Xj(e){return Jj(e.settled),Jj(e.deposit),{settled:e.settled,deposit:e.deposit,closeRequestedAt:e.closeRequestedAt}}var Zj,Qj=F((()=>{bS(),pj(),ME(),Zj=2n**96n-1n}));function $j(e){return`cumulativeAmount`in e}function eM(e){if($j(e))return BigInt(e.cumulativeAmount)}async function tM(e,t){t.opened?await e.store.set(t):await e.store.delete(Uj(t)),e.notifyUpdate(t)}async function nM(e,t,n){let r=eM(n);if(r===void 0)return;let i=await e.store.get(t);i&&i.channelId.toLowerCase()===n.channelId.toLowerCase()&&(i.cumulativeAmount=i.cumulativeAmount>r?i.cumulativeAmount:r,n.action===`close`&&(i.opened=!1),await tM(e,i))}function rM(e){return e?.action!==void 0}function iM(e){return rM(e)&&e.descriptor!==void 0}function aM(e,t,n){let r=n===`additionalDeposit`?e.additionalDepositRaw:e.cumulativeAmountRaw,i=n===`additionalDeposit`?e.additionalDeposit:e.cumulativeAmount;if(r)return BigInt(r);if(i)return N(i,t)}function oM(e,t,n,r){let i=aM(e,t,n);if(i===void 0)throw Error(`${n} required for ${r} action`);return i}function sM(e){return typeof e==`object`&&!!e}function cM(e){return typeof e==`string`&&de(e,{strict:!1})?e:void 0}function lM(e){let t=e.request.methodDetails;return sM(t)?{chainId:typeof t.chainId==`number`?t.chainId:void 0,escrowContract:cM(t.escrowContract),escrow:cM(t.escrow),feePayer:typeof t.feePayer==`boolean`?t.feePayer:void 0,feeToken:cM(t.feeToken),operator:cM(t.operator),sessionSnapshot:Ox(t,Mx.sessionSnapshot)}:{}}function uM(e,t){if(typeof e==`string`&&de(e,{strict:!1}))return e;throw Error(`tempo session challenge missing ${t}`)}function dM(e){if(typeof e==`string`)return BigInt(e);throw Error(`tempo session challenge missing amount`)}function fM(e){return typeof e==`string`?e:void 0}async function pM(e){let{allowCustomEscrow:t,challenge:n,escrowOverride:r,allowedChainIds:i,getClient:a}=e,o=lM(n);(o.chainId!==void 0||i?.length===0)&&gA(i,o.chainId);let s=o.chainId??(i?.length===1?i[0]:void 0),c=await a({chainId:s});hA(c,s);let l=s??c.chain?.id;if(gA(i,l),!l)throw Error(`No chainId configured for TIP-1034 session challenge.`);let u=Pj(n,r,t),d=uM(n.request.recipient,`recipient`),f=uM(n.request.currency,`currency`);return{amount:dM(n.request.amount),challenge:n,chainId:l,client:c,escrow:u,feePayer:o.feePayer,feeToken:o.feeToken,key:Hj({payee:d,token:f,escrow:u,chainId:l}),operator:o.operator,payee:d,snapshot:o.sessionSnapshot,suggestedDepositRaw:fM(n.request.suggestedDeposit),token:f}}async function mM(e){let{channelId:t,client:n,descriptor:r,expected:i,readChannelState:a=Yj}=e,o=ij({...r,chainId:i.chainId,escrow:i.escrow});hM({channelId:t,descriptor:r,expectedChannelId:o,payee:i.payee,payer:i.payer,authorizedSigner:i.authorizedSigner,token:i.token});let s=await a(n,o,i.escrow);if(s.deposit===0n)throw Error(`Channel ${o} cannot be reused (closed or not found on-chain).`);if(s.closeRequestedAt!==0)throw Error(`Channel ${o} cannot be reused (pending close request).`);return{channelId:o,state:s}}function hM(e){let{authorizedSigner:t,channelId:n,descriptor:r,expectedChannelId:i,payee:a,payer:o,token:s}=e;if(n&&n.toLowerCase()!==i.toLowerCase())throw Error(`context channelId does not match descriptor`);if(!Ij(r.payee,a))throw Error(`context descriptor payee does not match challenge`);if(!Ij(r.token,s))throw Error(`context descriptor token does not match challenge`);if(!Ij(r.payer,o))throw Error(`context descriptor payer does not match account`);if(!Ij(rj(r),t))throw Error(`context descriptor authorizedSigner does not match account`)}function gM(e){let{context:t,snapshot:n}=e,r=t?.descriptor??n?.descriptor;if(r)return{...t,channelId:t?.channelId??n?.channelId,descriptor:r}}function _M(e){let{context:t,decimals:n,requestAmount:r,snapshot:i,settled:a}=e;if(i)return[BigInt(i.acceptedCumulative),BigInt(i.requiredCumulative),BigInt(i.spent)+r,a].reduce((e,t)=>t>e?t:e,0n);let o=aM(t,n,`cumulativeAmount`);return o===void 0?a+r:o+r}async function vM(e){let{account:t,client:n,readChannelState:r,snapshot:i}=e,a=i.highestVoucher;if(!a)throw Error(`session snapshot is missing its highest signed voucher`);if(a.channelId.toLowerCase()!==i.channelId.toLowerCase())throw Error(`session snapshot voucher channelId does not match snapshot channelId`);let o=BigInt(i.acceptedCumulative),s=BigInt(a.cumulativeAmount),c=BigInt(i.requiredCumulative),l=BigInt(i.deposit),u=BigInt(i.settled),d=BigInt(i.spent);if(s!==o)throw Error(`session snapshot voucher amount does not match acceptedCumulative`);if(d>o)throw Error(`session snapshot spent exceeds acceptedCumulative`);if(u>l)throw Error(`session snapshot settled amount exceeds deposit`);if(!xj(i.escrow,i.chainId,{channelId:a.channelId,cumulativeAmount:s,signature:a.signature},rj(i.descriptor)))throw Error(`session snapshot highest voucher signature is invalid`);let f=await mM({channelId:i.channelId,client:n,descriptor:i.descriptor,expected:{chainId:i.chainId,escrow:i.escrow,payee:i.descriptor.payee,payer:t.address,authorizedSigner:jj(t),token:i.descriptor.token},readChannelState:r}),p=[o,c,f.state.settled].reduce((e,t)=>t>e?t:e,0n);if(p>f.state.deposit)throw Error(`recovered session cumulative amount exceeds on-chain channel deposit`);return{entry:{channelId:f.channelId,cumulativeAmount:p,deposit:f.state.deposit,descriptor:i.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0},spent:d}}function yM(e,t){return Ij(e.address,t.payer)?Ij(jj(e),rj(t)):!1}function bM(e){let{account:t,entry:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e;if(rM(r)){if(!iM(r))throw Error(`descriptor required for TIP-1034 session action`);return{type:`manual`,account:t,context:r,decimals:i,resolved:o}}if(!n&&r?.channelId&&!r.descriptor)throw Error(`descriptor required to reuse TIP-1034 channel`);let s=gM({context:r,snapshot:o.snapshot});return!n&&s&&yM(t,s.descriptor)?{type:`recover`,account:t,context:s,decimals:i,maxDeposit:a,resolved:o}:n?.opened&&yM(t,n.descriptor)?{type:`voucher`,account:t,entry:n,maxDeposit:a,resolved:o}:{type:`open`,account:t,context:r,maxDeposit:a,resolved:o}}async function xM(e,t,n=!1){switch(e.type){case`open`:return CM(e,t,n);case`recover`:return wM(e,t);case`voucher`:return TM(e,t);case`manual`:return EM(e,t,n)}}async function SM(e,t){if(e)return await DA(t.client,{account:t.account,amountOut:t.amountOut,tokenOut:t.tokenOut,tokenIn:e.tokenIn,slippage:e.slippage})}async function CM(e,t,n){let{account:r,resolved:i}=e,a=$E({contextDepositRaw:e.context?.depositRaw,maxDeposit:e.maxDeposit,requestAmount:i.amount,suggestedDepositRaw:i.suggestedDepositRaw}),o=await zj(i.client,r,{chainId:i.chainId,deposit:a,escrow:i.escrow,feePayer:i.feePayer,feeToken:i.feeToken,initialAmount:i.amount,operator:i.operator,payee:i.payee,prefixCalls:await SM(n,{account:r.address,amountOut:a,client:i.client,tokenOut:i.token}),token:i.token});return await tM(t,{channelId:o.channelId,cumulativeAmount:i.amount,deposit:a,descriptor:o.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0}),o}async function wM(e,t){let{account:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e,{descriptor:s}=r,c=await mM({channelId:r.channelId,client:o.client,descriptor:s,expected:{chainId:o.chainId,escrow:o.escrow,payee:o.payee,payer:n.address,authorizedSigner:jj(n),token:o.token}}),l=_M({context:r,decimals:i,requestAmount:o.amount,settled:c.state.settled,snapshot:o.snapshot});if(l>c.state.deposit)throw Error(`recovered voucher amount exceeds on-chain channel deposit`);tD(l,a);let u=await Lj(o.client,n,s,l,o.chainId,o.escrow);return await tM(t,{channelId:c.channelId,cumulativeAmount:l,deposit:c.state.deposit,descriptor:s,escrow:o.escrow,chainId:o.chainId,opened:!0}),u}async function TM(e,t){let{account:n,entry:r,resolved:i}=e,a=r.cumulativeAmount+i.amount;tD(a,e.maxDeposit);let o=await Lj(i.client,n,r.descriptor,a,i.chainId,i.escrow);return r.cumulativeAmount=a,await tM(t,r),o}async function EM(e,t,n){let{account:r,context:i,decimals:a,resolved:o}=e,{descriptor:s}=i,c=ij({...s,chainId:o.chainId,escrow:o.escrow});hM({channelId:i.channelId,descriptor:s,expectedChannelId:c,payee:o.payee,payer:r.address,authorizedSigner:jj(r),token:o.token});let l=await DM({account:r,channelId:c,context:i,decimals:a,descriptor:s,resolved:o},n);return await nM(t,o.key,l),l}async function DM(e,t){switch(e.context.action){case`open`:return OM(e);case`topUp`:return kM(e,t);case`voucher`:return AM(e);case`close`:return jM(e)}}async function OM(e){let{account:t,channelId:n,context:r,decimals:i,descriptor:a,resolved:o}=e;if(!r.transaction)throw Error(`transaction required for open action`);let s=oM(r,i,`cumulativeAmount`,`open`),c=await Lj(o.client,t,a,s,o.chainId,o.escrow);return{action:`open`,type:`transaction`,channelId:n,transaction:r.transaction,signature:c.signature,descriptor:a,cumulativeAmount:s.toString(),authorizedSigner:a.authorizedSigner}}async function kM(e,t){let{account:n,channelId:r,context:i,decimals:a,descriptor:o,resolved:s}=e,c=oM(i,a,`additionalDeposit`,`topUp`);return i.transaction?{action:`topUp`,type:`transaction`,channelId:r,transaction:i.transaction,descriptor:o,additionalDeposit:c.toString()}:Bj(s.client,n,o,c,s.chainId,s.feePayer,s.escrow,await SM(t,{account:n.address,amountOut:c,client:s.client,tokenOut:s.token}),s.feeToken)}function AM(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return Lj(a.client,t,i,oM(n,r,`cumulativeAmount`,`voucher`),a.chainId,a.escrow)}function jM(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return Rj(a.client,t,i,oM(n,r,`cumulativeAmount`,`close`),a.chainId,a.escrow)}var MM,NM,PM,FM=F((()=>{Px(),vA(),Xx(),MA(),Qj(),cj(),Ej(),Vj(),qj(),gD(),MM=J.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]*$/.test(e)),NM=J.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),PM=J.object({account:J.optional(J.custom()),autoSwap:J.optional(J.custom()),action:J.optional(J.enum([`open`,`topUp`,`voucher`,`close`])),channelId:J.optional(NM),cumulativeAmount:J.optional(Bx()),cumulativeAmountRaw:J.optional(J.string()),transaction:J.optional(MM),descriptor:J.optional(J.custom()),additionalDeposit:J.optional(Bx()),additionalDepositRaw:J.optional(J.string()),depositRaw:J.optional(J.string())})}));async function IM(e,t){let n=BM.get(e)??new Map;BM.set(e,n);let r=n.get(t),i,a=new Promise(e=>{i=e});return n.set(t,a),await r,()=>{i(),n.get(t)===a&&n.delete(t)}}function LM(e,t){try{return t?.channelId.toLowerCase()===e.channelId.toLowerCase()&&BigInt(t.acceptedCumulative)===e.cumulativeAmount}catch{return!1}}function RM(e,t,n){try{let r=e.response?.headers.get(q.paymentReceipt);if(r){let e=xE(r);if(e.challengeId===t.id&&LM(n,e))return!0}}catch{}return e.challenges?.some(e=>CD(e)?LM(n,wD(e)):!1)??!1}function zM(e={}){let{account:t,allowCustomEscrow:n=!1,autoSwap:r,channelStore:i,decimals:a=6,escrow:o,allowedChainIds:s,getClient:c,maxDeposit:l,topUpAmount:u,onChannelUpdate:d,resolveAccount:f}=e,p=mA({chain:Ve,getClient:c,rpcUrl:cO}),m=lA({account:t}),h=l===void 0?void 0:N(l,a),g=u===void 0?void 0:N(u,a),_=i??Wj(),v={store:_,notifyUpdate:e=>d?.(e)},y=async(e,t,n)=>{let r=m(e.client,t),i=t?.action?t.descriptor:n?.descriptor??gM({context:t,snapshot:e.snapshot})?.descriptor;return await f?.({account:r,chainId:e.chainId,operation:{kind:`authorizePaymentChannel`,...i?{authority:rj(i)}:{}}})??r},b=async(e,t,n)=>bM({account:await y(e,t,n),entry:n,context:t,decimals:a,maxDeposit:h,resolved:e}),x=KT(sE,{canHandleChallenge:({challenge:e})=>CD(e),context:PM,async createCredential(e){let{challenge:t,context:i}=e,a=await pM({allowCustomEscrow:n,challenge:t,escrowOverride:o,allowedChainIds:s,getClient:p}),c=mw(e),l=()=>{};try{let e=!rM(i)&&i?.descriptor===void 0;e&&(l=await IM(_,a.key),c&&(await _.get(a.key))?.opened&&await c.prepare());let n=await _.get(a.key),o=await b(a,i,n);if(!e&&c&&o.type===`open`){l=await IM(_,a.key);let e=await _.get(a.key);e?.channelId!==n?.channelId&&(n=e,n?.opened&&(await c.prepare(),n=await _.get(a.key)),o=await b(a,i,n))}let s,u=c&&o.type===`open`?{store:{get:e=>_.get(e),async set(e){s=e},delete:e=>_.delete(e)},notifyUpdate(){}}:v,d=await Fj(t,await xM(o,u,OA(i?.autoSwap??r,AA)),a.chainId,o.account);if(c&&s){let e=s;c.settle=async n=>{let r=n.status===`accepted`||RM(n,t,e);if(!r&&n.status===`pending`)return!1;try{if(r){let t=await _.get(a.key);(!t?.opened||t.channelId.toLowerCase()!==e.channelId.toLowerCase())&&(await _.set(e),v.notifyUpdate(e))}return!0}finally{l()}}}else l();return d}catch(e){throw l(),e}}}),S=async({challenge:e,channel:t,deposit:n,fetch:r,input:i,requiredCumulative:a,signal:o})=>{let s=t.deposit>n?t.deposit:n,c=eD({deposit:s,maxDeposit:h,requiredCumulative:a,suggestedDeposit:e.request.suggestedDeposit===void 0?void 0:BigInt(e.request.suggestedDeposit),topUpAmount:g});c>0n&&await kD({additionalDeposit:c,challenge:e,channel:t,channelId:t.channelId,createSessionCredential:(e,t)=>x.createCredential({challenge:e,context:t}),fetch:r,input:i,signal:o});let l=s+c;if(l===t.deposit)return;let u=await _.get(Uj(t)),d=u?.channelId.toLowerCase()===t.channelId.toLowerCase()?u:t,f={...d,deposit:d.deposit>l?d.deposit:l};await _.set(f),v.notifyUpdate(f)};return ow(x,async({challenge:e,context:t,fetch:r,input:i,signal:a})=>{if(!CD(e))return;let c=t===void 0?void 0:PM.parse(t);if(rM(c))return;let l=await pM({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:p}),u=await _.get(l.key);if(!u?.opened)return;let d=l.snapshot?.channelId.toLowerCase()===u.channelId.toLowerCase()?l.snapshot:void 0,f=u.cumulativeAmount+vE(e),m=d?BigInt(d.requiredCumulative):f,h=m>f?m:f,g=d?BigInt(d.deposit):u.deposit,v=g>u.deposit?g:u.deposit;h<=v&&v===u.deposit||!yM(await y(l,c,u),u.descriptor)||await S({challenge:e,channel:u,deposit:v,fetch:r,input:i,requiredCumulative:h,signal:a})}),dw(x,async({challenge:e,credential:t,fetch:r,headers:i,input:a,refetch:c,response:l,signal:u})=>{if(!CD(e))return l;if(!SE(l))return _E(qS(t).payload).action===`open`&&i.get(`accept`)?.toLowerCase().includes(`text/event-stream`)?await c?.()??l:l;let d=(await pM({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:p})).key,f=await _.get(d),m={assertVoucherWithinLocalLimit:e=>tD(e,h),createSessionCredential:(e,t)=>x.createCredential({challenge:e,context:t}),fetch:r,getChannel:()=>f??null,async topUpIfNeeded({deposit:t,requiredCumulative:n,signal:i}){f&&await S({challenge:e,channel:f,deposit:f.deposit>t?f.deposit:t,fetch:r,input:a,requiredCumulative:n,signal:i})}};return BD({onNeedVoucher:(t,n)=>VD({challenge:e,driver:m,input:a,signal:n},t),onReceipt(){},response:l,signal:u})})}var BM,VM=F((()=>{uw(),vw(),Px(),eC(),qT(),uA(),vA(),MA(),lO(),lE(),cj(),ME(),Vj(),qj(),FM(),gD(),BM=new WeakMap}));function HM(e,t){WM.set(e,t)}function UM(e){let t=WM.get(e);if(!t)throw Error(`Session manager internals are unavailable.`);return t}var WM,GM=F((()=>{WM=new WeakMap}));function KM(e){let t=null;return{wait(n=()=>!0){if(t)throw Error(`${e} wait already in progress`);return new Promise((e,r)=>{t={predicate:n,resolve:e,reject:r}})},settle(e){if(!t||!t.predicate(e))return;let n=t;t=null,n.resolve(e)},reject(e){if(!t)return;let n=t;t=null,n.reject(e)}}}function qM(e){let t=KM(`close-ready`),n=KM(`receipt`);return{waitForReceipt(e){return n.wait(e)},waitForCloseReady(){let n=e.getSocketSession()?.closeReadyReceipt;return n?Promise.resolve(n):t.wait()},settleReceipt(e){n.settle(e)},settleCloseReady(n){let r=e.getSocketSession();r&&r.challenge.id===n.challengeId&&r.channelId===n.channelId&&(r.closeReadyReceipt=n),t.settle(n)},rejectReceipt(e){n.reject(e)},rejectCloseReady(e){t.reject(e)}}}var JM=F((()=>{}));function YM(e){return e.method===Ax.tempo&&e.intent===jx.charge}function XM(e){if(!YM(e)||typeof e.request.amount!=`string`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function ZM(e,t,n){if(!n)return t;let r={...Sw(e instanceof Request?e.headers:void 0),...Sw(t?.headers)};return Object.keys(r).some(e=>e.toLowerCase()===q.paymentSession.toLowerCase())?t:{...t,headers:{...r,[q.paymentSession]:n}}}function QM(e,t){return e===void 0?t:{...PM.parse(e),...t}}function $M(e){let t=e.decimals??6,n=e.webSocket??globalThis.WebSocket;return{decimals:t,fetch:e.fetch??globalThis.fetch.bind(globalThis),maxVoucherCumulative:e.maxDeposit===void 0?null:N(e.maxDeposit,t),topUpAmount:e.topUpAmount===void 0?null:N(e.topUpAmount,t),WebSocket:n}}function eN(e){let t=e.client?.chain?.id;(t!==void 0||e.allowedChainIds?.length===0)&&gA(e.allowedChainIds,t);let n=e.allowCustomEscrow??!1,r=$M(e),i=mA({chain:Ve,getClient:e.client?()=>e.client:e.getClient,rpcUrl:cO}),a=lA({account:e.account}),o=sD(),s=e.credentialContext===void 0?void 0:QM(e.credentialContext,{}),c=qM({getSocketSession:()=>o.socketSession}),l=e.channelStore??Wj(),u=new Set,d;async function f(e){let t=await l.get(e);if(t?.opened&&!u.has(t.channelId))return t}let p={async get(e){let t=await f(e);return t&&d&&(d.seenExisting.add(e),!d.committed&&!d.created.has(e)&&(d.resumed??=t)),t},async set(e){let t=Uj(e);e.opened&&u.delete(e.channelId),d?.trackCreates&&!d.seenExisting.has(t)&&d.created.set(t,e),await l.set(e)},delete:e=>l.delete(e)};async function m(e){let t=Uj(e);u.add(e.channelId),d?.seenExisting.delete(t),d?.resumed===e&&(d.resumed=void 0),await Promise.resolve(l.delete(t)).catch(()=>void 0)}async function h(){let e=d;if(e?.created.size){for(let[t,n]of e.created)u.add(n.channelId),await Promise.resolve(l.delete(t)).catch(()=>void 0);e.created.clear(),await ie(e.committed??e.previous)}}function g(e){let t=Ox(e.request.methodDetails,Mx.sessionSnapshot);if(typeof t?.channelId!=`string`)return!1;let n=d;if(!n?.created.size||!o.channel)return!1;for(let[e,r]of n.created)if(r.channelId.toLowerCase()===t.channelId.toLowerCase()&&o.channel.channelId.toLowerCase()===t.channelId.toLowerCase())return n.created.delete(e),n.committed=fD({channel:o.channel,spent:o.spent,state:o.state}),!0;return!1}function _(e){return WE(o,e)}function v(){let e=o.state.status===`active`?o.state:d?.committed?.state??d?.previous.state;return e?.status===`active`?e.units:0}function y(e){let t=d,n=t?.committed?.channel?.entry??t?.resumed;!t||n?.channelId.toLowerCase()!==e.channelId.toLowerCase()||e.deposit<=n.deposit||(t.resumed=void 0,t.committed=fD({channel:o.channel,spent:o.spent,state:o.state}))}let b=zM({account:e.account,allowCustomEscrow:n,autoSwap:e.autoSwap,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount,escrow:e.escrow,allowedChainIds:e.allowedChainIds,decimals:r.decimals,maxDeposit:e.maxDeposit,topUpAmount:e.topUpAmount,channelStore:p,onChannelUpdate(e){e.channelId!==o.channel?.channelId&&(o.spent=0n),o.channel=e,o.lastChallenge&&_({type:`activated`,challengeId:o.lastChallenge.id,entry:e,spent:o.spent.toString(),units:v()}),y(e)}});fw(b);let x=ej({allowedChainIds:e.allowedChainIds,account:e.account,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount}),S=bw({fetch:r.fetch,methods:[b],onChallenge:async(e,t)=>{if(!SD(e))return;let n=d,r=n&&n.challengesReceived>0&&e.id===o.lastChallenge?.id,i=r&&Qx(e)===Qx(o.lastChallenge);n&&n.challengesReceived++,!i&&(g(e)||(n?.created.size?await h():r&&await ie(n.committed??n.previous)),o.lastChallenge=e,_({type:`challengeReceived`,challengeId:e.id}))}});function C(e,t){return b.createCredential({challenge:e,context:QM(s,t)})}function w(e){cD({maxVoucherCumulative:r.maxVoucherCumulative,receipt:e,runtime:o})}function T(e=o.state.status===`active`?o.state.units:0){!o.channel||!o.lastChallenge||o.state.status!==`active`&&o.state.status!==`withdrawable`&&o.state.status!==`closeRequested`&&_({type:`activated`,challengeId:o.lastChallenge.id,entry:o.channel,spent:o.spent.toString(),units:e})}async function ee(t){let n=t.headers.get(q.paymentSessionSnapshot);if(!n)return;let r=PE(n);gA(e.allowedChainIds,r.chainId);let s=await i({chainId:r.chainId});hA(s,r.chainId);let c=a(s),{entry:l,spent:u}=await vM({account:await e.resolveAccount?.({account:c,chainId:r.chainId,operation:{authority:rj(r.descriptor),kind:`authorizePaymentChannel`}})??c,client:s,snapshot:r});return ne(l.cumulativeAmount),await Promise.resolve(p.set(l)).catch(()=>void 0),o.channel=l,o.spent=u,l}async function E(t,n){if(!e.bootstrap||o.channel?.opened)return;let i=t instanceof Request?t.headers:void 0,{body:a,method:s,...c}=n??{},l=t instanceof Request?t.url:t,u={...c,method:`HEAD`,headers:{...Sw(i),...Sw(n?.headers),[q.acceptPayment]:`${Ax.tempo}/${jx.charge}`}};try{let e=await r.fetch(l,u);if(e.status!==402)return await ee(e);let t=sS(e).find(YM);if(!t||!XM(t))return;let n=await x.createCredential({challenge:t,context:{}}),i=await r.fetch(l,{...u,headers:{...Sw(u.headers),[q.authorization]:n}});return i.ok?await ee(i):void 0}catch{return}}function D(e,t){let n=o.socketSession;return uD({challengeId:e.id,channelId:t,closeReadyReceipt:n?.closeReadyReceipt,cumulativeAmount:o.channel?.channelId===t?o.channel.cumulativeAmount:0n,deliveredChunks:n?.deliveredChunks,socketChallengeId:n?.challenge.id,socketChannelId:n?.channelId,spent:o.spent,tickCost:n?.tickCost})}function O(e,t){let n=wD(t);if(!n)return;if(ij({...n.descriptor,chainId:n.chainId,escrow:n.escrow}).toLowerCase()!==n.channelId.toLowerCase())throw Error(`close snapshot descriptor does not match its channel ID`);if(n.channelId.toLowerCase()!==e.channelId.toLowerCase())throw Error(`close snapshot channel ID does not match local session`);if(n.chainId!==e.chainId||n.escrow.toLowerCase()!==e.escrow.toLowerCase())throw Error(`close snapshot payment scope does not match local session`);let r=BigInt(n.acceptedCumulative),i=BigInt(n.spent);if(r<0n||i<0n)throw Error(`close snapshot amounts must not be negative`);if(i>r)throw Error(`close snapshot spent exceeds accepted cumulative amount`);if(r>e.cumulativeAmount)throw Error(`close snapshot accepted cumulative exceeds local voucher state`);return{acceptedCumulative:r,spent:i}}function k(e,t){let n=O(e.channel,t);if(!n)return;let{acceptedCumulative:r,spent:i}=n;if(o.spent>r)throw Error(`close snapshot accepted cumulative is below locally confirmed spend`);return i>o.spent&&(o.spent=i),n}function te(e,t=e.challenge,n=!1){let r=(n?k(e,t):O(e.channel,t))?.acceptedCumulative??D(t,e.channelId);if(r>e.channel.cumulativeAmount)throw Error(`fallback close amount exceeds local voucher state`);return ne(r),r.toString()}function ne(e){YE({cumulativeAmount:e,maxVoucherCumulative:r.maxVoucherCumulative})}async function re(e){let{knownDeposit:t,...n}=e,i=await kD({...n,channel:o.channel,createSessionCredential:C,fetch:r.fetch});w(i);let a=bD({additionalDeposit:e.additionalDeposit,channel:o.channel,channelId:e.channelId,challengeId:o.lastChallenge?.id,currentState:o.state,knownDeposit:t,receipt:i,spent:o.spent});return a?.channel&&o.lastChallenge&&(await p.set(a.channel),_({type:`activated`,challengeId:o.lastChallenge.id,entry:a.channel,spent:o.spent.toString(),units:v()}),y(a.channel)),i}async function A(e){let t=o.channel?.channelId===e.channelId?o.channel.deposit:0n,n=t>e.deposit?t:e.deposit,i=eD({deposit:n,maxDeposit:r.maxVoucherCumulative,requiredCumulative:e.requiredCumulative,suggestedDeposit:e.challenge.request.suggestedDeposit===void 0?void 0:BigInt(e.challenge.request.suggestedDeposit),topUpAmount:r.topUpAmount});i!==0n&&await re({challenge:e.challenge,input:e.input,channelId:e.channelId,additionalDeposit:i,knownDeposit:n,signal:e.signal})}async function j(e,t){let n=dD({channel:o.channel,channelId:e,challengeId:o.lastChallenge?.id,cumulativeAmount:t,spent:o.spent,state:o.state});n&&o.channel&&(_({type:`activated`,challengeId:n.challengeId,entry:o.channel,spent:n.spent,units:n.units}),await l.set(o.channel))}async function ie(e){let t=pD(e,o.channel);o.channel=t.channel,o.spent=t.spent,o.state=t.state,o.channel?.opened&&await l.set(o.channel)}function ae(e){let t=e.headers.get(q.paymentReceipt),n=t?xE(t):null;return w(n),Object.assign(e,{receipt:n,challenge:o.lastChallenge,channelId:o.channel?.channelId??null,cumulative:o.channel?.cumulativeAmount??0n})}async function oe(e,t){if(d)throw Error(`SessionManager: a request is already in flight; concurrent requests on one manager are not supported`);o.lastUrl=e;let n=fD({channel:o.channel,spent:o.spent,state:o.state}),i={challengesReceived:0,committed:void 0,created:new Map,previous:n,seenExisting:new Set,resumed:void 0,trackCreates:!1};d=i;try{await E(e,t),i.trackCreates=!0;let a=ZM(e,t,o.channel?.opened?o.channel.channelId:void 0);s&&(a={...a,context:s});let c=!n.channel?.opened;async function l(){let n=i.resumed;return!c||!n?!1:(c=!1,await m(n),a=ZM(e,t,void 0),!0)}for(;;){let t;try{t=await S(e,a)}catch(e){if(i.created.size?await h():await ie(i.committed??n),await l())continue;throw e}let s=ae(t),c=!1;if(s.status===402){let t=await jD({input:e,init:a,response:s,createSessionCredential:C,fetch:r.fetch,getChannel:()=>o.channel,restoreCumulative:j,setChallenge(e){o.lastChallenge=e},topUpIfNeeded:A});t&&(c=!0,s=ae(t))}if(!c&&!s.ok&&!s.receipt){if(i.created.size?await h():await ie(i.committed??n),await l())continue;return s}return s}}finally{d=void 0}}async function se(e){let t=await ND({createSessionCredential:C,fetch:r.fetch,getMinimumSpent:()=>o.spent,lastUrl:o.lastUrl,resolveSignedCloseAmount:t=>te(e,t,!0),signedCloseAmount:te(e),setChallenge(e){o.lastChallenge=e},target:e});return t&&(T(),_({type:`closeStarted`}),_({type:`closed`,receipt:t})),t}let ce={createSessionCredential:C,doFetch:oe,fetch:r.fetch,getChannel:()=>o.channel,getChallenge:()=>o.lastChallenge,assertVoucherWithinLocalLimit:ne,acceptReceipt(e){w(e)},topUpIfNeeded:A},M={get channelId(){return o.channel?.channelId},get cumulative(){return o.channel?.cumulativeAmount??0n},get opened(){return o.channel?.opened??!1},get state(){return o.state},fetch:oe,async topUp(e){let t=yD({amount:e,assertVoucherWithinLocalLimit:ne,channel:o.channel,decimals:r.decimals,lastChallenge:o.lastChallenge,lastUrl:o.lastUrl});return re({additionalDeposit:t.additionalDeposit,challenge:t.challenge,channelId:t.channelId,input:t.input})},async sse(e,t){return PD(e,t,ce)},async ws(e,t){if(!r.WebSocket)throw Error("No WebSocket implementation available. Pass `webSocket` to sessionManager() in this runtime.");let n=DD(e),i=t?.signal?{signal:t.signal}:void 0;await E(n,i);let a=o.channel?.opened?o.channel.channelId:void 0,{challenge:s,credential:l,httpUrl:u,wsUrl:d}=await UD({async createSessionCredential(e,i){return o.lastChallenge=e,await cw(b,{challenge:e,context:i,fetch:r.fetch,input:n,signal:t?.signal}),C(e,i)},fetch:r.fetch,input:e,onProbeUrl(e){o.lastUrl=e.toString()},probeInit:ZM(n,i,a),signal:t?.signal});return o.lastChallenge=s,JD({challenge:s,credential:l,httpUrl:u,WebSocket:r.WebSocket,wsUrl:d,options:t,createSessionCredential:C,getChannel:()=>o.channel,setSocketSession(e){o.socketSession=e},async refreshChallenge(){let e=await HD({fetch:r.fetch,input:u,probeInit:ZM(u,i,o.channel?.opened?o.channel.channelId:void 0),signal:t?.signal});return o.lastChallenge=e.challenge,e.challenge},assertVoucherWithinLocalLimit:ne,acceptReceipt:w,rejectCloseReady:c.rejectCloseReady,rejectReceipt:c.rejectReceipt,settleCloseReady:c.settleCloseReady,settleReceipt:c.settleReceipt,topUpIfNeeded:A,waitForReceipt:c.waitForReceipt})},async close(){let e=o.socketSession,t=nD({channel:o.channel,currentSocket:e,lastChallenge:o.lastChallenge});if(!t)return;let n=e?.socket;if(e&&n?.readyState===eO.OPEN){let r=await mD({activeSocket:n,createSessionCredential:C,currentSocket:e,spent:o.spent,target:t,waitForCloseReady:c.waitForCloseReady,waitForReceipt:c.waitForReceipt});return T(),_({type:`closeStarted`}),_({type:`closed`,receipt:r}),r}return se(t)}};return HM(M,{consumeSseResponse(e,t,n){return FD(e,t,n,ce)},rehydrate({channel:e,challenge:t,input:n,spent:r}){if(!e.opened)throw Error(`Cannot restore a closed session channel.`);if(!SD(t))throw Error(`Cannot restore session: challenge is not tempo/session.`);if(r<0n)throw Error(`Cannot restore session: spent must not be negative.`);if(r>e.cumulativeAmount)throw Error(`Cannot restore session: spent exceeds local voucher state.`);ne(e.cumulativeAmount);let i=O(e,t),a=i&&i.spent>r?i.spent:r;o.lastUrl=n,o.lastChallenge=t,o.channel=e,o.spent=a,_({type:`challengeReceived`,challengeId:t.id}),_({type:`activated`,challengeId:t.id,entry:e,spent:a.toString(),units:0})}}),M}var tN=F((()=>{gS(),oT(),uw(),vw(),Px(),uA(),vA(),nj(),lO(),qj(),FM(),VM(),cj(),ME(),VE(),GM(),JM(),gD(),rO(),(function(e){e.serializeSnapshot=NE,e.deserializeSnapshot=PE})(eN||={})}));function nN(e){return e instanceof Date?e:new Date(e)}function rN(e){let t=e.getTime();if(!Number.isFinite(t))throw new Y({reason:`subscriptionExpires is invalid`});if(t%1e3!=0)throw new Y({reason:`subscriptionExpires must be representable as whole seconds`});let n=t/1e3;if(n<=0||!Number.isSafeInteger(n))throw new Y({reason:`subscriptionExpires cannot be represented in a Tempo key authorization`});return n}function iN(e){if(!/^[1-9]\d*$/.test(e.periodCount))throw new Y({reason:`periodCount is invalid`});let t=CN[e.periodUnit];if(t===void 0)throw new Y({reason:`periodUnit is invalid`});let n=BigInt(e.periodCount)*t;if(n>SN)throw new Y({reason:`subscription period cannot be represented as an unsigned 64-bit integer`});if(n>BigInt(2**53-1))throw new Y({reason:`subscription period cannot be represented exactly by this Tempo client`});return Number(n)}function aN(e){let{challengeExpires:t,request:n}=e;iN(n);let r=rN(nN(n.subscriptionExpires));if(t){let e=Math.floor(new Date(t).getTime()/1e3);if(!Number.isFinite(e)||r<=e)throw new Y({reason:`subscriptionExpires must be strictly later than challenge expires`})}}function oN(e){let t=yN(e.currency,`currency`),n=yN(e.recipient,`recipient`);return[{address:t,selector:xN,recipients:[n]}]}function sN(e){try{let t=re.fromBytes(k.toBytes(e));if(re.size(t)!==32)throw Error(`invalid challenge id size`);return t}catch{throw new Y({reason:`challenge id must encode 32 bytes`})}}async function cN(e){let{accessKey:t,account:n,challengeId:r,chainId:i,request:a}=e;if(typeof n.sign!=`function`)return;let o=uN({accessKey:t,challengeId:r,chainId:i,request:a}),s=await n.sign({hash:Ue.getSignPayload(o)}),c=We.from(s);if(c.type===`keychain`||c.type===`multisig`)throw new Y({reason:`keyAuthorization must use a primitive signature`});return Ue.from(o,{signature:s})}function lN(e){let{accessKey:t,challengeId:n,chainId:r,payload:i,request:a}=e;if(i.type!==`keyAuthorization`)throw new Y({reason:`invalid keyAuthorization payload`});let o=dN(i.signature),s=fN(o);if(pN({accessKey:t,authorization:o,chainId:r}),o.witness?.toLowerCase()!==sN(n))throw new Y({reason:`keyAuthorization challenge mismatch`});return mN(o,a),gN(hN(o),a),_N(o.scopes,a),{authorization:o,source:{address:vN(o,s),chainId:r}}}function uN(e){let{accessKey:t,challengeId:n,chainId:r,request:i}=e;return Ue.from({address:yN(t.accessKeyAddress,`accessKeyAddress`),chainId:BigInt(r),expiry:rN(nN(i.subscriptionExpires)),limits:[{token:yN(i.currency,`currency`),limit:BigInt(i.amount),period:iN(i)}],scopes:oN(i),type:t.keyType,witness:sN(n)})}function dN(e){try{return Ue.deserialize(e)}catch(e){throw e instanceof Ue.InvalidSignatureTypeError?new Y({reason:`keyAuthorization must use a primitive signature`}):new Y({reason:`invalid keyAuthorization payload`})}}function fN(e){let t=e.signature;if(!t)throw new Y({reason:`keyAuthorization must use a primitive signature`});return t}function pN(e){let{accessKey:t,authorization:n,chainId:r}=e;if(n.chainId!==BigInt(r))throw new Y({reason:`keyAuthorization chainId mismatch`});if(t){if(!fe(n.address,yN(t.accessKeyAddress,`accessKeyAddress`)))throw new Y({reason:`keyAuthorization access key mismatch`});if(n.type!==t.keyType)throw new Y({reason:`keyAuthorization key type mismatch`})}}function mN(e,t){if(aN({request:t}),e.expiry!==rN(nN(t.subscriptionExpires)))throw new Y({reason:`keyAuthorization expiry mismatch`})}function hN(e){let[t]=e.limits??[];if(!t||e.limits?.length!==1)throw new Y({reason:`keyAuthorization must contain exactly one token limit`});return t}function gN(e,t){if(!fe(e.token,yN(t.currency,`currency`)))throw new Y({reason:`keyAuthorization currency mismatch`});if(e.limit!==BigInt(t.amount))throw new Y({reason:`keyAuthorization amount mismatch`});if(e.period!==iN(t))throw new Y({reason:`keyAuthorization period mismatch`})}function _N(e,t){if(!e||e.length!==1)throw new Y({reason:`keyAuthorization must contain a recipient-scoped transferWithMemo call`});let n=yN(t.currency,`currency`),r=yN(t.recipient,`recipient`),i=new Set;for(let t of e){if(!fe(t.address,n))throw new Y({reason:`keyAuthorization call target mismatch`});let e=bN(t.selector);if(e!==`0xa9059cbb`&&e!==`0x95777d59`)throw new Y({reason:`keyAuthorization selector not allowed`});if(i.has(e))throw new Y({reason:`keyAuthorization duplicate selector`});if(i.add(e),t.recipients?.length!==1||!fe(t.recipients[0],r))throw new Y({reason:`keyAuthorization recipient mismatch`})}if(!i.has(`0x95777d59`))throw new Y({reason:`keyAuthorization must allow transferWithMemo`})}function vN(e,t){let n=Ue.getSignPayload(e);try{let e=We.extractAddress({payload:n,signature:t});if(!We.verify(t,{address:e,payload:n}))throw new Y({reason:`keyAuthorization signature is invalid`});return e}catch(e){throw e instanceof Y?e:new Y({reason:`keyAuthorization signature is invalid`})}}function yN(e,t){if(!de(e))throw new Y({reason:`${t} must be an address`});return e.toLowerCase()}function bN(e){return typeof e==`string`?e.toLowerCase():``}var xN,SN,CN,wN=F((()=>{bS(),xN=`0x95777d59`,SN=(1n<<64n)-1n,CN={dev_second:1n,day:86400n,week:604800n}}));function TN(e={}){let t=mA({chain:ve,getClient:e.getClient,rpcUrl:cO}),n=lA({account:e.account});return KT(cE,{context:ON,async createCredential({challenge:r,context:i}){let a=r.request.methodDetails?.chainId??iO.testnet,o=await t({chainId:a}),s=n(o,i),c=i?.accessKey??e.accessKey??r.request.methodDetails?.accessKey;if(!c)throw Error("No `accessKey` provided. The subscription challenge must include `accessKey`, or the client must pass one to parameters/context.");DN(r.request),await e.validateRequest?.(r.request);let l=await EN(o,{accessKey:c,account:s,challengeId:r.id,chainId:a,request:r.request}),u=lN({accessKey:c,challengeId:r.id,chainId:a,payload:{signature:Ue.serialize(l),type:`keyAuthorization`},request:r.request});if(!fe(u.source.address,s.address))throw Error(`keyAuthorization signer does not match the selected account`);return ZS({challenge:r,payload:{signature:Ue.serialize(l),type:`keyAuthorization`},source:`did:pkh:eip155:${a}:${s.address.toLowerCase()}`})}})}async function EN(e,t){let{accessKey:n,account:r,challengeId:i,chainId:a,request:o}=t,s=await cN({accessKey:n,account:r,challengeId:i,chainId:a,request:o});if(s)return s;let c=await e.request({method:`wallet_authorizeAccessKey`,params:[{address:n.accessKeyAddress,expiry:rN(nN(o.subscriptionExpires)),keyType:n.keyType,limits:[{token:o.currency,limit:re.fromNumber(BigInt(o.amount)),period:iN(o)}],scopes:oN(o),witness:sN(i)}]});return Ue.fromRpc(c.keyAuthorization)}function DN(e){iN(e),rN(nN(e.subscriptionExpires))}var ON,kN=F((()=>{eC(),qT(),uA(),vA(),Xx(),lO(),lE(),wN(),ON=J.object({accessKey:J.optional(J.custom()),account:J.optional(J.custom())})}));function AN(e={}){let t=e.expectedChainId!==void 0&&(e.allowedChainIds===void 0||e.allowedChainIds.includes(e.expectedChainId)),n=e.expectedChainId===void 0?e:{...e,allowedChainIds:t?[e.expectedChainId]:[]};return[ej(e),jN(n)]}var jN,MN=F((()=>{VM(),tN(),nj(),kN(),jN=Object.assign(zM,{manager:eN}),(function(e){e.charge=ej,e.common=AN,e.session=jN,e.subscription=TN})(AN||={})})),NN=F((()=>{nj(),MN(),kN(),VM(),tN()})),PN=Ze({orderTempoChargeChallengesByBalance:()=>IN,readTempoKeystore:()=>nP,resolveTempoAccount:()=>rP,tempo:()=>LN});async function FN(e){process.stdout.write(Buffer.from(await e.arrayBuffer()))}async function IN(e,t){let n=[],r=[];for(let[t,i]of e.entries())WN(i)&&(n.push(t),r.push(i));if(r.length<2)return[...e];let i=await GN(t).catch(()=>void 0);if(!i)return[...e];let a=await Promise.all(r.map(async(e,t)=>({challenge:e,index:t,score:await KN(e,i)})));a.sort((e,t)=>dP.indexOf(e.score)-dP.indexOf(t.score)||e.index-t.index);let o=[...e];for(let[e,t]of n.entries())o[t]=a[e].challenge;return o}function LN(){let e;return Yk({method:`tempo`,supports(e){return e.method===`tempo`&&[`charge`,`session`].includes(e.intent)},async setup({challenge:t,options:n,methodOpts:r}){let i=WO(n.account),a=t.request,o=a.currency,s=UN(r),c=XN({autoSwap:s.autoSwap??n.autoSwap,payWith:s.payWith??n.payWith,slippage:s.slippage??n.slippage,tokenIn:s.tokenIn}),l=o??``,u=a.decimals??6,d,f,p,m=!1,h=process.env.MPPX_PRIVATE_KEY?.trim()||(yO(i)?void 0:await GO(i).get());if(!h&&yO(i)&&iP()){m=!0;let e=rP(i);if(e){let r=CO(n.rpcUrl,{network:n.network});p=j({chain:await TO({network:n.network,rpcUrl:r}),transport:ue(r)}),JN({challenge:t,clientChainId:p.chain?.id}),d=p.chain?.blockExplorers?.default?.url;let i=o?await kO(p,o,e.wallet_address).catch(()=>void 0):void 0;l=i?.symbol??o??``,u=i?.decimals??a.decimals??6}}else if(h)f=_e(h);else{let e=oP();if(e){let t=await GO(e).get();t&&(f=_e(t))}if(!f)throw n.account?new I({code:`ACCOUNT_NOT_FOUND`,message:`Account "${i}" not found.`,exitCode:69}):new I({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}if(!m&&f){let e=CO(n.rpcUrl,{network:n.network});p=j({chain:await TO({network:n.network,rpcUrl:e}),transport:ue(e)}),JN({challenge:t,clientChainId:p.chain?.id}),d=p.chain?.blockExplorers?.default?.url;let r=o?await kO(p,o,f.address).catch(()=>void 0):void 0;l=r?.symbol??o??``,u=r?.decimals??a.decimals??6}if(m)return{tokenSymbol:l,tokenDecimals:u,explorerUrl:d,methods:[],async createCredential(e){let t=e.headers.get(`www-authenticate`);if(!t)throw Error(`No WWW-Authenticate header in 402 response.`);return aP(t)}};if(!f||!p)throw new I({code:`ACCOUNT_NOT_FOUND`,message:`Tempo requires a configured account.`,exitCode:69});let g=AN({account:f,...s.allowCustomEscrow===void 0?{}:{allowCustomEscrow:s.allowCustomEscrow},getClient:()=>p,...c===void 0?{}:{autoSwap:c},maxDeposit:(()=>{if(t.intent!==`session`)return;let e=t.request.suggestedDeposit,n=(s.deposit===void 0?void 0:String(s.deposit))??e??(OO(p.chain)?`10`:void 0);if(!n)throw new I({code:`MISSING_DEPOSIT`,message:`Session payment requires a deposit. Use -M deposit=<amount> or connect to testnet.`,exitCode:2});return n})()}),_=(()=>{if(!s.channel)return;let e=s.channel,t=QN(e);return{channelId:e,...t!==void 0&&{cumulativeAmountRaw:t.toString()}}})();return e={descriptor:void 0,async signVoucher({channelId:n,cumulativeAmount:r,escrowContract:i,chainId:a,action:o=`voucher`}){let s=e?.descriptor;if(!s)throw Error(`session descriptor not available`);let c={channelId:n,cumulativeAmount:r},l=await yj(p,f,c,i,a);return ZS({challenge:t,payload:{action:o,channelId:n,...o===`close`?{closeSignature:await bj(p,f,c,i,a)}:{},descriptor:s,cumulativeAmount:r.toString(),signature:l},source:`did:pkh:eip155:${a}:${f.address}`})},source:`did:pkh:eip155:${p.chain.id}:${f.address}`},{tokenSymbol:l,tokenDecimals:u,explorerUrl:d,methods:[...g],credentialContext:_}},prepareCredentialRequest({challenge:e,headers:t}){e.intent===`session`&&(t.Accept=`text/event-stream`)},async handleResponse(t){if(t.challenge.intent!==`session`||!e)return!1;let{challenge:n,credential:r,response:i,fetchUrl:a,fetchInit:o,verbose:s}=t,{silent:c,confirmEnabled:l,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,shownKeys:p}=t,m=c?e=>{}:e=>process.stderr.write(e),h=qS(r),g=n.request,_=g.methodDetails,v=h.payload.channelId,y=_?.escrowContract??_?.escrow??`0x4d50500000000000000000000000000000000000`,b=_?.chainId??0,x=BigInt(g.amount),S=`cumulativeAmount`in h.payload&&h.payload.cumulativeAmount?BigInt(h.payload.cumulativeAmount):0n;if(`descriptor`in h.payload&&(e.descriptor=h.payload.descriptor),s>=1){if(h.payload.action===`open`){let e=g.suggestedDeposit,t=e?` ${X.dim(`(deposit ${e} ${u})`)}`:``;m(`${l?``:`
|
|
@@ -240,9 +240,9 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
|
|
|
240
240
|
`);else try{let t=JSON.parse(e);u(t.token??t.choices?.[0]?.delta?.content??e)}catch{u(e)}o=``}}};for(;;){let{done:e,value:t}=await r.read();if(e)break;a+=i.decode(t,{stream:!0});let n=a.split(`
|
|
241
241
|
`);a=n.pop(),await d(n)}a.trim()&&await d([a]),t.channelId&&t.escrowContract&&t.chainId&&await VN({channelId:t.channelId,cumulativeAmount:n,escrowContract:t.escrowContract,chainId:t.chainId,fetchUrl:t.fetchUrl,fetchInit:t.fetchInit,session:t.session,info:t.info,verbose:t.verbose,tokenSymbol:t.tokenSymbol,tokenDecimals:t.tokenDecimals,explorerUrl:t.explorerUrl,confirmEnabled:!1})}async function VN(e){let t=await e.session.signVoucher({channelId:e.channelId,cumulativeAmount:e.cumulativeAmount,escrowContract:e.escrowContract,chainId:e.chainId,action:`close`}),n=await globalThis.fetch(e.fetchUrl,{...e.fetchInit,headers:{...Sw(e.fetchInit.headers),Authorization:t}});if(n.ok){if(eP(e.channelId),e.verbose>=1){let t=n.headers.get(q.paymentReceipt),r;if(t)try{let e=JSON.parse(k.toString(t));typeof e.txHash==`string`&&(r=e.txHash)}catch{}let i=r&&e.explorerUrl?` ${X.dim(gO(`${e.explorerUrl}/tx/${r}`,r))}`:``;e.info(`${X.dim(`Channel closed.`)} ${X.dim(`Spent ${SO(e.cumulativeAmount,e.tokenSymbol,e.tokenDecimals)}.`)}${i}\n`)}}else{let t=await n.text().catch(()=>``);e.info(`\n${X.dim(X.yellow(`Channel close failed`))} ${X.dim(`(${n.status})`)}\n`),e.info(`${X.dim(` channelId: ${e.channelId}`)}\n${X.dim(` cumulativeAmount: ${e.cumulativeAmount}`)}\n${X.dim(` escrowContract: ${e.escrowContract}`)}\n${X.dim(` chainId: ${e.chainId}`)}\n${X.dim(` response: ${t||`(empty)`}`)}\n`)}}function HN(e=100){return!process.stdin.isTTY||!process.stdout.isTTY?Promise.resolve(void 0):new Promise(t=>{let n=process.stdin.isRaw,r=``,i=()=>{clearTimeout(a),process.stdin.removeListener(`data`,o),process.stdin.isTTY&&process.stdin.setRawMode(n??!1),process.stdin.pause()},a=setTimeout(()=>{i(),t(void 0)},e),o=e=>{r+=e.toString();let n=r.match(/\x1b\]11;rgb:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);if(!n)return;i();let a=e=>Number.parseInt(e.slice(0,2),16);t({r:a(n[1]),g:a(n[2]),b:a(n[3])})};process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on(`data`,o),process.stdout.write(`\x1B]11;?\x07`)})}function UN(e){return qN(lP,e,uP)}function WN(e){return e.method===`tempo`&&e.intent===`charge`}async function GN(e){let t=WO(e.options.account),n=process.env.MPPX_PRIVATE_KEY?.trim()||(yO(t)?void 0:await GO(t).get()),r;if(n)r=_e(n).address;else if(yO(t)&&iP())r=rP(t)?.wallet_address;else{let e=oP();if(e){let t=await GO(e).get();t&&(r=_e(t).address)}}if(!r)return;let i=CO(e.options.rpcUrl,{network:e.options.network}),a=j({chain:await TO({network:e.options.network,rpcUrl:i}),transport:ue(i)});return{account:r,client:a}}async function KN(e,t){let n=e.request,r=n.currency,i=n.amount;if(typeof r!=`string`||typeof i!=`string`)return`unsupported`;let a=n.methodDetails?.chainId;if(a&&t.client.chain?.id&&a!==t.client.chain.id)return`unsupported`;let o=BigInt(i);if(o===0n)return`payable`;let s=await Fe.token.getBalance(t.client,{account:t.account,token:r}).then(e=>e.amount).catch(()=>void 0);return s===void 0?`unknownBalance`:s>=o?`payable`:`insufficientBalance`}function qN(e,t,n){if(t&&typeof t==`object`&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!n.includes(e));if(e.length)throw Error(`Unsupported CLI method option(s): ${e.join(`, `)}`)}let r=e.safeParse(t??{});if(r.success)return r.data;let i=r.error.issues.map(e=>`${e.path.length?e.path.join(`.`):`options`}: ${e.message}`).join(`, `);throw Error(`Invalid CLI options (${i})`)}function JN(e){let t=e.challenge.request.methodDetails?.chainId;if(!t||!e.clientChainId||t===e.clientChainId)return;let n=t===4217?` Use --network mainnet or --rpc-url https://rpc.tempo.xyz.`:t===42431?` Use --network testnet or --rpc-url https://rpc.moderato.tempo.xyz.`:``;throw new I({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${t}, but RPC is chainId ${e.clientChainId}.${n}`,exitCode:2})}function YN(e){if(e)return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function XN(e){let t=YN(e.tokenIn)??YN(e.payWith);if(!(!e.autoSwap&&!t&&e.slippage===void 0)){if(e.autoSwap===!1&&!t&&e.slippage===void 0)return!1;if(e.slippage!==void 0&&(!Number.isFinite(e.slippage)||e.slippage<0))throw Error(`Invalid CLI options (slippage: expected a non-negative number)`);return{...t?{tokenIn:t}:{},...e.slippage===void 0?{}:{slippage:e.slippage}}}}function ZN(){return c.join(process.env.XDG_CONFIG_HOME||c.join(b.homedir(),`.config`),`mppx`,`channels`)}function QN(e){try{let n=t.readFileSync(c.join(ZN(),e),`utf-8`).trim();return n?BigInt(n):void 0}catch{return}}function $N(e,n){let r=ZN();t.mkdirSync(r,{recursive:!0}),t.writeFileSync(c.join(r,e),n.toString(),`utf-8`)}function eP(e){try{t.unlinkSync(c.join(ZN(),e))}catch{}}function tP(){return b.platform()===`darwin`?c.join(b.homedir(),`Library`,`Application Support`,`tempo`,`wallet`,`keys.toml`):c.join(process.env.XDG_DATA_HOME||c.join(b.homedir(),`.local`,`share`),`tempo`,`wallet`,`keys.toml`)}function nP(){try{let e=t.readFileSync(tP(),`utf-8`),n=[],r;for(let t of e.split(`
|
|
242
242
|
`)){let e=t.trim();if(e===`[[keys]]`){r?.wallet_address&&n.push(r),r={wallet_type:`local`,wallet_address:``,chain_id:0};continue}if(!r)continue;let i=e.match(/^(\w+)\s*=\s*"?([^"]*)"?$/);if(!i)continue;let[,a,o]=i;a===`wallet_type`?r.wallet_type=o:a===`wallet_address`?r.wallet_address=o:a===`chain_id`&&(r.chain_id=Number.parseInt(o,10))}return r?.wallet_address&&n.push(r),n}catch{return[]}}function rP(e){let t=nP();if(t.length===0)return;let n=e.slice(6);if(n==="default"||n===``)return t[0];let r=Number.parseInt(n,10);if(!Number.isNaN(r)&&r>=0&&r<t.length)return t[r]}function iP(){if(fP!==void 0)return fP;try{m.execFileSync(`which`,[`tempo`],{stdio:`ignore`}),fP=!0}catch{fP=!1}return fP}async function aP(e){return new Promise((t,n)=>{m.execFile(`tempo`,[`mpp`,`sign`,`--challenge`,e],(e,r,i)=>{if(e){let t=i?.trim()||e.message;n(Error(`tempo mpp sign failed: ${t}`));return}let a=r.trim();if(!a){n(Error(`tempo mpp sign returned empty output`));return}t(a)})})}function oP(){let e=UO();if(yO(e.get())&&!iP()&&b.platform()===`darwin`)try{let t=m.execFileSync(`security`,[`dump-keychain`],{encoding:`utf-8`}),n=[];for(let e of t.split(`keychain:`)){let t=e.match(/"svce"<blob>="([^"]*)"/),r=e.match(/"acct"<blob>="([^"]*)"/);t?.[1]===sP&&r?.[1]&&n.push(r[1])}if(n.length>0)return e.set(n[0]),n[0]}catch{}}var sP,cP,lP,uP,dP,fP,pP=F((()=>{Dx(),oT(),Px(),eC(),NN(),ME(),Ej(),ZO(),LO(),Xk(),sP=`mppx`,cP=p.union([p.boolean(),p.literal(`true`).transform(()=>!0),p.literal(`false`).transform(()=>!1)]),lP=p.object({allowCustomEscrow:p.optional(cP),autoSwap:p.optional(cP),channel:p.optional(p.coerce.string()),deposit:p.optional(p.union([p.string(),p.number()])),payWith:p.optional(p.string()),slippage:p.optional(p.coerce.number()),tokenIn:p.optional(p.string())}),uP=[`allowCustomEscrow`,`autoSwap`,`channel`,`deposit`,`payWith`,`slippage`,`tokenIn`],dP=[`payable`,`unknownBalance`,`insufficientBalance`,`unsupported`]}));ES(),ZO(),Xk();const mP=[...Object.entries(rk),...Object.entries(ik),...Object.entries(ak),...Object.entries(ok)];function hP(){return Yk({method:`evm`,supports:gP,async setup({challenge:e,options:t}){let n=e.request,r=n.network?_P(pk(n.network)):void 0,i=n.network&&n.asset?mP.find(([,e])=>dk(e,n.asset,n.network)):void 0,a=n.extra?.name,o=n.extra?.version,s=n.asset&&n.network&&typeof a==`string`&&typeof o==`string`?tk({address:n.asset,decimals:i?.[1].decimals??6,network:n.network,transfer:{name:a,type:`eip3009`,version:o}}):void 0,c=await JO(t.account);return{explorerUrl:r?.blockExplorers?.default?.url,methods:[...Jk({account:c,...s&&{currencies:[s]}})],tokenDecimals:i?.[1].decimals??6,tokenSymbol:i?.[0]??``}}})}function gP(e){if(!wS(e))return!1;let t=e.request,n=t.extra,r=n?.assetTransferMethod;return t.scheme===`exact`&&typeof t.asset==`string`&&typeof t.network==`string`&&typeof n?.name==`string`&&typeof n?.version==`string`&&(r===void 0||r===`eip3009`)}function _P(e){return Object.values(Be).find(t=>t.id===e)}gS(),KS(),pP();const vP=[LN(),oA(),Zk(),hP()];async function yP(e,t,n){let r=n;for(let n of t??[]){let t=await n.preparePayment?.({challenge:e,...r===void 0?{}:{credentialContext:r}});t&&`credentialContext`in t&&(r=t.credentialContext)}return r}function bP(e,t){let n=t?.plugins?.find(t=>wP(t,e));if(n)return{plugin:n};let r=CP(t)?.filter(t=>t.name===e.method&&t.intent===e.intent),i=r?.find(t=>t.canHandleChallenge?.({challenge:e})??!0);if(i)return{method:i};if(r?.length)return{};let a=vP.find(t=>wP(t,e));return a?{plugin:a}:{}}function xP(e,t){let n=CP(t);if(n?.length){let r=jS(e,n,OS(n,t?.paymentPreferences).entries);if(r){let e=t?.plugins?.find(e=>wP(e,r.challenge));return{challenge:r.challenge,...e?{plugin:e}:{method:r.method}}}return}for(let n of e){let e=bP(n,t);if(e.plugin||e.method)return{challenge:n,...e}}}function SP(e){let t=CP(e);if(t?.length)return OS(t,e?.paymentPreferences).header}function CP(e){return Array.isArray(e?.methods)?e.methods.flat():void 0}function wP(e,t){return e.supports?e.supports(t):e.method===t.method}async function TP(e){let t=EP(e);if(!t)return;let n=await import(t);return{config:n.default??n,path:t}}function EP(e){if(e){let n=c.resolve(e);return t.existsSync(n)?n:void 0}let n=process.env.MPPX_CONFIG?.trim();if(n){let e=c.resolve(n);return t.existsSync(e)?e:void 0}}function DP(e,t){function n(t){let n={...t.request};if(t.method===`tempo`&&t.intent===`session`){let e={...n.methodDetails};delete e.sessionSnapshot,Object.keys(e).length?n.methodDetails=e:delete n.methodDetails}return Qx({...t,request:n,id:e.id,expires:e.expires})}if(n(t)!==n(e))throw Error(`Payment request changed on retry. Run the command again to approve the new payment.`)}pP(),gS(),Vj(),GM(),tN(),rO();function OP(e){return e??globalThis.fetch.bind(globalThis)}function kP(e,t){let n=e.request.methodDetails?.chainId;if(n!==void 0&&n!==t.chainId)throw Error(`Close challenge changed the session chain.`);if(typeof e.request.recipient!=`string`||e.request.recipient.toLowerCase()!==t.descriptor.payee.toLowerCase())throw Error(`Close challenge changed the session payee.`);if(typeof e.request.currency!=`string`||e.request.currency.toLowerCase()!==t.descriptor.token.toLowerCase())throw Error(`Close challenge changed the session token.`);if(Pj(e,t.escrow).toLowerCase()!==t.escrow.toLowerCase())throw Error(`Close challenge changed the session escrow.`);let r=wD(e);if(r&&r.channelId.toLowerCase()!==t.channelId.toLowerCase())throw Error(`Close challenge changed the session channel.`)}async function AP(e){kP(e.challenge,e.channel);let t=OP(e.fetch),n,r=async(r,i)=>{n&&=(await e.onChallenge?.(n),void 0);let a=await t(r,i);if(a.status!==402)return a;let o=sS(a).find(SD);if(!o)throw Error(`Refreshed close response did not include tempo/session.`);return kP(o,e.channel),n=o,a},i=eN({...e.manager,bootstrap:!1,escrow:e.channel.escrow,fetch:r});UM(i).rehydrate(e);let a=await i.close();if(!a)throw Error(`Session close response did not include a payment receipt.`);return{manager:i,receipt:a}}gS(),Vj(),qj(),rO(),cj(),Xx();var jP=class extends Error{name=`SessionStateError`;code=`SESSION_STATE_INVALID`;file;constructor(e,t={}){super(e,t.cause===void 0?void 0:{cause:t.cause}),this.file=t.file}},MP=class extends Error{name=`SessionBusyError`;code=`SESSION_BUSY`;exitCode=75;scope;owner;constructor(e,t){super(`Session scope is busy in process ${t.pid} on ${t.hostname}.`),this.scope=e,this.owner=t}};const NP=J.object({channelId:Kx(),cumulativeAmount:J.string(),deposit:J.string(),descriptor:J.object({payer:Gx(),payee:Gx(),operator:Gx(),token:Gx(),salt:Kx(),authorizedSigner:Gx(),expiringNonceHash:Kx()}),escrow:Gx(),chainId:J.number(),opened:J.boolean()}),PP=J.object({name:J.optional(J.string()),address:Gx()}),FP=J.object({method:J.literal(`tempo`),intent:J.literal(`session`),status:J.literal(`success`),timestamp:J.string(),reference:J.string(),challengeId:J.string(),channelId:Kx(),acceptedCumulative:J.string(),spent:J.string(),units:J.optional(J.number()),txHash:J.optional(Kx())}),IP=J.object({version:J.literal(1),method:J.literal(`tempo`),intent:J.literal(`session`),status:J.enum([`opening`,`open`,`closing`,`stale`]),channel:NP,account:PP,endpoint:J.string(),challenge:hS,receipt:J.optional(FP),spent:J.string(),units:J.number(),createdAt:J.string(),updatedAt:J.string()}),LP=J.object({version:J.literal(1),channelId:Kx()}),RP=J.object({version:J.literal(1),scope:J.string(),hostname:J.string(),pid:J.number(),token:J.string(),createdAt:J.string()});function zP(e,t,n,r){let i=e.safeParse(t);if(!i.success)throw Z(n,r,i.error);return i.data}function BP(e){let t=XP(e);return[t.payer,t.payee,t.token,t.escrow,t.chainId].join(`:`)}function VP(e){return{payer:e.descriptor.payer,payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId}}function HP(e={}){let t=e.stateRoot??WP(),n={root:t,channels:c.join(t,`channels`),locks:c.join(t,`locks`),preferred:c.join(t,`preferred`)},r=e.hostname??b.hostname(),i=e.pid??process.pid,a=e.now??(()=>new Date),o=e.isProcessAlive??SF;async function s(){for(let e of[n.root,n.channels,n.locks,n.preferred])await C.mkdir(e,{recursive:!0,mode:448}),await C.chmod(e,448)}async function l(e){let t=JP(e),r=GP(n,t),i=await pF(r);if(i===void 0)return;let a=iF(i,r);if(a.channel.channelId.toLowerCase()!==t)throw Z(r,`Session filename does not match its channel ID.`);return aF(a)}async function u(){let e;try{e=await C.readdir(n.channels,{withFileTypes:!0})}catch(e){if(wF(e,`ENOENT`))return[];throw Z(n.channels,`Unable to list managed sessions.`,e)}let t=[];for(let n of e){if(!n.isFile()||n.name.includes(`.tmp-`)||!n.name.endsWith(`.json`))continue;let e=n.name.slice(0,-5);JP(e);let r=await l(e);r&&t.push(r)}return t.sort((e,t)=>e.createdAt.localeCompare(t.createdAt))}async function d(e){await s();let t=eF(e.channel),r=JP(t.channelId),i=GP(n,r),o=await pF(i),c=o===void 0?void 0:iF(o,i);c&&oF(c,e,i);let l=nF(e.challenge,i);cF(l,t,i);let u=e.receipt?rF(e.receipt,t.channelId,i):void 0,d=c?Kj(c.channel):void 0,f=fF(t.cumulativeAmount,d?.cumulativeAmount??0n),p=fF(e.spent??0n,u?BigInt(u.spent):0n,c?BigInt(c.spent):0n);if(p>f)throw Z(i,`Session spend exceeds the locally authorized cumulative amount.`);let m=tF(Gj({...t,cumulativeAmount:f}),i),h=dF(c?.updatedAt,a(),i),g=uF(c?.receipt,u),_=$P(e.account,i),v=iF({version:1,method:`tempo`,intent:`session`,status:e.status,channel:m,account:{..._.name===void 0?c?.account.name===void 0?{}:{name:c.account.name}:{name:_.name},address:_.address},endpoint:QP(e.endpoint,i),challenge:l,...g!==void 0&&{receipt:g},spent:p.toString(),units:Math.max(c?.units??0,e.units??0,u?.units??0),createdAt:c?.createdAt??h,updatedAt:h},i);return await mF(i,v),aF(v)}async function f(e){let t=qP(n,e),r=await pF(t);if(r===void 0)return;let{channelId:i}=zP(LP,r,t,`Preferred session is invalid.`),a=await l(i);if(!a)throw Z(t,`Preferred session ${i} does not exist.`);return lF(a.channel,e,t),i}async function p(e,t){let r=JP(t),i=await l(r),a=qP(n,e);if(!i)throw Z(a,`Session ${r} does not exist.`);lF(i.channel,e,a),await mF(a,{version:1,channelId:r})}async function m(e,t){let r=qP(n,e),i=t===void 0?void 0:JP(t),a=await pF(r);if(a===void 0)return;let o=zP(LP,a,r,`Preferred session is invalid.`).channelId;i&&o.toLowerCase()!==i||await bF(r,`Unable to clear preferred session.`)}async function h(e){let t=JP(e),r=await l(t);r&&(await m(VP(r.channel),t),await bF(GP(n,t),`Unable to remove session.`))}async function g(e){await s();let t=KP(n,e);for(let n=0;n<3;n++){let n={version:1,scope:e,hostname:r,pid:i,token:_(),createdAt:a().toISOString()};try{if(await hF(t,n),await vF(_F(t))){await yF(t,n);continue}return{async release(){await yF(t,n)}}}catch(e){if(!wF(e,`EEXIST`))throw e}let s=await pF(t);if(s===void 0)continue;let c=zP(RP,s,t,`Session lock is invalid.`);if(c.scope!==e)throw Z(t,`Session lock scope is invalid.`);if(c.hostname!==r||o(c.pid))throw new MP(e,c);await gF(t,c)}let c=await pF(t);throw c===void 0?Z(t,`Unable to acquire session lock.`):new MP(e,zP(RP,c,t,`Session lock is invalid.`))}async function v(e){return g(BP(e))}return{root:t,get:l,list:u,upsert:d,remove:h,getPreferred:f,setPreferred:p,clearPreferred:m,acquire:v}}function UP(e,t){let n=ZP(t.scope),r=t.selection===`auto`||t.selection===`new`?void 0:JP(t.selection);function i(e){if(e.toLowerCase()!==n)throw new jP(`Session manager requested an unexpected payment scope.`)}async function a(n=!0){if(t.selection===`new`&&!r)return;let i=r??await e.getPreferred(t.scope);if(!i)return;let a=await e.get(i);if(!a)throw new jP(`Session ${i} does not exist.`);if(lF(a.channel,t.scope),!(n&&(a.status!==`open`||!a.channel.opened)))return r=i,a}return{async get(e){return i(e),(await a())?.channel},async set(n){if(i(Uj(n)),lF(n,t.scope),r&&r.toLowerCase()!==n.channelId.toLowerCase())throw new jP(`Session manager selected ${r}, but attempted to store ${n.channelId}.`);r||t.onNewChannel?.(n);let a=await e.upsert({...t.context(),channel:n});r=a.channel.channelId,await e.setPreferred(t.scope,a.channel.channelId)},async delete(n){i(n);let o=await a(!1);if(!o)return;let s=t.context();await e.upsert({...o,...s,status:s.status===`closing`?`closing`:`stale`,channel:o.channel,spent:s.spent??o.spent,units:s.units??o.units}),s.status!==`closing`&&await e.clearPreferred(t.scope,o.channel.channelId),r=void 0}}}function WP(){let e=process.env.XDG_STATE_HOME||c.join(b.homedir(),`.local`,`state`);return c.join(e,`mppx`,`sessions`,`v1`)}function GP(e,t){return c.join(e.channels,`${t}.json`)}function KP(e,t){let n=g(`sha256`).update(t).digest(`hex`);return c.join(e.locks,`${n}.lock`)}function qP(e,t){let n=g(`sha256`).update(BP(t)).digest(`hex`);return c.join(e.preferred,`${n}.json`)}function JP(e){return zP(Kx(),e,void 0,`Invalid session channel ID: ${e}.`).toLowerCase()}function YP(e,t,n){return zP(Gx(),e,n,`Invalid ${t}.`).toLowerCase()}function XP(e){if(!Number.isSafeInteger(e.chainId)||e.chainId<0)throw new jP(`Invalid session chain ID.`);return{payer:YP(e.payer,`session payer`),payee:YP(e.payee,`session payee`),token:YP(e.token,`session token`),escrow:YP(e.escrow,`session escrow`),chainId:e.chainId}}function ZP(e){let t=XP(e);return[t.payee,t.token,t.escrow,t.chainId].join(`:`)}function QP(e,t){if(typeof e!=`string`)throw Z(t,`Session endpoint is invalid.`);let n;try{n=new URL(e)}catch(e){throw Z(t,`Session endpoint is invalid.`,e)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw Z(t,`Session endpoint must use HTTP or HTTPS.`);if(n.username||n.password)throw Z(t,`Session endpoint must not contain credentials.`);let r=e.indexOf(`#`);return r===-1?e:e.slice(0,r)}function $P(e,t){return zP(PP,e,t,`Session account is invalid.`)}function eF(e){return Kj(tF(Gj(e)))}function tF(e,t){return zP(NP,e,t,`Stored session channel is invalid.`)}function nF(e,t){let n=hS.safeParse(e);if(!n.success||!SD(n.data))throw Z(t,`Stored session challenge is invalid.`);return n.data}function rF(e,t,n){let r=zP(FP,e,n,`Stored session receipt is invalid.`);if(r.channelId!==t.toLowerCase())throw Z(n,`Stored session receipt has a different channel ID.`);if(r.reference.toLowerCase()!==t.toLowerCase())throw Z(n,`Stored session receipt has a different reference.`);if(BigInt(r.spent)>BigInt(r.acceptedCumulative))throw Z(n,`Stored session receipt spend exceeds its accepted amount.`);return r}function iF(e,t){let n=zP(IP,e,t,`Stored session is invalid.`),{receipt:r,...i}=n,a=n.channel,o=n.account;if(o.address.toLowerCase()!==a.descriptor.payer.toLowerCase())throw Z(t,`Stored session account does not match the channel payer.`);let s=r?rF(r,a.channelId,t):void 0,c=n.spent,l=BigInt(a.cumulativeAmount);if(BigInt(c)>l)throw Z(t,`Stored session spend exceeds its cumulative authorization.`);if(s&&BigInt(s.acceptedCumulative)>l)throw Z(t,`Stored receipt exceeds the cumulative authorization.`);if(Date.parse(n.updatedAt)<Date.parse(n.createdAt))throw Z(t,`Stored session timestamps are not monotonic.`);let u=QP(n.endpoint,t);if(u!==n.endpoint)throw Z(t,`Stored session endpoint contains a fragment.`);let d=nF(n.challenge,t);return cF(d,Kj(a),t),{...i,account:o,channel:a,endpoint:u,challenge:d,...s&&{receipt:s}}}function aF(e){return{version:1,status:e.status,channel:Kj(e.channel),account:e.account,endpoint:e.endpoint,challenge:e.challenge,...e.receipt&&{receipt:e.receipt},spent:BigInt(e.spent),units:e.units,createdAt:e.createdAt,updatedAt:e.updatedAt}}function oF(e,t,n){let r=eF(t.channel),i=$P(t.account,n),a=Kj(e.channel);if(JSON.stringify(sF(r))!==JSON.stringify(sF(a)))throw Z(n,`Session update changed immutable channel identity.`);if(i.address.toLowerCase()!==e.account.address.toLowerCase())throw Z(n,`Session update changed the payer account.`)}function sF(e){return{channelId:e.channelId.toLowerCase(),descriptor:Object.fromEntries(Object.entries(e.descriptor).map(([e,t])=>[e,typeof t==`string`?t.toLowerCase():t])),escrow:e.escrow.toLowerCase(),chainId:e.chainId}}function cF(e,t,n){if(ij({...t.descriptor,chainId:t.chainId,escrow:t.escrow}).toLowerCase()!==t.channelId.toLowerCase())throw Z(n,`Session channel ID does not match its descriptor.`);let r=YP(e.request.recipient,`challenge recipient`,n),i=YP(e.request.currency,`challenge currency`,n);if(r!==t.descriptor.payee.toLowerCase())throw Z(n,`Session challenge payee does not match the channel.`);if(i!==t.descriptor.token.toLowerCase())throw Z(n,`Session challenge token does not match the channel.`);if(Pj(e,t.escrow).toLowerCase()!==t.escrow.toLowerCase())throw Z(n,`Session challenge escrow does not match the channel.`);if(CF(e.request.methodDetails)){let r=e.request.methodDetails;if(r.chainId!==void 0&&r.chainId!==t.chainId)throw Z(n,`Session challenge chain does not match the channel.`)}}function lF(e,t,n){let r=XP(t);if(e.descriptor.payer.toLowerCase()!==r.payer||e.descriptor.payee.toLowerCase()!==r.payee||e.descriptor.token.toLowerCase()!==r.token||e.escrow.toLowerCase()!==r.escrow||e.chainId!==r.chainId)throw Z(n,`Session channel does not match the selected payment scope.`)}function uF(e,t){return e?t&&Date.parse(t.timestamp)>=Date.parse(e.timestamp)?t:e:t}function dF(e,t,n){if(!Number.isFinite(t.getTime()))throw Z(n,`Session clock is invalid.`);let r=t.toISOString();return!e||Date.parse(r)>=Date.parse(e)?r:e}function fF(...e){return e.reduce((e,t)=>t>e?t:e,0n)}async function pF(e){let t;try{t=await C.readFile(e,`utf8`)}catch(t){if(wF(t,`ENOENT`))return;throw Z(e,`Unable to read session state.`,t)}try{return JSON.parse(t)}catch(t){throw Z(e,`Session state contains invalid JSON.`,t)}}async function mF(e,t){await C.mkdir(c.dirname(e),{recursive:!0,mode:448}),await C.chmod(c.dirname(e),448);let n=`${e}.tmp-${process.pid}-${_()}`,r;try{r=await C.open(n,`wx`,384),await r.writeFile(`${JSON.stringify(t,null,2)}\n`,`utf8`),await r.sync(),await r.close(),r=void 0,await C.rename(n,e),await C.chmod(e,384),await xF(c.dirname(e))}catch(t){throw await r?.close().catch(()=>void 0),await C.unlink(n).catch(()=>void 0),t instanceof jP?t:Z(e,`Unable to write session state.`,t)}}async function hF(e,t){let n;try{n=await C.open(e,`wx`,384),await n.writeFile(`${JSON.stringify(t)}\n`,`utf8`),await n.sync(),await n.close(),n=void 0,await xF(c.dirname(e))}catch(t){throw await n?.close().catch(()=>void 0),n&&await C.unlink(e).catch(()=>void 0),t}}async function gF(e,t){let n=_F(e);try{await C.link(e,n)}catch(t){if(wF(t,`EEXIST`)||wF(t,`ENOENT`))return;throw Z(e,`Unable to claim dead lock.`,t)}try{let r=await pF(n);if(r===void 0||zP(RP,r,n,`Session lock is invalid.`).token!==t.token)return;await bF(e,`Unable to reclaim dead lock.`)}finally{await bF(n,`Unable to release dead lock claim.`)}}function _F(e){return`${e}.reclaim`}async function vF(e){try{return await C.access(e),!0}catch(t){if(wF(t,`ENOENT`))return!1;throw Z(e,`Unable to inspect session lock.`,t)}}async function yF(e,t){let n=await pF(e);n!==void 0&&zP(RP,n,e,`Session lock is invalid.`).token===t.token&&await bF(e,`Unable to release session lock.`)}async function bF(e,t){try{await C.unlink(e),await xF(c.dirname(e))}catch(n){if(!wF(n,`ENOENT`))throw Z(e,t,n)}}async function xF(e){let t=await C.open(e,`r`);try{await t.sync()}finally{await t.close()}}function SF(e){try{return process.kill(e,0),!0}catch(e){if(wF(e,`ESRCH`))return!1;if(wF(e,`EPERM`))return!0;throw e}}function CF(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function wF(e,t){return e instanceof Error&&`code`in e&&e.code===t}function Z(e,t,n){return new jP(t,{...n!==void 0&&{cause:n},file:e})}Dx(),oT(),FM(),Qj(),cj(),ZO(),LO();const TF=p.object({status:p.enum([`opening`,`open`,`closing`,`stale`]),channelId:p.string(),account:p.string().optional(),payer:p.string(),payee:p.string(),authorizedSigner:p.string(),token:p.string(),escrow:p.string(),chainId:p.number(),cumulativeAmount:p.string(),confirmedSpend:p.string(),deposit:p.string(),units:p.number(),resourceUrl:p.string(),createdAt:p.string(),updatedAt:p.string()}),EF=p.object({channelId:p.string(),status:p.enum([`closed`,`already-closed`]),spent:p.string(),txHash:p.string().optional()}),DF=p.object({closed:p.array(EF),failed:p.array(p.object({channelId:p.string(),message:p.string()}))});function OF(e){return e===`mainnet`?ve.id:ye.id}function kF(e){if(e===ve.id)return`mainnet`;if(e===ye.id)return`testnet`}function AF(e){let t={};for(let n of e??[]){let e=n.indexOf(`:`);if(e===-1)throw new I({code:`INVALID_HEADER`,message:`Invalid header format: ${n}`,exitCode:2});t[n.slice(0,e).trim()]=n.slice(e+1).trim()}return t}function jF(e){return{status:e.status,channelId:e.channel.channelId,...e.account.name&&{account:e.account.name},payer:e.channel.descriptor.payer,payee:e.channel.descriptor.payee,authorizedSigner:e.channel.descriptor.authorizedSigner,token:e.channel.descriptor.token,escrow:e.channel.escrow,chainId:e.channel.chainId,cumulativeAmount:e.channel.cumulativeAmount.toString(),confirmedSpend:e.spent.toString(),deposit:e.channel.deposit.toString(),units:e.units,resourceUrl:e.endpoint,createdAt:e.createdAt,updatedAt:e.updatedAt}}function MF(e,t){throw e instanceof I?e:e instanceof MP?new I({code:e.code,message:e.message,exitCode:e.exitCode,cause:e}):e instanceof jP?new I({code:e.code,message:e.message,exitCode:65,cause:e}):new I({code:t,message:e instanceof Error?e.message:String(e),exitCode:75,...e instanceof Error&&{cause:e}})}async function NF(e,t){let n=await qO(t??e.account.name);if(!yM(n.account,e.channel.descriptor))throw new I({code:`SESSION_ACCOUNT_MISMATCH`,message:`Account ${n.account.address} cannot sign for session ${e.channel.channelId}.`,exitCode:2});return n}async function PF(e,t){if(t.network&&OF(t.network)!==e)throw new I({code:`CHAIN_MISMATCH`,message:`Session uses chainId ${e}, not ${t.network}.`,exitCode:2});let n=t.network??kF(e),r=CO(t.rpcUrl,{network:n}),i=await TO({network:n,rpcUrl:r});if(i.id!==e)throw new I({code:`CHAIN_MISMATCH`,message:`Session uses chainId ${e}, but RPC is chainId ${i.id}.`,exitCode:2});return j({chain:i,transport:ue(r)})}const FF=sb(`sessions`,{description:`Manage persistent payment sessions (list, view, close)`}).command(`list`,{description:`List persistent payment sessions`,options:p.object({account:p.string().optional().describe(`Filter by account name`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Filter by Tempo network`)}),output:p.object({sessions:p.array(TF)}),alias:{account:`a`},async run(e){try{let t=(await HP().list()).filter(t=>!(e.options.account&&t.account.name!==e.options.account||e.options.network&&t.channel.chainId!==OF(e.options.network))).map(jF),n={sessions:t};if(e.format===`json`&&e.formatExplicit)return e.ok(n);t.length===0&&console.log(`No sessions.`);for(let[e,n]of t.entries())e>0&&console.log(``),IF(n);return}catch(e){return MF(e,`SESSION_LIST_FAILED`)}}}).command(`view`,{description:`View a persistent payment session`,args:p.object({channelId:p.string().describe(`Full session channel ID`)}),output:TF,async run(e){try{let t=await HP().get(e.args.channelId);if(!t)throw new I({code:`SESSION_NOT_FOUND`,message:`Session ${e.args.channelId} was not found.`,exitCode:2});let n=jF(t);if(e.format===`json`&&e.formatExplicit)return e.ok(n);IF(n);return}catch(e){return MF(e,`SESSION_VIEW_FAILED`)}}}).command(`close`,{description:`Cooperatively close persistent payment sessions`,usage:[{suffix:`<channel-id> [options]`},{suffix:`--all --yes [options]`}],args:p.object({channelId:p.string().optional().describe(`Full session channel ID`)}),options:p.object({account:p.string().optional().describe(`Account name`),all:p.boolean().optional().default(!1).describe(`Close every matching session`),header:p.array(p.string()).optional().describe(`Add close request header (repeatable)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`),url:p.string().optional().describe(`Override the stored resource URL`),yes:p.boolean().optional().default(!1).describe(`Confirm closing every session`)}),output:p.union([EF,DF]),alias:{account:`a`,header:`H`,rpcUrl:`r`},async run(e){if(e.options.all&&e.args.channelId)return e.error({code:`INVALID_SESSION_CLOSE`,message:`Specify a channel ID or --all, not both.`,exitCode:2});if(!e.options.all&&!e.args.channelId)return e.error({code:`INVALID_SESSION_CLOSE`,message:`Specify a channel ID or --all.`,exitCode:2});if(e.options.all&&!e.options.yes)return e.error({code:`CONFIRMATION_REQUIRED`,message:`Closing all sessions requires --yes.`,exitCode:2});if(e.options.all&&(e.options.header||e.options.rpcUrl||e.options.url))return e.error({code:`INVALID_SESSION_CLOSE`,message:`--header, --rpc-url, and --url only apply to a single session.`,exitCode:2});let t=HP();async function n(e,n={}){let r=await t.get(e);if(!r)throw new I({code:`SESSION_NOT_FOUND`,message:`Session ${e} was not found.`,exitCode:2});let i=VP(r.channel),a=await t.acquire(i);try{let r=await t.get(e);if(!r)throw new I({code:`SESSION_NOT_FOUND`,message:`Session ${e} was not found.`,exitCode:2});let a=await NF(r,n.account),o=await PF(r.channel.chainId,n);if(ij({...r.channel.descriptor,escrow:r.channel.escrow,chainId:r.channel.chainId}).toLowerCase()!==r.channel.channelId.toLowerCase())throw new I({code:`SESSION_STATE_INVALID`,message:`Stored descriptor does not derive the session channel ID.`,exitCode:65});if((await Yj(o,r.channel.channelId,r.channel.escrow)).deposit===0n)return await t.remove(r.channel.channelId),{channelId:r.channel.channelId,status:`already-closed`,spent:r.spent.toString()};let s=QP(n.resourceUrl??r.endpoint),c={...a.source===`keychain`&&{name:a.accountName},address:a.account.address},l=(e=r.challenge)=>({status:`closing`,account:c,endpoint:s,challenge:e,...r.receipt&&{receipt:r.receipt},spent:r.spent,units:r.units}),u=await t.upsert({...l(),channel:r.channel}),d=AF(n.headers),f=u.challenge,p=await AP({channel:u.channel,challenge:u.challenge,fetch:async(e,t)=>globalThis.fetch(e,{...t,headers:{...d,...Sw(t?.headers)}}),input:s,spent:u.spent,async onChallenge(e){f=e,await t.upsert({...l(e),channel:u.channel})},manager:{account:a.account,client:o,channelStore:UP(t,{scope:i,selection:u.channel.channelId,context:()=>l(f)})}});return await t.remove(u.channel.channelId),{channelId:u.channel.channelId,status:`closed`,spent:p.receipt.spent,txHash:p.receipt.txHash}}finally{await a.release()}}try{if(e.options.all){let r=(await t.list()).filter(t=>(!e.options.account||t.account.name===e.options.account)&&(!e.options.network||t.channel.chainId===OF(e.options.network))),i=[],a=[];for(let t of r)try{i.push(await n(t.channel.channelId,{account:e.options.account,network:e.options.network}))}catch(e){a.push({channelId:t.channel.channelId,message:e instanceof Error?e.message:String(e)})}let o={closed:i,failed:a};if(a.length>0){for(let e of a)process.stderr.write(`${e.channelId}: ${e.message}\n`);process.exitCode=1}if(e.format===`json`&&e.formatExplicit)return e.ok(o);for(let e of i)console.log(`${e.channelId} ${e.status} ${e.spent}`);for(let e of a)console.log(`${e.channelId} failed ${e.message}`);return}let r=await n(e.args.channelId,{account:e.options.account,headers:e.options.header,network:e.options.network,resourceUrl:e.options.url,rpcUrl:e.options.rpcUrl});if(e.format===`json`&&e.formatExplicit)return e.ok(r);console.log(`${r.channelId} ${r.status} ${r.spent}`),r.txHash&&console.log(` transaction ${r.txHash}`);return}catch(e){return MF(e,`SESSION_CLOSE_FAILED`)}}});function IF(e){console.log(e.channelId),console.log(` status ${e.status}`),console.log(` cumulative amount ${e.cumulativeAmount}`),console.log(` confirmed spend ${e.confirmedSpend}`),console.log(` deposit ${e.deposit}`),console.log(` chain ${e.chainId}`),console.log(` payer ${e.payer}`),console.log(` payee ${e.payee}`),console.log(` token ${e.token}`),console.log(` resource ${e.resourceUrl}`)}Dx(),FM(),GM(),tN(),ME(),ZO(),LO();function LF(e,t){if(t&&e!==`auto`&&t.toLowerCase()!==e.toLowerCase())throw new I({code:`SESSION_SELECTION_CONFLICT`,message:`--session and -M channel= select different sessions.`,exitCode:2});let n=t??e;if(n===`auto`||n===`new`)return n;if(/^0x[0-9a-fA-F]{64}$/.test(n))return n.toLowerCase();throw new I({code:`INVALID_SESSION`,message:`Session must be auto, new, or a 32-byte channel ID.`,exitCode:2})}function RF(e){let t=e.allowCustomEscrow;if(t!==void 0){if(t===`true`)return!0;if(t===`false`)return!1;throw new I({code:`INVALID_ALLOW_CUSTOM_ESCROW`,message:`allowCustomEscrow must be true or false.`,exitCode:2})}}function zF(e,t,n,r){if(t.deposit!==void 0)return t.deposit;let i=e.request.suggestedDeposit;return typeof i==`string`?ce(BigInt(i),r):n?`10`:void 0}function BF(e,t){if(!e)return;if(e.challengeId!==t.challenge.id)throw Error(`Session receipt challenge does not match the paid request.`);if(e.channelId.toLowerCase()!==t.channelId.toLowerCase())throw Error(`Session receipt channel does not match the selected channel.`);let n=BigInt(e.acceptedCumulative),r=BigInt(e.spent);if(n>t.cumulative)throw Error(`Session receipt exceeds the local cumulative authorization.`);if(r>n)throw Error(`Session receipt spend exceeds its accepted authorization.`);return e}function VF(e,t){return e.channel.channelId.toLowerCase()===t.toLowerCase()}function HF(e){if(e.trim()!==`[DONE]`){if(e.length===0){process.stdout.write(`
|
|
243
|
-
`);return}try{let t=JSON.parse(e);process.stdout.write(t.token??t.choices?.[0]?.delta?.content??e)}catch{process.stdout.write(e)}}}async function UF(e){let{options:t}=e,n=await qO(t.account),r=CO(t.rpcUrl,{network:t.network}),i=await TO({network:t.network,rpcUrl:r}),a=j({chain:i,transport:ue(r)}),o=RF(e.methodOptions),s=await pM({allowCustomEscrow:o,challenge:e.challenge,getClient:async()=>a});if(s.chainId!==i.id)throw new I({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${s.chainId}, but RPC is chainId ${i.id}.`,exitCode:2});let{decimals:c}=await kO(a,s.token,n.account.address,{requireDecimals:!0}),l={payer:n.account.address,payee:s.payee,token:s.token,escrow:s.escrow,chainId:s.chainId},u=LF(t.session,e.methodOptions.channel),d=e.registry??HP(),f=await d.acquire(l).catch(e=>{throw e instanceof MP?new I({code:e.code,message:e.message,exitCode:e.exitCode,cause:e}):e});try{let r=u===`auto`?await d.getPreferred(l):u===`new`?void 0:u,s=r?await d.get(r):void 0;if(r&&!s)throw new I({code:`SESSION_NOT_FOUND`,message:`Session ${r} was not found.`,exitCode:2});if(s&&u!==`auto`&&(s.status!==`open`||!s.channel.opened||BP(VP(s.channel))!==BP(l)||!yM(n.account,s.channel.descriptor)))throw new I({code:`SESSION_MISMATCH`,message:`Session ${s.channel.channelId} cannot be used for this account and challenge.`,exitCode:2});let f=s?.status===`open`&&s.channel.opened?s:void 0,p=f?`open`:`opening`,m=e.challenge,h=f?.receipt,g=f?.spent??0n,_=f?.units??0,v=QP(e.endpoint),y={...n.source===`keychain`&&{name:n.accountName},address:n.account.address},b=UP(d,{scope:l,selection:u,context:()=>({status:p,account:y,endpoint:v,challenge:m,...h&&{receipt:h},spent:g,units:_}),onNewChannel(){p=`opening`,h=void 0,g=0n,_=0}}),{signal:x,...S}=e.init,C={...S,...x&&{signal:x},onReceipt(e){h=e,g=g>BigInt(e.spent)?g:BigInt(e.spent),_=Math.max(_,e.units??0)}};if(e.challengeResponse.status!==402||e.challengeResponse.bodyUsed)throw Error(`Session manager requires an unconsumed 402 challenge response.`);let w=!0,T=eN({account:n.account,allowCustomEscrow:o,bootstrap:!1,client:a,channelStore:b,credentialContext:e.credentialContext,decimals:c,maxDeposit:zF(e.challenge,e.methodOptions,OO(i),c),fetch:async(t,n)=>w?(w=!1,e.challengeResponse):e.fetch(t,n)});f&&UM(T).rehydrate({channel:f.channel,challenge:e.challenge,input:e.fetchInput,spent:f.spent});let{onReceipt:ee,...E}=C,D=await T.fetch(e.fetchInput,E);if(t.fail&&D.status>=400)throw new I({code:`HTTP_ERROR`,message:`HTTP error ${D.status}`,exitCode:22});if(D.status===402)throw new I({code:`PAYMENT_REJECTED`,message:`Payment rejected.`,exitCode:75});fO(D,{include:!1,verbose:t.include?Math.max(t.verbose,2):t.verbose,silent:t.silent}),m=D.challenge??e.challenge;let O=T.channelId;if(!O)throw Error(`Session manager did not select a channel.`);if(h=BF(D.receipt,{challenge:m,channelId:O,cumulative:T.cumulative})??h,SE(D)){let t=UM(T).consumeSseResponse(e.fetchInput,D,{onReceipt:ee,signal:e.init.signal??void 0});for await(let e of t)HF(e)}else process.stdout.write(Buffer.from(await D.arrayBuffer()));let k=await d.get(O);if(!k||!VF(k,O))throw Error(`Session ${O} was not persisted.`);if(h){let e=BF(h,{challenge:m,channelId:O,cumulative:T.cumulative});if(!e)throw Error(`Session receipt validation failed.`);h=e,g=g>BigInt(e.spent)?g:BigInt(e.spent),_=Math.max(_,e.units??0),p=`open`}await d.upsert({status:p,channel:k.channel,account:y,endpoint:v,challenge:m,...h&&{receipt:h},spent:g,units:_}),t.silent||(e.info(`Session retained ${O}\n`),e.info(`Close with: mppx sessions close ${O}\n`))}finally{await f.release()}}LO();function Q(e,t){return t?{label:e,detail:t,severity:`pass`}:{label:e,severity:`pass`}}function $(e,t,n){let r={label:e,severity:`fail`};return t&&(r.detail=t),n&&(r.hint=n),r}function WF(e,t,n){let r={label:e,severity:`warn`};return t&&(r.detail=t),n&&(r.hint=n),r}function GF(e,t,n){let r=t?{label:e,detail:t,severity:`skip`}:{label:e,severity:`skip`};return n&&(r.hint=n),r}const KF={pass:X.green(`✓`),fail:X.red(`✗`),warn:X.yellow(`⚠`),suggested:X.cyan(`◇`),skip:X.dim(`○`)};function qF(e){let t=KF[e.severity],n=e.detail?`${e.label} (${e.detail})`:e.label;console.log(` ${t} ${n}`),e.hint&&e.severity!==`pass`&&console.log(X.dim(` → ${e.hint}`))}function JF(e){console.log(`\n${X.bold(e)}`)}function YF(e,t){for(let n of e)qF(n),n.severity===`pass`?t.passed++:n.severity===`fail`?t.failed++:n.severity===`warn`?t.warnings++:n.severity===`suggested`?t.suggested++:n.severity===`skip`&&t.skipped++}async function XF(e,t,n=15e3){let r=new AbortController,i=setTimeout(()=>r.abort(),n);try{return await fetch(e,{...t,signal:r.signal})}finally{clearTimeout(i)}}function ZF(e){return e<1024?`${e}B`:e<1048576?`${(e/1024).toFixed(1)}KB`:`${(e/1048576).toFixed(1)}MB`}const QF=new Set([`get`,`post`,`put`,`patch`,`delete`,`head`,`options`,`trace`]);function $F(e){return typeof e==`string`&&/^0x[0-9a-fA-F]{40}$/.test(e)}function eI(e){return typeof e==`string`&&/^(0|[1-9][0-9]*)$/.test(e)}function tI(e){let t=e.indexOf(`:`);if(t<1)return null;let n=e.slice(0,t).toLowerCase();if(!QF.has(n))return null;let r=e.slice(t+1);if(!r)return null;let i=r.startsWith(`/`)?r:`/`+r;return{method:n.toUpperCase(),path:i}}function nI(e,t){if(e){try{let n=JSON.parse(e);if(n&&typeof n==`object`&&!Array.isArray(n)){let e=Object.keys(n);if(e.length>0&&e.every(e=>e.startsWith(`/`))){let e=n[t];return e===void 0?void 0:typeof e==`string`?e:JSON.stringify(e)}}}catch{}return e}}function rI(e){if(!e)return{};let t={};for(let n of e){let e=n.indexOf(`:`);e>0&&(t[n.slice(0,e).trim().toLowerCase()]=n.slice(e+1).trim())}return t}async function iI(e){let t=new URL(`openapi.json`,e.replace(/\/?$/,`/`)).href;try{let e=await XF(t,{});if(!e.ok)return{error:`HTTP ${e.status}`};let n=await e.text();return{doc:JSON.parse(n),raw:n}}catch(e){return e instanceof DOMException&&e.name===`AbortError`?{error:`Request timed out after 15s`}:e instanceof SyntaxError?{error:`Invalid JSON`}:{error:e.message}}}async function aI(e){let t=new URL(`/llms.txt`,e).href,n=`llms.txt found and nonempty`;try{let e=await XF(t,{});if(!e.ok)throw Error(`HTTP ${e.status}`);let r=(await e.text()).trim();if(!r)throw Error(`Empty document`);let i=e.headers.get(`content-type`)?.split(`;`)[0]?.trim().toLowerCase();if(i&&!i.startsWith(`text/`)||i===`text/html`||/^<(?:!doctype html|html|head|body)\b/i.test(r))throw Error(`Expected text documentation, received non-text or HTML content`);return Q(n,t)}catch(e){return{label:n,detail:`${t}: ${e.message}`,severity:`suggested`,hint:`Serve nonempty text documentation at /llms.txt.`}}}function oI(e){let t=[],n=[],r=e.paths;if(!r)return[];for(let[e,i]of Object.entries(r)){let r=lI(i.parameters);for(let[a,o]of Object.entries(i)){if(!QF.has(a)||!o||typeof o!=`object`||Array.isArray(o))continue;let i=o,s=uI(r,lI(i.parameters)),c=s.length>0?s:void 0;if(i[`x-payment-info`]){let n=i[`x-payment-info`];t.push({method:a.toUpperCase(),path:e,amount:n.amount,parameters:c})}else{let t=i.responses;t&&`402`in t&&n.push({method:a.toUpperCase(),path:e,parameters:c})}}}return t.length>0?t:n}function sI(e,t){let n=e.paths;if(!n)return;let r=n[t.path];if(!r)return;let i=r[t.method.toLowerCase()];if(!i?.requestBody)return;let a=i.requestBody.content?.[`application/json`];if(!a)return;if(a.example)return JSON.stringify(a.example);if(a.examples&&typeof a.examples==`object`){let e=Object.values(a.examples)[0];if(e?.value)return JSON.stringify(e.value)}let o=a.schema,s=new Set;if(o=fI(o,e,s),!o||o.type!==`object`)return;let c=pI(o,e,s);if(c&&typeof c==`object`&&Object.keys(c).length>0)return JSON.stringify(c)}function cI(e,t,n){if(!t.path.startsWith(`/`)||t.path.startsWith(`//`)||t.path.includes(`\\`))throw Error(`OpenAPI path must be an origin-relative path: ${t.path}`);let r=t.path;t.parameters&&(r=dI(r,t.parameters));let i=r.startsWith(`/`)?r.slice(1):r,a=new URL(e.replace(/\/?$/,`/`)),o=new URL(i,a);if(o.origin!==a.origin)throw Error(`OpenAPI path must be an origin-relative path: ${t.path}`);let s=o.href;if(n){let e=new URL(s);for(let t of n){let[n,...r]=t.split(`=`);n&&e.searchParams.set(n,r.join(`=`))}s=e.href}return s}function lI(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!=`object`)continue;let e=n;e.in===`path`&&typeof e.name==`string`&&t.push(e.schema&&typeof e.schema==`object`?{name:e.name,in:`path`,schema:e.schema,example:e.example}:{name:e.name,in:`path`,example:e.example})}return t}function uI(e,t){let n=[...e];for(let e of t){let t=n.findIndex(t=>t.name===e.name);t>=0?n[t]=e:n.push(e)}return n}function dI(e,t){return e.replace(/\{([^}]+)\}/g,(e,n)=>{let r=t.find(e=>e.name===n&&e.in===`path`);if(!r)return e;let i=r.example??r.schema?.example??r.schema?.default;return i===void 0?e:encodeURIComponent(String(i))})}function fI(e,t,n){if(!e||typeof e.$ref!=`string`)return e;if(n?.has(e.$ref))return;let r=e.$ref.replace(/^#\//,``).split(`/`),i=t;for(let e of r)if(i&&typeof i==`object`)i=i[e];else return;return i}function pI(e,t,n){let r=fI(e,t,n)??e;if(r.const!==void 0)return r.const;if(r.example!==void 0)return r.example;if(r.default!==void 0)return r.default;switch(r.type){case`string`:return r.enum&&Array.isArray(r.enum)?r.enum[0]:r.format===`email`?`test@example.com`:r.format===`uuid`?`00000000-0000-0000-0000-000000000000`:r.format===`uri`||r.format===`url`?`https://example.com`:r.format===`date`?`2026-01-01`:r.pattern===`^\\d{5}(?:-\\d{4})?$`?`10001`:r.pattern===`^[A-Z]{2}$`?`US`:`test`;case`number`:case`integer`:return r.minimum??1;case`boolean`:return!0;case`array`:return[];case`object`:{let e=r.properties;if(!e)return{};let i=r.required||[],a={};for(let r of i){let i=e[r];i&&(a[r]=pI(i,t,n))}return a}default:return null}}gS(),Px(),ew(),LO();const mI=Object.values(Be);function hI(e){let t=e.request.methodDetails;return typeof t?.chainId==`number`&&mI.find(e=>e.id===t.chainId)?.testnet===!0}async function gI(e,t,n,r){let i=[],a;try{a=cI(e,t,r?.query)}catch(e){return i.push($(`Request URL valid`,e.message)),{results:i}}let o=rI(r?.extraHeaders),s;r?.body&&!r.bodyIsAutogenerated&&(s=r.body,o[`content-type`]||=`application/json`);let c;try{let e={method:t.method};Object.keys(o).length>0&&(e.headers=o),s&&(e.body=s),c=await XF(a,e)}catch(e){return i.push($(`Request failed`,e.message)),{results:i}}if(!s&&(c.status===400||c.status===422)){let e=r?.body??(r?.discoveryDoc?sI(r.discoveryDoc,t):void 0);if(e){n&&console.log(X.dim(` Retrying with body: ${e}`)),s=e,o[`content-type`]=`application/json`;try{c=await XF(a,{method:t.method,headers:o,body:s})}catch(e){return i.push($(`Request failed`,e.message)),{results:i}}}}if(c.status!==402)return c.status===200?i.push(GF(`Returns 402 without credentials`,`Got 200 (endpoint may not require payment in all cases)`)):c.status===401||c.status===403?i.push(GF(`Returns 402 without credentials`,`Got ${c.status} (endpoint requires auth before payment gate)`)):i.push($(`Returns 402 without credentials`,`Got ${c.status} instead`,c.status===400||c.status===422?`Server requires a valid request body before returning 402. Add a requestBody schema with examples to your OpenAPI doc, or use --body.`:`Endpoints that require payment must return HTTP 402 with a WWW-Authenticate: Payment header when no valid credential is provided.`)),{results:i};i.push(Q(`Returns 402 without credentials`));let l=c.headers.get(q.wwwAuthenticate),u=DI(c);if(!l)return u.length>0?(i.push(GF(`Not an MPP endpoint`,`No WWW-Authenticate header — x402 protocol detected`)),i.push(...u)):i.push(GF(`Not an MPP endpoint`,`No WWW-Authenticate header (may be x402 or other protocol)`)),{results:i};if(u.length>0&&i.push(...u),!l.startsWith(`${kx.payment} `))return i.push(GF(`Not an MPP endpoint`,`WWW-Authenticate scheme is not Payment`)),{results:i};i.push(Q(`WWW-Authenticate header present`,`Payment scheme`));let d;try{d=sS(c)}catch(e){let t=e.message;i.push($(`Challenge parseable`,t,`The Payment challenge must include a request="<base64url>" parameter containing JSON-encoded payment details.`));let n=l.slice(l.indexOf(` `)+1);return i.push(WF(`Received`,n.length>200?n.slice(0,200)+`...`:n)),{results:i}}if(d.length===0)return i.push($(`Challenge parseable`,`No Payment challenges found in header`)),{results:i};let f=d.map(e=>`${e.method}/${e.intent}`).join(`, `);i.push(Q(`Challenge parseable`,d.length===1?f:`${d.length} methods: ${f}`));let p=new URL(e).hostname;_I(d,i),vI(d,i),yI(d,i),bI(d,p,i);let m=d.length>1;for(let e of d){let t=e.request;xI(e,t,i,m)}if(n)for(let e of d)console.log(X.dim(` Challenge (${e.method}/${e.intent}): ${JSON.stringify(e,null,2)}`));return{results:i,resolvedBody:s,challenges:d}}function _I(e,t){let n=e.filter(e=>!e.id);n.length===0?t.push(Q(`Challenge has id`)):t.push($(`Challenge has id`,`${n.length} missing`,`Every challenge must include a unique id field.`))}function vI(e,t){let n=e.filter(e=>!e.realm);n.length===0?t.push(Q(`Challenge has realm`)):t.push($(`Challenge has realm`,`${n.length} missing`,`Set realm to your server's hostname.`))}function yI(e,t){let n=new Date;for(let r of e){if(!r.expires){t.push(WF(`Challenge has expiration`,`missing expires field`,`Add an expires field (ISO 8601) to prevent replay attacks.`));return}if(new Date(r.expires)<=n){t.push($(`Challenge expires in the future`,`Expired at ${r.expires}`,`The expires timestamp must be in the future.`));return}}let r=Math.min(...e.map(e=>new Date(e.expires).getTime()-n.getTime()));t.push(Q(`Challenge expires in the future`,`${Math.round(r/6e4)}m from now`))}function bI(e,t,n){let r=e=>e.toLowerCase().replace(/\.$/,``),i=r(t),a=[...new Set(e.map(e=>e.realm??``))].filter(e=>{let t=r(e);return!t||t!==i&&!i.endsWith(`.${t}`)});a.length>0?n.push($(`Realm matches server hostname`,`realm="${a[0]}" vs host="${t}"`,`Set the realm to your production hostname (or base domain) in the challenge.`)):n.push(Q(`Realm matches server hostname`))}function xI(e,t,n,r){let i=r?`[${e.method}] `:``;e.method===Ax.tempo?SI(t,i,n,e):e.method===Ax.stripe?CI(t,i,n):e.method===Ax.evm&&wI(e,t,i,n)}function SI(e,t,n,r){let i=e.methodDetails,a=Array.isArray(i?.splits)&&i.splits.length>0;if($F(e.recipient)?n.push(Q(`${t}Valid recipient address`)):e.recipient===void 0&&a?n.push(Q(`${t}Uses splits (no single recipient)`)):e.recipient===void 0?n.push($(`${t}Valid recipient address`,`Missing recipient (and no splits defined)`,`Set request.recipient to a valid 0x address, or use methodDetails.splits for multiple recipients.`)):n.push($(`${t}Valid recipient address`,`Got: ${String(e.recipient)}`,`Set request.recipient to a valid 0x-prefixed 40-hex-char address.`)),$F(e.currency)){let e=hI(r)?`testnet`:`mainnet`;n.push(Q(`${t}Valid currency address`,e))}else n.push($(`${t}Valid currency address`,`Got: ${String(e.currency)}`,`Set request.currency to a valid token address.`));TI(e,t,n,`token's smallest unit (e.g. "10000" = $0.01 for 6-decimal tokens)`)}function CI(e,t,n){TI(e,t,n,`currency's smallest unit (e.g. "100" = $1.00 for USD)`);let r=e.currency;typeof r==`string`&&/^[a-z]{3}$/i.test(r)?n.push(Q(`${t}Valid currency code`,r.toUpperCase())):n.push($(`${t}Valid currency code`,r?`Got: ${r}`:`missing`,`Must be a three-letter ISO currency code (e.g. "usd").`));let i=e.methodDetails,a=i?.networkId;a?n.push(Q(`${t}Has networkId`,a.slice(0,20))):n.push($(`${t}Has networkId`,`Missing methodDetails.networkId`,`Set methodDetails.networkId to your Stripe Business Network profile ID.`));let o=i?.paymentMethodTypes;Array.isArray(o)&&o.length>0?n.push(Q(`${t}Has paymentMethodTypes`,o.join(`, `))):n.push($(`${t}Has paymentMethodTypes`,`Missing or empty`,`Set methodDetails.paymentMethodTypes to an array (e.g. ["card"]).`))}function wI(e,t,n,r){if($F(t.recipient)?r.push(Q(`${n}Valid recipient address`)):r.push($(`${n}Valid recipient address`,`Got: ${String(t.recipient)}`,`Set request.recipient to a valid 0x-prefixed Ethereum address.`)),$F(t.currency)){let t=hI(e)?`testnet`:`mainnet`;r.push(Q(`${n}Valid currency address`,t))}else r.push($(`${n}Valid currency address`,`Got: ${String(t.currency)}`,`Set request.currency to a valid ERC-20 token contract address.`));TI(t,n,r,`token's smallest unit`);let i=t.methodDetails?.chainId;typeof i==`number`&&i>0?r.push(Q(`${n}Has chainId`,String(i))):r.push($(`${n}Has chainId`,`Missing methodDetails.chainId`,`Set methodDetails.chainId to the EVM chain ID.`))}function TI(e,t,n,r){eI(e.amount)?n.push(Q(`${t}Amount is valid integer string`)):e.amount===void 0||e.amount===null?n.push($(`${t}Amount is valid integer string`,`Missing amount`,`Set request.amount to a string of digits in the ${r}.`)):n.push($(`${t}Amount is valid integer string`,`Got: ${String(e.amount)}`,`request.amount must be a string of digits (no decimals, no prefix).`))}async function EI(e,t,n){let r=[],i=cI(e,t,n?.query),a={[q.authorization]:`${kx.payment} dGhpcyBpcyBnYXJiYWdl`},o;n?.body&&(o=n.body,a[`content-type`]=`application/json`);try{let e=await XF(i,{method:t.method,headers:a,body:o??null});e.status===402?(r.push(Q(`Malformed credential returns 402`,`not 500`)),e.headers.get(q.wwwAuthenticate)?.startsWith(`${kx.payment} `)?r.push(Q(`Error response includes fresh challenge`)):r.push(WF(`Error response includes fresh challenge`,`No WWW-Authenticate header`,`When rejecting an invalid credential, respond with 402 and include a fresh WWW-Authenticate: Payment challenge so the client can retry.`))):e.status>=500?r.push($(`Malformed credential returns 402`,`Got ${e.status} (server error)`,`When the Authorization header contains an invalid credential, respond with 402 (not 500). Catch credential validation errors and return a fresh challenge.`)):r.push(WF(`Malformed credential returns 402`,`Got ${e.status}`,`When the Authorization header contains an invalid Payment credential, respond with 402 and a fresh WWW-Authenticate challenge. Returning ${e.status} prevents the client from retrying with a valid payment.`))}catch(e){r.push($(`Error handling test`,e.message))}return r}function DI(e){let t=[],n=e.headers.get(`payment-required`)??e.headers.get(`x-payment-required`);if(!n)return t;let r=e.headers.get(`payment-required`)?`PAYMENT-REQUIRED`:`X-Payment-Required`;try{let e=qC(n);t.push(Q(`x402 payment challenge`,`${r} with valid x402 v${e.x402Version} payload`))}catch{t.push(WF(`x402 payment challenge`,`${r} header present but failed schema validation`,`Ensure the PAYMENT-REQUIRED header contains a valid base64-encoded JSON payload matching the x402 schema.`))}return t}const OI=[`No discovery document found, endpoints could not be automatically found.`,`MPP servers must serve an OpenAPI document at /openapi.json with x-payment-info extensions.`,`The MPP SDKs can automatically expose this endpoint. See https://mpp.dev/sdk.`,``,`To test a specific endpoint: mppx validate <url> --endpoint POST:/your/path`].join(`
|
|
243
|
+
`);return}try{let t=JSON.parse(e);process.stdout.write(t.token??t.choices?.[0]?.delta?.content??e)}catch{process.stdout.write(e)}}}async function UF(e){let{options:t}=e,n=await qO(t.account),r=CO(t.rpcUrl,{network:t.network}),i=await TO({network:t.network,rpcUrl:r}),a=j({chain:i,transport:ue(r)}),o=RF(e.methodOptions),s=await pM({allowCustomEscrow:o,challenge:e.challenge,getClient:async()=>a});if(s.chainId!==i.id)throw new I({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${s.chainId}, but RPC is chainId ${i.id}.`,exitCode:2});let{decimals:c}=await kO(a,s.token,n.account.address,{requireDecimals:!0}),l={payer:n.account.address,payee:s.payee,token:s.token,escrow:s.escrow,chainId:s.chainId},u=LF(t.session,e.methodOptions.channel),d=e.registry??HP(),f=await d.acquire(l).catch(e=>{throw e instanceof MP?new I({code:e.code,message:e.message,exitCode:e.exitCode,cause:e}):e});try{let r=u===`auto`?await d.getPreferred(l):u===`new`?void 0:u,s=r?await d.get(r):void 0;if(r&&!s)throw new I({code:`SESSION_NOT_FOUND`,message:`Session ${r} was not found.`,exitCode:2});if(s&&u!==`auto`&&(s.status!==`open`||!s.channel.opened||BP(VP(s.channel))!==BP(l)||!yM(n.account,s.channel.descriptor)))throw new I({code:`SESSION_MISMATCH`,message:`Session ${s.channel.channelId} cannot be used for this account and challenge.`,exitCode:2});let f=s?.status===`open`&&s.channel.opened?s:void 0,p=f?`open`:`opening`,m=e.challenge,h=f?.receipt,g=f?.spent??0n,_=f?.units??0,v=QP(e.endpoint),y={...n.source===`keychain`&&{name:n.accountName},address:n.account.address},b=UP(d,{scope:l,selection:u,context:()=>({status:p,account:y,endpoint:v,challenge:m,...h&&{receipt:h},spent:g,units:_}),onNewChannel(){p=`opening`,h=void 0,g=0n,_=0}}),{signal:x,...S}=e.init,C={...S,...x&&{signal:x},onReceipt(e){h=e,g=g>BigInt(e.spent)?g:BigInt(e.spent),_=Math.max(_,e.units??0)}};if(e.challengeResponse.status!==402||e.challengeResponse.bodyUsed)throw Error(`Session manager requires an unconsumed 402 challenge response.`);let w=!0,T=eN({account:n.account,allowCustomEscrow:o,bootstrap:!1,client:a,channelStore:b,credentialContext:e.credentialContext,decimals:c,maxDeposit:zF(e.challenge,e.methodOptions,OO(i),c),fetch:async(t,n)=>w?(w=!1,e.challengeResponse):e.fetch(t,n)});f&&UM(T).rehydrate({channel:f.channel,challenge:e.challenge,input:e.fetchInput,spent:f.spent});let{onReceipt:ee,...E}=C,D=await T.fetch(e.fetchInput,E);if(t.fail&&D.status>=400)throw new I({code:`HTTP_ERROR`,message:`HTTP error ${D.status}`,exitCode:22});if(D.status===402)throw new I({code:`PAYMENT_REJECTED`,message:`Payment rejected.`,exitCode:75});fO(D,{include:!1,verbose:t.include?Math.max(t.verbose,2):t.verbose,silent:t.silent}),m=D.challenge??e.challenge;let O=T.channelId;if(!O)throw Error(`Session manager did not select a channel.`);if(h=BF(D.receipt,{challenge:m,channelId:O,cumulative:T.cumulative})??h,SE(D)){let t=UM(T).consumeSseResponse(e.fetchInput,D,{onReceipt:ee,signal:e.init.signal??void 0});for await(let e of t)HF(e)}else process.stdout.write(Buffer.from(await D.arrayBuffer()));let k=await d.get(O);if(!k||!VF(k,O))throw Error(`Session ${O} was not persisted.`);if(h){let e=BF(h,{challenge:m,channelId:O,cumulative:T.cumulative});if(!e)throw Error(`Session receipt validation failed.`);h=e,g=g>BigInt(e.spent)?g:BigInt(e.spent),_=Math.max(_,e.units??0),p=`open`}await d.upsert({status:p,channel:k.channel,account:y,endpoint:v,challenge:m,...h&&{receipt:h},spent:g,units:_}),t.silent||(e.info(`Session retained ${O}\n`),e.info(`Close with: mppx sessions close ${O}\n`))}finally{await f.release()}}LO();function Q(e,t){return t?{label:e,detail:t,severity:`pass`}:{label:e,severity:`pass`}}function $(e,t,n){let r={label:e,severity:`fail`};return t&&(r.detail=t),n&&(r.hint=n),r}function WF(e,t,n){let r={label:e,severity:`warn`};return t&&(r.detail=t),n&&(r.hint=n),r}function GF(e,t,n){let r=t?{label:e,detail:t,severity:`skip`}:{label:e,severity:`skip`};return n&&(r.hint=n),r}const KF={pass:X.green(`✓`),fail:X.red(`✗`),warn:X.yellow(`⚠`),suggested:X.cyan(`◇`),skip:X.dim(`○`)};function qF(e){let t=KF[e.severity],n=e.detail?`${e.label} (${e.detail})`:e.label;console.log(` ${t} ${n}`),e.hint&&e.severity!==`pass`&&console.log(X.dim(` → ${e.hint}`))}function JF(e){console.log(`\n${X.bold(e)}`)}function YF(e,t){for(let n of e)qF(n),n.severity===`pass`?t.passed++:n.severity===`fail`?t.failed++:n.severity===`warn`?t.warnings++:n.severity===`suggested`?t.suggested++:n.severity===`skip`&&t.skipped++}async function XF(e,t,n=15e3){let r=new AbortController,i=setTimeout(()=>r.abort(),n);try{return await fetch(e,{...t,redirect:`error`,signal:r.signal})}finally{clearTimeout(i)}}function ZF(e){return e<1024?`${e}B`:e<1048576?`${(e/1024).toFixed(1)}KB`:`${(e/1048576).toFixed(1)}MB`}const QF=new Set([`get`,`post`,`put`,`patch`,`delete`,`head`,`options`,`trace`]);function $F(e){return typeof e==`string`&&/^0x[0-9a-fA-F]{40}$/.test(e)}function eI(e){return typeof e==`string`&&/^(0|[1-9][0-9]*)$/.test(e)}function tI(e){let t=e.indexOf(`:`);if(t<1)return null;let n=e.slice(0,t).toLowerCase();if(!QF.has(n))return null;let r=e.slice(t+1);if(!r)return null;let i=r.startsWith(`/`)?r:`/`+r;return{method:n.toUpperCase(),path:i}}function nI(e,t){if(e){try{let n=JSON.parse(e);if(n&&typeof n==`object`&&!Array.isArray(n)){let e=Object.keys(n);if(e.length>0&&e.every(e=>e.startsWith(`/`))){let e=n[t];return e===void 0?void 0:typeof e==`string`?e:JSON.stringify(e)}}}catch{}return e}}function rI(e){if(!e)return{};let t={};for(let n of e){let e=n.indexOf(`:`);e>0&&(t[n.slice(0,e).trim().toLowerCase()]=n.slice(e+1).trim())}return t}async function iI(e){let t=new URL(`openapi.json`,e.replace(/\/?$/,`/`)).href;try{let e=await XF(t,{});if(!e.ok)return{error:`HTTP ${e.status}`};let n=await e.text();return{doc:JSON.parse(n),raw:n}}catch(e){return e instanceof DOMException&&e.name===`AbortError`?{error:`Request timed out after 15s`}:e instanceof SyntaxError?{error:`Invalid JSON`}:{error:e.message}}}async function aI(e){let t=new URL(`/llms.txt`,e).href,n=`llms.txt found and nonempty`;try{let e=await XF(t,{});if(!e.ok)throw Error(`HTTP ${e.status}`);let r=(await e.text()).trim();if(!r)throw Error(`Empty document`);let i=e.headers.get(`content-type`)?.split(`;`)[0]?.trim().toLowerCase();if(i&&!i.startsWith(`text/`)||i===`text/html`||/^<(?:!doctype html|html|head|body)\b/i.test(r))throw Error(`Expected text documentation, received non-text or HTML content`);return Q(n,t)}catch(e){return{label:n,detail:`${t}: ${e.message}`,severity:`suggested`,hint:`Serve nonempty text documentation at /llms.txt.`}}}function oI(e){let t=[],n=[],r=e.paths;if(!r)return[];for(let[e,i]of Object.entries(r)){let r=lI(i.parameters);for(let[a,o]of Object.entries(i)){if(!QF.has(a)||!o||typeof o!=`object`||Array.isArray(o))continue;let i=o,s=uI(r,lI(i.parameters)),c=s.length>0?s:void 0;if(i[`x-payment-info`]){let n=i[`x-payment-info`];t.push({method:a.toUpperCase(),path:e,amount:n.amount,parameters:c})}else{let t=i.responses;t&&`402`in t&&n.push({method:a.toUpperCase(),path:e,parameters:c})}}}return t.length>0?t:n}function sI(e,t){let n=e.paths;if(!n)return;let r=n[t.path];if(!r)return;let i=r[t.method.toLowerCase()];if(!i?.requestBody)return;let a=i.requestBody.content?.[`application/json`];if(!a)return;if(a.example)return JSON.stringify(a.example);if(a.examples&&typeof a.examples==`object`){let e=Object.values(a.examples)[0];if(e?.value)return JSON.stringify(e.value)}let o=a.schema,s=new Set;if(o=fI(o,e,s),!o||o.type!==`object`)return;let c=pI(o,e,s);if(c&&typeof c==`object`&&Object.keys(c).length>0)return JSON.stringify(c)}function cI(e,t,n){if(!t.path.startsWith(`/`)||t.path.startsWith(`//`)||t.path.includes(`\\`))throw Error(`OpenAPI path must be an origin-relative path: ${t.path}`);let r=t.path;t.parameters&&(r=dI(r,t.parameters));let i=r.startsWith(`/`)?r.slice(1):r,a=new URL(e.replace(/\/?$/,`/`)),o=new URL(i,a);if(o.origin!==a.origin)throw Error(`OpenAPI path must be an origin-relative path: ${t.path}`);let s=o.href;if(n){let e=new URL(s);for(let t of n){let[n,...r]=t.split(`=`);n&&e.searchParams.set(n,r.join(`=`))}s=e.href}return s}function lI(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!=`object`)continue;let e=n;e.in===`path`&&typeof e.name==`string`&&t.push(e.schema&&typeof e.schema==`object`?{name:e.name,in:`path`,schema:e.schema,example:e.example}:{name:e.name,in:`path`,example:e.example})}return t}function uI(e,t){let n=[...e];for(let e of t){let t=n.findIndex(t=>t.name===e.name);t>=0?n[t]=e:n.push(e)}return n}function dI(e,t){return e.replace(/\{([^}]+)\}/g,(e,n)=>{let r=t.find(e=>e.name===n&&e.in===`path`);if(!r)return e;let i=r.example??r.schema?.example??r.schema?.default;return i===void 0?e:encodeURIComponent(String(i))})}function fI(e,t,n){if(!e||typeof e.$ref!=`string`)return e;if(n?.has(e.$ref))return;let r=e.$ref.replace(/^#\//,``).split(`/`),i=t;for(let e of r)if(i&&typeof i==`object`)i=i[e];else return;return i}function pI(e,t,n){let r=fI(e,t,n)??e;if(r.const!==void 0)return r.const;if(r.example!==void 0)return r.example;if(r.default!==void 0)return r.default;switch(r.type){case`string`:return r.enum&&Array.isArray(r.enum)?r.enum[0]:r.format===`email`?`test@example.com`:r.format===`uuid`?`00000000-0000-0000-0000-000000000000`:r.format===`uri`||r.format===`url`?`https://example.com`:r.format===`date`?`2026-01-01`:r.pattern===`^\\d{5}(?:-\\d{4})?$`?`10001`:r.pattern===`^[A-Z]{2}$`?`US`:`test`;case`number`:case`integer`:return r.minimum??1;case`boolean`:return!0;case`array`:return[];case`object`:{let e=r.properties;if(!e)return{};let i=r.required||[],a={};for(let r of i){let i=e[r];i&&(a[r]=pI(i,t,n))}return a}default:return null}}gS(),Px(),ew(),LO();const mI=Object.values(Be);function hI(e){let t=e.request.methodDetails;return typeof t?.chainId==`number`&&mI.find(e=>e.id===t.chainId)?.testnet===!0}async function gI(e,t,n,r){let i=[],a;try{a=cI(e,t,r?.query)}catch(e){return i.push($(`Request URL valid`,e.message)),{results:i}}let o=rI(r?.extraHeaders),s;r?.body&&!r.bodyIsAutogenerated&&(s=r.body,o[`content-type`]||=`application/json`);let c;try{let e={method:t.method};Object.keys(o).length>0&&(e.headers=o),s&&(e.body=s),c=await XF(a,e)}catch(e){return i.push($(`Request failed`,e.message)),{results:i}}if(!s&&(c.status===400||c.status===422)){let e=r?.body??(r?.discoveryDoc?sI(r.discoveryDoc,t):void 0);if(e){n&&console.log(X.dim(` Retrying with body: ${e}`)),s=e,o[`content-type`]=`application/json`;try{c=await XF(a,{method:t.method,headers:o,body:s})}catch(e){return i.push($(`Request failed`,e.message)),{results:i}}}}if(c.status!==402)return c.status===200?i.push(GF(`Returns 402 without credentials`,`Got 200 (endpoint may not require payment in all cases)`)):c.status===401||c.status===403?i.push(GF(`Returns 402 without credentials`,`Got ${c.status} (endpoint requires auth before payment gate)`)):i.push($(`Returns 402 without credentials`,`Got ${c.status} instead`,c.status===400||c.status===422?`Server requires a valid request body before returning 402. Add a requestBody schema with examples to your OpenAPI doc, or use --body.`:`Endpoints that require payment must return HTTP 402 with a WWW-Authenticate: Payment header when no valid credential is provided.`)),{results:i};i.push(Q(`Returns 402 without credentials`));let l=c.headers.get(q.wwwAuthenticate),u=DI(c);if(!l)return u.length>0?(i.push(GF(`Not an MPP endpoint`,`No WWW-Authenticate header — x402 protocol detected`)),i.push(...u)):i.push(GF(`Not an MPP endpoint`,`No WWW-Authenticate header (may be x402 or other protocol)`)),{results:i};if(u.length>0&&i.push(...u),!l.startsWith(`${kx.payment} `))return i.push(GF(`Not an MPP endpoint`,`WWW-Authenticate scheme is not Payment`)),{results:i};i.push(Q(`WWW-Authenticate header present`,`Payment scheme`));let d;try{d=sS(c)}catch(e){let t=e.message;i.push($(`Challenge parseable`,t,`The Payment challenge must include a request="<base64url>" parameter containing JSON-encoded payment details.`));let n=l.slice(l.indexOf(` `)+1);return i.push(WF(`Received`,n.length>200?n.slice(0,200)+`...`:n)),{results:i}}if(d.length===0)return i.push($(`Challenge parseable`,`No Payment challenges found in header`)),{results:i};let f=d.map(e=>`${e.method}/${e.intent}`).join(`, `);i.push(Q(`Challenge parseable`,d.length===1?f:`${d.length} methods: ${f}`));let p=new URL(e).hostname;_I(d,i),vI(d,i),yI(d,i),bI(d,p,i);let m=d.length>1;for(let e of d){let t=e.request;xI(e,t,i,m)}if(n)for(let e of d)console.log(X.dim(` Challenge (${e.method}/${e.intent}): ${JSON.stringify(e,null,2)}`));return{results:i,resolvedBody:s,challenges:d}}function _I(e,t){let n=e.filter(e=>!e.id);n.length===0?t.push(Q(`Challenge has id`)):t.push($(`Challenge has id`,`${n.length} missing`,`Every challenge must include a unique id field.`))}function vI(e,t){let n=e.filter(e=>!e.realm);n.length===0?t.push(Q(`Challenge has realm`)):t.push($(`Challenge has realm`,`${n.length} missing`,`Set realm to your server's hostname.`))}function yI(e,t){let n=new Date;for(let r of e){if(!r.expires){t.push(WF(`Challenge has expiration`,`missing expires field`,`Add an expires field (ISO 8601) to prevent replay attacks.`));return}if(new Date(r.expires)<=n){t.push($(`Challenge expires in the future`,`Expired at ${r.expires}`,`The expires timestamp must be in the future.`));return}}let r=Math.min(...e.map(e=>new Date(e.expires).getTime()-n.getTime()));t.push(Q(`Challenge expires in the future`,`${Math.round(r/6e4)}m from now`))}function bI(e,t,n){let r=e=>e.toLowerCase().replace(/\.$/,``),i=r(t),a=[...new Set(e.map(e=>e.realm??``))].filter(e=>{let t=r(e);return!t||t!==i&&!i.endsWith(`.${t}`)});a.length>0?n.push($(`Realm matches server hostname`,`realm="${a[0]}" vs host="${t}"`,`Set the realm to your production hostname (or base domain) in the challenge.`)):n.push(Q(`Realm matches server hostname`))}function xI(e,t,n,r){let i=r?`[${e.method}] `:``;e.method===Ax.tempo?SI(t,i,n,e):e.method===Ax.stripe?CI(t,i,n):e.method===Ax.evm&&wI(e,t,i,n)}function SI(e,t,n,r){let i=e.methodDetails,a=Array.isArray(i?.splits)&&i.splits.length>0;if($F(e.recipient)?n.push(Q(`${t}Valid recipient address`)):e.recipient===void 0&&a?n.push(Q(`${t}Uses splits (no single recipient)`)):e.recipient===void 0?n.push($(`${t}Valid recipient address`,`Missing recipient (and no splits defined)`,`Set request.recipient to a valid 0x address, or use methodDetails.splits for multiple recipients.`)):n.push($(`${t}Valid recipient address`,`Got: ${String(e.recipient)}`,`Set request.recipient to a valid 0x-prefixed 40-hex-char address.`)),$F(e.currency)){let e=hI(r)?`testnet`:`mainnet`;n.push(Q(`${t}Valid currency address`,e))}else n.push($(`${t}Valid currency address`,`Got: ${String(e.currency)}`,`Set request.currency to a valid token address.`));TI(e,t,n,`token's smallest unit (e.g. "10000" = $0.01 for 6-decimal tokens)`)}function CI(e,t,n){TI(e,t,n,`currency's smallest unit (e.g. "100" = $1.00 for USD)`);let r=e.currency;typeof r==`string`&&/^[a-z]{3}$/i.test(r)?n.push(Q(`${t}Valid currency code`,r.toUpperCase())):n.push($(`${t}Valid currency code`,r?`Got: ${r}`:`missing`,`Must be a three-letter ISO currency code (e.g. "usd").`));let i=e.methodDetails,a=i?.networkId;a?n.push(Q(`${t}Has networkId`,a.slice(0,20))):n.push($(`${t}Has networkId`,`Missing methodDetails.networkId`,`Set methodDetails.networkId to your Stripe Business Network profile ID.`));let o=i?.paymentMethodTypes;Array.isArray(o)&&o.length>0?n.push(Q(`${t}Has paymentMethodTypes`,o.join(`, `))):n.push($(`${t}Has paymentMethodTypes`,`Missing or empty`,`Set methodDetails.paymentMethodTypes to an array (e.g. ["card"]).`))}function wI(e,t,n,r){if($F(t.recipient)?r.push(Q(`${n}Valid recipient address`)):r.push($(`${n}Valid recipient address`,`Got: ${String(t.recipient)}`,`Set request.recipient to a valid 0x-prefixed Ethereum address.`)),$F(t.currency)){let t=hI(e)?`testnet`:`mainnet`;r.push(Q(`${n}Valid currency address`,t))}else r.push($(`${n}Valid currency address`,`Got: ${String(t.currency)}`,`Set request.currency to a valid ERC-20 token contract address.`));TI(t,n,r,`token's smallest unit`);let i=t.methodDetails?.chainId;typeof i==`number`&&i>0?r.push(Q(`${n}Has chainId`,String(i))):r.push($(`${n}Has chainId`,`Missing methodDetails.chainId`,`Set methodDetails.chainId to the EVM chain ID.`))}function TI(e,t,n,r){eI(e.amount)?n.push(Q(`${t}Amount is valid integer string`)):e.amount===void 0||e.amount===null?n.push($(`${t}Amount is valid integer string`,`Missing amount`,`Set request.amount to a string of digits in the ${r}.`)):n.push($(`${t}Amount is valid integer string`,`Got: ${String(e.amount)}`,`request.amount must be a string of digits (no decimals, no prefix).`))}async function EI(e,t,n){let r=[],i=cI(e,t,n?.query),a={[q.authorization]:`${kx.payment} dGhpcyBpcyBnYXJiYWdl`},o;n?.body&&(o=n.body,a[`content-type`]=`application/json`);try{let e=await XF(i,{method:t.method,headers:a,body:o??null});e.status===402?(r.push(Q(`Malformed credential returns 402`,`not 500`)),e.headers.get(q.wwwAuthenticate)?.startsWith(`${kx.payment} `)?r.push(Q(`Error response includes fresh challenge`)):r.push(WF(`Error response includes fresh challenge`,`No WWW-Authenticate header`,`When rejecting an invalid credential, respond with 402 and include a fresh WWW-Authenticate: Payment challenge so the client can retry.`))):e.status>=500?r.push($(`Malformed credential returns 402`,`Got ${e.status} (server error)`,`When the Authorization header contains an invalid credential, respond with 402 (not 500). Catch credential validation errors and return a fresh challenge.`)):r.push(WF(`Malformed credential returns 402`,`Got ${e.status}`,`When the Authorization header contains an invalid Payment credential, respond with 402 and a fresh WWW-Authenticate challenge. Returning ${e.status} prevents the client from retrying with a valid payment.`))}catch(e){r.push($(`Error handling test`,e.message))}return r}function DI(e){let t=[],n=e.headers.get(`payment-required`)??e.headers.get(`x-payment-required`);if(!n)return t;let r=e.headers.get(`payment-required`)?`PAYMENT-REQUIRED`:`X-Payment-Required`;try{let e=qC(n);t.push(Q(`x402 payment challenge`,`${r} with valid x402 v${e.x402Version} payload`))}catch{t.push(WF(`x402 payment challenge`,`${r} header present but failed schema validation`,`Ensure the PAYMENT-REQUIRED header contains a valid base64-encoded JSON payload matching the x402 schema.`))}return t}const OI=[`No discovery document found, endpoints could not be automatically found.`,`MPP servers must serve an OpenAPI document at /openapi.json with x-payment-info extensions.`,`The MPP SDKs can automatically expose this endpoint. See https://mpp.dev/sdk.`,``,`To test a specific endpoint: mppx validate <url> --endpoint POST:/your/path`].join(`
|
|
244
244
|
`);Xx();const kI={fundingCurrency:J.optional(J.string()),method:J.string(),reference:J.string(),externalId:J.optional(J.string()),subscriptionId:J.optional(J.string()),status:J.literal(`success`),timestamp:Vx()};J.object(kI);const AI=J.looseObject(kI);function jI(e){let t=k.toString(e);return MI(JSON.parse(t))}function MI(e){return AI.parse(e)}gS(),Px(),NN(),lO(),rO(),ZO(),LO();async function NI(e,t,n){try{n||console.log(X.dim(` Provisioning testnet wallet and funding via faucet...`));let t=he(),r=_e(t),i=j({chain:ye,transport:ue()});if(SD(e)){let{chainId:t,operator:n}=e.request.methodDetails??{};if(t===ye.id&&typeof n==`string`&&de(n)&&n!==me){let e=await Fe.faucet.fund(i,{account:n});await Promise.all(e.map(e=>Me(i,{hash:e})))}}let a=await Fe.faucet.fund(i,{account:r});await Promise.all(a.map(e=>Me(i,{hash:e}))),n||console.log(X.dim(` Using wallet: ${r.address}`));let o=e.request.currency;if(typeof o==`string`)for(let e=0;e<10;e++){let e=await Fe.token.getBalance(i,{account:r.address,token:o}).catch(()=>void 0);if(e&&e.amount>0n)break;await new Promise(e=>setTimeout(e,500))}return{methods:[...AN({account:r})]}}catch(e){t&&console.log(X.dim(` Provisioning failed: ${e.message}`));return}}async function PI(){let e=WO(),{isTempoAccount:t}=await Promise.resolve().then(()=>(LO(),uO)),{resolveTempoAccount:n}=await Promise.resolve().then(()=>(pP(),PN));if(t(e)){let t=n(e);if(t)return t.wallet_address}try{return(await JO()).address}catch{return}}function FI(e){try{let{execSync:t}=m,n=t(`stripe config --list`,{encoding:`utf8`,timeout:5e3}).match(/test_mode_api_key\s*=\s*'([^']+)'/);if(n?.[1])return e&&console.log(X.dim(` Using Stripe test key from stripe CLI`)),n[1]}catch{}}async function II(e,t,n){let r=j({chain:e,transport:ue()}),[i,a,o]=await Promise.all([n?De(r,{address:t,abi:se,functionName:`balanceOf`,args:[n]}):0n,De(r,{address:t,abi:se,functionName:`decimals`}),De(r,{address:t,abi:se,functionName:`symbol`}).catch(()=>void 0)]);return{balance:i,decimals:a,symbol:o??void 0}}function LI(e){return Object.values(Be).find(t=>t.id===e)}function RI(e,t){return`$${(Number(e)/10**t).toFixed(2)}`}function zI(e){switch(e.method){case Ax.evm:return`no EVM payment plugin yet`;case`solana`:return`no Solana payment plugin yet`;default:return`no plugin for ${e.method}/${e.intent}`}}async function BI(e,t,n,r){let i=[],a=cI(e,t,r.query),o=rI(r.extraHeaders),s;r.body&&(s=r.body,o[`content-type`]=`application/json`);let c;try{c=await XF(a,{method:t.method,headers:o,body:s??null})}catch(e){return i.push($(`Payment: fetch challenge`,e.message)),i}if(c.status!==402)return i.push(GF(`Payment: skipped`,`Endpoint returned ${c.status}`)),i;let l;try{l=sS(c)}catch(e){return i.push($(`Payment: parse challenge`,e.message)),i}if(l.length===0)return i.push($(`Payment: parse challenge`,`No Payment challenges in response`)),i;let u=[];bI(l,new URL(a).hostname,u);let d=u.filter(e=>e.severity===`fail`);if(d.length>0)return i.push(...d),r.onResults?.(d),i;let f=await TP().catch(()=>void 0),p=l.find(e=>{if(e.method!==Ax.tempo||CP(f?.config)?.some(t=>t.name===e.method&&t.intent===e.intent))return!1;let t=e.request.methodDetails;return typeof t?.chainId==`number`&&t.chainId!==iO.mainnet});if(p){let e=await NI(p,n,r.silent);if(e)try{await GI(i,await dT({methods:e.methods,polyfill:!1,async onChallenge(e,{createCredential:t}){DP(p,e);let n=await t(await yP(e,f?.config.extensions));return i.push(Q(`Payment: submitted`,`ephemeral testnet wallet`)),n},fetch:(e,t)=>XF(e,t??{},3e4)}).fetch(a,{method:t.method,headers:o,body:s??null}),n,ye)}catch(e){i.push($(`Payment: create credential`,e.message))}else i.push($(`Payment: auto-provision wallet`,`Failed to create and fund testnet wallet`));r.onResults?.(i)}let m=r.interactive,h=process.env.MPPX_STRIPE_SECRET_KEY??FI(n),g=h?.startsWith(`sk_test_`)||h?.startsWith(`rk_test_`),_=new Set([Ax.tempo,Ax.evm,Ax.stripe]);for(let e of l){if(e===p||!_.has(e.method))continue;r.silent||console.log(``);let c=i.length,l=()=>{r.onResults&&i.length>c&&r.onResults(i.slice(c))},u=`Payment [${e.method}]`;try{switch(e.method){case Ax.tempo:case Ax.evm:await VI(e,u,{results:i,url:a,endpoint:t,fetchHeaders:o,fetchBody:s,verbose:n,loaded:f,isInteractive:m,options:r});break;case Ax.stripe:await HI(e,u,{results:i,url:a,endpoint:t,fetchHeaders:o,fetchBody:s,verbose:n,loaded:f,isInteractive:m,isStripeTestKey:g??!1,stripeKey:h,options:r})}}finally{l()}}return i}async function VI(e,t,n){let{results:r,url:i,endpoint:a,fetchHeaders:o,fetchBody:s,verbose:c,loaded:l,options:u}=n,d=e.request,f=d.methodDetails,p=eI(d.amount)?BigInt(d.amount):void 0,m=f?.decimals??d.decimals??6,h=d.currency,{plugin:g,method:_}=bP(e,l?.config);if(!g&&!_){r.push(GF(t,zI(e)));return}let v;if(!_){try{v=await PI()}catch{}if(!v){r.push(GF(t,`no wallet configured. Run "mppx account create" to create one.`));return}}let y;if(e.method===Ax.tempo){let e=f?.chainId??(_?void 0:ve.id);e!==void 0&&(y=e===ye.id?ye:LI(e))}else if(e.method===Ax.evm){let e=f?.chainId;e&&(y=LI(e))}if(p&&h&&!y){r.push(GF(t,`unable to resolve payment chain and verify token decimals`));return}let b;if(p&&h&&y)try{let n;if(e.method===Ax.tempo){let e=await kO(j({chain:y,transport:ue()}),h,v??me,{requireDecimals:!0});n=e.balance,m=e.decimals,b=e.symbol}else{let e=await II(y,h,v);n=e.balance,m=e.decimals,b=e.symbol}if(v&&n<p){let e=RI(p,m),i=RI(n,m),a=b??`tokens`;r.push(GF(t,`insufficient balance (have ${i}, need ${e} ${a} on ${y.name})`,`Fund wallet ${v} with at least ${e} ${a} on ${y.name}.`));return}}catch(e){c&&console.log(X.dim(` Balance check skipped: ${e.message}`)),r.push(GF(t,`unable to verify token balance and decimals from the payment chain`));return}let x=p?RI(p,m):`unknown amount`,S=b??(h?.length===3?h.toUpperCase():``),C=y?.name,w=`${x}${S?` ${S}`:``}${C?` on ${C}`:``}`;if(u.silent||console.log(X.dim(v?` Attempting payment with wallet ${v}`:` Attempting payment with configured method`)),!_&&y?.testnet)u.silent||console.log(X.dim(` Auto-approved: ${w} (testnet)`));else if(!u.yes&&!n.isInteractive){r.push(GF(t,`non-interactive mode, use --yes to approve`));return}else if(u.yes)u.silent||console.log(X.dim(` Auto-approved: ${w}`));else if(!await xO(` ${X.yellow(`Pay`)} ${w}. Continue?`,!1)){r.push(GF(t,`declined`));return}let T,ee,E;if(g)try{let t=await g.setup({challenge:e,options:{network:`mainnet`},methodOpts:{}});T=t.methods,ee=t.createCredential,E=t.credentialContext}catch(e){r.push(GF(t,e.message));return}else T=[_];if(_&&SD(e)){let n=!0,u=dT({methods:[_],polyfill:!1,async onChallenge(n,{createCredential:i}){let a=await yP(n,l?.config.extensions);DP(e,n);let o=await i(a);return r.push(Q(`${t}: submitted`)),o},fetch:async(t,r)=>n?(n=!1,new Response(null,{status:402,headers:{[q.wwwAuthenticate]:Qx(e)}})):XF(t,r??{},3e4)});try{await GI(r,await u.fetch(i,{method:a.method,headers:o,body:s??null}),c,y)}catch(e){r.push($(t,e.message))}return}let D=await UI(e,T,ee,t,r,l?.config.extensions,E);D&&(g?.prepareCredentialRequest?.({challenge:e,credential:D,headers:o}),await WI(r,i,a,D,o,s,c,y,dS(e)))}async function HI(e,t,n){let{results:r,url:i,endpoint:a,fetchHeaders:o,fetchBody:s,verbose:c,loaded:l,options:u,stripeKey:d}=n,{plugin:f,method:p}=bP(e,l?.config);if(!f&&!p){r.push(GF(t,`no Stripe payment method available`));return}let m=!!(f&&!l?.config.plugins?.includes(f)&&n.isStripeTestKey),h=e.request,g=eI(h.amount)?BigInt(h.amount):void 0,_=h.decimals??2,v=h.currency,y=g?RI(g,_):`unknown amount`,b=v?.length===3?v.toUpperCase():``,x=`${y}${b?` ${b}`:``} via Stripe${m?` (testmode)`:``}`;if(m)u.silent||console.log(X.dim(` Attempting: ${x}`));else if(!u.yes&&!n.isInteractive){r.push(GF(t,`non-interactive mode, use --yes to approve`));return}else if(u.yes)u.silent||console.log(X.dim(` Auto-approved: ${x}`));else if(!await xO(` ${X.yellow(`Pay`)} ${x}. Continue?`,!1)){r.push(GF(t,`declined`));return}let S,C,w;if(f)try{let t={paymentMethod:`pm_card_visa`};d&&(t.secretKey=d);let n=await f.setup({challenge:e,options:{},methodOpts:t});S=n.methods,C=n.createCredential,w=n.credentialContext}catch(e){r.push(GF(t,e.message));return}else S=[p];let T=await UI(e,S,C,t,r,l?.config.extensions,w);if(T){if(f?.prepareCredentialRequest?.({challenge:e,credential:T,headers:o}),m){let n=await XF(i,{method:a.method,headers:{...o,[dS(e)]:T},body:s??null},3e4);n.status>=200&&n.status<300?r.push(Q(`${t}: successful`,`HTTP ${n.status}`)):r.push(GF(`${t}: server is in livemode`,void 0,`Run your server with a Stripe test key to automatically validate Stripe payments in testmode.`));return}await WI(r,i,a,T,o,s,c,void 0,dS(e))}}async function UI(e,t,n,r,i,a,o){let s=new Response(null,{status:402,headers:{[q.wwwAuthenticate]:Qx(e)}});try{let c=await yP(e,a,o),l;return l=n?await n(s,c):await dT({methods:t,polyfill:!1}).createCredential(s,c),i.push(Q(`${r}: submitted`)),l}catch(e){let t=e.message;t.toLowerCase().includes(`insufficient`)?i.push(GF(r,`insufficient balance: ${t}`)):i.push($(r,t));return}}async function WI(e,t,n,r,i,a,o,s,c=q.authorization){let l;try{l=await XF(t,{method:n.method,headers:{...i,[c]:r},body:a??null},3e4)}catch(t){return e.push($(`Payment: send credential`,t.message)),e}return GI(e,l,o,s)}async function GI(e,t,n,r){if(t.status===402){let n=await t.text().catch(()=>``),r=`Payment rejected`;try{let e=JSON.parse(n);r=e.detail??e.title??r}catch{}return e.push($(`Payment: accepted`,r,`The server rejected a valid credential. Check that your payment verification logic accepts the credential format and that the payment was processed on-chain.`)),e}if(t.status>=400&&t.status<500)e.push(WF(`Payment: post-payment response`,`Got ${t.status}`,`Payment succeeded but the endpoint returned a client error. The endpoint likely requires request body parameters. Use --body to provide them.`));else if(t.status>=500)return e.push($(`Payment: server response`,`Got ${t.status}`,`Payment was accepted but the server errored while generating the response. Check server logs for the underlying error.`)),e;else e.push(Q(`Payment: successful`,`HTTP ${t.status}`));let i=t.headers.get(q.paymentReceipt);if(!i)e.push($(`Payment-Receipt header present`,void 0,`After accepting payment, include a Payment-Receipt header with a base64url-encoded JSON object containing: method, reference, status ("success"), and timestamp (ISO 8601).`));else{e.push(Q(`Payment-Receipt header present`));try{let t=jI(i);if(e.push(Q(`Receipt parseable`)),t.status===`success`?e.push(Q(`Receipt status is "success"`)):e.push($(`Receipt status is "success"`,`Got: ${t.status}`)),t.reference){let n=/^0x[0-9a-fA-F]{64}$/.test(t.reference),r=t.reference.startsWith(`pi_`);n||r?e.push(Q(`Receipt reference valid`,t.reference.slice(0,20)+`...`)):e.push(WF(`Receipt reference format`,t.reference.slice(0,40)))}else e.push(WF(`Receipt has reference`,`No reference field`));if(t.timestamp){let n=new Date(t.timestamp),r=Date.now()-n.getTime();r<6e4?e.push(Q(`Receipt timestamp recent`,`${Math.round(r/1e3)}s ago`)):e.push(WF(`Receipt timestamp recent`,`${Math.round(r/6e4)}m ago`))}n&&console.log(X.dim(` Receipt: ${JSON.stringify(t,null,2)}`))}catch(t){e.push($(`Receipt parseable`,t.message))}}let a=t.headers.get(`content-type`)??``,o=await t.text().catch(()=>``);if(o.length>0)e.push(Q(`Response body non-empty`,`${a.split(`;`)[0]}, ${ZF(o.length)}`));else{let n=[...t.headers.entries()].filter(([e])=>!e.startsWith(`x-`)&&![`content-type`,`content-length`,`date`,`server`,`connection`,`keep-alive`,`cache-control`,`vary`,`access-control-allow-origin`,`payment-receipt`,`payment-session`,`payment-session-snapshot`].includes(e.toLowerCase()));n.length>0?e.push(WF(`Response body empty -- data may be in headers only`,n.map(([e])=>e).join(`, `))):e.push(WF(`Response body empty`))}if(a?e.push(Q(`Content-Type header set`,a.split(`;`)[0])):e.push(WF(`Content-Type header set`)),i)try{let t=jI(i);if(t.reference&&/^0x[0-9a-fA-F]{64}$/.test(t.reference)){let n=r?.blockExplorers?.default?.url;if(n){let r=n.includes(`tempo`)?`receipt`:`tx`;e.push(Q(`On-chain transaction`,`${n}/${r}/${t.reference}`))}}}catch{}return e}async function*KI(e){let t=e.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``),n=e.verbose??!1,r=await ZI(t,e);yield{phase:`discovery`,discovery:r,results:r.checks};for(let i of r.endpoints){yield{phase:`endpoint`,endpoint:i};let a,o=!1;e.endpoint?a=e.body:(a=nI(e.body,i.path),!a&&r.doc&&(a=sI(r.doc,i),o=!!a));let{results:s,resolvedBody:c,challenges:l}=await gI(t,i,n,{body:a,bodyIsAutogenerated:o,query:e.query,extraHeaders:e.headers,discoveryDoc:r.doc??void 0}),u=c??a,d=s.some(e=>e.severity===`pass`&&e.label===`Challenge parseable`),f=!s.some(e=>e.severity===`fail`),p=(l??[]).filter(e=>e.method!==`stripe`).map(e=>e.request.methodDetails?.chainId).filter(e=>typeof e==`number`),m=p.some(XI),h=p.some(e=>!XI(e)),g=!d&&s.some(e=>e.label===`Not an MPP endpoint`),_=s.some(e=>e.severity===`pass`&&e.label===`WWW-Authenticate header present`),v=s.some(e=>e.severity===`fail`&&e.label===`Challenge parseable`);if(yield{phase:`challenge`,endpoint:i,results:s,isMpp:d,isTestnet:m,isMainnet:h,isNonMppPayment:g,isMalformedChallenge:!d&&_&&v,methods:l?.map(e=>e.method)??[]},d&&(yield{phase:`errorHandling`,endpoint:i,results:await EI(t,i,{body:u,query:e.query})},!e.skipPayment&&f)){let r=e.onPaymentResults,a=await BI(t,i,n,{body:u,query:e.query,extraHeaders:e.headers,yes:e.yes,silent:!r,interactive:e.interactive,...r&&{onResults:r}});yield{phase:`payment`,endpoint:i,results:a,succeeded:a.some(e=>e.severity===`pass`&&e.label===`Payment: successful`)}}}}async function qI(e){let t=e.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``),n,r=[],i,a=!1,o=!1;for await(let t of KI(e))switch(t.phase){case`discovery`:n=t.discovery;break;case`endpoint`:i={method:t.endpoint.method,path:t.endpoint.path,challenge:[],errorHandling:[],payment:[]},r.push(i);break;case`challenge`:i&&(i.challenge=t.results),t.isMpp&&(t.isTestnet&&(a=!0),t.isMainnet&&(o=!0));break;case`errorHandling`:i&&(i.errorHandling=t.results);break;case`payment`:i&&(i.payment=t.results)}let s={passed:0,failed:0,warnings:0,suggested:0,skipped:0};if(n)for(let e of n.checks)e.severity===`pass`?s.passed++:e.severity===`fail`?s.failed++:e.severity===`warn`?s.warnings++:e.severity===`suggested`?s.suggested++:e.severity===`skip`&&s.skipped++;for(let e of r)for(let t of[...e.challenge,...e.errorHandling,...e.payment])t.severity===`pass`?s.passed++:t.severity===`fail`?s.failed++:t.severity===`warn`?s.warnings++:t.severity===`suggested`?s.suggested++:t.severity===`skip`&&s.skipped++;if(!n)throw Error(`Discovery phase did not complete`);let c=JI(r,n,{sawTestnet:a,sawMainnet:o});return{url:t,discovery:n,endpoints:r,summary:s,suggestions:c}}function JI(e,t,n){let r=[],i=e.flatMap(e=>[...e.challenge,...e.payment]);t.found||r.push(OI);let a=n.sawMainnet,o=n.sawTestnet,s=i.some(e=>e.label.includes(`[stripe]`)&&e.label.includes(`livemode`));return a&&!o?r.push(`Validate your testnet server to test without real funds (Tempo wallets are automatically provisioned).`):o&&!a&&r.push(`Validate your mainnet server to confirm real payments work end-to-end.`),s&&r.push(`Validate your testmode Stripe server to test card payments end-to-end (auto-pays with test card).`),r}const YI=Object.values(Be);function XI(e){return YI.find(t=>t.id===e)?.testnet===!0}async function ZI(e,t){let n=[],r=[],i=null,a=!1,o=!1;n.push(await aI(e));let s=new URL(e).origin,c;t.discoveryPath?c=[new URL(t.discoveryPath,e+`/`).href.replace(/\/openapi\.json$/i,``)]:(c=[e,s,`${s}/api`],c=[...new Set(c)]);let l,u=[];for(let e of c)if(l=await iI(e),`error`in l)u.push(`${e}/openapi.json: ${l.error}`);else break;if(!l||`error`in l)n.push({label:`Document found`,detail:u.join(`; `),hint:`MPP servers must serve an OpenAPI document at /openapi.json with x-payment-info extensions.`,severity:`fail`});else{a=!0,n.push({label:`Document found and parseable`,severity:`pass`});let e=WT(l.doc),t=e.filter(e=>e.severity===`error`),r=e.filter(e=>e.severity===`warning`);if(t.length>0){n.push({label:`Valid OpenAPI structure`,detail:`${t.length} error(s)`,severity:`fail`});for(let e of t)n.push({label:e.message,detail:e.path,severity:`fail`})}else o=!0,n.push({label:`Valid OpenAPI structure`,severity:`pass`});for(let e of r)n.push({label:e.message,detail:e.path,severity:`warn`});i=l.doc}if(t.endpoint){let e=tI(t.endpoint);e&&r.push(e)}else if(i){r=oI(i);let e=BigInt(`999999999999999999`);r.sort((t,n)=>{let r=eI(t.amount)?BigInt(t.amount):e,i=eI(n.amount)?BigInt(n.amount):e;return r<i?-1:+(r>i)}),r.length>0?n.push({label:`Paid endpoints found`,detail:`${r.length} endpoint(s)`,severity:`pass`}):n.push({label:`Paid endpoints found`,detail:`No endpoints with x-payment-info`,severity:`warn`})}return{found:a,valid:o,endpoints:r,checks:n,doc:i}}Dx(),LO();const QI=sb(`validate`,{description:`Validate an MPP server implementation end-to-end`,args:p.object({url:p.string().describe(`Base URL of the MPP server to validate`)}),options:p.object({endpoint:p.string().optional().describe(`Endpoint to test (METHOD:path). Skips discovery.`),body:p.string().optional().describe(`Request body. With --endpoint, used directly. In discovery mode, JSON with / keys is a per-path mapping.`),query:p.array(p.string()).optional().describe(`Query parameter (key=value, repeatable)`),header:p.array(p.string()).optional().describe(`Request header (key:value, repeatable)`),verbose:p.number().default(0).meta({count:!0}).describe(`Verbosity level`),yes:p.boolean().default(!1).describe(`Auto-approve mainnet payments`),outputJson:p.boolean().default(!1).describe(`Output results as JSON (auto-enabled in known agent environments)`)}),alias:{endpoint:`e`,header:`H`,verbose:`v`,yes:`y`,outputJson:`j`},async run(e){if(e.options.outputJson||vO()){let t=await qI({url:e.args.url,endpoint:e.options.endpoint,body:e.options.body,query:e.options.query,headers:e.options.header,verbose:e.options.verbose>0,yes:e.options.yes,interactive:!1});console.log(JSON.stringify(t,null,2));let n=t.endpoints.length===0&&!e.options.endpoint;(t.summary.failed>0||!t.discovery.found||n)&&process.exit(1);return}let t=e.args.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``);console.log(`\n${X.bold(`mppx validate`)} ${X.dim(t)}\n`);let n={passed:0,failed:0,warnings:0,suggested:0,skipped:0},r=!1,i=!1,a=!1,o=!1,s=!1,c=!1,l=!1,u=0;for await(let t of KI({url:e.args.url,endpoint:e.options.endpoint,body:e.options.body,query:e.options.query,headers:e.options.header,verbose:e.options.verbose>0,yes:e.options.yes,interactive:!!process.stdin.isTTY,onPaymentResults:e=>YF(e,n)}))switch(t.phase){case`discovery`:if(JF(`Discovery (/openapi.json)`),YF(t.results,n),l=t.discovery.found,!l&&!e.options.endpoint){console.log(``);let[e,...t]=OI.split(`
|
|
245
|
-
`);console.log(X.yellow(` ${e}`));for(let e of t)console.log(e?X.dim(` ${e}`):``);console.log(``),process.exit(1)}t.discovery.endpoints.length===0&&!e.options.endpoint&&l&&(console.log(X.dim(` Use --endpoint to specify endpoints manually.`)),console.log(``),process.exit(1));break;case`endpoint`:u++,JF(`${t.endpoint.method} ${t.endpoint.path}`);break;case`challenge`:console.log(X.dim(` Challenge`)),YF(t.results,n),t.isMpp&&(r=!0,t.isTestnet&&(o=!0),t.isMainnet&&(s=!0)),t.isNonMppPayment&&(i=!0),t.isMalformedChallenge&&(a=!0);break;case`errorHandling`:console.log(X.dim(` Error Handling`)),YF(t.results,n);break;case`payment`:t.succeeded&&(c=!0)}$I(n,{sawMppEndpoint:r,sawNonMppPaymentEndpoint:i,sawMalformedChallenge:a,sawTestnet:o,sawMainnet:s,paymentSucceeded:c},u)}});function $I(e,t,n){!t.sawMppEndpoint&&n>0&&(console.log(``),t.sawMalformedChallenge?(console.log(X.yellow(` Payment scheme detected but challenge format is invalid on ${n} endpoint(s).`)),console.log(X.dim(` The server uses WWW-Authenticate: Payment but the challenge parameters do not conform to MPP.`)),console.log(X.dim(` Fix: encode payment details as base64url JSON in a request="..." parameter. See errors above.`))):t.sawNonMppPaymentEndpoint?(console.log(X.yellow(` No MPP endpoints found. Tested ${n} endpoint(s) but none use WWW-Authenticate: Payment.`)),console.log(X.dim(` This server may use x402 or another payment protocol.`))):e.skipped>0&&e.failed===0?(console.log(X.yellow(` Could not reach payment gate on any endpoint (all returned 401/403/200).`)),console.log(X.dim(` The server may require authentication before payment. Try providing auth or use --endpoint with a public path.`))):(console.log(X.yellow(` No MPP endpoints found. Tested ${n} endpoint(s) but none use WWW-Authenticate: Payment.`)),console.log(X.dim(` This server may use x402 or another payment protocol.`))),console.log(``),process.exit(1)),console.log(``);let r=[];e.passed>0&&r.push(X.green(`${e.passed} passed`)),e.failed>0&&r.push(X.red(`${e.failed} failed`)),e.warnings>0&&r.push(X.yellow(`${e.warnings} warning(s)`)),e.suggested>0&&r.push(X.cyan(`${e.suggested} suggested`)),e.skipped>0&&r.push(X.yellow(`${e.skipped} skipped`)),console.log(`${X.bold(`Summary:`)} ${r.join(`, `)}`),t.paymentSucceeded&&t.sawTestnet&&!t.sawMainnet?(console.log(``),console.log(X.dim(` Tip: also validate your mainnet server to confirm real payments work end-to-end.`))):t.sawMainnet&&!t.sawTestnet&&(console.log(``),console.log(X.dim(` Tip: also validate your testnet server for free. This CLI automatically provisions and funds a testnet wallet for testing.`))),console.log(``),e.failed>0&&process.exit(1)}function eL(e){return nL(e)?e.offers:[e]}function tL(e){let{_canonicalRequest:t,intent:n,name:r}=e,i=t.methodDetails??{},a=rL(t.amount)??rL(i.amount)??null,o=rL(t.currency)??rL(i.currency),s=rL(e.description)??rL(t.description),c={amount:a,...o?{currency:o}:{},...s?{description:s}:{},intent:n,method:r},l=new Set([`amount`,`currency`,`description`,`methodDetails`]);for(let[e,n]of Object.entries(t))!l.has(e)&&n!==void 0&&(c[e]=n);return c}function nL(e){return`offers`in e&&!(`_canonicalRequest`in e)}function rL(e){return typeof e==`string`?e:void 0}var iL=F((()=>{})),aL=Ze({generate:()=>oL,generateProxy:()=>sL});function oL(e,t){let n=e.methods,r=new Map,i={};for(let e of n)r.set(`${e.name}/${e.intent}`,e),i[e.intent]=(i[e.intent]??0)+1;for(let e of n)i[e.intent]===1&&r.set(e.intent,e);let a=t.routes.map(e=>lL(e,r));return cL({info:{title:t.info?.title??e.realm,version:t.info?.version??`1.0.0`},routes:a,serviceInfo:t.serviceInfo})}function sL(e){let t=e.routes.map(t=>({...t,path:uL(e.basePath,t.path)}));return cL({info:{title:e.info?.title??`API Proxy`,version:e.info?.version??`1.0.0`},routes:t,serviceInfo:e.serviceInfo})}function cL(e){let t={};for(let n of e.routes){let e=n.method.toLowerCase(),r={responses:{...n.payment?{402:{description:`Payment Required`}}:{},200:{description:`Successful response`}}};n.payment&&(r[`x-payment-info`]=LT.parse(n.payment)),n.summary&&(r.summary=n.summary),n.requestBody&&(r.requestBody=n.requestBody),t[n.path]||(t[n.path]={}),t[n.path][e]=r}let n={info:e.info,openapi:`3.1.0`,paths:t};return e.serviceInfo&&(n[`x-service-info`]=e.serviceInfo),n}function lL(e,t){if(`handler`in e){let t=e.handler._internal;if(!t)throw Error(`Route ${e.method.toUpperCase()} ${e.path} is missing discovery metadata`);return{method:e.method,path:e.path,payment:{offers:eL(t).map(tL)},...e.requestBody?{requestBody:e.requestBody}:{},...e.summary?{summary:e.summary}:{}}}let n=t.get(e.intent);if(!n)throw Error(`Unknown intent "${e.intent}" for route ${e.method.toUpperCase()} ${e.path}. Available: ${[...t.keys()].join(`, `)}`);let{description:r,...i}=e.options,a={_canonicalRequest:Ix(n,i),...typeof r==`string`?{description:r}:{},intent:n.intent,name:n.name};return{method:e.method,path:e.path,payment:tL(a),...e.requestBody?{requestBody:e.requestBody}:{},...e.summary?{summary:e.summary}:{}}}function uL(e,t){if(!e)return t;let n=e.startsWith(`/`)?e:`/${e}`;return`${n.endsWith(`/`)?n.slice(0,-1):n}${t}`}var dL=F((()=>{Rx(),UT(),iL()}));Dx(),gS(),oT(),UC(),nw(),aw(),Px(),rO(),ew(),ES(),DC(),ZO(),LO();const fL=`0.13.2`,pL=p.object({address:p.string(),isDefault:p.boolean().optional(),name:p.string(),source:p.string().optional()}),mL=p.object({address:p.string(),balances:p.array(p.string()).optional(),name:p.string(),type:p.string().optional()}),hL=p.object({message:p.string(),path:p.string(),severity:p.string()}),gL=p.object({description:p.string().optional(),id:p.string(),name:p.string().optional(),paidEndpoints:p.number(),status:p.string().optional(),url:p.string().optional()}),_L=p.object({description:p.string().optional(),method:p.string(),path:p.string(),payment:p.unknown().optional()});function vL(e){return e.format===`json`&&e.formatExplicit}function yL(e,t,n){if(vL(e))return e.ok(t);n()}async function bL(t){if(!t.body)return;let n=t.body.getReader();try{for(;;){let{done:t,value:r}=await n.read();if(t)break;process.stdout.write(Buffer.from(r))||await e(process.stdout,`drain`)}}finally{n.releaseLock()}}function xL(){return process.stdin.isTTY===!1&&process.stdin.listenerCount(`data`)===0&&process.stdin.listenerCount(`readable`)===0}function SL(e){return typeof e==`string`?e:void 0}function CL(e){return Array.isArray(e.endpoints)?e.endpoints.filter(e=>typeof e==`object`&&!!e):[]}function wL(e){let t=CL(e);return{...SL(e.description)?{description:SL(e.description)}:{},id:SL(e.id)??SL(e.name)??`unknown`,...SL(e.name)?{name:SL(e.name)}:{},paidEndpoints:t.filter(e=>e.payment).length,...SL(e.status)?{status:SL(e.status)}:{},...SL(e.serviceUrl)||SL(e.url)?{url:SL(e.serviceUrl)??SL(e.url)}:{}}}function TL(e){return{...SL(e.description)?{description:SL(e.description)}:{},method:SL(e.method)??`GET`,path:SL(e.path)??`/`,...e.payment===void 0?{}:{payment:e.payment}}}function EL(e){if(!e)return`free`;if(typeof e!=`object`)return String(e);let t=e,n=SL(t.amount),r=SL(t.currency),i=SL(t.method),a=SL(t.intent);return[n,r,i&&a?`${i}/${a}`:i??a].filter(Boolean).join(` `)}function DL(e){return e.request.currency??e.request.asset}function OL(e,t){if(!t)return[...e];let n=t.toLowerCase();return e.filter(e=>{let t=DL(e);return typeof t==`string`&&t.toLowerCase()===n})}async function kL(e,t,n={}){let r=()=>HC().getChallenges(e),i=()=>tw().getChallenges(n.ignoreX402ResponseUrl?new Response(null,{headers:e.headers,status:e.status}):e);if(t===`mpp`)return r();if(t===`x402`)return i();let a=[],o;try{a=await r()}catch(e){o=e}let s=[],c;try{s=await i()}catch(e){c=e}if(a.length||s.length)return[...a,...s];if(o)throw o;if(c)throw c;return[]}function AL(e){return rw({name:`selected-challenge`,isPaymentRequired:e=>e.status===402,getChallenges:()=>[e],setCredential:e=>e})}function jL(e,t){if(!wS(e))return new Response(null,{status:402,headers:{[q.wwwAuthenticate]:Qx(e)}});let n=e.request;return n.resource?new Response(null,{status:402,headers:{[lC]:ZC({accepts:[iC(n)],...n.extensions&&{extensions:n.extensions},resource:n.resource,x402Version:2})}}):t}function ML(e){let{host:t,hostname:n}=new URL(e);return!n.endsWith(`.localhost`)||n===`localhost`?{url:e}:{host:t,url:e.replace(n,`127.0.0.1`)}}async function NL(e,t,n,r){let i=t,a=ML(i),o={...n,redirect:`manual`,headers:Sw(n.headers)};a.host&&IL(o.headers,a.host);for(let t=0;t<=20;t++){let n=await e(a.url,o),s=n.headers.get(`location`);if(!r||!s||![301,302,303,307,308].includes(n.status))return{init:o,logicalUrl:i,response:n,target:a};if(t===20)throw TypeError(`Too many redirects`);await n.body?.cancel().catch(()=>{});let c=new URL(s,i),l=new URL(i),u=Sw(o.headers);if(c.origin!==l.origin)for(let e of[`authorization`,`cookie`,`host`,`proxy-authorization`])for(let t of Object.keys(u))t.toLowerCase()===e&&delete u[t];let d=(o.method??(o.body?`POST`:`GET`)).toUpperCase(),f=n.status===303&&d!==`GET`&&d!==`HEAD`||(n.status===301||n.status===302)&&d===`POST`;if(f)for(let e of[`content-encoding`,`content-language`,`content-length`,`content-location`,`content-type`])for(let t of Object.keys(u))t.toLowerCase()===e&&delete u[t];i=c.href,a=ML(i),a.host&&IL(u,a.host);let p={...o};f&&(delete p.body,p.method=`GET`),o={...p,headers:u,redirect:`manual`}}throw TypeError(`Too many redirects`)}function PL(e,t,n){let r=new URL(e),i=new URL(n||e);return i.origin!==r.origin&&FL(i),ML(i.href)}function FL(e){throw new I({code:`UNSAFE_PAYMENT_REDIRECT`,message:`Refusing to send a payment credential to redirected origin ${e.origin}.`,exitCode:1})}function IL(e,t){for(let t of Object.keys(e))t.toLowerCase()===`host`&&delete e[t];t&&(e.Host=t)}function LL(e){let t=e.request.resource;return typeof t?.url==`string`?t.url:void 0}async function RL(){let e=process.env.MPPX_SERVICES_URL??`https://mpp.dev/api/services`,t=await globalThis.fetch(e);if(!t.ok)throw new I({code:`SERVICES_FETCH_FAILED`,message:`Failed to fetch services registry: HTTP ${t.status}`,exitCode:1});let n=await t.json();if(!n||typeof n!=`object`||!Array.isArray(n.services))throw new I({code:`SERVICES_INVALID`,message:`Services registry response did not contain a services array.`,exitCode:1});return n.services}function zL(e,t){let n=t.toLowerCase();return e.find(e=>{let t=SL(e.id)?.toLowerCase(),r=SL(e.name)?.toLowerCase();return t===n||r===n})}const BL=sb(`mppx`,{mcp:{tools:{discovery:`direct`}},version:fL,description:`Make HTTP requests with automatic payment handling`,usage:[{suffix:`<url> [options]`}],args:p.object({url:p.string().describe(`URL to make request to`)}),options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),autoSwap:p.boolean().optional().describe(`Auto-swap source tokens into payment currency`),config:p.string().optional().describe(`Path to config file`),confirm:p.boolean().optional().default(!1).describe(`Show confirmation prompts`),currency:p.string().optional().describe(`Payment currency/token address to select`),data:p.string().optional().describe(`Send request body (implies POST unless -X is set)`),fail:p.boolean().optional().describe(`Fail silently on HTTP errors (exit 22)`),header:p.array(p.string()).optional().describe(`Add header (repeatable)`),include:p.boolean().optional().describe(`Include response headers in output`),insecure:p.boolean().optional().describe(`Skip TLS certificate verification (true for localhost/.local)`),jsonBody:p.string().optional().describe(`Send JSON body (sets Content-Type and Accept, implies POST)`),location:p.boolean().optional().describe(`Follow redirects`),method:p.string().optional().describe(`HTTP method`),methodOpt:p.array(p.string()).optional().describe(`Method-specific option (key=value, repeatable)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),payWith:p.string().optional().describe(`Source token for Tempo auto-swap`),protocol:p.enum([`auto`,`mpp`,`x402`]).default(`auto`).describe(`Payment protocol to use`),rpcUrl:p.string().optional().describe(`RPC endpoint, defaults to public RPC for chain (env: MPPX_RPC_URL)`),session:p.string().optional().default(`auto`).refine(e=>e===`auto`||e===`new`||/^0x[0-9a-fA-F]{64}$/.test(e),`Expected auto, new, or a 32-byte channel ID`).describe(`Session selection: auto, new, or channel ID`),silent:p.boolean().default(!1).describe(`Silent mode (suppress progress and info)`),slippage:p.number().optional().describe(`Tempo auto-swap max slippage percentage`),userAgent:p.string().optional().describe(`Set User-Agent header`),verbose:p.number().default(0).meta({count:!0}).describe(`Verbosity (-v details, -vv headers)`)}),alias:{account:`a`,config:`c`,data:`d`,fail:`f`,header:`H`,include:`i`,insecure:`k`,jsonBody:`J`,location:`L`,method:`X`,methodOpt:`M`,rpcUrl:`r`,silent:`s`,userAgent:`A`,verbose:`v`},examples:[{args:{url:`mpp.dev/api/ping/paid`},description:`Make a payment request`}],async run(e){let t=e.options.silent?e=>{}:e=>process.stderr.write(e),n=await TP(e.options.config);n&&e.options.verbose>=1&&t(`${X.dim(`Using config`)} ${X.blue(c.relative(process.cwd(),n.path))}\n`);let r=$O(),i={"User-Agent":e.options.userAgent??`mppx/${fL}${r?` AIAgent/${r}`:``}`};if(e.options.header)for(let t of e.options.header){let n=t.indexOf(`:`);if(n===-1)return e.error({code:`INVALID_HEADER`,message:`Invalid header format: ${t}`,exitCode:2});i[t.slice(0,n).trim()]=t.slice(n+1).trim()}let a=SP(n?.config);a&&!Object.keys(i).some(e=>e.toLowerCase()===`accept-payment`)&&(i[`Accept-Payment`]=a);let o=(()=>{let t=/^https?:\/\//.test(e.args.url),n=/^(localhost|.*\.localhost|127\.0\.0\.1|\[::1\])(:\d+)?/.test(e.args.url);return t?e.args.url:`${n?`http`:`https`}://${e.args.url}`})(),{hostname:s}=new URL(o),l=e.options.insecure||s===`localhost`||s.endsWith(`.localhost`)||s.endsWith(`.local`)?async(e,t)=>{let n=process.env.NODE_TLS_REJECT_UNAUTHORIZED;process.env.NODE_TLS_REJECT_UNAUTHORIZED=`0`;try{return await globalThis.fetch(e,t)}finally{n===void 0?delete process.env.NODE_TLS_REJECT_UNAUTHORIZED:process.env.NODE_TLS_REJECT_UNAUTHORIZED=n}}:globalThis.fetch,u=ML(o),d=u.url;u.host&&(i.Host=u.host);try{let r=_O(e.options.methodOpt),a=HP(),s={redirect:e.options.location?`follow`:`manual`};e.options.jsonBody?(s.body=e.options.jsonBody,i[`Content-Type`]??=`application/json`,i.Accept??=`application/json`):e.options.data&&(s.body=e.options.data),e.options.method?s.method=e.options.method.toUpperCase():s.body&&(s.method=`POST`),Object.keys(i).length>0&&(s.headers=i);let c={include:e.options.include??!1,verbose:e.options.verbose,silent:e.options.silent};e.options.verbose>=2&&dO(o,s,t);let f=await NL(l,o,s,e.options.location??!1),p=f.response;if(p.status!==402){if(e.options.session!==`auto`)return e.error({code:`UNSUPPORTED_SESSION`,message:`--session requires a tempo/session payment challenge.`,exitCode:2});if(e.options.fail&&p.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${p.status}`,exitCode:22});fO(p,c),await bL(p);return}let m=p.url?new URL(p.url):void 0,h=u.host!==void 0&&m?.hostname===`127.0.0.1`,g=await kL(p,e.options.protocol,{ignoreX402ResponseUrl:h});if(g.length===0)return e.error({code:`UNSUPPORTED_PROTOCOL`,message:e.options.protocol===`auto`?`Server did not offer a payment challenge.`:`Server did not offer an ${e.options.protocol} payment challenge.`,exitCode:2});let _=OL(g,e.options.currency);if(e.options.currency&&_.length===0){let t=g.map(DL).filter(e=>typeof e==`string`).join(`, `);return e.error({code:`UNSUPPORTED_CURRENCY`,message:`Server did not offer payment currency ${e.options.currency}.${t?` Offered currencies: ${t}.`:``}`,exitCode:2})}let v=CP(n?.config)?.length?_:await IN(_,{options:{account:e.options.account,network:e.options.network,rpcUrl:e.options.rpcUrl}}),y=xP(v,n?.config);if(!y){let t=v.map(e=>`${e.method}/${e.intent}`).join(`, `);return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method. Server offers: ${t}. Add it to mppx.config.ts using defineConfig().`,exitCode:2})}let{challenge:b,plugin:x,method:S}=y,C=wS(b),w=C?void 0:PL(o,u,f.logicalUrl),T=jL(b,p),ee=b.request.currency??``,E=b.request.decimals??6,D,O;x&&(O=await x.setup({challenge:b,options:{account:e.options.account,autoSwap:e.options.autoSwap,network:e.options.network,payWith:e.options.payWith,rpcUrl:e.options.rpcUrl,slippage:e.options.slippage},methodOpts:r}),ee=O.tokenSymbol,E=O.tokenDecimals,D=O.explorerUrl);let te=!e.options.silent&&e.options.confirm,ne=new Set;{fO(p,b.method===`tempo`&&b.intent===`session`&&e.options.include?{...c,include:!1,verbose:Math.max(c.verbose,2)}:c);let n=(()=>{let e=new Set([`id`,`request`]),t=[];for(let[n,r]of Object.entries(b))e.has(n)||r===void 0||t.push([n,hO(n,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),r={tokenSymbol:ee,tokenDecimals:E,explorerUrl:D},i=(()=>{let e=new Set([`decimals`,`currency`,`methodDetails`]),t=[];for(let[n,i]of Object.entries(b.request))e.has(n)||i===void 0||t.push([n,pO(n,i,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),a=(()=>{let e=b.request.methodDetails;if(!e)return[];let t=[];for(let[n,i]of Object.entries(e))if(i!==void 0){if(n===`memo`&&typeof i==`string`){let e=mO(i);t.push([n,e?`${e}\n${X.dim(i)}`:i])}else t.push([n,pO(n,i,r)])}return t.sort(([e],[t])=>e.localeCompare(t))})(),o=[[`Challenge`,n],[`Request`,i],...a.length?[[`Details`,a]]:[]];for(let[,e]of o)for(let[t]of e)ne.add(t);let s=Math.max(...o.flatMap(([,e])=>e.map(([e])=>e.length))),l=` ${``.padEnd(s)} `;if(e.options.verbose>=1||te){t(`${X.bold(X.yellow(`Payment Required`))}\n`);for(let[e,n]of o){t(`${X.bold(e)}\n`);for(let[e,r]of n){let[n,...i]=r.split(`
|
|
245
|
+
`);console.log(X.yellow(` ${e}`));for(let e of t)console.log(e?X.dim(` ${e}`):``);console.log(``),process.exit(1)}t.discovery.endpoints.length===0&&!e.options.endpoint&&l&&(console.log(X.dim(` Use --endpoint to specify endpoints manually.`)),console.log(``),process.exit(1));break;case`endpoint`:u++,JF(`${t.endpoint.method} ${t.endpoint.path}`);break;case`challenge`:console.log(X.dim(` Challenge`)),YF(t.results,n),t.isMpp&&(r=!0,t.isTestnet&&(o=!0),t.isMainnet&&(s=!0)),t.isNonMppPayment&&(i=!0),t.isMalformedChallenge&&(a=!0);break;case`errorHandling`:console.log(X.dim(` Error Handling`)),YF(t.results,n);break;case`payment`:t.succeeded&&(c=!0)}$I(n,{sawMppEndpoint:r,sawNonMppPaymentEndpoint:i,sawMalformedChallenge:a,sawTestnet:o,sawMainnet:s,paymentSucceeded:c},u)}});function $I(e,t,n){!t.sawMppEndpoint&&n>0&&(console.log(``),t.sawMalformedChallenge?(console.log(X.yellow(` Payment scheme detected but challenge format is invalid on ${n} endpoint(s).`)),console.log(X.dim(` The server uses WWW-Authenticate: Payment but the challenge parameters do not conform to MPP.`)),console.log(X.dim(` Fix: encode payment details as base64url JSON in a request="..." parameter. See errors above.`))):t.sawNonMppPaymentEndpoint?(console.log(X.yellow(` No MPP endpoints found. Tested ${n} endpoint(s) but none use WWW-Authenticate: Payment.`)),console.log(X.dim(` This server may use x402 or another payment protocol.`))):e.skipped>0&&e.failed===0?(console.log(X.yellow(` Could not reach payment gate on any endpoint (all returned 401/403/200).`)),console.log(X.dim(` The server may require authentication before payment. Try providing auth or use --endpoint with a public path.`))):(console.log(X.yellow(` No MPP endpoints found. Tested ${n} endpoint(s) but none use WWW-Authenticate: Payment.`)),console.log(X.dim(` This server may use x402 or another payment protocol.`))),console.log(``),process.exit(1)),console.log(``);let r=[];e.passed>0&&r.push(X.green(`${e.passed} passed`)),e.failed>0&&r.push(X.red(`${e.failed} failed`)),e.warnings>0&&r.push(X.yellow(`${e.warnings} warning(s)`)),e.suggested>0&&r.push(X.cyan(`${e.suggested} suggested`)),e.skipped>0&&r.push(X.yellow(`${e.skipped} skipped`)),console.log(`${X.bold(`Summary:`)} ${r.join(`, `)}`),t.paymentSucceeded&&t.sawTestnet&&!t.sawMainnet?(console.log(``),console.log(X.dim(` Tip: also validate your mainnet server to confirm real payments work end-to-end.`))):t.sawMainnet&&!t.sawTestnet&&(console.log(``),console.log(X.dim(` Tip: also validate your testnet server for free. This CLI automatically provisions and funds a testnet wallet for testing.`))),console.log(``),e.failed>0&&process.exit(1)}function eL(e){return nL(e)?e.offers:[e]}function tL(e){let{_canonicalRequest:t,intent:n,name:r}=e,i=t.methodDetails??{},a=rL(t.amount)??rL(i.amount)??null,o=rL(t.currency)??rL(i.currency),s=rL(e.description)??rL(t.description),c={amount:a,...o?{currency:o}:{},...s?{description:s}:{},intent:n,method:r},l=new Set([`amount`,`currency`,`description`,`methodDetails`]);for(let[e,n]of Object.entries(t))!l.has(e)&&n!==void 0&&(c[e]=n);return c}function nL(e){return`offers`in e&&!(`_canonicalRequest`in e)}function rL(e){return typeof e==`string`?e:void 0}var iL=F((()=>{})),aL=Ze({generate:()=>oL,generateProxy:()=>sL});function oL(e,t){let n=e.methods,r=new Map,i={};for(let e of n)r.set(`${e.name}/${e.intent}`,e),i[e.intent]=(i[e.intent]??0)+1;for(let e of n)i[e.intent]===1&&r.set(e.intent,e);let a=t.routes.map(e=>lL(e,r));return cL({info:{title:t.info?.title??e.realm,version:t.info?.version??`1.0.0`},routes:a,serviceInfo:t.serviceInfo})}function sL(e){let t=e.routes.map(t=>({...t,path:uL(e.basePath,t.path)}));return cL({info:{title:e.info?.title??`API Proxy`,version:e.info?.version??`1.0.0`},routes:t,serviceInfo:e.serviceInfo})}function cL(e){let t={};for(let n of e.routes){let e=n.method.toLowerCase(),r={responses:{...n.payment?{402:{description:`Payment Required`}}:{},200:{description:`Successful response`}}};n.payment&&(r[`x-payment-info`]=LT.parse(n.payment)),n.summary&&(r.summary=n.summary),n.requestBody&&(r.requestBody=n.requestBody),t[n.path]||(t[n.path]={}),t[n.path][e]=r}let n={info:e.info,openapi:`3.1.0`,paths:t};return e.serviceInfo&&(n[`x-service-info`]=e.serviceInfo),n}function lL(e,t){if(`handler`in e){let t=e.handler._internal;if(!t)throw Error(`Route ${e.method.toUpperCase()} ${e.path} is missing discovery metadata`);return{method:e.method,path:e.path,payment:{offers:eL(t).map(tL)},...e.requestBody?{requestBody:e.requestBody}:{},...e.summary?{summary:e.summary}:{}}}let n=t.get(e.intent);if(!n)throw Error(`Unknown intent "${e.intent}" for route ${e.method.toUpperCase()} ${e.path}. Available: ${[...t.keys()].join(`, `)}`);let{description:r,...i}=e.options,a={_canonicalRequest:Ix(n,i),...typeof r==`string`?{description:r}:{},intent:n.intent,name:n.name};return{method:e.method,path:e.path,payment:tL(a),...e.requestBody?{requestBody:e.requestBody}:{},...e.summary?{summary:e.summary}:{}}}function uL(e,t){if(!e)return t;let n=e.startsWith(`/`)?e:`/${e}`;return`${n.endsWith(`/`)?n.slice(0,-1):n}${t}`}var dL=F((()=>{Rx(),UT(),iL()}));Dx(),gS(),oT(),UC(),nw(),aw(),Px(),rO(),ew(),ES(),DC(),ZO(),LO();const fL=`0.13.4`,pL=p.object({address:p.string(),isDefault:p.boolean().optional(),name:p.string(),source:p.string().optional()}),mL=p.object({address:p.string(),balances:p.array(p.string()).optional(),name:p.string(),type:p.string().optional()}),hL=p.object({message:p.string(),path:p.string(),severity:p.string()}),gL=p.object({description:p.string().optional(),id:p.string(),name:p.string().optional(),paidEndpoints:p.number(),status:p.string().optional(),url:p.string().optional()}),_L=p.object({description:p.string().optional(),method:p.string(),path:p.string(),payment:p.unknown().optional()});function vL(e){return e.format===`json`&&e.formatExplicit}function yL(e,t,n){if(vL(e))return e.ok(t);n()}async function bL(t){if(!t.body)return;let n=t.body.getReader();try{for(;;){let{done:t,value:r}=await n.read();if(t)break;process.stdout.write(Buffer.from(r))||await e(process.stdout,`drain`)}}finally{n.releaseLock()}}function xL(){return process.stdin.isTTY===!1&&process.stdin.listenerCount(`data`)===0&&process.stdin.listenerCount(`readable`)===0}function SL(e){return typeof e==`string`?e:void 0}function CL(e){return Array.isArray(e.endpoints)?e.endpoints.filter(e=>typeof e==`object`&&!!e):[]}function wL(e){let t=CL(e);return{...SL(e.description)?{description:SL(e.description)}:{},id:SL(e.id)??SL(e.name)??`unknown`,...SL(e.name)?{name:SL(e.name)}:{},paidEndpoints:t.filter(e=>e.payment).length,...SL(e.status)?{status:SL(e.status)}:{},...SL(e.serviceUrl)||SL(e.url)?{url:SL(e.serviceUrl)??SL(e.url)}:{}}}function TL(e){return{...SL(e.description)?{description:SL(e.description)}:{},method:SL(e.method)??`GET`,path:SL(e.path)??`/`,...e.payment===void 0?{}:{payment:e.payment}}}function EL(e){if(!e)return`free`;if(typeof e!=`object`)return String(e);let t=e,n=SL(t.amount),r=SL(t.currency),i=SL(t.method),a=SL(t.intent);return[n,r,i&&a?`${i}/${a}`:i??a].filter(Boolean).join(` `)}function DL(e){return e.request.currency??e.request.asset}function OL(e,t){if(!t)return[...e];let n=t.toLowerCase();return e.filter(e=>{let t=DL(e);return typeof t==`string`&&t.toLowerCase()===n})}async function kL(e,t,n={}){let r=()=>HC().getChallenges(e),i=()=>tw().getChallenges(n.ignoreX402ResponseUrl?new Response(null,{headers:e.headers,status:e.status}):e);if(t===`mpp`)return r();if(t===`x402`)return i();let a=[],o;try{a=await r()}catch(e){o=e}let s=[],c;try{s=await i()}catch(e){c=e}if(a.length||s.length)return[...a,...s];if(o)throw o;if(c)throw c;return[]}function AL(e){return rw({name:`selected-challenge`,isPaymentRequired:e=>e.status===402,getChallenges:()=>[e],setCredential:e=>e})}function jL(e,t){if(!wS(e))return new Response(null,{status:402,headers:{[q.wwwAuthenticate]:Qx(e)}});let n=e.request;return n.resource?new Response(null,{status:402,headers:{[lC]:ZC({accepts:[iC(n)],...n.extensions&&{extensions:n.extensions},resource:n.resource,x402Version:2})}}):t}function ML(e){let{host:t,hostname:n}=new URL(e);return!n.endsWith(`.localhost`)||n===`localhost`?{url:e}:{host:t,url:e.replace(n,`127.0.0.1`)}}async function NL(e,t,n,r){let i=t,a=ML(i),o={...n,redirect:`manual`,headers:Sw(n.headers)};a.host&&IL(o.headers,a.host);for(let t=0;t<=20;t++){let n=await e(a.url,o),s=n.headers.get(`location`);if(!r||!s||![301,302,303,307,308].includes(n.status))return{init:o,logicalUrl:i,response:n,target:a};if(t===20)throw TypeError(`Too many redirects`);await n.body?.cancel().catch(()=>{});let c=new URL(s,i),l=new URL(i),u=Sw(o.headers);if(c.origin!==l.origin)for(let e of[`authorization`,`cookie`,`host`,`proxy-authorization`])for(let t of Object.keys(u))t.toLowerCase()===e&&delete u[t];let d=(o.method??(o.body?`POST`:`GET`)).toUpperCase(),f=n.status===303&&d!==`GET`&&d!==`HEAD`||(n.status===301||n.status===302)&&d===`POST`;if(f)for(let e of[`content-encoding`,`content-language`,`content-length`,`content-location`,`content-type`])for(let t of Object.keys(u))t.toLowerCase()===e&&delete u[t];i=c.href,a=ML(i),a.host&&IL(u,a.host);let p={...o};f&&(delete p.body,p.method=`GET`),o={...p,headers:u,redirect:`manual`}}throw TypeError(`Too many redirects`)}function PL(e,t,n){let r=new URL(e),i=new URL(n||e);return i.origin!==r.origin&&FL(i),ML(i.href)}function FL(e){throw new I({code:`UNSAFE_PAYMENT_REDIRECT`,message:`Refusing to send a payment credential to redirected origin ${e.origin}.`,exitCode:1})}function IL(e,t){for(let t of Object.keys(e))t.toLowerCase()===`host`&&delete e[t];t&&(e.Host=t)}function LL(e){let t=e.request.resource;return typeof t?.url==`string`?t.url:void 0}async function RL(){let e=process.env.MPPX_SERVICES_URL??`https://mpp.dev/api/services`,t=await globalThis.fetch(e);if(!t.ok)throw new I({code:`SERVICES_FETCH_FAILED`,message:`Failed to fetch services registry: HTTP ${t.status}`,exitCode:1});let n=await t.json();if(!n||typeof n!=`object`||!Array.isArray(n.services))throw new I({code:`SERVICES_INVALID`,message:`Services registry response did not contain a services array.`,exitCode:1});return n.services}function zL(e,t){let n=t.toLowerCase();return e.find(e=>{let t=SL(e.id)?.toLowerCase(),r=SL(e.name)?.toLowerCase();return t===n||r===n})}const BL=sb(`mppx`,{mcp:{tools:{discovery:`direct`}},version:fL,description:`Make HTTP requests with automatic payment handling`,usage:[{suffix:`<url> [options]`}],args:p.object({url:p.string().describe(`URL to make request to`)}),options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),autoSwap:p.boolean().optional().describe(`Auto-swap source tokens into payment currency`),config:p.string().optional().describe(`Path to config file`),confirm:p.boolean().optional().default(!1).describe(`Show confirmation prompts`),currency:p.string().optional().describe(`Payment currency/token address to select`),data:p.string().optional().describe(`Send request body (implies POST unless -X is set)`),fail:p.boolean().optional().describe(`Fail silently on HTTP errors (exit 22)`),header:p.array(p.string()).optional().describe(`Add header (repeatable)`),include:p.boolean().optional().describe(`Include response headers in output`),insecure:p.boolean().optional().describe(`Skip TLS certificate verification (true for localhost/.local)`),jsonBody:p.string().optional().describe(`Send JSON body (sets Content-Type and Accept, implies POST)`),location:p.boolean().optional().describe(`Follow redirects`),method:p.string().optional().describe(`HTTP method`),methodOpt:p.array(p.string()).optional().describe(`Method-specific option (key=value, repeatable)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),payWith:p.string().optional().describe(`Source token for Tempo auto-swap`),protocol:p.enum([`auto`,`mpp`,`x402`]).default(`auto`).describe(`Payment protocol to use`),rpcUrl:p.string().optional().describe(`RPC endpoint, defaults to public RPC for chain (env: MPPX_RPC_URL)`),session:p.string().optional().default(`auto`).refine(e=>e===`auto`||e===`new`||/^0x[0-9a-fA-F]{64}$/.test(e),`Expected auto, new, or a 32-byte channel ID`).describe(`Session selection: auto, new, or channel ID`),silent:p.boolean().default(!1).describe(`Silent mode (suppress progress and info)`),slippage:p.number().optional().describe(`Tempo auto-swap max slippage percentage`),userAgent:p.string().optional().describe(`Set User-Agent header`),verbose:p.number().default(0).meta({count:!0}).describe(`Verbosity (-v details, -vv headers)`)}),alias:{account:`a`,config:`c`,data:`d`,fail:`f`,header:`H`,include:`i`,insecure:`k`,jsonBody:`J`,location:`L`,method:`X`,methodOpt:`M`,rpcUrl:`r`,silent:`s`,userAgent:`A`,verbose:`v`},examples:[{args:{url:`mpp.dev/api/ping/paid`},description:`Make a payment request`}],async run(e){let t=e.options.silent?e=>{}:e=>process.stderr.write(e),n=await TP(e.options.config);n&&e.options.verbose>=1&&t(`${X.dim(`Using config`)} ${X.blue(c.relative(process.cwd(),n.path))}\n`);let r=$O(),i={"User-Agent":e.options.userAgent??`mppx/${fL}${r?` AIAgent/${r}`:``}`};if(e.options.header)for(let t of e.options.header){let n=t.indexOf(`:`);if(n===-1)return e.error({code:`INVALID_HEADER`,message:`Invalid header format: ${t}`,exitCode:2});i[t.slice(0,n).trim()]=t.slice(n+1).trim()}let a=SP(n?.config);a&&!Object.keys(i).some(e=>e.toLowerCase()===`accept-payment`)&&(i[`Accept-Payment`]=a);let o=(()=>{let t=/^https?:\/\//.test(e.args.url),n=/^(localhost|.*\.localhost|127\.0\.0\.1|\[::1\])(:\d+)?/.test(e.args.url);return t?e.args.url:`${n?`http`:`https`}://${e.args.url}`})(),{hostname:s}=new URL(o),l=e.options.insecure||s===`localhost`||s.endsWith(`.localhost`)||s.endsWith(`.local`)?async(e,t)=>{let n=process.env.NODE_TLS_REJECT_UNAUTHORIZED;process.env.NODE_TLS_REJECT_UNAUTHORIZED=`0`;try{return await globalThis.fetch(e,t)}finally{n===void 0?delete process.env.NODE_TLS_REJECT_UNAUTHORIZED:process.env.NODE_TLS_REJECT_UNAUTHORIZED=n}}:globalThis.fetch,u=ML(o),d=u.url;u.host&&(i.Host=u.host);try{let r=_O(e.options.methodOpt),a=HP(),s={redirect:e.options.location?`follow`:`manual`};e.options.jsonBody?(s.body=e.options.jsonBody,i[`Content-Type`]??=`application/json`,i.Accept??=`application/json`):e.options.data&&(s.body=e.options.data),e.options.method?s.method=e.options.method.toUpperCase():s.body&&(s.method=`POST`),Object.keys(i).length>0&&(s.headers=i);let c={include:e.options.include??!1,verbose:e.options.verbose,silent:e.options.silent};e.options.verbose>=2&&dO(o,s,t);let f=await NL(l,o,s,e.options.location??!1),p=f.response;if(p.status!==402){if(e.options.session!==`auto`)return e.error({code:`UNSUPPORTED_SESSION`,message:`--session requires a tempo/session payment challenge.`,exitCode:2});if(e.options.fail&&p.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${p.status}`,exitCode:22});fO(p,c),await bL(p);return}let m=p.url?new URL(p.url):void 0,h=u.host!==void 0&&m?.hostname===`127.0.0.1`,g=await kL(p,e.options.protocol,{ignoreX402ResponseUrl:h});if(g.length===0)return e.error({code:`UNSUPPORTED_PROTOCOL`,message:e.options.protocol===`auto`?`Server did not offer a payment challenge.`:`Server did not offer an ${e.options.protocol} payment challenge.`,exitCode:2});let _=OL(g,e.options.currency);if(e.options.currency&&_.length===0){let t=g.map(DL).filter(e=>typeof e==`string`).join(`, `);return e.error({code:`UNSUPPORTED_CURRENCY`,message:`Server did not offer payment currency ${e.options.currency}.${t?` Offered currencies: ${t}.`:``}`,exitCode:2})}let v=CP(n?.config)?.length?_:await IN(_,{options:{account:e.options.account,network:e.options.network,rpcUrl:e.options.rpcUrl}}),y=xP(v,n?.config);if(!y){let t=v.map(e=>`${e.method}/${e.intent}`).join(`, `);return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method. Server offers: ${t}. Add it to mppx.config.ts using defineConfig().`,exitCode:2})}let{challenge:b,plugin:x,method:S}=y,C=wS(b),w=C?void 0:PL(o,u,f.logicalUrl),T=jL(b,p),ee=b.request.currency??``,E=b.request.decimals??6,D,O;x&&(O=await x.setup({challenge:b,options:{account:e.options.account,autoSwap:e.options.autoSwap,network:e.options.network,payWith:e.options.payWith,rpcUrl:e.options.rpcUrl,slippage:e.options.slippage},methodOpts:r}),ee=O.tokenSymbol,E=O.tokenDecimals,D=O.explorerUrl);let te=!e.options.silent&&e.options.confirm,ne=new Set;{fO(p,b.method===`tempo`&&b.intent===`session`&&e.options.include?{...c,include:!1,verbose:Math.max(c.verbose,2)}:c);let n=(()=>{let e=new Set([`id`,`request`]),t=[];for(let[n,r]of Object.entries(b))e.has(n)||r===void 0||t.push([n,hO(n,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),r={tokenSymbol:ee,tokenDecimals:E,explorerUrl:D},i=(()=>{let e=new Set([`decimals`,`currency`,`methodDetails`]),t=[];for(let[n,i]of Object.entries(b.request))e.has(n)||i===void 0||t.push([n,pO(n,i,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),a=(()=>{let e=b.request.methodDetails;if(!e)return[];let t=[];for(let[n,i]of Object.entries(e))if(i!==void 0){if(n===`memo`&&typeof i==`string`){let e=mO(i);t.push([n,e?`${e}\n${X.dim(i)}`:i])}else t.push([n,pO(n,i,r)])}return t.sort(([e],[t])=>e.localeCompare(t))})(),o=[[`Challenge`,n],[`Request`,i],...a.length?[[`Details`,a]]:[]];for(let[,e]of o)for(let[t]of e)ne.add(t);let s=Math.max(...o.flatMap(([,e])=>e.map(([e])=>e.length))),l=` ${``.padEnd(s)} `;if(e.options.verbose>=1||te){t(`${X.bold(X.yellow(`Payment Required`))}\n`);for(let[e,n]of o){t(`${X.bold(e)}\n`);for(let[e,r]of n){let[n,...i]=r.split(`
|
|
246
246
|
`);t(` ${X.dim(e.padEnd(s))} ${n}\n`);for(let e of i)t(`${l}${e}\n`)}}}if(te&&(t(`
|
|
247
247
|
`),!await xO(`Proceed with ${b.intent}?`,!0))){t(`Aborted.
|
|
248
248
|
`);return}}let re=process.env.MPPX_PRIVATE_KEY?.trim()||!yO(WO(e.options.account));if(SD(b)&&re&&!S){try{await UF({challenge:b,challengeResponse:T,credentialContext:await yP(b,n?.config.extensions,O?.credentialContext),endpoint:f.logicalUrl,fetch:l,fetchInput:w.url,init:{...f.init,redirect:`manual`},info:t,methodOptions:r,options:{account:e.options.account,fail:e.options.fail,include:e.options.include,network:e.options.network,rpcUrl:e.options.rpcUrl,session:e.options.session,silent:e.options.silent,verbose:e.options.verbose},registry:a})}catch(e){return MF(e,`SESSION_REQUEST_FAILED`)}return}if(e.options.session!==`auto`)return e.error({code:`UNSUPPORTED_SESSION`,message:S&&SD(b)?`--session cannot override a configured session method. Configure its channelStore instead.`:`--session requires a tempo/session payment challenge.`,exitCode:2});let A=S&&SD(b)?void 0:await yP(b,n?.config.extensions,O?.credentialContext),j,ie;if(S&&SD(b)){let e=T;j=await dT({methods:[S],polyfill:!1,async onChallenge(e,{createCredential:t}){let r=await yP(e,n?.config.extensions,O?.credentialContext);return DP(b,e),t(r)},fetch:async(t,n)=>{if(e){let t=e;return e=void 0,t}return l(t,n)}}).fetch(w.url,{...f.init,context:A,redirect:`manual`})}else{if(O?.createCredential)ie=await O.createCredential(T,A);else if(O)ie=await dT({methods:O.methods,polyfill:!1,transport:AL(b)}).createCredential(T,A);else if(S)ie=await dT({methods:[S],polyfill:!1,transport:AL(b)}).createCredential(T,A);else throw Error(`unreachable`);let n=C?uC:dS(b),r={...Sw(f.init.headers),[n]:ie},i=C?ML((LL(b)??p.url)||o):w;C&&IL(r,i.host),x?.prepareCredentialRequest?.({challenge:b,credential:ie,headers:r});let a={...f.init,redirect:`manual`,headers:r};e.options.verbose>=2&&dO(i.url,a,t),j=await l(i.url,a)}if(e.options.fail&&j.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${j.status}`,exitCode:22});if(j.status===402){let n=await j.text();t(`${X.bold(X.red(`Payment Rejected`))}\n`);try{let e=JSON.parse(n),r=[];for(let[t,n]of Object.entries(e))n!==void 0&&r.push([t,String(n)]);r.sort(([e],[t])=>e.localeCompare(t));let i=Math.max(...r.map(([e])=>e.length));for(let[e,n]of r)t(` ${X.dim(e.padEnd(i))} ${n}\n`)}catch{n&&t(` ${n}\n`)}return e.error({code:`PAYMENT_REJECTED`,message:`Payment rejected`,exitCode:75})}if(fO(j,c),!(ie&&await x?.handleResponse?.({challenge:b,credential:ie,response:j,fetchUrl:d,fetchInit:s,silent:e.options.silent,verbose:e.options.verbose,confirmEnabled:te,confirm:xO,tokenSymbol:ee,tokenDecimals:E,explorerUrl:D,shownKeys:ne}))){let n=j.headers.get(q.paymentReceipt);if(n&&e.options.verbose>=1)try{let e=JSON.parse(k.toString(n));t(`\n${X.bold(X.green(`Payment Receipt`))}\n`);let r=[],i=e.channelId,a=e.reference,o=i&&a&&i===a,s=new Set([`acceptedCumulative`,`spent`]);for(let[t,n]of Object.entries(e)){if(n===void 0||ne.has(t)||t===`reference`&&o)continue;let e=x?.formatReceiptField?.(t,n);e===void 0?s.has(t)&&typeof n==`string`?r.push([t,`${n} ${X.dim(`(${SO(BigInt(n),ee,E)})`)}`]):(t===`reference`||t===`txHash`)&&typeof n==`string`&&D?r.push([t,gO(`${D}/tx/${n}`,n)]):r.push([t,String(n)]):r.push([t,e])}r.sort(([e],[t])=>e.localeCompare(t));let c=Math.max(...r.map(([e])=>e.length));for(let[e,n]of r)t(` ${X.dim(e.padEnd(c))} ${n}\n`);t(`
|